/* Server version: WI-V6.3.1.26351 Firebird 2.5 
   SQLDialect: 3. ODS: 11.2. Forced writes: On. Sweep inteval: 0.
   Page size: 16384. Cache pages: 2000 (32000 Kb). Read-only: False. */
SET NAMES WIN1252;

SET SQL DIALECT 3;

CONNECT '192.168.10.199:c:\sci\bancopadrao\vsci.fdb' USER 'SYSDBA' PASSWORD 'masterkey';

SET AUTODDL ON;

/* Create Procedure... */
SET TERM ^ ;

CREATE PROCEDURE SP_EXPORTA_BLOCOC_SAI_REG300(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRPERFIL INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE PROCEDURE SP_GET_EVT_FILA_ESOCIAL(PRCODEMP INTEGER,
PREXCLUSAO INTEGER)
 RETURNS(BDCODIGO INTEGER,
BDCODEMP INTEGER,
BDCHAVE VARCHAR(50),
BDXML BLOB,
BDCODTIPO INTEGER,
BDSTATUS INTEGER,
BDDATAEVENTO DATE,
BDMOTIVO VARCHAR(100),
BDGRUPO INTEGER,
BDDATAININAOPERIOD DATE,
BDDATAINITABELA DATE,
BDDATAINIPERIOD DATE,
BDDATAINISST DATE)
 AS
 BEGIN SUSPEND; END
^


/* Create Views... */
/* Create view: VW_FGTS_13S_CC */
SET TERM ; ^

CREATE VIEW VW_FGTS_13S_CC(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODCENTRO,
BDCODTPCC,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  S13.BDCODEMP,
  S13.BDCODCOL,
  S13.BDREF13,
  pfn.BDCODCENTRO,
  pfn.BDCODTPCC,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  S13.BDBASEFGTS13,
  S13.BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  3 BDTIPO
FROM VRHF_EMP_T13SAL S13
left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = s13.bdcodemp and pfn.bdcodcol = s13.bdcodcol and pfn.bdordem = s13.bdordem)
;

/* Create view: VW_FGTS_A13_CC */
CREATE VIEW VW_FGTS_A13_CC(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODCENTRO,
BDCODTPCC,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  A13.BDCODEMP,
  A13.BDCODCOL,
  A13.BDREFA13,
  pfn.BDCODCENTRO,
  pfn.BDCODTPCC,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  A13.BDBASEFGTSA13,
  A13.BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  2 BDTIPO
FROM VRHF_EMP_TA13SAL A13
left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = a13.bdcodemp and pfn.bdcodcol = a13.bdcodcol and pfn.bdordem = a13.bdordem)
;

/* Create view: VW_FGTS_AVULSA_CC */
CREATE VIEW VW_FGTS_AVULSA_CC(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODCENTRO,
BDCODTPCC,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  FA.BDCODEMP,
  FA.BDCODCOL,
  CAST((SUBSTRING(CAST(FA.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FA.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFFA,
  pfn.BDCODCENTRO,
  pfn.BDCODTPCC,
  SUM(FA.BDBFGTSFA + FA.BDBFGTS13FA + COALESCE(FA.bdbfgtsfefa,0)),
  SUM(FA.BDFGTSFA + FA.BDFGTS13FA + COALESCE(FA.bdfgtsfefa,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBFGTS13FAASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  5 BDTIPO
FROM VRHF_EMP_TFOLHAAVULSA FA
left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = fa.bdcodemp and pfn.bdcodcol = fa.bdcodcol and pfn.bdordem = fa.bdordem)
GROUP BY FA.BDCODEMP, FA.BDCODCOL, BDREFFA, pfn.BDCODCENTRO,pfn.BDCODTPCC
;

/* Create view: VW_FGTS_C13_CC */
CREATE VIEW VW_FGTS_C13_CC(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODCENTRO,
BDCODTPCC,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  C13.BDCODEMP,
  C13.BDCODCOL,
  C13.BDREFC13,
  pfn.BDCODCENTRO,
  pfn.BDCODTPCC,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  C13.BDBASEFGTSC13,
  C13.BDFGTSC13,
  4 BDTIPO
FROM VRHF_EMP_TC13SAL C13
left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = c13.bdcodemp and pfn.bdcodcol = c13.bdcodcol and pfn.bdordem = c13.bdordem)
;

/* Create view: VW_FGTS_FOL_COMPLEMENTAR_CC */
CREATE VIEW VW_FGTS_FOL_COMPLEMENTAR_CC(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODCENTRO,
BDCODTPCC,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFCOMP,
  cast(null as integer),
  cast(null as integer),
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  BDBFGTSFC + BDBFGTS13FC + COALESCE(BDBFGTSFEFC,0),
  BDFGTSFC + BDFGTS13FC + COALESCE(BDFGTSFEFC,0),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM VRHF_EMP_TFOLHACOMP
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdrefcomp,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  SUM(X.bdbfgtsfc) + SUM(X.bdbfgts13fc) + SUM(COALESCE(BDBFGTSFEFC,0)),
  SUM(X.bdfgtsfC) + SUM(X.bdfgts13fC) + SUM(COALESCE(BDFGTSFEFC,0)),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM vrhf_emp_tfoltomcomp x
join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem)
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdrefCOMP, pfn.bdcodcentro, pfn.bdcodtpcc
;

/* Create view: VW_FGTS_FOL_NORMAL_CC */
CREATE VIEW VW_FGTS_FOL_NORMAL_CC(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODCENTRO,
BDCODTPCC,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  cast(null as integer),
  cast(null as integer),
  Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0),
  Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  cast(null as integer),
  cast(null as integer),
  SUM(Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0)),
  SUM(Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHAINT Y
group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  SUM(X.bdbfgtsft) + SUM(X.bdbfgts13ft) + SUM(COALESCE(X.bdbfgtsFEft,0)),
  SUM(X.bdfgtsft) + SUM(X.bdfgts13ft) + SUM(COALESCE(x.bdfgtsFEft,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem)
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador, pfn.bdcodcentro, pfn.bdcodtpcc
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  SUM(X.bdbfgtsft) + SUM(X.bdbfgts13ft) + SUM(COALESCE(X.bdbfgtsFEft,0)),
  SUM(X.bdfgtsft) + SUM(X.bdfgts13ft) + SUM(COALESCE(x.bdfgtsFEft,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomint x
join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem)
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador, pfn.bdcodcentro, pfn.bdcodtpcc
;

/* Alter view (drop/create): VW_FICHA_FGTS for view: VW_UNION_FGTS_CC */
/* Alter view (drop): VW_FICHA_FGTS for view: VW_UNION_FGTS_CC */
DROP VIEW VW_UNION_FGTS;

DROP VIEW VW_FICHA_FGTS;

/* Alter view (create): VW_FICHA_FGTS for view: VW_UNION_FGTS_CC */
/* Create view: VW_FICHA_FGTS */
CREATE VIEW VW_FICHA_FGTS(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREF_FFGTS,
  X.BDBFGTS_FFGTS,
  X.BDFGTS_FFGTS,
  0.00 BDBFGTSFC_FFGTS,
  0.00 BDFGTSFC_FFGTS,
  0.00 BDBFGTS13_FFGTS,
  0.00 BDFGTS13_FFGTS,
  0.00 BDBFGTSAD13_FFGTS,
  0.00 BDFGTSAD13_FFGTS,
  0.00 BDBFGTSC13_FFGTS,
  0.00 BDFGTSC13_FFGTS,
  9 BDTIPO
FROM VRHF_EMP_TFICHAFGTS X
WHERE X.BDTIPO_FFGTS = 1 AND -- Folha normal
  NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhanormal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND
  NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomador Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) AND -- tomador
  NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhaint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND  -- intermitente
  NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) -- intermitente tomador
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREF_FFGTS,
  0.00 BDBFGTSN_FFGTS,
  0.00 BDFGTSN_FFGTS,
  0.00 BDBFGTSFC_FFGTS,
  0.00 BDFGTSFC_FFGTS,
  0.00 BDBFGTS13_FFGTS,
  0.00 BDFGTS13_FFGTS,
  X.BDBFGTS_FFGTS,
  X.BDFGTS_FFGTS,
  0.00 BDBFGTSC13_FFGTS,
  0.00 BDFGTSC13_FFGTS,
  9 BDTIPO
FROM VRHF_EMP_TFICHAFGTS X
WHERE X.BDTIPO_FFGTS = 3 AND -- Adiantamento de 13 salario
  NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_ta13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFA13 = X.BDREF_FFGTS)
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREF_FFGTS,
  0.00 BDBFGTSN_FFGTS,
  0.00 BDFGTSN_FFGTS,
  0.00 BDBFGTSFC_FFGTS,
  0.00 BDFGTSFC_FFGTS,
  X.BDBFGTS_FFGTS,
  X.BDFGTS_FFGTS,
  0.00 BDBFGTSAD13_FFGTS,
  0.00 BDFGTSAD13_FFGTS,
  0.00 BDBFGTSC13_FFGTS,
  0.00 BDFGTSC13_FFGTS,
  9 BDTIPO
FROM VRHF_EMP_TFICHAFGTS X
WHERE X.BDTIPO_FFGTS = 4 AND -- 13 salario
  NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_t13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREF13 = X.BDREF_FFGTS)
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREF_FFGTS,
  0.00 BDBFGTSN_FFGTS,
  0.00 BDFGTSN_FFGTS,
  0.00 BDBFGTSFC_FFGTS,
  0.00 BDFGTSFC_FFGTS,
  0.00 BDBFGTS13_FFGTS,
  0.00 BDFGTS13_FFGTS,
  0.00 BDBFGTSAD13_FFGTS,
  0.00 BDFGTSAD13_FFGTS,
  X.BDBFGTS_FFGTS,
  X.BDFGTS_FFGTS,
  9 BDTIPO
FROM VRHF_EMP_TFICHAFGTS X
WHERE X.BDTIPO_FFGTS = 5 AND -- Complemento de 13 salario
  NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tc13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFC13 = X.BDREF_FFGTS)
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREF_FFGTS,
  0.00 BDBFGTSN_FFGTS,
  0.00 BDFGTSN_FFGTS,
  X.BDBFGTS_FFGTS,
  X.BDFGTS_FFGTS,
  0.00 BDBFGTS13_FFGTS,
  0.00 BDFGTS13_FFGTS,
  0.00 BDBFGTSAD13_FFGTS,
  0.00 BDFGTSAD13_FFGTS,
  0.00 BDBFGTSC13_FFGTS,
  0.00 BDFGTSC13_FFGTS,
  9 BDTIPO
FROM VRHF_EMP_TFICHAFGTS X
WHERE X.BDTIPO_FFGTS = 7 AND -- Folha complementar
  NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacomp Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFCOMP = X.BDREF_FFGTS) AND
  NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcomp Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFCOMP = X.BDREF_FFGTS) -- tomador
;

/* Create view: VW_UNION_FGTS_CC */
CREATE VIEW VW_UNION_FGTS_CC(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODCENTRO,
BDCODTPCC,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_NORMAL_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_COMPLEMENTAR_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_A13_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_13S_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_C13_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_AVULSA_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  cast(null as integer),
  cast(null as integer),
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM vw_ficha_fgts
;


/* Alter View (Drop, Create)... */
/* Drop altered view: VW_CONSULTA_RDE */
DROP VIEW VW_CONSULTA_RDE;

/* Create altered view: VW_CONSULTA_RDE */
/* Create view: VW_CONSULTA_RDE */
CREATE VIEW VW_CONSULTA_RDE(
BDCODEMP,
BDCODRDE,
BDREFRDE,
BDDESCRICAORDE)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODRDE,
  X.BDREFRDE,
  'Emiss?o: '||SUBSTRING(CAST(X.BDDATAEMIRDE AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(X.BDDATAEMIRDE AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(X.BDDATAEMIRDE AS VARCHAR(10)) FROM 1 FOR 4)||
  '. '||CAST(X.BDCODEMP AS VARCHAR(9))||' - '||EMP.BDNOMEMP BDDESC
FROM
  VRH_EMP_TRDE X,
  VW_TEMPRESAS_REF EMP
WHERE
  X.BDCODEMP = EMP.BDCODEMP
;

/* Drop altered view: VW_CONSULTA_RDT */
DROP VIEW VW_CONSULTA_RDT;

/* Create altered view: VW_CONSULTA_RDT */
/* Create view: VW_CONSULTA_RDT */
CREATE VIEW VW_CONSULTA_RDT(
BDCODEMP,
BDCODCOL,
BDCODRDT,
BDDESCRICAORDT)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODRDT,
  'Emiss?o: '||SUBSTRING(CAST(X.BDDATAEMIRDT AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(X.BDDATAEMIRDT AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(X.BDDATAEMIRDT AS VARCHAR(10)) FROM 1 FOR 4)||
  '. '||CAST(X.BDCODEMP AS VARCHAR(9))||'. Col - '||COLCAD.BDNOMCOL BDDESC
FROM VRH_EMP_TRDT X
JOIN VRH_EMP_TCOLCON COL ON X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
;

/* Drop altered view: VW_EMP_REF_TOTAL */
SET TERM ^ ;

ALTER PROCEDURE SP_APURACAO_BLOCOM_VALIDAONLINE(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

SET TERM ; ^

DROP VIEW VW_EMP_REF_TOTAL;

/* Create altered view: VW_EMP_REF_TOTAL */
/* Create view: VW_EMP_REF_TOTAL */
CREATE VIEW VW_EMP_REF_TOTAL(
BDCODEMP,
BDREFEMP,
BDRETINSS,
BDVLRMININSS,
BDSUFRAMA,
BDCODACESSOSN,
BDPERFILSPED,
BDATIVIDADESPED,
BDSOMFREVLRCONTAB,
BDSOMFREBASEICMS,
BDCODPLATROCA,
BDCODPLACFOP,
BDCODCONFIPI,
BDCODCONFIRLP,
BDCODCONFDIMESC,
BDCODPORTEEMP,
BDCODAPUCON,
BDCODESCCONT,
BDCODREGAPU,
BDCONTPRODEC,
BDNRPARPRODEC,
BDCODCONFATIVO,
BDLANBCICMSVALCONT,
BDLANBCICMSISEOUT,
BDLANCLISAISER,
BDLANPROENT,
BDLANPROSAI,
BDMOVSER,
BDPERCISS,
BDREDPERCISS,
BDMOVIRRF,
BDALIQIRRF,
BDISENTOIRRF,
BDEMPINATIVA,
BDEMPDIFPAPEL,
BDEMPBARREST,
BDVERIFICARNOTASJALAN,
BDLRISSSN,
BDCOMERCIO,
BDINDUSTRIA,
BDSERVICO,
BDANEXOIII,
BDANEXOIV,
BDANEXOV,
BDSUBSTRIB,
BDCODCONFDACON,
BDCODCONFBLOCOM,
BDCODCONFBLOCOP,
BDCODCONFGIASP,
BDNOMEMP,
BDCODCONFICMSSPED,
BDCODCONFCIAP,
BDREDBCICMSENT,
BDREDBCICMSSAI,
BDCODCONFDASN,
BDRETPARPIS,
BDRETPARCOFINS,
BDRETPARCSLL,
BDRETPARIRRF,
BDRETPARISSQN,
BDRETPARINSS,
BDRETPARFUNRURAL,
BDTIPOAPURACAO,
BDCODCONFGIAMG,
BDCODCONFDAMEF,
BDCREDPRESUMIDO,
BDTERMOACEITE,
BDANTECIPAIMPOSTO,
BDTIPODECLARANTEDMED,
BDREGISTROANSDMED,
BDNUMEROCNESDMED,
BDDTOBRIGSPEDCONT,
BDTIPOAPURACAORET,
BDTIPOAPURACAORETIR,
BDDTOBRIGSPEDICMS,
BDLANCAPARCELAAUTO,
BDCODIGOPLA,
BDCODCONFGIAES,
BDCODCONFGIARO,
BDINDATIV,
BDCODCONFGIAPR,
BDANEXOVI,
BDINDNATPJ,
BDMANTERPARCELAS,
BDCODPLANOINCONS,
BDCODCONFGIARJ,
BDCODCONFDFC,
BDCODCONFCPRBREINF,
BDANEXOIII_2018,
BDANEXOIV_2018,
BDANEXOV_2018,
BDRELFOLHAANEXOIII,
BDCODCONFDOT)
 AS 
SELECT X.BDCODEMP,
       X.BDREFEMP,
       parger.bdretinss,
       parger.bdvlrmininss,
       X.bdsuframa,
       parfed.bdcodacessosn,
       parfed.bdperfilsped,
       parfed.bdatividadesped,
       parinteg.bdsomfrevlrcontab,
       parinteg.bdsomfrebaseicms,
       parinteg.bdcodplatroca,
       parinteg.bdcodplacfop,
       parger.BDCODCONFIPI,
       parger.BDCODCONFIRLP,

       parsc.BDCODCONFDIMESC,
       PAREST.BDCODPORTEEMP,
       parsc.BDCODAPUCON,
       parsc.BDCODESCCONT ,
       parsc.BDCODREGAPU ,
       parsc.BDCONTPRODEC ,
       parsc.BDNRPARPRODEC ,

       parger.BDCODCONFATIVO,
       parger.BDLANBCICMSVALCONT,
       parger.BDLANBCICMSISEOUT,
       parger.BDLANCLISAISER,
       parger.BDLANPROENT,
       parger.BDLANPROSAI,
       parger.BDMOVSER,
       parger.BDPERCISS,
       parger.BDREDPERCISS,
       parger.BDMOVIRRF,
       parger.BDALIQIRRF,
       parger.BDISENTOIRRF,
       parger.BDEMPINATIVA,
       parger.BDEMPDIFPAPEL,
       parger.BDEMPBARREST,
       parger.BDVERIFICARNOTASJALAN,
       paratvsn.bdlrisssn,
       paratvsn.bdcomercio,
       paratvsn.bdindustria,
       paratvsn.bdservico,
       paritatvsn.bdanexoiii,
       paritatvsn.bdanexoiv,
       paritatvsn.bdanexov,
       PAREST.BDSUBSTRIB,
       PARGER.bdcodconfdacon,
       PARGER.BDCODCONFBLOCOM,
       PARGER.bdcodconfblocop,
       parsp.BDCODCONFGIASP,
       X.BDNOMEMP,
       PARFED.bdcodconficmssped,
       PARGER.BDCODCONFCIAP,
       PAREST.BDREDBCICMSENT,
       PAREST.BDREDBCICMSSAI,
       parger.BDCODCONFDASN,
       parger.BDRETPARPIS,
       parger.BDRETPARCOFINS,
       parger.BDRETPARCSLL,
       parger.BDRETPARIRRF,
       parger.BDRETPARISSQN,
       parger.BDRETPARINSS,
       parger.BDRETPARFUNRURAL,
       parger.bdtipoapuracao,
       parmg.BDCODCONFGIAMG,
       parmg.BDCODCONFDAMEF,
       parmg.bdcredpresumido,
       parmg.bdtermoaceite,
       parfed.bdantecipaimposto,
       parfed.BDTIPODECLARANTEDMED,
       parfed.BDREGISTROANSDMED,
       parfed.BDNUMEROCNESDMED,
       parfed.BDDTOBRIGSPEDCONT,
       parger.BDTIPOAPURACAORET,
       parger.BDTIPOAPURACAORETIR,
       parfed.BDDTOBRIGSPEDICMS,
       parinteg.BDLANCAPARCELAAUTO,
       parinteg.bdcodigopla,
       pares.BDCODCONFGIAES,
       parro.BDCODCONFGIARO,
       parfed.BDINDATIV,
       parpr.bdcodconfgiapr,
       paritatvsn.BDANEXOVI,
       PARFED.BDINDNATPJ,
       parinteg.bdmanterparcelas,
       parinteg.bdcodplanoincons,
       parrj.BDCODCONFGIARJ,
       parpr.bdcodconfdfc,
       PARGER.BDCODCONFCPRBREINF,
       paritatvsn.BDANEXOIII_2018,
       paritatvsn.BDANEXOIV_2018,
       paritatvsn.BDANEXOV_2018,
       paritatvsn.BDRELFOLHAANEXOIII,
       pares.bdcodconfdot

FROM VW_TEMPRESAS_REF_MAX_MIN emp


JOIN TEMPRESAS_REF X ON (x.bdcodemp = emp.bdCODEMP AND x.bdrefemp = emp.bdrefemp)

LEFT OUTER JOIN VW_VEF_BASE_TEMPPARGER parger ON (parger.bdcodemp = emp.bdcodemp AND parger.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARFED parfed ON (parfed.bdcodemp = emp.bdcodemp AND parfed.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTSC parsc ON (parsc.bdcodemp = emp.bdcodemp AND parsc.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARFEDPORATV paratvsn ON (paratvsn.bdcodemp = emp.bdcodemp AND paratvsn.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPITEMSATV paritatvsn ON (paritatvsn.bdcodemp = emp.bdcodemp AND paritatvsn.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPAREST PAREST ON (PAREST.bdcodemp = emp.bdcodemp AND PAREST.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTSP parsp ON (parsp.bdcodemp = emp.bdcodemp AND parsp.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTMG parmg ON (parmg.bdcodemp = emp.bdcodemp AND parmg.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARINTEG parinteg ON (parinteg.bdcodemp = emp.bdcodemp AND parinteg.bdrefemp = emp.bdrefemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTES pares ON (pares.bdcodemp = emp.bdcodemp ) --alt.: #7125 - Para p?ginas novas no cadastro de empresa, pode n?o existir a referencia procurada, portanto s? ? usado o c?digo da empresa para ligar as views
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTRO parro ON (parro.bdcodemp = emp.bdcodemp ) --alt.: #7125 - Para p?ginas novas no cadastro de empresa, pode n?o existir a referencia procurada, portanto s? ? usado o c?digo da empresa para ligar as views
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTPR parpr ON (parpr.bdcodemp = emp.bdcodemp ) --alt.: #7125 - Para p?ginas novas no cadastro de empresa, pode n?o existir a referencia procurada, portanto s? ? usado o c?digo da empresa para ligar as views
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTRJ parrj ON (parrj.bdcodemp = emp.bdcodemp)
;

/* Drop altered view: VW_FGTS_FOL_NORMAL */
DROP VIEW VW_FGTS_FOL_NORMAL;

/* Create altered view: VW_FGTS_FOL_NORMAL */
/* Create view: VW_FGTS_FOL_NORMAL */
CREATE VIEW VW_FGTS_FOL_NORMAL(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0),
  Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  SUM(Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0)),
  SUM(Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHAINT Y
GROUP BY Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  SUM(X.bdbfgtsft) + SUM(X.bdbfgts13ft) + SUM(COALESCE(X.bdbfgtsFEft,0)),
  SUM(X.bdfgtsft) + SUM(X.bdfgts13ft) + SUM(COALESCE(x.bdfgtsFEft,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  SUM(X.bdbfgtsft) + SUM(X.bdbfgts13ft) + SUM(COALESCE(X.bdbfgtsFEft,0)),
  SUM(X.bdfgtsft) + SUM(X.bdfgts13ft) + SUM(COALESCE(x.bdfgtsFEft,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomint x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador
;

/* Drop altered view: VW_TAREFAS */
DROP VIEW VW_TAREFAS_USUARIO;

DROP VIEW VW_TAREFAS;

/* Create altered view: VW_TAREFAS */
/* Create view: VW_TAREFAS */
CREATE VIEW VW_TAREFAS(
BDCODEMP,
BDAPEEMP,
BDCODST,
BDDATAPREVISAO,
BDDATASOLICITADA,
BDDATAFIM,
BDDATASOL,
BDCODUSU,
BDNOMUSUSOL,
BDTIPOSOLICITACAO,
BDTIPO,
BDDATA,
BDHORA,
BDCODUSURESPONSAVEL,
BDNOMUSURESP,
BDCODIMP,
BDCODOBRIGACAO,
BDCODSERVICO,
BDTIPODESCRICAO,
BDSTATUS,
BDALERTA,
BDCODCID,
BDNOMCID,
BDSIGLAUF,
BDASCENDENTE,
BDCODSIS,
BDNOMSIS,
BDCODPERIODICIDADE,
BDPERIODICIDADE,
BDCOMPETENCIA,
BDVENCIMENTO,
BDENTREGA,
BDTEMPOESTIMADO,
BDCODPTS,
BDSERIEPTS,
BDNOMEMP,
BDFILIAL,
BDNOMEFILIAL,
BDCLASSIFICACAO,
BDCODCOL,
BDCODCOLVINC,
BDNOMCOLVINC,
BDREFSOL,
BDCODIMPOBRSER,
BDOBSUSUARIO,
BDOBSTAREFA,
BDCODTIPO,
BDCODGRUPO,
BDCODSITWEB,
BDVISUALIZADA)
 AS 
SELECT TSOL.bdcodemp,
       '' AS bdapeemp, --emp.bdapeemp,
       TSOL.bdcodst, TSOL.bddataprevisao, tsol.bddatasolicitada, tsol.bddatafim,
       tsol.bddatasol, tsol.bdcodusu, (tususol.bdnomusu) AS "bdnomususol", tsol.bdtiposolicitacao,

       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN 'Imposto'
            WHEN (tsol.bdtiposolicitacao = 1) THEN 'Obriga??o'
            WHEN (tsol.bdtiposolicitacao = 2) THEN 'Servi?o'
       END AS "bdTIPO",

       CASE WHEN (NOT this.bdstatus IN (0,6)) THEN this.bddata END AS bddata,
       CASE WHEN (NOT this.bdstatus IN (0,6)) THEN this.bdhora END AS bdhora,

       this.bdcodusuresponsavel ,

       (tusuresp.bdnomusu) AS "BDNOMUSURESP",


       TSOL.bdcodimp,
       TSOL.bdcodobrigacao,
       TSOL.bdcodservico,

       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN TIMP.BDDESCIMP
            WHEN (tsol.bdtiposolicitacao = 1) THEN TOBR.bddescricao
            WHEN (tsol.bdtiposolicitacao = 2) THEN TSER.bddescricao
       END AS "bdTIPODESCRICAO",
       CASE WHEN ((tsol.bddatafim IS NOT NULL) AND (tsol.BDAGUARD IS NOT NULL)) THEN 5 -- aguardando
            WHEN ((tsol.bddatafim IS NOT NULL) AND (this.bdstatus = 4)) THEN 3 -- finalizada
            WHEN (this.bdstatus = 3) THEN 2 -- pausada
            WHEN (this.bdstatus IN (1,2)) THEN 1 -- iniciada
            WHEN ((tsol.bdvencimento IS NOT NULL) AND (tsol.bdvencimento < CURRENT_DATE)) THEN 8 -- vencida
            WHEN ((tsol.bdentrega IS NOT NULL) AND (tsol.bdentrega < CURRENT_DATE)) THEN 4 --atrasada
            ELSE 0 -- sem alteracao
       END AS "bdSTATUS",
       tsol.bdalerta,
       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN TIMP.bdcodcid
            WHEN (tsol.bdtiposolicitacao = 1) THEN TOBR.bdcodcid
            WHEN (tsol.bdtiposolicitacao = 2) THEN NULL
       END AS "bdCODCID",
       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN TCIDI.bdnomcid
            WHEN (tsol.bdtiposolicitacao = 1) THEN TCIDO.bdnomcid
            WHEN (tsol.bdtiposolicitacao = 2) THEN NULL
       END AS "bdNOMCID",
       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN TUFI.bdsiglauf
            WHEN (tsol.bdtiposolicitacao = 1) THEN TUFO.bdsiglauf
            WHEN (tsol.bdtiposolicitacao = 2) THEN NULL
       END AS "bdNOMUF",

       (SELECT FIRST 1 task.bdcodst FROM vct_empresa_tsolicitatarefa task
        INNER JOIN vct_empresa_tarefasubordinada tsub ON (tsub.bdcodemp = task.bdcodemp AND tsub.bdcodst = task.bdcodst AND tsub.bdcodstsub = tsol.bdcodst)
        WHERE task.bdcodemp = tsol.bdcodemp
        AND task.bddatafim IS NULL
        ) AS bdascendente,

       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN TIMPSIS.bdcodsis
            WHEN (tsol.bdtiposolicitacao = 1) THEN TOBRSIS.bdcodsis
            WHEN (tsol.bdtiposolicitacao = 2) THEN TSERSIS.bdcodsis
       END AS "bdCODSIS",
       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN TIMPSIS.bdnomsis
            WHEN (tsol.bdtiposolicitacao = 1) THEN TOBRSIS.bdnomsis
            WHEN (tsol.bdtiposolicitacao = 2) THEN TSERSIS.bdnomsis
       END AS "bdNOMSIS",

       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN timp.bdperapuracao
            WHEN (tsol.bdtiposolicitacao = 1) THEN tobr.bdperiodicidade
            WHEN (tsol.bdtiposolicitacao = 2) THEN tser.bdperiodicidade
       END AS "bdCODPERIODICIDADE",

       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN
                 CASE WHEN (timp.bdperapuracao = 00) THEN 'Semanal'
                      WHEN (timp.bdperapuracao = 01) THEN '1? Decendio'
                      WHEN (timp.bdperapuracao = 02) THEN '2? Decendio'
                      WHEN (timp.bdperapuracao = 03) THEN '3? Decendio'
                      WHEN (timp.bdperapuracao = 04) THEN '1? Quinzena'
                      WHEN (timp.bdperapuracao = 05) THEN '2? Quinzena'
                      WHEN (timp.bdperapuracao = 06) THEN 'Mensal'
                      WHEN (timp.bdperapuracao = 07) THEN 'Trimestral'
                      WHEN (timp.bdperapuracao = 08) THEN 'Trimestral parcelado'
                      WHEN (timp.bdperapuracao = 09) THEN 'Trimestral antecipado'
                      WHEN (timp.bdperapuracao = 10) THEN 'Anual'
                      WHEN (timp.bdperapuracao = 11) THEN 'Indefinido'
                      WHEN (timp.bdperapuracao = 12) THEN 'Di?rio'
                 END
            WHEN (tsol.bdtiposolicitacao = 1) THEN
                 CASE WHEN (tobr.bdperiodicidade = 00) THEN 'Semanal'
                      WHEN (tobr.bdperiodicidade = 01) THEN '1? Decendio'
                      WHEN (tobr.bdperiodicidade = 02) THEN '2? Decendio'
                      WHEN (tobr.bdperiodicidade = 03) THEN '3? Decendio'
                      WHEN (tobr.bdperiodicidade = 04) THEN '1? Quinzena'
                      WHEN (tobr.bdperiodicidade = 05) THEN '2? Quinzena'
                      WHEN (tobr.bdperiodicidade = 06) THEN 'Mensal'
                      WHEN (tobr.bdperiodicidade = 07) THEN 'Trimestral'
                      WHEN (tobr.bdperiodicidade = 08) THEN 'Trimestral parcelado'
                      WHEN (tobr.bdperiodicidade = 09) THEN 'Trimestral antecipado'
                      WHEN (tobr.bdperiodicidade = 10) THEN 'Anual'
                      WHEN (tobr.bdperiodicidade = 11) THEN 'Indefinido'
                      WHEN (tobr.bdperiodicidade   = 12) THEN 'Di?rio'
                 END
            WHEN (tsol.bdtiposolicitacao = 2) THEN
                 CASE WHEN (tser.bdperiodicidade = 00) THEN 'Semanal'
                      WHEN (tser.bdperiodicidade = 01) THEN '1? Decendio'
                      WHEN (tser.bdperiodicidade = 02) THEN '2? Decendio'
                      WHEN (tser.bdperiodicidade = 03) THEN '3? Decendio'
                      WHEN (tser.bdperiodicidade = 04) THEN '1? Quinzena'
                      WHEN (tser.bdperiodicidade = 05) THEN '2? Quinzena'
                      WHEN (tser.bdperiodicidade = 06) THEN 'Mensal'
                      WHEN (tser.bdperiodicidade = 07) THEN 'Trimestral'
                      WHEN (tser.bdperiodicidade = 08) THEN 'Trimestral parcelado'
                      WHEN (tser.bdperiodicidade = 09) THEN 'Trimestral antecipado'
                      WHEN (tser.bdperiodicidade = 10) THEN 'Anual'
                      WHEN (tser.bdperiodicidade = 11) THEN 'Indefinido'
                      WHEN (tser.bdperiodicidade = 12) THEN 'Di?rio'
                 END
       END AS "bdPERIODICIDADE",
       CASE WHEN (((tsol.bdtiposolicitacao = 0) AND (timp.bdperapuracao = 10)) OR
                  ((tsol.bdtiposolicitacao = 1) AND (tobr.bdperiodicidade = 10)) OR
                  ((tsol.bdtiposolicitacao = 2) AND (tser.bdperiodicidade = 10))) THEN CAST(SUBSTRING(tsol.bdrefsol FROM 1 FOR 4) AS INTEGER)
            ELSE tsol.bdrefsol END AS BDCOMPETENCIA,
       tsol.bdvencimento,
       tsol.bdentrega,
       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN timp.bdtempoestimado
            WHEN (tsol.bdtiposolicitacao = 1) THEN tobr.bdtempoestimado
            WHEN (tsol.bdtiposolicitacao = 2) THEN COALESCE(tsol.bdtempoestimado, tser.bdtempoestimado)
       END AS "BDTEMPOESTIMADO",
       pts.bdcodpts, pts.bdserie,
       '' AS bdnomemp, --emp.bdnomemp,
       tsol.bdfilial,
       '' AS bdnomefilial, --fil.bdnomemp AS bdnomefilial,
       CASE WHEN (tsol.bdtiposolicitacao = 0) THEN timp.bdclassimp
            WHEN (tsol.bdtiposolicitacao = 1) THEN tobr.bdclassificacao
            WHEN (tsol.bdtiposolicitacao = 2) THEN tser.bdclassificacao
       END AS "bdCLASSIFICACAO",
       TSOL.bdcodcol, TSOL.bdcodcolvinc, tcolvinc.bdnomcol, TSOL.bdrefsol,
       CASE WHEN (TSOL.bdtiposolicitacao = 0) THEN TIMP.bdcodimp
            WHEN (TSOL.bdtiposolicitacao = 1) THEN TOBR.bdcodobrser
            WHEN (TSOL.bdtiposolicitacao = 2) THEN TSER.bdcodobrser
       END AS BDCODIMPOBRSER,
       THIS.bdobservacao, TOBS.BDDESCRICAO, TSOL.BDCODTIPO, THIS.BDCODGRUPO, THIS.BDCODSITWEB, TSOL.BDVISUALIZADA  
FROM vct_empresa_tsolicitatarefa TSOL
LEFT OUTER JOIN timposto TIMP ON (TIMP.BDCODIMP = TSOL.bdcodimp)
LEFT OUTER JOIN vct_base_obrigacao TOBR ON (TOBR.bdcodobrser = TSOL.bdcodobrigacao)
LEFT OUTER JOIN vct_base_servico TSER ON (TSER.bdcodobrser = TSOL.bdcodservico)
LEFT OUTER JOIN vct_empresa_thistoricotarefa THIS ON (THIS.BDCODEMP = TSOL.bdcodemp AND THIS.BDCODST = TSOL.BDCODST AND this.bdcodht = (SELECT FIRST 1 bdcodht FROM vct_empresa_thistoricotarefa WHERE bdcodemp = this.bdcodemp AND bdcodst = this.bdcodst ORDER BY bdcodht DESC))
LEFT OUTER JOIN VCT_EMPRESA_TOBSTAREFA TOBS ON (TOBS.BDCODEMP = TSOL.BDCODEMP AND TOBS.BDCODST = TSOL.BDCODST AND TOBS.BDCODOBS = (SELECT FIRST 1 BDCODOBS FROM VCT_EMPRESA_TOBSTAREFA WHERE BDCODEMP = TOBS.BDCODEMP AND BDCODST = TOBS.BDCODST ORDER BY BDCODOBS DESC))

LEFT OUTER JOIN tcidade tcido ON (tcido.bdcodcid = tobr.bdcodcid)
LEFT OUTER JOIN tuf tufo ON (tufo.bdcoduf = tcido.bdcoduf)
LEFT OUTER JOIN tcidade tcidi ON (tcidi.bdcodcid = tobr.bdcodcid)
LEFT OUTER JOIN tuf tufi ON (tufi.bdcoduf = tcidi.bdcoduf)
LEFT OUTER JOIN tsistema timpsis ON (timpsis.bdcodsis = timp.bdcodsis)
LEFT OUTER JOIN tsistema tobrsis ON (tobrsis.bdcodsis = tobr.bdcodsis)
LEFT OUTER JOIN tsistema tsersis ON (tsersis.bdcodsis = tser.bdcodsis)
LEFT OUTER JOIN vct_empresa_protocolo_tarefa ept ON (ept.bdcodemp = tsol.bdcodemp AND ept.bdcodst = tsol.bdcodst)
LEFT OUTER JOIN vct_empresa_protocolosaida pts ON (pts.bdcodemp = ept.bdcodemp AND pts.bdcodpts = ept.bdcodpts)
LEFT OUTER JOIN vw_vrh_emp_tcolcon_cad tcolvinc ON (tcolvinc.bdcodemp = tsol.bdcodemp AND tcolvinc.bdcodcol = tsol.bdcodcolvinc)
LEFT OUTER JOIN tusuario tususol ON (tususol.bdcodusu = tsol.bdcodusu)
LEFT OUTER JOIN tusuario tusuresp ON (tusuresp.bdcodusu = this.bdcodusuresponsavel)
ORDER BY tsol.bdvencimento desc
;

/* Drop altered view: VW_TEMPRESAS_REF_JOIN */
DROP VIEW VW_TEMPRESAS_REF_JOIN;

/* Create altered view: VW_TEMPRESAS_REF_JOIN */
/* Create view: VW_TEMPRESAS_REF_JOIN */
CREATE VIEW VW_TEMPRESAS_REF_JOIN(
BDCODEMP,
BDREFEMP,
BDCODPLAPADRAO,
BDCODHIST,
BDCODCENTROS,
BDCODCID,
BDCODCONT,
BDCODCONTEF,
BDCODCONTRH,
BDCODNATJUR,
BDCODCNAE,
BDNOMEMP,
BDAPEEMP,
BDENDEMP,
BDNUMEMP,
BDBAIEMP,
BDCEPEMP,
BDDDDEMP,
BDFONEEMP,
BDFAXEMP,
BDEMAILEMP,
BDCOMPLEMP,
BDLOGREMP,
BDIEEMP,
BDIMEMP,
BDSITEMP,
BDDDDFAXEMP,
BDDOCAUXILIAR,
BDCODPLANOONLINE,
BDCODPLATRIB,
BDOPCAOESOCIAL,
BDOPCAOESOCIALDESC)
 AS 
SELECT
    X.BDCODEMP,
    X.BDREFEMP,
    X.BDCODPLAPADRAO,
    X.BDCODHIST,
    X.BDCODCENTROS,
    X.BDCODCID,
    X.BDCODCONT,
    X.BDCODCONTEF,
    X.BDCODCONTRH,
    X.BDCODNATJUR,
    X.BDCODCNAE,
    X.BDNOMEMP,
    X.BDAPEEMP,
    X.BDENDEMP,
    X.BDNUMEMP,
    X.BDBAIEMP,
    X.BDCEPEMP,
    X.BDDDDEMP,
    X.BDFONEEMP,
    X.BDFAXEMP,
    X.BDEMAILEMP,
    X.BDCOMPLEMP,
    X.BDLOGREMP,
    X.BDIEEMP,
    X.BDIMEMP,
    X.BDSITEMP,
    X.BDDDDFAXEMP,
    X.BDDOCAUXILIAR,
    X.BDCODPLANOONLINE,
    X.BDCODPLATRIB,
    X.BDOPCAOESOCIAL,
    ESOCIALTIPODADOS.BDDESCRICAO

FROM TEMPRESAS_REF X
LEFT OUTER JOIN VW_TEMPRESAS_REF_MAX XMAX ON (X.BDCODEMP = XMAX.BDCODEMP)
JOIN VW_TEMPRESAS_REF_MIN XMIN ON (X.BDCODEMP = XMIN.BDCODEMP)
LEFT OUTER JOIN VRH_ESOCIAL_TTIPODADOS  ESOCIALTIPODADOS ON (ESOCIALTIPODADOS.BDOPCAOESOCIAL = X.BDOPCAOESOCIAL)
WHERE X.BDREFEMP = COALESCE(XMAX.BDREFEMP,XMIN.BDREFEMP)
;

/* Drop altered view: VW_TTERCEIRO */
SET TERM ^ ;

ALTER PROCEDURE SP_EXPORTA_DIMOB(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRDECLRETIF VARCHAR(5),
PRNUMRECIBO VARCHAR(10),
PRSITUACAOESPECIAL VARCHAR(5),
PRDATAEVENTO DATE,
PRSITEVENTO INTEGER,
PRCONSOLIDAR VARCHAR(5))
 AS
 BEGIN EXIT; END
^

ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRTIPOLANC INTEGER,
PRRETIFICADORA INTEGER,
PRARQUIVO VARCHAR(100),
PRTIPOLANCEXP INTEGER)
 AS
 BEGIN EXIT; END
^

ALTER PROCEDURE SP_IMPORTACAO_SEM_PART(PRSESSAO INTEGER,
PRCODPARTDEFAULT INTEGER)
 AS
 BEGIN EXIT; END
^

ALTER PROCEDURE SP_TERCEIRO(PRCODTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER /* DM_BDENDERECO */ VARCHAR(60),
BDNUMTER VARCHAR(10),
BDCOMPTER /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDCEPTER VARCHAR(9),
BDBAITER /* DM_BDBAIRRO */ VARCHAR(50),
BDDDDTER VARCHAR(3),
BDFONETER /* DM_BDTELEFONE */ VARCHAR(15),
BDFAXTER /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILTER /* DM_BDEMAIL */ VARCHAR(200),
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3))
 AS
 BEGIN SUSPEND; END
^

ALTER PROCEDURE SP_VRH_RELATORIOCUSTOCOL(PREMP VARCHAR(15000),
PRCOL VARCHAR(30000),
PRAUT VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSITCOL SMALLINT,
PRAGRUPA SMALLINT = 0,
PRCC VARCHAR(10000) = null,
PRAGRUPAFILIAIS SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDTIPOCOL INTEGER,
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDNOMCOLUPPER /* DM_BDNOMCOL */ VARCHAR(70),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREMUNERACAO NUMERIC(18,6),
BDENCREMUNERACAO NUMERIC(18,6),
BDINSSPATRONAL NUMERIC(18,6),
BDTERC NUMERIC(18,6),
BDRAT NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDRATAPO NUMERIC(18,6),
BDPROV13 NUMERIC(18,6),
BDENCPROV13 NUMERIC(18,6),
BDPROVFER NUMERIC(18,6),
BDENCPROVFER NUMERIC(18,6),
BDBENIFICIOS NUMERIC(18,6),
BDNOMTPCC /* DM_BDNOMEMP */ VARCHAR(100),
BDTOTAL NUMERIC(18,6),
BDCODSIT INTEGER,
BDDESCSIT VARCHAR(70),
BDCODFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS_X(PRCODEMP VARCHAR(1024),
PRREFEMP INTEGER,
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRDETALHARCC INTEGER,
PRLCC /* DM_MAXVARCHAR */ VARCHAR(32765),
PRLANCAMENTOSEMCC INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRCONTASSEMMOVIMENTO INTEGER,
PRIGNORAZERAMENTO INTEGER = 0)
 RETURNS(PRHISTORICO VARCHAR(100),
PRDATA DATE,
PRCHAVE INTEGER,
PRCONTA INTEGER,
PRCONTRA INTEGER,
PRCREDITO NUMERIC(18,2),
PRDEBITO NUMERIC(18,2),
PRCONCILIADO VARCHAR(5),
PREMPRESA INTEGER,
PRNOMEEMPRESA /* DM_BDNOMEMP */ VARCHAR(100),
PRCC INTEGER,
PRNOME_CONTA VARCHAR(100),
PRNOME_CONTA_ORIGINAL VARCHAR(100),
PRCLASS_CONTA VARCHAR(40),
PRCLASS_CONTRA VARCHAR(40),
PRNOME_CONTA_CONTRA VARCHAR(100),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCOMPL VARCHAR(200),
PRCNPJEMP VARCHAR(18),
PRCODMATRIZ INTEGER,
PRGRPCTA INTEGER,
PRCODHIST INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODTPHI INTEGER,
PRPARTICIPANTECONTA INTEGER,
PRPARTICIPANTECONTRA INTEGER,
PRCODTERCEIROCONTA INTEGER,
PRCODTERCEIROCONTRA INTEGER,
PRCGC_CONTA VARCHAR(18),
PRCODEMPFILIAL INTEGER,
PRTIPOLANCFILIAL INTEGER,
PRTIPOLAN INTEGER,
PRCHAVEONLINE VARCHAR(120),
PRCODCENTRO INTEGER,
PRTRANSACAO INTEGER,
PRTRANFECHADA /* DM_BOOLEAN */ VARCHAR(5),
PRCONCILIACAOPENDENTE INTEGER,
PRDEBCRE INTEGER)
 AS
 BEGIN SUSPEND; END
^

SET TERM ; ^

DROP VIEW VW_VEF_TOT_CID_ENT;

DROP VIEW VW_VEF_TOT_CID_SAI;

DROP VIEW VW_VEF_TOT_NAT_ENT_UF;

DROP VIEW VW_VEF_TOT_NAT_SAI_UF;

DROP VIEW VW_VEF_TOT_UF_ENT;

DROP VIEW VW_VEF_TOT_UF_SAI;

DROP VIEW VW_VEF_TOTEXP_UF_ENT_GIASP;

DROP VIEW VW_VEF_TOTEXP_UF_GIASP;

DROP VIEW VW_VEF_TOTEXP_UF_SAI_GIASP;

DROP VIEW VW_TTERCEIRO;

/* Create altered view: VW_TTERCEIRO */
/* Create view: VW_TTERCEIRO */
CREATE VIEW VW_TTERCEIRO(
BDCODTER,
BDCODPLAPADRAO,
BDCODTPLA,
BDCGCTER,
BDREFEMP,
BDAPELIDOTER,
BDNOMETER,
BDLOGRTER,
BDENDTER,
BDNUMTER,
BDCOMPTER,
BDCEPTER,
BDBAITER,
BDDDDTER,
BDFONETER,
BDFAXTER,
BDEMAILTER,
BDIETER,
BDDATACADTER,
BDIMTER,
BDPRURALTER,
BDENQSIMPLESFEDTER,
BDINSCSUFRAMATER,
BDCODGPS,
BDCODCID,
BDCODPAIS,
BDDESCPAIS,
BDDDDFAXTER,
BDORGAOPUBLICO,
BDINATIVO,
BDCODTIPO,
BDINDIMUNEISE,
BDCPFPROD)
 AS 
SELECT
    TER.BDCODTER       ,
    TER.BDCODPLAPADRAO ,
    TER.BDCODTPLA      ,
    TER.BDCGCTER       ,
    T.BDREFEMP,
    X.BDAPELIDOTER,
    X.BDNOMETER ,
    X.BDLOGRTER ,
    X.BDENDTER  ,
    X.BDNUMTER  ,
    X.BDCOMPTER ,
    X.BDCEPTER  ,
    X.BDBAITER  ,
    X.BDDDDTER  ,
    X.BDFONETER ,
    X.BDFAXTER  ,
    X.BDEMAILTER ,
    X.BDIETER     ,
    X.BDDATACADTER,
    X.BDIMTER     ,
    X.BDPRURALTER ,
    X.BDENQSIMPLESFEDTER,
    X.BDINSCSUFRAMATER ,
    X.BDCODGPS ,
    X.BDCODCID ,
    X.BDCODPAIS,
    TPAIS.bddescpais,
    X.BDDDDFAXTER,
    X.BDORGAOPUBLICO,
    COALESCE(X.BDINATIVO, 'FALSE'),
    TER.bdcodtipo,
    X.bdindimuneise,
    x.bdcpfprod

FROM tterceiro TER
LEFT OUTER JOIN VW_TTERCEIRO_REF_MAX_MIN T ON TER.bdcodter = T.bdcodter
JOIN tterceiro_ref X ON (x.bdcodTER = TER.bdcodter AND x.bdrefemp = T.bdrefemp)
LEFT OUTER JOIN tpais ON (tpais.bdcodpais = X.bdcodpais)
;

/* Drop altered view: VW_UNION_MOVIMENTACOES */
DROP VIEW VW_UNION_MOVIMENTACOES;

/* Create altered view: VW_UNION_MOVIMENTACOES */
/* Create view: VW_UNION_MOVIMENTACOES */
CREATE VIEW VW_UNION_MOVIMENTACOES(
BDCODEMP,
BDCODCOL,
BDDATAMOV,
BDCODMFG,
BDCODSEFMFG,
BDDESCMFG,
BDTIPO)
 AS 
SELECT
  RESC.BDCODEMP,
  RESC.BDCODCOL,
  RESC.BDDATARESCISAO,
  PRES.BDCODMFG,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  'Rescis?o'
FROM
  VRH_EMP_TRESCISAO RESC,
  VRH_BASE_TPREPRESC PRES,
  VRH_BASE_TMOTFGTS MFG
WHERE
  PRES.bdtipomov = 0 AND
  RESC.BDCODPRES = PRES.BDCODPRES
  AND PRES.BDCODMFG = MFG.BDCODMFG

UNION

SELECT
  SIT.BDCODEMP,
  SIT.BDCODCOL,
  SIT.BDDATAINISIT,
  PSIT.BDCODMFGENT,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  'Situa??o (afastamento) Entrada'
FROM
  VRH_EMP_TSITCOL SIT,
  VRH_BASE_TPREPSIT PSIT,
  VRH_BASE_TMOTFGTS MFG
WHERE
  SIT.BDCODSIT = PSIT.BDCODSIT
  AND PSIT.BDCODMFGENT = MFG.BDCODMFG

UNION

SELECT
  SIT.BDCODEMP,
  SIT.BDCODCOL,
  SIT.BDDATAFIMSIT,
  PSIT.BDCODMFGSAI,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  'Situa??o (afastamento) Retorno'
FROM
  VRH_EMP_TSITCOL SIT,
  VRH_BASE_TPREPSIT PSIT,
  VRH_BASE_TMOTFGTS MFG

WHERE
  SIT.BDDATAFIMSIT IS NOT NULL AND
  SIT.BDCODSIT = PSIT.BDCODSIT
  AND PSIT.BDCODMFGSAI = MFG.BDCODMFG

UNION

SELECT
  TRANS.BDCODEMPORIG,
  TRANS.BDCODCOLORIG,
  TRANS.BDDATATRF,
  PTRANS.BDCODMFG,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  'Transfer?ncia'
FROM
  VRH_EMP_TTRANSCOL TRANS,
  vrh_base_tprepresc PTRANS,
  VRH_BASE_TMOTFGTS MFG
WHERE
  PTRANS.bdtipomov = 1 AND
  TRANS.BDCODPTRAN = PTRANS.bdcodpres
  AND PTRANS.BDCODMFG = MFG.BDCODMFG
;

/* Drop altered view: VW_VEF_TABELAS_TREDICMSSN */
DROP VIEW VW_VEF_TABELAS_TREDICMSSN;

/* Create altered view: VW_VEF_TABELAS_TREDICMSSN */
/* Create view: VW_VEF_TABELAS_TREDICMSSN */
CREATE VIEW VW_VEF_TABELAS_TREDICMSSN(
BDCODRED,
BDCODUF,
BDREFERENCIA,
BDCODREDFAIXA,
BDFAIXADE,
BDFAIXAATE,
BDALIQRED)
 AS 
SELECT icms.bdCODRED, icms.bdCODUF, icms.bdREFERENCIA,
       fx.bdCODREDFAIXA, fx.bdFAIXADE, fx.bdFAIXAATE, fx.bdALIQRED
FROM VEF_TABELAS_TREDICMSSN icms
JOIN VEF_TABELAS_TREDICMSFAIXASSN fx ON (fx.bdCODRED = icms.bdCODRED)
WHERE (
       icms.bdREFERENCIA = (SELECT FIRST 1 x.bdREFERENCIA
                            FROM VEF_TABELAS_TREDICMSSN x
                            WHERE x.bdCODUF = icms.bdCODUF
                              AND x.bdREFERENCIA <= CASE icms.bdCODUF
                                                      WHEN 18 THEN -- No caso do Paran? caso seja ap?s 2017, vaio jogar fixo para 2017, pois deve verificar as al?quotas anteriores a 2018 e ap?s e pegar a menor al?quota
                                                        IIF(((SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE) > 201712),
                                                            201712,
                                                            (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE))
                                                      ELSE (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE)
                                                    END
                            ORDER BY x.bdCODUF DESC, x.bdREFERENCIA DESC)
       )
;

/* Drop altered view: VW_VRH_EMP_TCOL_HIST_COMPLETA */
DROP VIEW VW_VRH_EMP_TCOL_HIST_COMPLETA;

/* Create altered view: VW_VRH_EMP_TCOL_HIST_COMPLETA */
/* Create view: VW_VRH_EMP_TCOL_HIST_COMPLETA */
CREATE VIEW VW_VRH_EMP_TCOL_HIST_COMPLETA(
BDCODEMP,
BDCODCOL,
BDCIDNASC,
BDCODPAIS,
BDNATURALIZADOCOL,
BDDATACHEBRASILCOL,
BDCONTRCOL,
BDCASADOBR,
BDFILHOSBR,
BDPORTNAT,
BDDATANATURALIZACAO,
BDCODPOSTESTRCOL,
BDCODPAISNAS,
BDCODPAISRES,
BDNOMCIDN,
BDUFN,
BDDESCPAISNAS,
BDDESCPAISRES,
BDDTAPOSENT)
 AS 
SELECT
    HIST.BDCODEMP,
    HIST.BDCODCOL,
    COL.BDCODCIDNASC,
    HIST.BDCODPAIS,
    HIST.BDNATURALIZADOCOL,
    COLCAD.BDDATACHEBRASILCOL,
    HIST.BDCONTRCOL,
    COLCAD.BDCASADOBR,
    COLCAD.BDFILHOSBR,
    HIST.BDPORTNAT,
    HIST.BDDATANATURALIZACAO,
    HIST.BDCODPOSTESTRCOL,
    HIST.BDCODPAISNAS,
    COLCAD.BDCODPAISRES,
    CID.BDNOMCID,
    UF.BDSIGLAUF,
    PN.BDDESCPAIS,
    PR.BDDESCPAIS,
    HIST.BDDTAPOSENT
FROM VRH_EMP_TCOL_HIST HIST
LEFT OUTER JOIN VRH_EMP_TCOLCON COL ON (COL.BDCODEMP = HIST.BDCODEMP AND COL.BDCODCOL = HIST.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = HIST.BDCODEMP AND COLCAD.BDCODCOL = HIST.BDCODCOL)
LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = COL.BDCODCIDNASC)
LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
LEFT OUTER JOIN TPAIS PR ON (PR.BDCODPAIS = COLCAD.BDCODPAISRES)
LEFT OUTER JOIN TPAIS PN ON (PN.BDCODPAIS = HIST.BDCODPAISNAS)
;

/* Drop altered view: VWEF_EMPMENSAL_ABA_FEDE */
DROP VIEW VWEF_EMPMENSAL_ABA_FEDE_REF;

DROP VIEW VWEF_EMPMENSAL_ABA_FEDE;

/* Create altered view: VWEF_EMPMENSAL_ABA_FEDE */
/* Create view: VWEF_EMPMENSAL_ABA_FEDE */
CREATE VIEW VWEF_EMPMENSAL_ABA_FEDE(
BDCODEMP,
BDREFEMP,
BDPERFILSPED,
BDATIVIDADESPED,
BDTIPODECLARANTEDMED,
BDREGISTROANSDMED,
BDNUMEROCNESDMED,
BDLRISSSN,
BDINDNATPJ,
BDINDATIV,
BDCODACESSOSN)
 AS 
SELECT
  EFFED.BDCODEMP,
  EFFED.BDREFEMP,
  CASE
    WHEN EFFED.BDPERFILSPED = 0 THEN 'A - Perfil A'
    WHEN EFFED.BDPERFILSPED = 1 THEN 'B - Perfil B'
    WHEN EFFED.BDPERFILSPED = 2 THEN 'C - Perfil C'
    WHEN EFFED.BDPERFILSPED IS NULL THEN 'A - Perfil A'
  END BDPERFILSPED,
  CASE
    WHEN EFFED.BDATIVIDADESPED = 1 THEN '1 - Outros'
    WHEN EFFED.BDATIVIDADESPED <> 1 THEN '0 - Industrial ou equiparado a industrial'
    WHEN EFFED.BDATIVIDADESPED IS NULL THEN '0 - Industrial ou equiparado a industrial'
  END BDATIVIDADESPED,
  CASE
    WHEN EFFED.BDTIPODECLARANTEDMED = 1 THEN '1 - Prestador de servi?o de sa?de'
    WHEN EFFED.BDTIPODECLARANTEDMED = 2 THEN '2 - Operadora de plano privado de assist?ncia a sa?de'
    WHEN EFFED.BDTIPODECLARANTEDMED = 3 THEN '3 - Prestador de servi?o de sa?de e operadora de plano privado de assist?ncia a sa?de'
    WHEN EFFED.BDTIPODECLARANTEDMED NOT IN (1,2,3) THEN '0 - N?o se aplica'
    WHEN EFFED.BDTIPODECLARANTEDMED IS NULL THEN '0 - N?o se aplica'
  END BDTIPODECLARANTEDMED,
  COALESCE(EFFED.BDREGISTROANSDMED, 0) BDREGISTROANSDMED,
  COALESCE(EFFED.BDNUMEROCNESDMED, 0) BDNUMEROCNESDMED,
  COALESCE(EFFEDATV.BDLRISSSN, 0.000000) BDLRISSSN,

  
  CASE
    WHEN EFFED.BDINDNATPJ = 0 THEN '00 ? Sociedade empres?ria em geral'
    WHEN EFFED.BDINDNATPJ = 1 THEN '01 ? Sociedade cooperativa'
    WHEN EFFED.BDINDNATPJ = 2 THEN '02 ? Entidade sujeita ao PIS/Pasep exclusivamente com base na folha de sal?rios'
    WHEN EFFED.BDINDNATPJ = 3 THEN '03 - Pessoa jur?dica em geral participante de SCP como s?cia ostensiva'
    WHEN EFFED.BDINDNATPJ = 4 THEN '04 ? Sociedade cooperativa participante de SCP como s?cia ostensiva'
    WHEN EFFED.BDINDNATPJ = 5 THEN '05 ? Sociedade em Conta de Participa??o - SCP'
    ELSE '00 ? Sociedade empres?ria em geral'
  END BDINDNATPJ,

  i.bdcodexportar||' - '||i.bddescricao bdindativ,
  EFFED.BDCODACESSOSN


FROM
  VEF_BASE_TEMPPARFED EFFED
LEFT OUTER JOIN VEF_BASE_TEMPPARFEDPORATV EFFEDATV ON (EFFED.BDCODEMP = EFFEDATV.BDCODEMP AND EFFED.BDREFEMP = EFFEDATV.BDREFEMP)
LEFT OUTER JOIN vef_base_ttabindativ i ON (effed.bdindativ = i.bdindativ)
;

/* Drop altered view: VWEF_EMPMENSAL_ABA_PGER */
DROP VIEW VWEF_EMPMENSAL_ABA_PGER;

/* Create altered view: VWEF_EMPMENSAL_ABA_PGER */
/* Create view: VWEF_EMPMENSAL_ABA_PGER */
CREATE VIEW VWEF_EMPMENSAL_ABA_PGER(
BDCODEMP,
BDREFEMP,
BDSUBSTRIB,
BDCODPORTEEMP,
BDREDBCICMSENT,
BDREDBCICMSSAI,
BDPARICMSEMP,
BDDIAVCTOICMS,
BDANTFERIADOICMS,
BDVCTOMESICMS,
BDDIAJUROSICMS,
BDJURICMSEMP,
BDJUROMESDIA,
BDPELASELIC,
BDDIAMULTAICMS,
BDMULTAICMSEMP,
BDMULTAMESDIA,
BDMULTAMAXICMS)
 AS 
SELECT
  EFPAREST.BDCODEMP,
  EFPAREST.BDREFEMP,
  CASE
    WHEN EFPAREST.BDSUBSTRIB = 1 THEN 'N?o'
    WHEN EFPAREST.BDSUBSTRIB = 2 THEN 'Substitu?do solid?rio'
    WHEN EFPAREST.BDSUBSTRIB NOT IN (1,2) THEN 'Sim'
    WHEN EFPAREST.BDSUBSTRIB IS NULL THEN 'Sim'
  END BDSUBSTRIB,
  COALESCE(EFPAREST.BDCODPORTEEMP||'-'||PORTEEMP.BDDESPORTEEMP, '') BDCODPORTEEMP,
  COALESCE(EFPAREST.BDREDBCICMSENT, 0.000000) BDREDBCICMSENT,
  COALESCE(EFPAREST.BDREDBCICMSSAI, 0.000000) BDREDBCICMSSAI,
  COALESCE(EFPAREST.BDPARICMSEMP, 'FALSE') BDPARICMSEMP,
  COALESCE(EFPAREST.BDDIAVCTOICMS, 0) BDDIAVCTOICMS,
  COALESCE(EFPAREST.BDANTFERIADOICMS, 'FALSE') BDANTFERIADOICMS,
  CASE
    WHEN EFPAREST.BDVCTOMESICMS = 1 THEN 'Seguinte'
    WHEN EFPAREST.BDVCTOMESICMS = 2 THEN 'Subsequente'
    WHEN EFPAREST.BDVCTOMESICMS = 3 THEN 'Dia ?til'
    WHEN EFPAREST.BDVCTOMESICMS IS NULL THEN 'Do movimento'
    WHEN EFPAREST.BDVCTOMESICMS NOT IN (1,2,3) THEN 'Do movimento'
  END BDVCTOMESICMS,
  COALESCE(EFPAREST.BDDIAJUROSICMS, 0) BDDIAJUROSICMS,
  COALESCE(EFPAREST.BDJURICMSEMP, 0.000000) BDJURICMSEMP,
  CASE
    WHEN EFPAREST.BDJUROMESDIA = 1 THEN 'M?s'
    WHEN EFPAREST.BDJUROMESDIA <> 1 THEN 'Dia'
    WHEN EFPAREST.BDJUROMESDIA IS NULL THEN 'Dia'
  END BDJUROMESDIA,
  CASE
    WHEN EFPAREST.BDPELASELIC = 1 THEN 'Selic'
    WHEN EFPAREST.BDPELASELIC = 2 THEN 'TJLP'
    WHEN EFPAREST.BDPELASELIC NOT IN (1,2) THEN 'Nenhum'
    WHEN EFPAREST.BDPELASELIC IS NULL THEN 'Nenhum'
  END BDPELASELIC,
  COALESCE(EFPAREST.BDDIAMULTAICMS, 0) BDDIAMULTAICMS,
  COALESCE(EFPAREST.BDMULTAICMSEMP, 0.000000) BDMULTAICMSEMP,
  CASE
    WHEN EFPAREST.BDMULTAMESDIA = 1 THEN 'M?s'
    WHEN EFPAREST.BDMULTAMESDIA <> 1 THEN 'Dia'
    WHEN EFPAREST.BDMULTAMESDIA IS NULL THEN 'Dia'
  END BDMULTAMESDIA,
  COALESCE(EFPAREST.BDMULTAMAXICMS, 0.000000) BDMULTAMAXICMS
FROM
  VEF_BASE_TEMPPAREST EFPAREST
LEFT OUTER JOIN TPORTE_EMPRESA PORTEEMP ON (EFPAREST.BDCODPORTEEMP = PORTEEMP.BDCODPORTEEMP)
;

/* Drop altered view: VWGR_FIN_CONTRATO */
DROP VIEW VWGR_FIN_CONTRATO;

/* Create altered view: VWGR_FIN_CONTRATO */
/* Create view: VWGR_FIN_CONTRATO */
CREATE VIEW VWGR_FIN_CONTRATO(
BDCODCLI,
BDCODESC,
BDCODCONTR,
BDDESCCONTR,
BDDATAINI,
BDDATAINIPOREXT,
BDDATAFIN,
BDDIAVENC,
BDCHAVECTABAN,
BDDESCCTABAN,
BDNOMCLI,
BDAPECLI,
BDDATACADCLI,
BDNOMREDUZCLI,
BDCNPJCLI,
BDCODCLIMATRIZ,
BDNOMCLIMATRIZ,
BDCEPCLI,
BDCXPCLI,
BDLOGRCLI,
BDENDCLI,
BDNUMCLI,
BDCOMPLCLI,
BDBAICLI,
BDCODCID,
BDNOMCID,
BDSIGLAUF,
BDIMCLI,
BDIECLI,
BDDDDCLI,
BDFONECLI,
BDDDDFAXCLI,
BDFAXCLI,
BDDDDCELCLI,
BDCELCLI,
BDEMAILCLI,
BDDATAINIATIVCLI,
BDDATAFIMATIVCLI,
BDORGAOPUBLICO,
BDCODCNAE,
BDDESCCNAE,
BDCODNATJUR,
BDDESCNAT,
BDORGAOCLI,
BDNUMREGCLI,
BDDATAREGCLI,
BDNOMECARTORIO,
BDLIVROREG,
BDFOLHAREG,
BDDOCAUXREG,
BDCAPITALSOC,
BDDESCENQFED,
BDNUMFUN,
BDCOMERCIO,
BDINDUSTRIA,
BDSERVICO,
BDANEXOIII,
BDANEXOIV,
BDANEXOV,
BDANEXOVI)
 AS 
SELECT cli.bdcodcli, contr.bdcodesc, contr.bdcodcontr, contr.bddesccontr, contr.bddataini,
(SELECT EXTRACT(DAY FROM bddataini)||' de '||
TRIM(CASE EXTRACT(MONTH FROM bddataini)
      WHEN 1 THEN 'janeiro'
      WHEN 2 THEN 'fevereiro'
      WHEN 3 THEN 'mar?o'
      WHEN 4 THEN 'abril'
      WHEN 5 THEN 'maio'
      WHEN 6 THEN 'junho'
      WHEN 7 THEN 'julho'
      WHEN 8 THEN 'agosto'
      WHEN 9 THEN 'setembro'
      WHEN 10 THEN 'outubro'
      WHEN 11 THEN 'novembro'
      WHEN 12 THEN 'dezembro'
END)||' de '||EXTRACT(YEAR FROM bddataini)
FROM vfin_esc_tcontrato contraux
WHERE contraux.bdcodcli = contr.bdcodcli
AND contraux.bdcodesc = contr.bdcodesc
AND contraux.bdcodcontr = contr.bdcodcontr) bddatainiporext,
contr.bddatafin, contr.bddiavenc, contr.bdchavectaban, cta.bddescctaban, cliref.bdnomcli, cliref.bdapecli,
cli.bddatacadcli, cliref.bdnomreduzcli, cli.bdcnpjcli, cli.bdcodclimatriz,
(mat.bdnomcli) bdnomclimatriz, cliref.bdcepcli, cliref.bdcxpcli, cliref.bdlogrcli, cliref.bdendcli, cliref.bdnumcli,
cliref.bdcomplcli, cliref.bdbaicli, cliref.bdcodcid, cid.bdnomcid, uf.bdsiglauf, cliref.bdimcli, cliref.bdiecli, cliref.bddddcli,
cliref.bdfonecli, cliref.bddddfaxcli, (cliref.bdfonefaxcli) bdfaxcli, cliref.bddddcelcli,
cliref.bdcelcli, cliref.bdemailcli, cli.bddatainiativcli, cli.bddatafimativcli,
(CASE WHEN UPPER(cliref.bdorgaopublico) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdorgaopublico,
cliref.bdcodcnae, cnae.bddesccnae, cliref.bdcodnatjur, natjur.bddescnat, cli.bdorgaocli,
cli.bdnumregcli, cli.bddataregcli, cli.bdnomecartorio, cli.bdlivroreg, cli.bdfolhareg,
cli.bddocauxreg, cliref.bdcapitalsoc, cadenq.bddescenqfed, cliref.bdnumfun,
(CASE WHEN UPPER(enqfed.bdcomercio) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdcomercio,
(CASE WHEN UPPER(enqfed.bdindustria) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdindustria,
(CASE WHEN UPPER(enqfed.bdservico) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdservico,
(CASE WHEN UPPER(enqfed.bdanexoiii) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdanexoiii,
(CASE WHEN UPPER(enqfed.bdanexoiv) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdanexoiv,
(CASE WHEN UPPER(enqfed.bdanexov) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdanexov,
(CASE WHEN UPPER(enqfed.bdanexovi) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdanexovi
FROM vfin_esc_tcontrato contr
LEFT OUTER JOIN vfin_esc_tcontasban cta ON (cta.bdchavectaban = contr.bdchavectaban)
LEFT OUTER JOIN vfin_base_tcliente cli ON (cli.bdcodcli = contr.bdcodcli)
LEFT OUTER JOIN vw_vfin_clientes_ref cliref ON (cliref.bdcodcli = contr.bdcodcli)
LEFT OUTER JOIN vw_vfin_clientes_ref mat ON (mat.bdcodcli = cli.bdcodclimatriz)
LEFT OUTER JOIN tcidade cid ON (cid.bdcodcid = cliref.bdcodcid)
LEFT OUTER JOIN tuf uf ON (uf.bdcoduf = cid.bdcoduf)
LEFT OUTER JOIN tcnae cnae ON (cnae.bdcodcnae = cliref.bdcodcnae)
LEFT OUTER JOIN tnatjur natjur ON (natjur.bdcodnatjur = cliref.bdcodnatjur)
LEFT OUTER JOIN vfin_base_tclienqfed enqfed ON (enqfed.bdcodcli = cli.bdcodcli AND enqfed.bdrefcli = cliref.bdrefcli)
LEFT OUTER JOIN tcadenqfed cadenq ON (cadenq.bdcodenqfed = enqfed.bdcodenqfed)
ORDER BY contr.bdcodcontr, contr.bdcodcli, contr.bdcodesc
;

/* Drop altered view: VWGR_FIN_ESCRITORIO */
DROP VIEW VWGR_FIN_ESCRITORIO;

/* Create altered view: VWGR_FIN_ESCRITORIO */
/* Create view: VWGR_FIN_ESCRITORIO */
CREATE VIEW VWGR_FIN_ESCRITORIO(
BDCODESC,
BDNOMESC,
BDCNPJESC,
BDCRCESC,
BDINIATIVESC,
BDFIMATIVESC,
BDCODESCMATRIZ,
BDNOMESCMATRIZ,
BDCODCNAEESC,
BDDESCCNAEESC,
BDCEPESC,
BDLOGRESC,
BDENDESC,
BDNUMESC,
BDCOMPLESC,
BDBAIESC,
BDCODCIDESC,
BDNOMCIDESC,
BDSIGLAUFESC,
BDIMESC,
BDIEESC,
BDDDDESC,
BDFONEESC,
BDDDDFAXESC,
BDFAXESC,
BDDDDCELULARESC,
BDCELULARESC,
BDEMAILESC,
BDCODCONTAB,
BDNOMECONTAB,
BDCPFCONTAB,
BDRGCONTAB,
BDCRCCONTAB,
BDCMCCONTAB,
BDDATANASCCONTAB,
BDTIPOCONTCONTAB,
BDQUALICONTAB,
BDEXPQUALICONTAB,
BDDESCQUALICONTAB,
BDCODOCUPACONTAB,
BDDESCOCUPACONTAB,
BDINDCRCCONTAB,
BDCEPCONTAB,
BDLOGRCONTAB,
BDENDCONTAB,
BDNUMCONTAB,
BDCOMPLCONTAB,
BDCODCIDCONTAB,
BDNOMCIDCONTAB,
BDSIGLAUFCONTAB,
BDDDDCONTAB,
BDFONECONTAB,
BDDDDFAXCONTAB,
BDFAXCONTAB,
BDDDDCELULARCONTAB,
BDCELULARCONTAB,
BDEMAILCONTAB,
BDCODFISCAL,
BDNOMEFISCAL,
BDCPFFISCAL,
BDRGFISCAL,
BDCRCFISCAL,
BDCMCFISCAL,
BDDATANASCFISCAL,
BDTIPOCONTFISCAL,
BDQUALIFISCAL,
BDEXPQUALIFISCAL,
BDDESCQUALIFISCAL,
BDCODOCUPAFISCAL,
BDDESCOCUPAFISCAL,
BDINDCRCFISCAL,
BDCEPFISCAL,
BDLOGRFISCAL,
BDENDFISCAL,
BDNUMFISCAL,
BDCOMPLFISCAL,
BDCODCIDFISCAL,
BDNOMCIDFISCAL,
BDSIGLAUFFISCAL,
BDDDDFISCAL,
BDFONEFISCAL,
BDDDDFAXFISCAL,
BDFAXFISCAL,
BDDDDCELULARFISCAL,
BDCELULARFISCAL,
BDEMAILFISCAL,
BDCODFOLHA,
BDNOMEFOLHA,
BDCPFFOLHA,
BDRGFOLHA,
BDCRCFOLHA,
BDCMCFOLHA,
BDDATANASCFOLHA,
BDTIPOCONTFOLHA,
BDQUALIFOLHA,
BDEXPQUALIFOLHA,
BDDESCQUALIFOLHA,
BDCODOCUPAFOLHA,
BDDESCOCUPAFOLHA,
BDINDCRCFOLHA,
BDCEPFOLHA,
BDLOGRFOLHA,
BDENDFOLHA,
BDNUMFOLHA,
BDCOMPLFOLHA,
BDCODCIDFOLHA,
BDNOMCIDFOLHA,
BDSIGLAUFFOLHA,
BDDDDFOLHA,
BDFONEFOLHA,
BDDDDFAXFOLHA,
BDFAXFOLHA,
BDDDDCELULARFOLHA,
BDCELULARFOLHA,
BDEMAILFOLHA,
BDDESCENQFEDESC,
BDANEXOIIIESC,
BDANEXOIVESC,
BDANEXOVESC,
BDANEXOVIESC,
BDPERMULATE,
BDPERMULATEPOREXT,
BDFORMACALCJUR,
BDPERJURATE,
BDPERJURATEPOREXT)
 AS 
SELECT esc.bdcodesc, esc.bdnomesc, esc.bdcnpjesc, esc.bdcrcesc, esc.bdiniativesc,
esc.bdfimativesc, esc.bdcodescmatriz, (mat.bdnomesc) bdnomescmatriz, (esc.bdcodcnae) bdcodcnaeesc,
(cnae.bddesccnae) bddesccnaeesc, esc.bdcepesc, esc.bdlogresc, esc.bdendesc, esc.bdnumesc,
esc.bdcomplesc, esc.bdbaiesc, (esc.bdcodcid) bdcodcidesc, (cidesc.bdnomcid) bdnomcidesc,
(ufesc.bdsiglauf) bdsiglaufesc, esc.bdimesc, esc.bdieesc, esc.bddddesc, esc.bdfoneesc, esc.bddddfaxesc,
esc.bdfaxesc, esc.bddddcelularesc, esc.bdcelularesc, esc.bdemailesc,

(contcontab.bdcodcont) bdcodcontab, (contcontab.bdnomecont) bdnomecontab,
(contcontab.bdcpfcont) bdcpfcontab, (contcontab.bdrgcont) bdrgcontab,
(contcontab.bdcrccont) bdcrccontab, (contcontab.bdcmccont) bdcmccontab,
(contcontab.bddatanasccont) bddatanasccontab,
(CASE WHEN contcontab.bdtipocontabilista = 0 THEN 'Contabilista'
      WHEN contcontab.bdtipocontabilista = 1 THEN 'Escrit?rio'
      WHEN contcontab.bdtipocontabilista = 2 THEN 'Individual'
      ELSE 'N?o informado' END) bdtipocontcontab,
(contcontab.bdqualificacaosoc) bdqualicontab, (quacontab.bdexpqualisoc) bdexpqualicontab,
(quacontab.bddescqualisoc) bddescqualicontab, (contcontab.bdcodocupa) bdcodocupacontab,
(ocucontab.bddescocupa) bddescocupacontab, (contcontab.bdindcrc) bdindcrccontab,
(contcontab.bdcepcont) bdcepcontab, (contcontab.bdlogrcont) bdlogrcontab,
(contcontab.bdendcont) bdendcontab, (contcontab.bdnumerocont) bdnumcontab,
(contcontab.bdcomplcont) bdcomplcontab, (contcontab.bdcodcid) bdcodcidcontab,
(cidcontab.bdnomcid) bdnomcidcontab, (ufcontab.bdsiglauf) bdsiglaufcontab,
(contcontab.bddddcont) bddddcontab, (contcontab.bdfonecont) bdfonecontab,
(contcontab.bddddfaxcont) bddddfaxcontab, (contcontab.bdfaxcont) bdfaxcontab,
(contcontab.bddddcelularcont) bddddcelularcontab, (contcontab.bdcelularcont) bdcelularcontab,
(contcontab.bdemailcont) bdemailcontab,

(contfiscal.bdcodcont) bdcodfiscal, (contfiscal.bdnomecont) bdnomefiscal,
(contfiscal.bdcpfcont) bdcpffiscal, (contfiscal.bdrgcont) bdrgfiscal,
(contfiscal.bdcrccont) bdcrcfiscal, (contfiscal.bdcmccont) bdcmcfiscal,
(contfiscal.bddatanasccont) bddatanascfiscal,
(CASE WHEN contfiscal.bdtipocontabilista = 0 THEN 'Contabilista'
      WHEN contfiscal.bdtipocontabilista = 1 THEN 'Escrit?rio'
      WHEN contfiscal.bdtipocontabilista = 2 THEN 'Individual'
      ELSE 'N?o informado' END) bdtipocontfiscal,
(contfiscal.bdqualificacaosoc) bdqualifiscal, (quafiscal.bdexpqualisoc) bdexpqualifiscal,
(quafiscal.bddescqualisoc) bddescqualifiscal, (contfiscal.bdcodocupa) bdcodocupafiscal,
(ocufiscal.bddescocupa) bddescocupafiscal, (contfiscal.bdindcrc) bdindcrcfiscal,
(contfiscal.bdcepcont) bdcepfiscal, (contfiscal.bdlogrcont) bdlogrfiscal,
(contfiscal.bdendcont) bdendfiscal, (contfiscal.bdnumerocont) bdnumfiscal,
(contfiscal.bdcomplcont) bdcomplfiscal, (contfiscal.bdcodcid) bdcodcidfiscal,
(cidfiscal.bdnomcid) bdnomcidfiscal, (uffiscal.bdsiglauf) bdsiglauffiscal,
(contfiscal.bddddcont) bddddfiscal, (contfiscal.bdfonecont) bdfonefiscal,
(contfiscal.bddddfaxcont) bddddfaxfiscal, (contfiscal.bdfaxcont) bdfaxfiscal,
(contfiscal.bddddcelularcont) bddddcelularfiscal, (contfiscal.bdcelularcont) bdcelularfiscal,
(contfiscal.bdemailcont) bdemailfiscal,

(contfolha.bdcodcont) bdcodfolha, (contfolha.bdnomecont) bdnomefolha,
(contfolha.bdcpfcont) bdcpffolha, (contfolha.bdrgcont) bdrgfolha,
(contfolha.bdcrccont) bdcrcfolha, (contfolha.bdcmccont) bdcmcfolha,
(contfolha.bddatanasccont) bddatanascfolha,
(CASE WHEN contfolha.bdtipocontabilista = 0 THEN 'Contabilista'
      WHEN contfolha.bdtipocontabilista = 1 THEN 'Escrit?rio'
      WHEN contfolha.bdtipocontabilista = 2 THEN 'Individual'
      ELSE 'N?o informado' END) bdtipocontfolha,
(contfolha.bdqualificacaosoc) bdqualifolha, (quafolha.bdexpqualisoc) bdexpqualifolha,
(quafolha.bddescqualisoc) bddescqualifolha, (contfolha.bdcodocupa) bdcodocupafolha,
(ocufolha.bddescocupa) bddescocupafolha, (contfolha.bdindcrc) bdindcrcfolha,
(contfolha.bdcepcont) bdcepfolha, (contfolha.bdlogrcont) bdlogrfolha,
(contfolha.bdendcont) bdendfolha, (contfolha.bdnumerocont) bdnumfolha,
(contfolha.bdcomplcont) bdcomplfolha, (contfolha.bdcodcid) bdcodcidfolha,
(cidfolha.bdnomcid) bdnomcidfolha, (uffolha.bdsiglauf) bdsiglauffolha,
(contfolha.bddddcont) bddddfolha, (contfolha.bdfonecont) bdfonefolha,
(contfolha.bddddfaxcont) bddddfaxfolha, (contfolha.bdfaxcont) bdfaxfolha,
(contfolha.bddddcelularcont) bddddcelularfolha, (contfolha.bdcelularcont) bdcelularfolha,
(contfolha.bdemailcont) bdemailfolha,

(enqfed.bddescenqfed) bddescenqfedesc,
(CASE WHEN UPPER(parfat.bdanexoiii) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdanexoiiiesc,
(CASE WHEN UPPER(parfat.bdanexoiv)  = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdanexoivesc,
(CASE WHEN UPPER(parfat.bdanexov) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdanexovesc,
(CASE WHEN UPPER(parfat.bdanexovi) = 'TRUE' THEN 'Sim' ELSE 'N?o' END) bdanexoviesc,
(parfat.bdpermulate||'%') bdpermulate, (parfat.bdpermulate||' por cento') bdpermulateporext,
(CASE WHEN parfat.bdformacalcjur = 0 THEN 'Di?rio' ELSE 'Mensal' END) bdformacalcjur,
(parfat.bdperjurate||'%') bdperjurate, (parfat.bdperjurate||' por cento') bdperjurateporext

FROM tescritorio esc
LEFT OUTER JOIN tescritorio mat ON (mat.bdcodesc = esc.bdcodescmatriz)
LEFT OUTER JOIN tcnae cnae ON (cnae.bdcodcnae = esc.bdcodcnae)
LEFT OUTER JOIN tcidade cidesc ON (cidesc.bdcodcid = esc.bdcodcid)
LEFT OUTER JOIN tuf ufesc ON (ufesc.bdcoduf = cidesc.bdcoduf)
LEFT OUTER JOIN vfin_base_tescparfat parfat ON (parfat.bdcodesc = esc.bdcodesc)
LEFT OUTER JOIN tcadenqfed enqfed ON (enqfed.bdcodenqfed = parfat.bdcodenqfed)

LEFT OUTER JOIN tcontador_padrao contcontab ON (contcontab.bdcodcont = esc.bdcodcont)
LEFT OUTER JOIN tqualificacaosoc quacontab ON (quacontab.bdqualificacaosoc = contcontab.bdqualificacaosoc)
LEFT OUTER JOIN tocupacao ocucontab ON (ocucontab.bdcodocupa = contcontab.bdcodocupa)
LEFT OUTER JOIN tcidade cidcontab ON (cidcontab.bdcodcid = contcontab.bdcodcid)
LEFT OUTER JOIN tuf ufcontab ON (ufcontab.bdcoduf = cidcontab.bdcoduf)

LEFT OUTER JOIN tcontador_padrao contfiscal ON (contfiscal.bdcodcont = esc.bdcodcontef)
LEFT OUTER JOIN tqualificacaosoc quafiscal ON (quafiscal.bdqualificacaosoc = contfiscal.bdqualificacaosoc)
LEFT OUTER JOIN tocupacao ocufiscal ON (ocufiscal.bdcodocupa = contfiscal.bdcodocupa)
LEFT OUTER JOIN tcidade cidfiscal ON (cidfiscal.bdcodcid = contfiscal.bdcodcid)
LEFT OUTER JOIN tuf uffiscal ON (uffiscal.bdcoduf = cidfiscal.bdcoduf)

LEFT OUTER JOIN tcontador_padrao contfolha ON (contfolha.bdcodcont = esc.bdcodcontrh)
LEFT OUTER JOIN tqualificacaosoc quafolha ON (quafolha.bdqualificacaosoc = contfolha.bdqualificacaosoc)
LEFT OUTER JOIN tocupacao ocufolha ON (ocufolha.bdcodocupa = contfolha.bdcodocupa)
LEFT OUTER JOIN tcidade cidfolha ON (cidfolha.bdcodcid = contfolha.bdcodcid)
LEFT OUTER JOIN tuf uffolha ON (uffolha.bdcoduf = cidfolha.bdcoduf)
ORDER BY esc.bdcodesc
;

/* Drop altered view: VWGR_FIN_SOCIOS */
DROP VIEW VWGR_FIN_SOCIOS;

/* Create altered view: VWGR_FIN_SOCIOS */
/* Create view: VWGR_FIN_SOCIOS */
CREATE VIEW VWGR_FIN_SOCIOS(
BDCODEMP,
BDCODSOC,
BDNOMSOC,
BDCGCCEISOC,
BDRGSOC,
BDORGEMISOC,
BDCODUFRG,
BDSIGLAUFRG,
BDDATANASCSOC,
BDESTCIVILSOC,
BDESTCIVILSOCDESC,
BDCODCBO,
BDDESCCBO,
BDDESCQUALISOC,
BDCEPSOC,
BDLOGRSOC,
BDENDSOC,
BDNUMSOC,
BDCOMPLSOC,
BDBAISOC,
BDCODCID,
BDNOMCIDSOC,
BDSIGLAUFSOC,
BDDDSOC,
BDTELRESSOC,
BDDDDFAXSOC,
BDFAXSOC,
BDDDCELSOC,
BDTELCELSOC,
BDEMAILSOC,
BDSIGNATARIOSPED,
BDDATAENTSOC,
BDDATASAISOC,
BDRESPONSAVELSOC,
BDEXTERIORSOC,
BDCODPAIS,
BDDESCPAIS,
BDPERSOC,
BDCPFRESPLEGALSOC,
BDREGESTCIVILSOC,
BDQUALILEGALDIPJSOC,
BDQUALIRESPLEGALSOC,
BDQUALISPEDSOC)
 AS 
select emp.bdcodemp, emp.bdcodsoc, emp.bdnomsoc, emp.bdcgcceisoc, emp.BDRGSOC, emp.bdorgemisoc, emp.bdcodufrg, ufrg.bdsiglauf bdsiglaufrg, emp.bddatanascsoc,
       emp.BDESTCIVILSOC,
       (CASE WHEN emp.BDESTCIVILSOC = 0 THEN 'Solteiro'
        WHEN emp.BDESTCIVILSOC = 1 THEN 'Casado'
        WHEN emp.BDESTCIVILSOC = 2 THEN 'Divorciado'
        WHEN emp.BDESTCIVILSOC = 3 THEN 'Vi?vo'
        WHEN emp.BDESTCIVILSOC = 4 THEN 'Separado judicialmente'
        WHEN emp.BDESTCIVILSOC = 5 THEN 'Uni?o est?vel'
        ELSE 'Outros' END) BDESTCIVILSOCDESC, emp.bdcodcbo, cbo.bddesccbo, Qsoc.bddescqualisoc,
       emp.bdcepsoc,
       emp.bdlogrsoc, emp.bdendsoc, emp.bdnumsoc,
       emp.bdcomplsoc, emp.bdbaisoc, emp.bdcodcid, cid.bdnomcid BDNOMCIDSOC, UF.BDSIGLAUF BDSIGLAUFSOC,
       emp.BDDDDSOC AS bdddsoc, emp.bdtelressoc, emp.BDDDDFAXSOC, emp.BDFAXSOC, emp.bdddcelsoc, emp.bdtelcelsoc, emp.bdemailsoc,
       emp.BDSIGNATARIOSPED, emp.bddataentsoc, emp.bddatasaisoc, emp.bdresponsavelsoc,
       emp.bdexteriorsoc, emp.bdcodpais, Pais.bddescpais,
       emp.BDPERSOC, emp.BDCPFRESPLEGALSOC,
       emp.BDREGESTCIVILSOC,
       qdipj.bddescqualisoc as BDQUALILEGALDIPJSOC,
       qresp.bddescqualisoc as BDQUALIRESPLEGALSOC,
       qsped.bddescqualisoc as BDQUALISPEDSOC
from VW_EMPRESAS_TSOC_REF emp
left outer join VRH_BASE_TCBO cbo on (cbo.bdcodcbo = emp.bdcodcbo)
left outer join TQUALIFICACAOSOC qsoc on (qsoc.BDQUALIFICACAOSOC = emp.BDQUALIFICACAOSOC)
left outer join tqualificacaosoc qsped on (qsped.bdqualificacaosoc = emp.bdqualispedsoc)
left outer join tqualificacaosoc qresp on (qresp.bdqualificacaosoc = emp.bdqualiresplegalsoc)
left outer join tqualificacaosoc qdipj on (qdipj.bdqualificacaosoc = emp.bdqualilegaldipjsoc)
left outer join TPAIS Pais on (pais.BDCODPAIS = emp.BDCODPAIS)
left outer join tcidade cid on (cid.bdcodcid = emp.bdcodcid)
left outer join TUF UF on (UF.BDCODUF = cid.BDCODUF)
left outer join TUF UFRG on (UFRG.bdcoduf = emp.bdcodufrg)
;

/* Drop altered view: VWGR_SCI_EMPRESAS */
DROP VIEW VWGR_SCI_EMPRESAS;

/* Create altered view: VWGR_SCI_EMPRESAS */
/* Create view: VWGR_SCI_EMPRESAS */
CREATE VIEW VWGR_SCI_EMPRESAS(
BDCODEMP,
BDCODMATRIZ,
BDCNPJEMP,
BDDATAINIATIVEMP,
BDORGAOEMP,
BDDATAREGEMP,
BDDATACONSTEMP,
BDDESCCARTEMP,
BDDATAFIMATIVEMP,
BDREFEMP,
BDCODPLAPADRAO,
BDCODHIST,
BDCODCENTROS,
BDCODPLATRIB,
BDCODCID,
BDCODCONT,
BDCODNATJUR,
BDCODCNAE,
BDNOMEMP,
BDAPEEMP,
BDENDEMP,
BDNUMEMP,
BDBAIEMP,
BDCEPEMP,
BDDDDEMP,
BDFONEEMP,
BDFAXEMP,
BDEMAILEMP,
BDCOMPLEMP,
BDLOGREMP,
BDIEEMP,
BDIMEMP,
BDSITEMP,
BDCODPLANOONLINE,
BDLOGOEMP,
BDNOMESC,
BDINIATIVESC,
BDFIMATIVESC,
BDLOGOESC,
BDLOGRESC,
BDENDESC,
BDNUMESC,
BDBAIESC,
BDCEPESC,
BDCNPJESC,
BDDDDESC,
BDFONEESC,
BDRAMALESC,
BDEMAILESC,
BDCONTTERCESC,
BDCOMPLESC,
BDFAXESC,
BDCODCIDESC,
BDCRCESC,
BDAPEPLA,
BDNOMPLA,
BDNOMCID,
BDANIVCID,
BDSIGLAUF,
BDDESCUF,
BDNOMECONT,
BDCPFCONT,
BDCRCCONT,
BDENDCONT,
BDLOGRCONT,
BDNUMEROCONT,
BDCOMPLCONT,
BDCEPCONT,
BDBAIRROCONT,
BDDDDCONT,
BDFONECONT,
BDFAXCONT,
BDEMAILCONT,
BDCMCCONT,
BDESCOLARIDADECONT,
BDTIPOCONTABILISTA,
BDCODOCUPA,
BDCODQUACONT,
BDCODQUA,
BDREGJUN,
BDCODCIDSOC,
BDNOMSOC,
BDENDSOC,
BDNUMSOC,
BDCOMPLSOC,
BDBAISOC,
BDCEPSOC,
BDCGCCEISOC,
BDDDSOC,
BDTELRESSOC,
BDTELCELSOC,
BDEMAILSOC,
BDLOGRSOC,
BDQUALIRESPLEGALSOC,
BDEXTERIORSOC,
BDDATAENTSOC,
BDDATASAISOC,
BDCODPAISSOC,
BDQUALIFICACAOSOC,
BDDESCQUALISOC,
BDRESPONSAVELSOC,
BDCPFRESPLEGALSOC,
BDPARAMREL,
BDEXPQUALISOC,
BDQUALISOCDIPJ,
BDDESCQUALISOCREP,
BDDESCQUALISOCSPED,
BDPERSONALIZACAO,
BDQTDCOTASOC,
BDVALCOTASOC,
BDPERCCOTASOC,
BDCODCONTEF,
BDNOMECONTEF,
BDCPFCONTEF,
BDCRCCONTEF,
BDENDCONTEF,
BDLOGRCONTEF,
BDNUMEROCONTEF,
BDCOMPLCONTEF,
BDCEPCONTEF,
BDBAIRROCONTEF,
BDDDDCONTEF,
BDFONECONTEF,
BDFAXCONTEF,
BDEMAILCONTEF,
BDCMCCONTEF,
BDESCOLARIDADECONTEF,
BDTIPOCONTABILISTAEF,
BDCODOCUPAEF,
BDCODCONTRH,
BDNOMECONTRH,
BDCPFCONTRH,
BDCRCCONTRH,
BDENDCONTRH,
BDLOGRCONTRH,
BDNUMEROCONTRH,
BDCOMPLCONTRH,
BDCEPCONTRH,
BDBAIRROCONTRH,
BDDDDCONTRH,
BDFONECONTRH,
BDFAXCONTRH,
BDEMAILCONTRH,
BDCMCCONTRH,
BDESCOLARIDADECONTRH,
BDTIPOCONTABILISTARH,
BDCODOCUPARH,
BDLIVRO,
BDFOLHA,
BDNOMECARTORIO,
BDRGSOC,
BDORGEMISOC,
BDSIGLAUFRG,
BDDESCUFRG,
BDESTCIVILSOC,
BDCODCBO,
BDDESCCBO,
BDCODACESSOSN,
BDSECAOCNAE,
BDTIPOCNAE,
BDCLASSIFICACAOCNAE,
BDDESCCNAE,
BDDESCCNAEADICIONAIS,
BDNOMCIDESC,
BDSIGLAUFESC,
BDCODESC,
BDCODSOC,
BDCODFPAS,
BDASSINATURACONTEF,
BDASSINATURASOC)
 AS 
SELECT temp.BDCODEMP, temp.BDCODMATRIZ, temp.BDCNPJEMP, temp.BDDATAINIATIVEMP,
       temp.BDORGAOEMP, temp.BDDATAREGEMP, temp.BDDATACONSTEMP, temp.BDDESCCARTEMP, --alt:14844 - incluido temp.BDDATACONSTEMP. Ana - 05/08/2016
       temp.BDDATAFIMATIVEMP,

       tref.BDREFEMP, tref.BDCODPLAPADRAO, tref.BDCODHIST, tref.BDCODCENTROS, tref.bdcodplatrib,
       tref.BDCODCID,
       tref.BDCODCONT, tref.BDCODNATJUR, tref.BDCODCNAE, tref.BDNOMEMP,
       tref.BDAPEEMP, tref.BDENDEMP, tref.BDNUMEMP, tref.BDBAIEMP, tref.BDCEPEMP,
       tref.BDDDDEMP, tref.BDFONEEMP, tref.BDFAXEMP, tref.BDEMAILEMP, tref.BDCOMPLEMP,
       tref.BDLOGREMP, tref.BDIEEMP, tref.BDIMEMP, tref.BDSITEMP, TREF.BDCODPLANOONLINE, timg.BDLOGOEMP,

       tesc.BDNOMESC, tesc.BDINIATIVESC, tesc.BDFIMATIVESC, tesc.BDLOGOESC, tesc.BDLOGRESC,
       tesc.BDENDESC, tesc.BDNUMESC, tesc.BDBAIESC, tesc.BDCEPESC, tesc.BDCNPJESC,
       tesc.BDDDDESC, tesc.BDFONEESC, tesc.BDRAMALESC, tesc.BDEMAILESC, tesc.BDCONTTERCESC,
       tesc.BDCOMPLESC, tesc.BDFAXESC, tesc.BDCODCID "BDCODCIDESC", tesc.BDCRCESC,

       tpla.BDAPELIDO "BDAPEPLA", tpla.bdnome "BDNOMPLA",

       tcid.bdnomcid, tcid.bdanivcid,

       tuf.bdsiglauf, tuf.bddescuf,

       tcon.bdnomecont, tcon.bdcpfcont, tcon.bdcrccont, tcon.bdendcont,
       tcon.bdlogrcont, tcon.bdnumerocont, tcon.bdcomplcont, tcon.bdcepcont,
       tcon.bdbairrocont, tcon.bddddcont, tcon.bdfonecont, tcon.bdfaxcont,
       tcon.bdemailcont, tcon.bdcmccont, tcon.bdescolaridadecont, tcon.bdtipocontabilista,
       tcon.bdcodocupa, tqcont.bdEXPQUALISOC, tqcont.bddescqualisoc,

       vsuc_base_temp.bdregjun,

       tsoc.BDCODCID "BDCODCIDSOC", tsoc_ref.BDNOMSOC, tsoc.BDENDSOC, tsoc.BDNUMSOC,
       tsoc.BDCOMPLSOC, tsoc.BDBAISOC, tsoc.BDCEPSOC, tsoc.BDCGCCEISOC, tsoc_ref.bddddsoc AS BDDDSOC,
       tsoc_ref.BDTELRESSOC, tsoc_ref.BDTELCELSOC, tsoc_ref.BDEMAILSOC,
       tsoc.BDLOGRSOC, tsoc.BDQUALIRESPLEGALSOC, tsoc.BDEXTERIORSOC, tsoc.BDDATAENTSOC,
       tsoc.BDDATASAISOC, tsoc.BDCODPAIS "BDCODPAISSOC", tqua.bddescqualisoc, tqua.bddescqualisoc,
       tsoc.BDRESPONSAVELSOC, tsoc.BDCPFRESPLEGALSOC,
       0, tqua.BDEXPQUALISOC,
       tqdipj.bddescqualisoc, tqrep.bddescqualisoc, tqsped.bddescqualisoc,
       CASE WHEN (tesc.bdprintesc = 1) THEN tesc.bdnomesc
            WHEN (tesc.bdprintesc = 2) THEN tesc.bdnomesc||' - '||(SELECT FIRST 1 BDPERSONALIZACAO FROM TPERSONALIZACAO)
            ELSE
            (SELECT FIRST 1 BDPERSONALIZACAO FROM TPERSONALIZACAO) END AS "bdpersonalizacao",
       tcot.bdqtdcota, tcot.bdvalcota, tcot.bdperccota,

       tconef.bdcodcont, tconef.bdnomecont, tconef.bdcpfcont, tconef.bdcrccont, tconef.bdendcont,
       tconef.bdlogrcont, tconef.bdnumerocont, tconef.bdcomplcont, tconef.bdcepcont,
       tconef.bdbairrocont, tconef.bddddcont, tconef.bdfonecont, tconef.bdfaxcont,
       tconef.bdemailcont, tconef.bdcmccont, tconef.bdescolaridadecont, tconef.bdtipocontabilista,
       tconef.bdcodocupa,

       tconrh.bdcodcont, tconrh.bdnomecont, tconrh.bdcpfcont, tconrh.bdcrccont, tconrh.bdendcont,
       tconRH.bdlogrcont, tconRH.bdnumerocont, tconRH.bdcomplcont, tconrh.bdcepcont,
       tconRH.bdbairrocont, tconRH.bddddcont, tconRH.bdfonecont, tconRH.bdfaxcont,
       tconRH.bdemailcont, tconRH.bdcmccont, tconRH.bdescolaridadecont, tconRH.bdtipocontabilista,
       tconRH.bdcodocupa, temp.bdlivro, temp.bdfolha, temp.bdnomecartorio, tsoc.BDRGSOC, tsoc.BDORGEMISOC,
       tUFSoc.bdsiglauf "BDSIGLAUFRG", tUFSoc.bddescuf "BDDESCUFRG",
       CASE WHEN (tsoc.bdestcivilsoc = 0) THEN 'Solteiro'
            WHEN (tsoc.bdestcivilsoc = 1) THEN 'Casado'
            WHEN (tsoc.bdestcivilsoc = 2) THEN 'Divorciado'
            WHEN (tsoc.bdestcivilsoc = 3) THEN 'Vi?vo'
            WHEN (tsoc.bdestcivilsoc = 4) THEN 'Separado judicialmente'
            WHEN (tsoc.bdestcivilsoc = 5) THEN 'Uni?o est?vel'
            WHEN (tsoc.bdestcivilsoc = 6) THEN 'Outros'
            ELSE
            'N?o informado' END AS "BDESTCIVILSOC",
       tsoc.bdcodcbo, tCBO.bddesccbo, parfed.bdcodacessosn,
       cnae.bdsecao, cnae.bdtipocnae, cnae.bdclassificacao, cnae.bddesccnae,
       CAST(TRIM(COALESCE(cnae.bddesccnae, '')||CASE WHEN (cnae.bddesccnae <> '' AND cnaeadc.BDDESCCNAEAdicionais <> '') THEN '; ' ELSE '' END||COALESCE(cnaeadc.BDDESCCNAEAdicionais, '')) AS VARCHAR(10000)),
       tcidesc.bdnomcid, ufesc.bdsiglauf, tesc.bdcodesc, tsoc.bdcodsoc, fpas.bdcodfpas, tconef.bdassinatura, tsoc.bdassinatura

FROM tempresas temp
JOIN vw_tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
LEFT OUTER JOIN tempresas_img timg ON (timg.bdcodemp = temp.bdcodemp)
LEFT OUTER JOIN tplano_padrao tpla ON (tpla.bdcodplapadrao = tref.bdcodplapadrao)
LEFT OUTER JOIN tcidade tcid ON (tcid.bdcodcid = tref.bdcodcid)
LEFT OUTER JOIN tuf ON (tuf.bdcoduf = tcid.bdcoduf)
LEFT OUTER JOIN tcontador_padrao tcon ON (tcon.bdcodcont = tref.bdcodcont)
LEFT OUTER JOIN tcontador_padrao tconef ON (tconef.bdcodcont = tref.bdcodcontef)
LEFT OUTER JOIN tcontador_padrao tconrh ON (tconrh.bdcodcont = tref.bdcodcontrh)
LEFT OUTER JOIN vsuc_base_temp ON (vsuc_base_temp.bdcodemp = temp.bdcodemp)
LEFT OUTER JOIN tescritorio tesc ON (tesc.bdcodesc = tcon.bdcodesc)
LEFT OUTER JOIN empresas_tsoc tsoc ON (tsoc.bdcodemp = temp.bdcodemp
                                       AND tsoc.bdcodsoc = (SELECT FIRST 1 empresas_tsoc.bdcodsoc FROM empresas_tsoc
                                                            WHERE empresas_tsoc.bdcodemp = temp.bdcodemp
                                                            AND empresas_tsoc.bddataentsoc <= CURRENT_DATE
                                                            AND (empresas_tsoc.bddatasaisoc >= CURRENT_DATE OR (empresas_tsoc.bddatasaisoc IS NULL))
                                                            AND empresas_tsoc.bdresponsavelsoc = 'TRUE'
                                                            ORDER BY empresas_tsoc.bddataentsoc DESC))
LEFT OUTER JOIN vw_empresas_tsoc_ref_max_min socref ON (socref.bdcodemp = tsoc.bdcodemp AND socref.bdcodsoc = tsoc.bdcodsoc)
LEFT OUTER JOIN empresas_tsoc_ref tsoc_ref ON (tsoc_ref.bdcodemp = socref.bdcodemp AND tsoc_ref.bdcodsoc = socref.bdcodsoc AND tsoc_ref.bdrefsoc = socref.bdrefsoc)


LEFT OUTER JOIN tqualificacaosoc tqua ON (tqua.bdqualificacaosoc = tsoc.bdqualificacaosoc)                    
LEFT OUTER JOIN empresas_tsoccotas tcot ON (tcot.bdcodemp = tsoc.bdcodemp AND tcot.bdcodsoc = tsoc.bdcodsoc
                                            AND tcot.bdrefcota = (SELECT FIRST 1 empresas_tsoccotas.bdrefcota FROM empresas_tsoccotas
                                                                  WHERE empresas_tsoccotas.bdcodemp = tsoc.bdcodemp
                                                                  AND empresas_tsoccotas.bdcodsoc = tsoc.bdcodsoc
                                                                  AND empresas_tsoccotas.bdrefcota <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                                                                  ORDER BY empresas_tsoccotas.bdrefcota DESC))
LEFT OUTER JOIN tuf tUFSoc ON (tUFSoc.bdcoduf = tsoc.bdcodufrg)
LEFT OUTER JOIN tqualificacaosoc tqdipj ON (tqdipj.bdqualificacaosoc = tsoc.bdqualilegaldipjsoc)
LEFT OUTER JOIN tqualificacaosoc tqrep ON (tqrep.bdqualificacaosoc = tsoc.bdqualiresplegalsoc)
LEFT OUTER JOIN tqualificacaosoc tqsped ON (tqsped.bdqualificacaosoc = tsoc.bdqualispedsoc)
LEFT OUTER JOIN tqualificacaosoc tqcont ON (tqcont.bdqualificacaosoc = tcon.bdqualificacaosoc)
LEFT OUTER JOIN VRH_BASE_TCBO tCBO ON (tCBO.bdcodcbo = tsoc.bdcodcbo)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARFED parfed ON (parfed.bdcodemp = temp.bdcodemp AND parfed.bdrefemp = tref.bdrefemp)
LEFT OUTER JOIN TCNAE cnae ON (cnae.bdcodcnae = tref.bdcodcnae)


LEFT OUTER JOIN(SELECT LIST(CNAEADD.BDDESCCNAE, '; ') AS BDDESCCNAEADICIONAIS, CNAEADICIONAIS.BDCODEMP, CNAEADICIONAIS.BDREFEMP
                FROM VRH_BASE_EMP_CNAEADIC CNAEADICIONAIS
                LEFT OUTER JOIN TCNAE CNAEADD ON (CNAEADD.BDCODCNAE = CNAEADICIONAIS.BDCODCNAE)
                GROUP BY CNAEADICIONAIS.BDCODEMP, CNAEADICIONAIS.BDREFEMP) AS CNAEADC ON (CNAEADC.BDCODEMP = TREF.BDCODEMP) AND (CNAEADC.BDREFEMP = TREF.BDREFEMP)

LEFT OUTER JOIN tcidade tcidesc ON (tcidesc.bdcodcid = tesc.bdcodcid)
LEFT OUTER JOIN tuf ufesc ON (ufesc.bdcoduf = tcidesc.bdcoduf)
LEFT OUTER JOIN VRHF_BASE_TEMPGPS gps ON (gps.bdcodemp = temp.bdcodemp) AND (gps.bdrefemp = tref.bdrefemp)
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS fpas ON (fpas.bdcodfpasterc = gps.bdcodfpasterc)
;

/* Drop altered view: VWRH_EMPMENSAL_ABA_GPS */
DROP VIEW VWRH_EMPMENSAL_ABA_GPS;

/* Create altered view: VWRH_EMPMENSAL_ABA_GPS */
/* Create view: VWRH_EMPMENSAL_ABA_GPS */
CREATE VIEW VWRH_EMPMENSAL_ABA_GPS(
BDCODEMP,
BDREFEMP,
BDCODFPASTERC,
BDSIMPLESGPS,
BDEMPEMP,
BDAUTEMP,
BDFUNEMP,
BDFAP,
BDCODFPAS,
BDCODTERC,
BDPERTERC,
BDDESCFPAS,
BDDESCTERC,
BDCCATVCONCOM,
BDINDCOMP,
BDDESONTOMAEMP,
BDCODCLATRI,
BDDESCCLATRI,
BDESCOOPERATIVA,
BDESCONSTRUTORA,
BDAPURAT,
BDAPUFAP,
BDACINTISENMULTA)
 AS 
SELECT
  RHGPS.BDCODEMP,
  RHGPS.BDREFEMP,
  RHGPS.BDCODFPASTERC,
  CASE
    WHEN RHGPS.BDSIMPLESGPS = 1 THEN 'Optante'
    WHEN RHGPS.BDSIMPLESGPS = 2 THEN 'Optante - fat. anual superior a R$ 1.200.000,00'
    WHEN RHGPS.BDSIMPLESGPS = 3 THEN 'N?o Optante - prod.Rural PF (CEI e FPAS 604)'
    WHEN RHGPS.BDSIMPLESGPS = 4 THEN 'N?o Optante - c/liminar p/n?o pagto.Contr.Soc.'
    WHEN RHGPS.BDSIMPLESGPS = 5 THEN 'Optante - C/liminar p/n?o pagto.Contr.Social'
    WHEN RHGPS.BDSIMPLESGPS IS NULL THEN 'N?o Optante'
    WHEN RHGPS.BDSIMPLESGPS NOT IN (1,2,3,4,5) THEN 'N?o Optante'
  END BDSIMPLESGPS,
  RHGPS.BDEMPEMP,
  RHGPS.BDAUTEMP,
  RHGPS.BDFUNEMP,
  RHGPS.BDFAP,
  RHFPASTERC.BDCODFPAS,
  RHFPASTERC.BDCODTERC,
  CASE
    WHEN RHGPS.BDSIMPLESGPS IN (1,2,5) THEN
      0
    ELSE
      RHFPASTERC.BDPERTERC
  END,
  CAST(FPAS.BDDESCFPAS AS VARCHAR(10000)) BDDESCFPAS,
  TTERC.BDDESCTERC,
  RHGPS.BDCCATVCONCOM,
  RHGPS.BDINDCOMP,
  RHGPS.BDDESONTOMAEMP,
  ESOC.BDCODCLATRI,
  CT.BDDESCCLATRI,
  CASE
    WHEN ESOC.BDESCOOPERATIVA = 0 THEN 'N?o'
    WHEN ESOC.BDESCOOPERATIVA = 1 THEN 'De trabalho'
    WHEN ESOC.BDESCOOPERATIVA = 2 THEN 'De produ??o'
    WHEN ESOC.BDESCOOPERATIVA = 3 THEN 'Outras'
    ELSE                            'N?o informado'
  END BDESCOOPERATIVA,
  ESOC.BDESCONSTRUTORA,
  CASE
    WHEN ESOC.BDAPURAT = 1 THEN 'CNAE preponderante de cada estabelecimento'
    ELSE 'CNAE preponderante da empresa'
  END BDAPURAT,
  CASE
    WHEN ESOC.BDAPUFAP = 1 THEN 'FAP atribu?do ? cada estabelecimento'
    ELSE 'FAP atribu?do ? empresa'
  END BDAPUFAP,
  CASE
    WHEN ESOC.BDACINTISENMULTA = 1 THEN 'Com acordo'
    ELSE 'Sem acordo'
  END BDACINTISENMULTA
FROM
  VRHF_BASE_TEMPGPS RHGPS
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS RHFPASTERC ON (RHGPS.BDCODFPASTERC = RHFPASTERC.BDCODFPASTERC)
LEFT OUTER JOIN VRH_BASE_TFPAS FPAS ON (RHFPASTERC.BDCODFPAS = FPAS.BDCODFPAS)
LEFT OUTER JOIN VRH_BASE_TTERCEIROS TTERC ON (RHFPASTERC.BDCODTERC = TTERC.BDCODTERC)
LEFT OUTER JOIN VRHF_BASE_TEMPESOCIAL ESOC ON (ESOC.BDCODEMP = RHGPS.BDCODEMP AND ESOC.BDREFEMP = RHGPS.BDREFEMP)
LEFT OUTER JOIN VRH_BASE_CLASSTRIBUTARIA CT ON (CT.BDCODCLATRI = ESOC.BDCODCLATRI)
;

/* Drop altered view: VWRH_EMPMENSAL_ABA_GRCS */
DROP VIEW VWRH_EMPMENSAL_ABA_GRCS;

/* Create altered view: VWRH_EMPMENSAL_ABA_GRCS */
/* Create view: VWRH_EMPMENSAL_ABA_GRCS */
CREATE VIEW VWRH_EMPMENSAL_ABA_GRCS(
BDCODEMP,
BDREFEMP,
BDCODSINPAT,
BDCAPSOCEMP,
BDTIPOESTABE,
BDDESCSINPAT)
 AS 
SELECT
  RHGRCS.BDCODEMP,
  RHGRCS.BDREFEMP,
  RHGRCS.BDCODSINPAT,
  RHGRCS.BDCAPSOCEMP,
  CASE
    WHEN RHGRCS.BDTIPOESTABE = 1 THEN 'Principal'
    WHEN RHGRCS.BDTIPOESTABE = 2 THEN 'Filial'
    WHEN RHGRCS.BDTIPOESTABE = 3 THEN 'Outros'
    WHEN RHGRCS.BDTIPOESTABE NOT IN (1,2,3) THEN '?nico'
    WHEN RHGRCS.BDTIPOESTABE IS NULL THEN '?nico'
  END BDTIPOESTABE,
  SINDPAT.BDDESCSINPAT
FROM
  VRHF_BASE_TEMPGRCS RHGRCS
LEFT OUTER JOIN VRHF_BASE_TSINDPATRONAL SINDPAT ON (RHGRCS.BDCODSINPAT = SINDPAT.BDCODSINPAT)
;

/* Drop altered view: VWRH_EMPMENSAL_ABA_PCALC */
DROP VIEW VWRH_EMPMENSAL_ABA_PCALC;

/* Create altered view: VWRH_EMPMENSAL_ABA_PCALC */
/* Create view: VWRH_EMPMENSAL_ABA_PCALC */
CREATE VIEW VWRH_EMPMENSAL_ABA_PCALC(
BDCODEMP,
BDREFEMP,
BDFECHAMESEMP,
BDFECHAVTEMP,
BDPAGEMP,
BDCODPAGEMP,
BDARREMP,
BDTIPOARREMP,
BDPERCADSALEMP,
BDMESDSREMP,
BDREFHOREMP,
BDCALCFCNAFNEMP,
BDCALCC13NAFNEMP,
BDPAGEMPCONTR,
BDARREDONDAFN,
BDARREDONDAFC,
BDARREDONDAFE,
BDARREDONDAFA,
BDARREDONDAAD,
BDARREDONDAA13,
BDARREDONDA13,
BDARREDONDAC13,
BDARREDONDAAU,
BDDESCFALHORASDIAS,
BDPERCLIMIDESCPAR,
BDCALCC13FNNEGEMP)
 AS 
SELECT
  RHCALC.BDCODEMP,
  RHCALC.BDREFEMP,
  COALESCE(RHCALC.BDFECHAMESEMP, 0) BDFECHAMESEMP,
  COALESCE(RHCALC.BDFECHAVTEMP, 0) BDFECHAVTEMP,
  CASE
    WHEN RHCALC.BDPAGEMP = 1 THEN 'M?s da compet?ncia da folha'
    WHEN RHCALC.BDPAGEMP <> 1 THEN 'M?s posterior a compet?ncia da folha'
    WHEN RHCALC.BDPAGEMP IS NULL THEN 'M?s posterior a compet?ncia da folha'
  END BDPAGEMP,
  RHCALC.BDPAGEMP BDCODPAGEMP,
  CASE
    WHEN RHCALC.BDARREMP = 1 THEN 'Centavos'
    WHEN RHCALC.BDARREMP = 2 THEN 'De 5 em 5'
    WHEN RHCALC.BDARREMP = 3 THEN 'De 10 em 10'
    WHEN RHCALC.BDARREMP NOT IN (1,2,3) THEN 'N?o arredondar'
    WHEN RHCALC.BDARREMP IS NULL THEN 'N?o arredondar'
  END BDARREMP,
  CASE
    WHEN RHCALC.BDTIPOARREMP = 1 THEN 'Para cima - n?o desconta no m?s seguinte'
    WHEN RHCALC.BDTIPOARREMP = 2 THEN 'Para baixo - acrescenta no m?s seguinte'
    WHEN RHCALC.BDTIPOARREMP = 3 THEN 'Para baixo - n?o acrescenta no m?s seguinte'
    WHEN RHCALC.BDTIPOARREMP NOT IN (1,2,3) THEN 'Para cima - desconta no m?s seguinte'
    WHEN RHCALC.BDTIPOARREMP IS NULL THEN 'Para cima - desconta no m?s seguinte'
  END BDTIPOARREMP,
  COALESCE(RHCALC.BDPERCADSALEMP, 0.0000) BDPERCADSALEMP,
  CASE
    WHEN RHCALC.BDMESDSREMP = 1 THEN 'M?s subsequente'
    WHEN RHCALC.BDMESDSREMP <> 1 THEN 'M?s atual'
    WHEN RHCALC.BDMESDSREMP IS NULL THEN 'M?s atual'
  END BDMESDSREMP,
  COALESCE(RHCALC.BDREFHOREMP, 'FALSE') BDREFHOREMP,
  COALESCE(RHPAR.BDCALCFCNAFNEMP, 'FALSE') BDCALCFCNAFNEMP,
  COALESCE(RHPAR.BDCALCC13NAFNEMP, 'FALSE') BDCALCC13NAFNEMP,
  CASE
    WHEN RHCALC.BDPAGEMPCONTR = 1 THEN 'M?s da compet?ncia da folha'
    WHEN RHCALC.BDPAGEMPCONTR <> 1 THEN 'M?s posterior a compet?ncia da folha'
    WHEN RHCALC.BDPAGEMPCONTR IS NULL THEN 'M?s posterior a compet?ncia da folha'
  END BDPAGEMPCONTR,
  RHCALC.BDARREDONDAFN,
  RHCALC.BDARREDONDAFC,
  RHCALC.BDARREDONDAFE,
  RHCALC.BDARREDONDAFA,
  RHCALC.BDARREDONDAAD,
  RHCALC.BDARREDONDAA13,
  RHCALC.BDARREDONDA13,
  RHCALC.BDARREDONDAC13,
  RHCALC.BDARREDONDAAU,
  RHCALC.BDDESCFALHORASDIAS,
  RHCALC.BDPERCLIMIDESCPAR,    --Sol. 14911 - Bruno L. R. - 23/03/2017
  COALESCE(RHPAR.BDCALCC13FNNEGEMP, 'FALSE') BDCALCC13FNNEGEMP
FROM
VRHF_BASE_TEMPCALC RHCALC
LEFT OUTER JOIN VRHF_BASE_TEMPPAR RHPAR ON (RHCALC.BDCODEMP = RHPAR.BDCODEMP AND RHCALC.BDREFEMP = RHPAR.BDREFEMP)
;

/* Drop altered view: VWRH_EMPMENSAL_ABA_PGER */
DROP VIEW VWRH_EMPMENSAL_ABA_PGER;

/* Create altered view: VWRH_EMPMENSAL_ABA_PGER */
/* Create view: VWRH_EMPMENSAL_ABA_PGER */
CREATE VIEW VWRH_EMPMENSAL_ABA_PGER(
BDCODEMP,
BDREFEMP,
BDTIPOFEREMP,
BDSOMSALFEREMP,
BDTIPOAD13EMP,
BDSOMSALAD13EMP,
BDANOSAVPREVIOIND,
BDLIMINARAVPREVEMP,
BDTIPCALCFERCOLINF,
BDTIPCALCFERCOLSUP,
BDINDSITESPECIAL)
 AS 
SELECT
  RHCALC.BDCODEMP,
  RHCALC.BDREFEMP,
  CASE
    WHEN RHCALC.BDTIPOFEREMP = 1 THEN '1/12 (mensal)'
    WHEN RHCALC.BDTIPOFEREMP = 2 THEN '1/30 (di?rio)'
    WHEN RHCALC.BDTIPOFEREMP NOT IN (1,2) THEN 'Convencional (Anual)'
    WHEN RHCALC.BDTIPOFEREMP IS NULL THEN 'Convencional (Anual)'
  END BDTIPOFEREMP,
  COALESCE(RHCALC.BDSOMSALFEREMP, 'FALSE') BDSOMSALFEREMP,
  CASE
    WHEN RHCALC.BDTIPOAD13EMP = 1 THEN '1/12 (mensal)'
    WHEN RHCALC.BDTIPOAD13EMP = 2 THEN '1/30 (di?rio)'
    WHEN RHCALC.BDTIPOAD13EMP NOT IN (1,2) THEN 'Convencional (Anual)'
    WHEN RHCALC.BDTIPOAD13EMP IS NULL THEN 'Convencional (Anual)'
  END BDTIPOAD13EMP,
  COALESCE(RHCALC.BDSOMSALAD13EMP, 'FALSE') BDSOMSALAD13EMP,
  CASE
    WHEN BDANOSAVPREVIOIND = 1 THEN 'Ap?s o primeiro ano de servi?o'
    ELSE                            'Ap?s o segundo ano de servi?o'
  END BDANOSAVPREVIOIND,
  CASE
    WHEN BDLIMINARAVPREVEMP = 0 THEN 'N?o possui'
    WHEN BDLIMINARAVPREVEMP = 1 THEN 'Segurados'
    WHEN BDLIMINARAVPREVEMP = 2 THEN 'Patronal'
    WHEN BDLIMINARAVPREVEMP = 3 THEN 'Segurados e patronal'
    WHEN BDLIMINARAVPREVEMP = 4 THEN 'Segurados e 13? sal?rio'
    WHEN BDLIMINARAVPREVEMP = 5 THEN 'Patronal e 13? sal?rio'
    WHEN BDLIMINARAVPREVEMP = 6 THEN 'Segurados, patronal e 13? sal?rio'
    ELSE 'N?o informado'
  END BDLIMINARAVPREVEMP,
  FCINF.BDDESCRICAO,
  FCSUP.BDDESCRICAO,
  CASE
    WHEN CHAR_LENGTH(EMP.BDCNPJEMP) = 18 THEN
      CASE
        WHEN ES.BDINDSITESPECIAL = 0 THEN 'Situa??o normal'
        WHEN ES.BDINDSITESPECIAL = 1 THEN 'Extin??o'
        WHEN ES.BDINDSITESPECIAL = 2 THEN 'Fus?o'
        WHEN ES.BDINDSITESPECIAL = 3 THEN 'Cis?o'
        WHEN ES.BDINDSITESPECIAL = 4 THEN 'Incorpora??o'
        ELSE 'N?o informado'
      END
    ELSE
      CASE
        WHEN ES.BDINDSITESPECIAL = 0 THEN 'Situa??o normal'
        WHEN ES.BDINDSITESPECIAL = 1 THEN 'Encerramento de esp?lio'
        WHEN ES.BDINDSITESPECIAL = 2 THEN 'Sa?da do pa?s em car?ter permanente'
        ELSE 'N?o informado'
      END
  END BDINDSITESPECIAL
FROM
VRHF_BASE_TEMPCALC RHCALC
JOIN TEMPRESAS EMP ON EMP.BDCODEMP = RHCALC.BDCODEMP
LEFT OUTER JOIN VRHF_BASE_TEMPPAR RHPAR ON (RHCALC.BDCODEMP = RHPAR.BDCODEMP AND RHCALC.BDREFEMP = RHPAR.BDREFEMP)
LEFT OUTER JOIN VRHF_BASE_TTIPOCALCFERCOLETIVA FCINF ON (FCINF.BDTIPCALCFERCOL = RHCALC.BDTIPCALCFERCOLINF)
LEFT OUTER JOIN VRHF_BASE_TTIPOCALCFERCOLETIVA FCSUP ON (FCSUP.BDTIPCALCFERCOL = RHCALC.BDTIPCALCFERCOLSUP)
LEFT OUTER JOIN VRHF_BASE_TEMPESOCIAL ES ON (ES.BDCODEMP = RHCALC.BDCODEMP AND ES.BDREFEMP = RHCALC.BDREFEMP)
;

/* Drop altered view: VWRH_EMPMENSAL_ABA_PROP */
DROP VIEW VWRH_EMPMENSAL_ABA_PROP;

/* Create altered view: VWRH_EMPMENSAL_ABA_PROP */
/* Create view: VWRH_EMPMENSAL_ABA_PROP */
CREATE VIEW VWRH_EMPMENSAL_ABA_PROP(
BDCODEMP,
BDREFEMP,
BDPROPADMEMP,
BDPROPRESEMP,
BDPROPFEREMP,
BDPROPSITEMP,
BDPROPTOMEMP)
 AS 
SELECT
  RHPROP.BDCODEMP,
  RHPROP.BDREFEMP,
  CASE
    WHEN RHPROP.BDPROPADMEMP = 1 THEN 'Divis?o por 30 considerando at? o ?ltimo dia do m?s'
    WHEN RHPROP.BDPROPADMEMP = 2 THEN 'Divis?o por 30 dias considerando meses com no m?ximo 30 dias'
    WHEN RHPROP.BDPROPADMEMP NOT IN (1,2) THEN 'Divis?o pelos dias do m?s e multiplica pelos dias trabalhados'
    WHEN RHPROP.BDPROPADMEMP IS NULL THEN 'Divis?o pelos dias do m?s e multiplica pelos dias trabalhados'
  END BDPROPADMEMP,
  CASE
    WHEN RHPROP.BDPROPRESEMP = 1 THEN 'Divis?o por 30'
    WHEN RHPROP.BDPROPRESEMP <> 1 THEN 'Divis?o por dias do m?s'
    WHEN RHPROP.BDPROPRESEMP IS NULL THEN 'Divis?o por dias do m?s'
  END BDPROPRESEMP,
  CASE
    WHEN RHPROP.BDPROPFEREMP = 1 THEN 'Divis?o por 30'
    WHEN RHPROP.BDPROPFEREMP <> 1 THEN 'Divis?o por dias do m?s'
    WHEN RHPROP.BDPROPFEREMP IS NULL THEN 'Divis?o por dias do m?s'
  END BDPROPFEREMP,
  CASE
    WHEN RHPROP.BDPROPSITEMP = 1 THEN 'Divis?o por 30'
    WHEN RHPROP.BDPROPSITEMP <> 1 THEN 'Divis?o por dias do m?s'
    WHEN RHPROP.BDPROPSITEMP IS NULL THEN 'Divis?o por dias do m?s'
  END BDPROPSITEMP,
  CASE
    WHEN RHPROP.bdproptomemp = 1 THEN 'Divis?o por 30'
    WHEN RHPROP.bdproptomemp <> 1 THEN 'Divis?o por dias do m?s'
    WHEN RHPROP.bdproptomemp IS NULL THEN 'Divis?o por dias do m?s'
  END bdproptomemp

FROM
VRHF_BASE_TEMPPROP RHPROP
;

/* Drop altered view: VWRH_EMPMENSAL_ABA_RAIS */
DROP VIEW VWRH_EMPMENSAL_ABA_RAIS;

/* Create altered view: VWRH_EMPMENSAL_ABA_RAIS */
/* Create view: VWRH_EMPMENSAL_ABA_RAIS */
CREATE VIEW VWRH_EMPMENSAL_ABA_RAIS(
BDCODEMP,
BDREFEMP,
BDNATESTEMP,
BDDATABASEEMP,
BDPATEMP,
BDNROPROPEMP,
BDSERPROPRIOPATEMP,
BDPATREFCONVENIOEMP,
BDPATCESTAALIMENTOEMP,
BDPATADMCOZINHAEMP,
BDPATREFTRANSPEMP,
BDPATALICONVENIOEMP,
BDSINDICALIZEMP,
BDCODEMPPAT,
BDSOCOSTCONTAPART,
BDCODTPPONT,
BDDESCTCP,
BDENTSFL,
BDTRABTEMP,
BDREGMTE)
 AS 
SELECT
  RHRAIS.BDCODEMP,
  RHRAIS.BDREFEMP,
  CASE
    WHEN RHRAIS.BDNATESTEMP = 1 THEN '10 - Aut?nomo, profissional liberal e condom?nio'
    WHEN RHRAIS.BDNATESTEMP = 2 THEN '20 - Empresa Privada, sociedade civil, associa??o de classe e sindicato'
    WHEN RHRAIS.BDNATESTEMP = 3 THEN '30 - Funda??o mantida com recursos privados'
    WHEN RHRAIS.BDNATESTEMP = 4 THEN '35 - Funda??o mantida com recursos p?blicos'
    WHEN RHRAIS.BDNATESTEMP = 5 THEN '40 - Sociedade de economia mista'
    WHEN RHRAIS.BDNATESTEMP = 6 THEN '50 - Empresa p?blica'
    WHEN RHRAIS.BDNATESTEMP = 7 THEN '60 - ?rg?o aut?nomo de direito p?blico'
    WHEN RHRAIS.BDNATESTEMP = 8 THEN '70 - Autarquia'
    WHEN RHRAIS.BDNATESTEMP = 9 THEN '80 - Administra??o p?blica direita'
    WHEN RHRAIS.BDNATESTEMP = 10 THEN '90 - Cart?rio'
    WHEN RHRAIS.BDNATESTEMP NOT IN (1,2,3,4,5,6,7,8,9,10) THEN '00 - Nenhum'
    WHEN RHRAIS.BDNATESTEMP IS NULL THEN '00 - Nenhum'
  END BDNATESTEMP,
  RHRAIS.BDDATABASEEMP,
  COALESCE(RHRAIS.BDPATEMP, 'FALSE') BDPATEMP,
  RHRAIS.BDNROPROPEMP,
  RHRAIS.BDSERPROPRIOPATEMP,
  RHRAIS.BDPATREFCONVENIOEMP,
  RHRAIS.BDPATCESTAALIMENTOEMP,
  RHRAIS.BDPATADMCOZINHAEMP,
  RHRAIS.BDPATREFTRANSPEMP,
  RHRAIS.BDPATALICONVENIOEMP,
  COALESCE(RHRAIS.BDSINDICALIZEMP, 'FALSE') BDSINDICALIZEMP,
  RHRAIS.BDCODEMPPAT,
  ESOC.BDSOCOSTCONTAPART,
  RHRAIS.BDCODTPPONT,
  TCP.BDDESCRICAO BDDESCTCP,
  RHRAIS.BDENTSFL,
  RHRAIS.BDTRABTEMP,
  RHRAIS.BDREGMTE
FROM
  VRHF_BASE_TEMPRAIS RHRAIS
  LEFT OUTER JOIN VRHF_BASE_TEMPESOCIAL ESOC ON (ESOC.BDCODEMP = RHRAIS.BDCODEMP AND ESOC.BDREFEMP = RHRAIS.BDREFEMP)
  LEFT OUTER JOIN VRH_BASE_TCONTROLE_PONTO TCP ON (TCP.BDCODTPPONT = RHRAIS.BDCODTPPONT)
;

/* Drop altered view: VWRH_EMPMENSAL_ABA_SEFIP */
DROP VIEW VWRH_EMPMENSAL_ABA_SEFIP;

/* Create altered view: VWRH_EMPMENSAL_ABA_SEFIP */
/* Create view: VWRH_EMPMENSAL_ABA_SEFIP */
CREATE VIEW VWRH_EMPMENSAL_ABA_SEFIP(
BDCODEMP,
BDREFEMP,
BDCODBAN,
BDCODAG,
BDCODUF,
BDIDENTEMP,
BDCATSEFIPEMP,
BDISENFILEMP,
BDCETRTALIZAEMP,
BDCODSEFIPEMP,
BDNOMBAN,
BDNOMAG,
BDSIGLAUF)
 AS 
SELECT
  RHSEFIP.BDCODEMP,
  RHSEFIP.BDREFEMP,
  RHSEFIP.BDCODBAN,
  RHSEFIP.BDCODAG,
  RHSEFIP.BDCODUF,
  RHSEFIP.BDIDENTEMP,
  CASE
    WHEN RHSEFIP.BDCATSEFIPEMP = 1 THEN 'Entidade filantr?pica'
    WHEN RHSEFIP.BDCATSEFIPEMP = 2 THEN 'Clube de futebol'
    WHEN RHSEFIP.BDCATSEFIPEMP = 3 THEN 'Pessoa f?sica urbana'
    WHEN RHSEFIP.BDCATSEFIPEMP = 4 THEN 'Pessoa f?sica rural'
    WHEN RHSEFIP.BDCATSEFIPEMP = 5 THEN 'Pessoa jur?dica rural'
    WHEN RHSEFIP.BDCATSEFIPEMP = 6 THEN 'Sind. agregador trab. avulso'
    WHEN RHSEFIP.BDCATSEFIPEMP NOT IN (1,2,3,4,5,6) THEN 'Outros'
    WHEN RHSEFIP.BDCATSEFIPEMP IS NULL THEN 'Outros'
  END BDCATSEFIPEMP,
  RHSEFIP.BDISENFILEMP,
  CASE
    WHEN RHSEFIP.BDCETRTALIZAEMP = 1 THEN 'Centralizadora'
    WHEN RHSEFIP.BDCETRTALIZAEMP = 2 THEN 'Centralizada'
    WHEN RHSEFIP.BDCETRTALIZAEMP NOT IN (1,2) THEN 'N?o centraliza'
    WHEN RHSEFIP.BDCETRTALIZAEMP IS NULL THEN 'N?o centraliza'
  END BDCETRTALIZAEMP,
  RHSEFIP.BDCODSEFIPEMP,
  BANCO.BDNOMBAN,
  BANAG.BDNOMAG,
  UF.BDSIGLAUF
FROM
  VRHF_BASE_TEMPSEFIP RHSEFIP
LEFT OUTER JOIN TBANCOS BANCO ON (RHSEFIP.BDCODBAN = BANCO.BDCODBAN)
LEFT OUTER JOIN TBANCOS_AG BANAG ON (RHSEFIP.BDCODBAN = BANAG.BDCODBAN AND RHSEFIP.BDCODAG = BANAG.BDCODAG)
LEFT OUTER JOIN TUF UF ON (RHSEFIP.BDCODUF = UF.BDCODUF)
;

/* Drop altered view: VWSCI_EMPMENSAL_ABA_ESOCIAL */
DROP VIEW VWSCI_EMPMENSAL_ABA_ESOCIAL;

/* Create altered view: VWSCI_EMPMENSAL_ABA_ESOCIAL */
/* Create view: VWSCI_EMPMENSAL_ABA_ESOCIAL */
CREATE VIEW VWSCI_EMPMENSAL_ABA_ESOCIAL(
BDCODEMP,
BDREFEMP,
BDCODCLATRI,
BDDESCCLATRI,
BDESCOOPERATIVA,
BDESCONSTRUTORA,
BDESFGTSFIN,
BDESDEBAUTFGTS,
BDESAGERECFGTS,
BDESSMSRESP,
BDAPURAT,
BDAPUFAP,
BDACINTISENMULTA,
BDSOCOSTCONTAPART,
BDINDSITESPECIAL,
BDOPCAOESOCIAL,
BDINDCCONTRAAPRENDIZ,
BDINDCCONTRAPCD,
BDINDICATIVOREGELETR,
BDRELPORINTERM,
BDENTIDADEPAA)
 AS 
select X.BDCODEMP, X.BDREFEMP, X.BDCODCLATRI, Y.BDDESCCLATRI,
       case
         when X.BDESCOOPERATIVA = 0 then 'Não'
         when X.BDESCOOPERATIVA = 1 then 'De trabalho'
         when X.BDESCOOPERATIVA = 2 then 'De produção'
         when X.BDESCOOPERATIVA = 3 then 'Outras'
         else 'Não informado'
       end BDESCOOPERATIVA,
       X.BDESCONSTRUTORA, X.BDESFGTSFIN, X.BDESDEBAUTFGTS, X.BDESAGERECFGTS, X.BDESSMSRESP,
       case
         when X.BDAPURAT = 1 then 'CNAE preponderante de cada estabelecimento'
         else 'CNAE preponderante da empresa'
       end BDAPURAT,
       case
         when X.BDAPUFAP = 1 then 'FAP atribuído à cada estabelecimento'
         else 'FAP atribuído à empresa'
       end BDAPUFAP,
       case
         when X.BDACINTISENMULTA = 1 then 'Com acordo'
         else 'Sem acordo'
       end BDACINTISENMULTA,
       X.BDSOCOSTCONTAPART,
       case
         when X.BDINDSITESPECIAL = 1 then 'Extinção'
         when X.BDINDSITESPECIAL = 2 then 'Fusão'
         when X.BDINDSITESPECIAL = 3 then 'Cisão'
         when X.BDINDSITESPECIAL = 4 then 'Incorporação'
         else 'Situação normal'
       end BDINDSITESPECIAL,
       COALESCE(T.BDDESCRICAO,'Nenhum')   ,
       case
         when X.BDINDCCONTRAAPRENDIZ = 0 then 'Não informado'
         when X.BDINDCCONTRAAPRENDIZ = 1 then 'Dispensado de acordo com a lei'
         when X.BDINDCCONTRAAPRENDIZ = 2 then 'Dispensado, mesmo que parcialmente, em virtude de processo judicial'
         when X.BDINDCCONTRAAPRENDIZ = 3 then 'Obrigado'
       end BDINDCCONTRAAPRENDIZ,
       case
         when coalesce(X.BDINDCCONTRAPCD, 0) = 0 then 'Não informado'
         when X.BDINDCCONTRAPCD = 1 then 'Dispensado de acordo com a lei'
         when X.BDINDCCONTRAPCD = 2 then 'Dispensado, mesmo que parcialmente, em virtude de processo judicial'
         when X.BDINDCCONTRAPCD = 3 then 'Com exigibilidade de suspensa, mesmo que parcialmente em virtude de Termo de Compromisso  firmado com o Ministério do Trabalho'
         when X.BDINDCCONTRAPCD = 4 then 'Obrigado'
       end BDINDCCONTRAPCD,
       case
         when coalesce(X.BDINDICATIVOREGELETR, 0) = 0 then 'Não informado'
         when X.BDINDICATIVOREGELETR = 1 then 'Não optou pelo registro eletrônico de empregados'
         when X.BDINDICATIVOREGELETR = 2 then 'Optou pelo registro eletrônico de empregados'
       end BDINDICATIVOREGELETR,
       case
         when coalesce(X.BDRELPORINTERM, 'FALSE') = 'FALSE' then 'NÃO'
         when X.BDRELPORINTERM = 'TRUE' then 'SIM'
       end BDRELPORINTERM,
       case
         when coalesce(R.BDENTIDADEPAA, 'FALSE') = 'FALSE' then 'NÃO'
         when R.BDENTIDADEPAA = 'TRUE' then 'SIM'
       end BDENTIDADEPAA
from VRHF_BASE_TEMPESOCIAL X
LEFT OUTER JOIN VRH_BASE_CLASSTRIBUTARIA Y ON (Y.BDCODCLATRI = X.BDCODCLATRI)
LEFT OUTER JOIN TEMPRESAS_REF R ON R.BDCODEMP = X.BDCODEMP AND R.BDREFEMP = X.BDREFEMP
LEFT OUTER JOIN VRH_ESOCIAL_TFASEAMENTO F ON F.BDCODEMP = X.BDCODEMP
LEFT OUTER JOIN VRH_ESOCIAL_TTIPODADOS T on T.BDOPCAOESOCIAL = F.BDOPCAOESOCIAL
;

/*  Empty VRHF_SPF_BC_RAT for SP_CONSULTAEMPRESAS(param list change)  */
SET TERM ^ ;

ALTER PROCEDURE VRHF_SPF_BC_RAT(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* Alter empty procedure SP_CONSULTAEMPRESAS with new param-list */
ALTER PROCEDURE SP_CONSULTAEMPRESAS(PRREFMICRO INTEGER,
PRCODEMP VARCHAR(10240),
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDDATAINIATIVEMP DATE,
BDORGAOEMP VARCHAR(8),
BDDATAREGEMP DATE,
BDDATACONSTEMP DATE,
BDOMIE DM_BOOLEAN,
BDDESCCARTEMP VARCHAR(40),
BDDATAFIMATIVEMP DATE,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCODCENTROS INTEGER,
BDCODCID INTEGER,
BDCODCONT INTEGER,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDNOMFANEMP VARCHAR(200),
BDNOMREDUZEMP DM_BDNOMREDUZEMP,
BDAPEEMP DM_BDAPEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDLOGREMP VARCHAR(15),
BDIEEMP VARCHAR(20),
BDIMEMP VARCHAR(20),
BDSITEMP VARCHAR(5),
BDDDDFAXEMP INTEGER,
BDNOMCID VARCHAR(40),
BDCODUF INTEGER,
BDNOMECONT VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCUF VARCHAR(40),
BDCODPLANOONLINE INTEGER,
BDCODENQFED INTEGER,
BDPERSONALIZACAO VARCHAR(120),
BDCODCONTEF INTEGER,
BDLIVRO VARCHAR(15),
BDFOLHA VARCHAR(15),
BDNOMECARTORIO VARCHAR(100),
BDDATACADEMP DATE,
BDTIPOAPURACAORET INTEGER,
BDCODPLATRIB INTEGER,
BDTRANMANUAL VARCHAR(5),
BDTIPOAPURACAORETIR INTEGER,
BDCODESC INTEGER,
BDCODPLAPADRAOREF INTEGER,
BDCODIBGE INTEGER,
BDFORMATRIBUTACAO INTEGER,
BDSTATUS_ES INTEGER,
BDABRIRRATEIO DM_BOOLEAN,
BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
BDINTEGRANET DM_BOOLEAN,
BDIGNORAREDISS DM_BOOLEAN,
BDDATAINIESOCIAL DATE,
BDOPCAOESOCIAL INTEGER,
BDDDDCELULAREMP INTEGER,
BDCELULAREMP DM_BDTELEFONE,
BDCODCLI INTEGER,
BDDATAOBRIGREINF DATE,
BDNRTCE VARCHAR(20),
BDSTATUSEMP INTEGER,
BDQTDBACKUPEMP INTEGER,
BDMATRIZNAOCADSIS VARCHAR(5),
BDSITUACAOESOCIAL INTEGER,
BDCODGIARS INTEGER,
BDINCORPORADORAS DM_BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

/* Alter Procedure... */
/* empty dependent procedure body */
/* Clear: ULTIMO_DIA_MES for: ANO_BISEXTO */
ALTER PROCEDURE ULTIMO_DIA_MES(PRMES SMALLINT,
PRANO INTEGER)
 RETURNS(ULTDIA INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (ANO_BISEXTO) */
ALTER PROCEDURE ANO_BISEXTO(PRANO INTEGER)
 RETURNS(PRBISEXTO SMALLINT)
 AS
DECLARE VARIABLE wvar INTEGER;
BEGIN

  wvar = (prano / 4 * 4);

  IF (wvar = prAno) THEN
     prbisexto = 1; -- ? ano bisexto
  ELSE
     prbisexto = 0; -- n?o ? ano bisexto

  SUSPEND;

END
^

/* Alter (CHAR_ACENTUADO) */
ALTER PROCEDURE CHAR_ACENTUADO RETURNS(BDACENTO VARCHAR(10),
BDSEMACENTO VARCHAR(10))
 AS
DECLARE VARIABLE wacento VARCHAR(1000);
DECLARE VARIABLE wsemacento VARCHAR(1000);
DECLARE VARIABLE charac VARCHAR(10);
DECLARE VARIABLE characc VARCHAR(10);
DECLARE VARIABLE terminado SMALLINT;
BEGIN
    bdacento = '?';
    bdsemacento = 'a';
    SUSPEND;
    bdsemacento = 'e';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'i';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'o';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'u';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'A';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'E';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'I';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'O';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'U';
    bdacento = '?';
    SUSPEND;
    bdsemacento = 'c';
    bdacento = '?';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'C';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'A';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'O';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'e';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'A';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'E';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'O';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'e';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'i';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'u';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'A';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'E';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'I';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'O';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'U';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'A';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = '?';
    bdsemacento = 'O';
    SUSPEND;
END
^

/* Alter (CLEAR_ALL_TEMPORARY_TABLE) */
ALTER PROCEDURE CLEAR_ALL_TEMPORARY_TABLE AS
DECLARE VARIABLE WTABELA VARCHAR(250);
BEGIN
  /*
    Sol: 14207 Patrick T. S? 24/04/2016. Implementada importa??o temporaria de participantes e lan?amentos de sa?da.
    Tabelas que iniciam com TMP e terminam com TEMP devem ser limpas sempre que o servidor ligar/reiniciar.
    TMP - Tabelas tempor?rias(Global temporary table)
    TMP_TTABLE_TEMP - Tabelas tempor?rias sem ser global temporary table.
  */
  --22326
  FOR SELECT RDB$RELATION_NAME FROM RDB$RELATIONS
      WHERE RDB$SYSTEM_FLAG = 0
      AND RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      ORDER BY RDB$RELATION_NAME
      INTO :wTabela
  DO
    EXECUTE STATEMENT 'DELETE FROM '||wTabela;
    
  /*
    Sol: 14207 Patrick T. S? 03/05/2016. Deve apagar todos os registros das tabelas de inconsistencias existentes. ao ligar/reiniciar o servidor.
  */
  FOR SELECT RDB$RELATION_NAME FROM RDB$RELATIONS
      WHERE  RDB$RELATION_NAME LIKE 'VEF_INCON_%'
      ORDER BY RDB$RELATION_NAME
      INTO :wTabela
  DO
    EXECUTE STATEMENT 'DELETE FROM '||wTabela; 

  /*N?o ? temporaria*/
  DELETE FROM TEXPORTACAO_SPED      WHERE BDID IS NOT NULL;
  DELETE FROM TEXPORTACAO_SPED_INCO WHERE BDID IS NOT NULL;       
    
END
^

/* empty dependent procedure body */
/* Clear: VCT_TAREFAS_AUTOMATICAS for: GET_VENCIMENTO */
ALTER PROCEDURE VCT_TAREFAS_AUTOMATICAS(CODEMP INTEGER = 0,
DATA DATE = CURRENT_DATE)
 RETURNS(TOTAL INTEGER,
IMPOSTOS INTEGER,
OBRIGACOES INTEGER,
SERVICOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (GET_VENCIMENTO) */
ALTER PROCEDURE GET_VENCIMENTO(PRDATA DATE,
PRDIA INTEGER,
PRANTECIPA VARCHAR(5),
PRVENCE INTEGER,
PRAPURACAO INTEGER,
PRALERTA INTEGER,
PRCIDADE INTEGER,
PRMES INTEGER = 0,
PRCODEMP INTEGER = 0)
 RETURNS(BDDATA DATE)
 AS
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WCOUNTX INTEGER;
BEGIN
  /*
  PRDIA = dia de vencimento do m?s
  PRANTECIPA = 1 - antecipa domingos e feriados
  PRVENCE = 0 - No m?s do movimento
            1 - No m?s seguinte
            2 - No m?s subsequente
            3 - Dias ?teis
  PRAPURACAO =  0 - Semanal
                1 - 1? Decendio
                2 - 2? Decendio
                3 - 3? Decendio
                4 - 1? Quinzena
                5 - 2? Quinzena
                6 - Mensal
                7 - Trimestral
                8 - Trimestral parcelado
                9 - Trimestral antecipado
               10 - Anual
               11 - Indefinido
  */


  IF (PRDATA IS NULL) THEN
     EXIT;

  /* inicializa vari?veis */
  IF (prvence <> 3) THEN
     wdia = prdia;
  ELSE
     wdia = SUBSTRING(prdata FROM 9 FOR 2);
  IF ((prdia = 0) OR (prdia IS NULL)) THEN
     wdia = 1;
  IF ((prmes IS NOT NULL) AND (prmes <> 0) AND (PRAPURACAO = 10)) THEN
     wmes = prmes;
  ELSE
     wmes = SUBSTRING(prdata FROM 6 FOR 2);
  wano = SUBSTRING(prdata FROM 1 FOR 4);

  IF (prvence = 4) THEN
     BEGIN
       SELECT bddatainiativemp FROM tempresas WHERE bdcodemp = :prcodemp INTO :wdata;
--       1991-02-27
       wdia = SUBSTRING(wdata FROM 9 FOR 2);
       wmes = SUBSTRING(wdata FROM 6 FOR 2);
     END
  ELSE
     wdata = prdata;

  /* apura??o */
  IF (prapuracao =  0) THEN -- 0 - Semanal
     BEGIN
       wdata = prdata;
     END
  ELSE
  IF (prapuracao =  1) THEN -- 1 - 1? Decendio
     BEGIN
       wdia = 11;
     END
  ELSE
  IF (prapuracao =  2) THEN -- 2 - 2? Decendio
     BEGIN
       wdia = 21;
     END
  ELSE
  IF (prapuracao =  3) THEN -- 3 - 3? Decendio
     BEGIN
       wdia = 31; -- n?o h? necessidade de verificar m?s e ano bisexto, pois isso acontecer? no processo "add dia"
     END
  ELSE
  IF (prapuracao =  4) THEN -- 4 - 1? Quinzena
     BEGIN
       IF (prdia IS NULL) THEN
          wdia = SUBSTRING(prdata FROM 9 FOR 2);
       ELSE
          wdia = prdia;
     END
  ELSE
  IF (prapuracao =  5) THEN -- 5 - 2? Quinzena
     BEGIN
       IF (prdia IS NULL) THEN
          wdia = SUBSTRING(prdata FROM 9 FOR 2);
       ELSE
          wdia = prdia;
     END
  ELSE
  IF (prapuracao =  6) THEN -- 6 - Mensal
     BEGIN
       wdata = prdata;
     END
  ELSE
  --Leonardo Pereira - sol. 20777 - prvence 0 e 3 n?o ? tratado mais a frente, apenas prvence 1 e 2.
  IF (prapuracao =  7) THEN -- 7 - Trimestral
     BEGIN
       IF (wmes IN (1,2,3)) THEN
          if (prvence = 3) then
              wmes = 4;
          ELSE
            wmes = 3;
       ELSE
       IF (wmes IN (4,5,6)) THEN
          if (prvence = 3) then
             wmes = 7;
          ELSE
            wmes = 6;
       ELSE
       IF (wmes IN (7,8,9)) THEN
          if (prvence = 3) then
              wmes = 10;
          ELSE
            wmes = 9;
       ELSE
       IF (wmes IN (10,11,12)) THEN
          BEGIN
            if (prvence = 3) then
               BEGIN
                 wmes = 1;
                 wano = wano+1;
               END
             ELSE
               wmes = 12;
          END
     END
  ELSE
  IF (prapuracao =  8) THEN -- 8 - Trimestral parcelado
     BEGIN
       IF (wmes IN (1,2,3)) THEN
          wmes = 4;
       ELSE
       IF (wmes IN (4,5,6)) THEN
          wmes = 7;
       ELSE
       IF (wmes IN (7,8,9)) THEN
          wmes = 10;
       ELSE
       IF (wmes IN (10,11,12)) THEN
          BEGIN
            wmes = 1;
            wano = wano + 1;
          END
     END
  ELSE
  IF (prapuracao =  9) THEN -- 9 - Trimestral antecipado
     BEGIN
/* gilberto - 30/10/2014 - retirado pois incrementa 2 meses quando op??o m?s seguinte estiver habilitada
       if (wmes < 12) then
          wmes = wmes + 1;
       else
          begin
            wmes = 1;
            wano = wano + 1;
          end
*/
     END
  ELSE
  IF (prapuracao = 10) THEN -- 10 - Anual
     BEGIN
       IF (prvence <> 4) THEN
          BEGIN
            wdia = 31;
            wmes = 12;
          END
     END
  ELSE
  IF (prapuracao = 11) THEN -- 11 - Indefinido
     BEGIN
       wdata = prdata;
     END

  /* add m?s e ano */
  IF (prvence = 1) THEN
     BEGIN
       wmes = wmes + prvence;
       IF (wmes > 12) THEN
          BEGIN
            wmes = 1;
            wano = wano + 1;
          END
     END
  ELSE
  IF (prvence = 2) THEN
     BEGIN
       wmes = wmes + prvence;
       IF (wmes > 12) THEN
          BEGIN
            wmes = wmes - 12;
            wano = wano + 1;
          END
     END

  /* add dia */
  IF (wmes = 2) THEN
     BEGIN
       IF ((wano / 4 * 4) = wano) THEN
          BEGIN
            IF (wdia > 29) THEN
               wdia = 29;
          END
       ELSE
          BEGIN
            IF (wdia > 28) THEN
               wdia = 28;
          END
     END
  ELSE
  IF (wmes IN (1,3,5,7,8,10,12)) THEN
     BEGIN
       IF (wdia > 31) THEN
          wdia = 31;
     END
  ELSE
  IF (wmes IN (4,6,9,11)) THEN
     BEGIN
       IF (wdia > 30) THEN
          wdia = 30;
     END

  /* monta data atual */
  wdata = CAST(wano||'/'||wmes||'/'||wdia AS DATE);

  /* dias ?teis */
  IF (prvence = 3) THEN
     BEGIN
       wcount = 0;
       WHILE (wcount < prdia) DO
         BEGIN
           wdata = addday(wdata, 1);
           wcount = wcount + 1;

           SELECT FIRST 1 fer.bdcodferi
           FROM tferiadosnovo fer
           WHERE ((fer.bddataferi = :wdata)
           OR (fer.bdmesdiaferi = CAST(SUBSTRING(:wdata FROM 9 FOR 2)||SUBSTRING(:wdata FROM 6 FOR 2) AS VARCHAR(4))))
           AND fer.bdcodcid IS NULL
           INTO :wdia;
           IF ((wdia IS NOT NULL) AND (wDia <> 0)) THEN
              wdata = addday(wdata, 1);

           IF ((UPPER(sdow(wdata)) = 'S?B') OR
               (UPPER(sdow(wdata)) = 'SUN')) THEN
              wdata = addday(wdata, 1);

           IF ((UPPER(sdow(wdata)) = 'DOM') OR
               (UPPER(sdow(wdata)) = 'WES')) THEN
              wdata = addday(wdata, 1);
         END
     END

  /* antecipa vencimento */
  IF ((UPPER(prantecipa) = 'TRUE') OR (UPPER(prantecipa) = '1')) THEN
     BEGIN
       IF (((prvence = 3) AND (wdata - prdata > 0)) OR (prvence <> 3))  THEN
          BEGIN
            wcount = 0;
            wDia = 0;
            WHILE ((wcount = 0) OR
                   (((wdia IS NOT NULL) AND (wdia <> 0)) OR
                   ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
                   ((UPPER(sdow(wdata)) = 'S?B') OR (UPPER(sdow(wdata)) = 'SUN')))) DO
              BEGIN
                wdia = 0;
                SELECT FIRST 1 fer.bdcodferi
                FROM tferiadosnovo fer
                WHERE (fer.bddataferi = :wdata)
--                or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
                AND fer.bdcodcid IS NULL
                INTO :wdia;
                IF (((wdia IS NOT NULL) AND (wdia <> 0)) OR
                   ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
                   ((UPPER(sdow(wdata)) = 'S?B') OR (UPPER(sdow(wdata)) = 'SUN'))) THEN
                   wcount = 0;
                ELSE
                   wcount = 1;
     
                IF (wcount = 0) THEN
                   wdata = addday(wdata, -1);
              END
          END
     END
  ELSE
  /* posterga vencimento */
     BEGIN
       IF (((prvence = 3) AND (wdata - prdata > 0)) OR (prvence <> 3))  THEN
          BEGIN
            wcount = 0;
            wDia = 0;
            WHILE ((wcount = 0) OR
                   (((wDia IS NOT NULL) AND (wdia <> 0)) OR
                   ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
                   ((UPPER(sdow(wdata)) = 'S?B') OR (UPPER(sdow(wdata)) = 'SUN')))) DO
              BEGIN
                wdia = 0;
                SELECT FIRST 1 fer.bdcodferi
                FROM tferiadosnovo fer
                WHERE (fer.bddataferi = :wdata)
--                or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
                AND fer.bdcodcid IS NULL
                INTO :wdia;
                IF (((wdia IS NOT NULL) AND (wdia <> 0)) OR
                   ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
                   ((UPPER(sdow(wdata)) = 'S?B') OR (UPPER(sdow(wdata)) = 'SUN'))) THEN
                   wcount = 0;
                ELSE
                   wcount = 1;
     
                IF (wcount = 0) THEN
                   wdata = addday(wdata, 1);
              END
          END
     END

  /* alreta */
  IF ((pralerta IS NOT NULL) AND (pralerta > 0)) THEN
     BEGIN
       wcount = 1;
       wcountx = 0;
       wDia = 0;
       WHILE ((wcount <= pralerta) OR
              ((((wDia IS NOT NULL) AND (wdia <> 0)) OR
               ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
               ((UPPER(sdow(wdata)) = 'S?B') OR (UPPER(sdow(wdata)) = 'SUN'))))) DO
         BEGIN
           wdia = 0;
           SELECT FIRST 1 fer.bdcodferi
           FROM tferiadosnovo fer
           WHERE (fer.bddataferi = :wdata)
--           or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
           AND fer.bdcodcid IS NULL
           INTO :wdia;
           IF (((wdia IS NOT NULL) AND (wdia <> 0)) OR
              ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
              ((UPPER(sdow(wdata)) = 'S?B') OR (UPPER(sdow(wdata)) = 'SUN'))) THEN
              wdata = addday(wdata, -1);
           ELSE
              wcount = wcount + 1;

           wdata = addday(wdata, -1);
         END
     END

--  bddata = wdata;-- gilberto - alterado para n?o gerar tarefa em meses anteriores a execu??o da gera??o de tarefas autom?ticas
/* gilberto - 04/04/2016
  IF ((SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2)) < (SUBSTRING(prdata FROM 1 FOR 4)||SUBSTRING(prdata FROM 6 FOR 2))) THEN
     bddata = addyear(wdata, 1);
  ELSE*/
     bddata = wdata;
  SUSPEND;
END
^

/* Alter (GETPRIVILEGIOSEMPRESAS) */
ALTER PROCEDURE GETPRIVILEGIOSEMPRESAS(PRCODEMP INTEGER,
PRPRIVILEGIO VARCHAR(200))
 RETURNS(BDCODEMP INTEGER,
BDCODGRUPO INTEGER,
BDCODUSU INTEGER,
BDITEMPRIV VARCHAR(200))
 AS
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(2000);
DECLARE VARIABLE WCOUNTGRP INTEGER;
DECLARE VARIABLE WCOUNTUSU INTEGER;
DECLARE VARIABLE WSQLX VARCHAR(2000);
BEGIN
  -- verifica se o usuario pertence aos grupos 1 ou 2
  SELECT COUNT(bdcodgrupo) FROM tgrupousuario_usuario
  WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario)
  AND bdcodgrupo IN (1,2)
  INTO :wcount;
  IF (wcount > 0) THEN
     BEGIN
       -- carrega todas as empresas e privilegios
       wsql = 'select bdcodemp from tempresas ';
       IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
          wsql = wsql||'where bdcodemp = '||prcodemp;
       wsql = wsql||' order by bdcodemp';
       FOR EXECUTE STATEMENT wsql INTO :bdcodemp DO
           BEGIN
             -- retorna todos os privilegios do ususario se n?o houver empresa configurada
             wsqlx = 'select distinct 1 as bdcodgrupo, (select bdcodusu from sp_get_usuario) bdcodusu, tpriv.bditempriv ';
             wsqlx = wsqlx||'from tprivilegio_grupousuario tpriv ';
             IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
                wsqlx = wsqlx||'where upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||''') ';
             wsqlx = wsqlx||'order by tpriv.bditempriv ';
             FOR EXECUTE STATEMENT wsqlx INTO :bdcodgrupo, :bdcodusu, :bditempriv DO
                 SUSPEND;
           END
     END
  ELSE
     BEGIN
       -- verifica se h? empresas no grupo de usu?rios
       wsql = 'select count(bdcodemp) from tempresa_grupousuario tegu ';
       wsql = wsql||'inner join tgrupousuario_usuario tgrp on(tgrp.bdcodgrupo = tegu.bdcodgrupo and tgrp.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
       EXECUTE STATEMENT wsql INTO :wcountgrp;
       -- verifica as empresas por usu?rio
       wsql = 'select count(bdcodemp) from tempresa_usuario where bdcodusu = (select bdcodusu from sp_get_usuario) ';
       EXECUTE STATEMENT wsql INTO :wcountusu;

       -- verifica se tem empresa configurada para usuario ou grupo de usuario
       wsql = 'select count(temp.bdcodemp) ';--  select temp.bdcodemp, temp.bdcodgrupo, tgrp.bdcodusu
       wsql = wsql||'from tempresa_grupousuario temp ';
       wsql = wsql||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = temp.bdcodgrupo and tgrp.bdcodusu = (select x.bdcodusu from sp_get_usuario x)) ';
       IF (wcountusu > 0) THEN
          wsql = wsql||'inner join tempresa_usuario teu on (teu.bdcodemp = temp.bdcodemp and teu.bdcodusu = tgrp.bdcodusu) ';
       IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
          wsql = wsql||'and temp.bdcodemp = '||prcodemp;
       EXECUTE STATEMENT wsql INTO :wcount;
     
       IF (wcount = 0) THEN
          BEGIN
/*            -- verifica se ha grupos sem escritorio
            select count(tgrp.bdcodgrupo) from tgrupousuario tgrp
            inner join tgrupousuario_usuario tusu on (tusu.bdcodgrupo = tgrp.bdcodgrupo and tusu.bdcodusu = (select bdcodusu from sp_get_usuario))
            where tgrp.bdcodesc is null
            into :wcount;
            
            if (wcount > 0) then
               begin
                 -- retorna todas as empresas
                 wsql = 'select distinct temp.bdcodemp from tempresas temp ';
                 wsql = wsql||'inner join tgrupousuario_usuario tusu on (tusu.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                 wsql = wsql||'inner join tgrupousuario tgrp on (tgrp.bdcodgrupo = tusu.bdcodgrupo and tgrp.bdcodesc = temp.bdcodesc) ';
                 if (wcountgrp > 0) then
                    wsql = wsql||'inner join tempresa_grupousuario tegu on (tegu.bdcodemp = temp.bdcodemp and tegu.bdcodgrupo =  tgrp.bdcodgrupo) ';
                 if (wcountusu > 0) then
                    wsql = wsql||'inner join tempresa_usuario teu on (teu.bdcodemp = temp.bdcodemp and teu.bdcodusu = tusu.bdcodusu) ';
                 if ((prcodemp <> 0) or (prcodemp is not null)) then
                    wsql = wsql||'where bdcodemp = '||prcodemp;
                 wsql = wsql||' order by temp.bdcodemp';
                 for execute statement wsql into :bdcodemp do
                     begin
                       -- retorna todos os privilegios do ususario se n?o houver empresa configurada
                       wsqlx = 'select tpriv.bdcodgrupo, tgrp.bdcodusu, tpriv.bditempriv ';
                       wsqlx = wsqlx||'from tprivilegio_grupousuario tpriv ';
                       wsqlx = wsqlx||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = tpriv.bdcodgrupo and tgrp.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                       if ((prprivilegio is not null) and (trim(prprivilegio) <> '')) then
                          wsqlx = wsqlx||'where upper(tpriv.bditempriv) containing upper('''||trim(prprivilegio)||''') ';
                       for execute statement wsqlx into :bdcodgrupo, :bdcodusu, :bditempriv do
                           suspend;
                     end
               end
            else*/
               BEGIN
                 -- retorna empresas por escritorio
                 wsql = 'select distinct temp.bdcodemp from tempresas temp ';
                 IF (wcountgrp > 0) THEN
                    BEGIN
                      wsql = wsql||'inner join tgrupousuario_usuario tusu on (tusu.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                      wsql = wsql||'inner join tgrupousuario tgrp on (tgrp.bdcodgrupo = tusu.bdcodgrupo and tgrp.bdcodesc = temp.bdcodesc) ';
                      wsql = wsql||'inner join tempresa_grupousuario tegu on (tegu.bdcodemp = temp.bdcodemp and tegu.bdcodgrupo =  tgrp.bdcodgrupo) ';
                    END
                 IF (wcountusu > 0) THEN
                    wsql = wsql||'inner join tempresa_usuario teu on (teu.bdcodemp = temp.bdcodemp and teu.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                 IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
                    wsql = wsql||' where temp.bdcodemp = '||prcodemp;
                 wsql = wsql||' order by temp.bdcodemp';
                 FOR EXECUTE STATEMENT wsql INTO :bdcodemp DO
                     BEGIN
                       -- retorna todos os privilegios do ususario se n?o houver empresa configurada
                       wsqlx = 'select tpriv.bdcodgrupo, tgrp.bdcodusu, tpriv.bditempriv ';
                       wsqlx = wsqlx||'from tprivilegio_grupousuario tpriv ';
                       wsqlx = wsqlx||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = tpriv.bdcodgrupo and tgrp.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                       IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
                          wsqlx = wsqlx||'where upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||''') ';
                       wsqlx = wsqlx||'order by tpriv.bdcodgrupo, tpriv.bditempriv ';
                       FOR EXECUTE STATEMENT wsqlx INTO :bdcodgrupo, :bdcodusu, :bditempriv DO
                           SUSPEND;
                     END
               END
          END
       ELSE
          BEGIN
            -- retorna privilegios do usuario com empresa configurada
            wsql = 'select temp.bdcodemp, temp.bdcodgrupo, tgrp.bdcodusu, tpriv.bditempriv ';
            wsql = wsql||'from tempresa_grupousuario temp ';
            wsql = wsql||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = temp.bdcodgrupo and tgrp.bdcodusu = (select x.bdcodusu from sp_get_usuario x)) ';

            IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
               wsql = wsql||'inner join tprivilegio_grupousuario tpriv on (tpriv.bdcodgrupo = tgrp.bdcodgrupo and (upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||'''))) ';
            ELSE
               wsql = wsql||'inner join tprivilegio_grupousuario tpriv on (tpriv.bdcodgrupo = tgrp.bdcodgrupo ) ';
            IF (wcountusu > 0) THEN
               wsql = wsql||'inner join tempresa_usuario tusu on (tusu.bdcodemp = temp.bdcodemp and tusu.bdcodusu = tgrp.bdcodusu) ';
            IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
               wsql = wsql||'where temp.bdcodemp = '||prcodemp;
            FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodgrupo, :bdcodusu, :bditempriv DO
               SUSPEND;
          END
     END
END
^

/* Alter (SP_ALTERA_PROD_GRID) */
ALTER PROCEDURE SP_ALTERA_PROD_GRID(PRSESSAO INTEGER,
PRCODPRODVINC INTEGER,
PRCODPRODNOVO INTEGER)
 AS
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPRODVINC INTEGER;
DECLARE VARIABLE WCODPRODOUTEMP INTEGER;
DECLARE VARIABLE WCODPRODMSMEMP INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WORIGEM INTEGER;
DECLARE VARIABLE WENTRADA INTEGER;
DECLARE VARIABLE WQTDPRODREL INTEGER;
DECLARE VARIABLE WCODENTRADA VARCHAR(60);
DECLARE VARIABLE WDESCPROD VARCHAR(200);
BEGIN
  /****************************************************************************/
  /*                   Patrick T. S?   06/09/2017 - 19:40                     */
  /*            Altera??o do campo "Produto ?nico na grid com F4              */
  /****************************************************************************/
  wEntrada = 0;
  /*Dados do produto na grid (Que foi pressionado F4)*/
  SELECT T.BDEDITCHAVE, T.BDCODEMP, T.BDORIGEMPROD,
         T.BDCODENTRADA, T.BDDESCPROD, T.BDCODTERLAYOUT
  FROM TMP_TCADPRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODPRODVINC = :PRCODPRODVINC
  INTO :wCodProd, :wCodEmp, :wOrigem,
       :wCodEntrada, :wDescProd, :wCodTer;

  /*Busca se na importa??o existe mais de um produto relacionado ao mesmo c?digo.
    Exemplo: C?digo | Descri??o | C?digo Entrada
               1    |   CAMISA  |   001.001
               1    |   CAMISA  |   001.002
               1    |   CAMISA  |   001.003
    OU banco HHC - Empresa 73 - Chave NFe 41-1708-07.407.774/0001-80-55-001-000.016.396-114.028.665-6
  */
  SELECT COUNT(T.BDEDITCHAVE) BDQTDPRODREL
  FROM TMP_TCADPRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDEDITCHAVE = :wCodProd
  GROUP BY T.BDEDITCHAVE
  INTO :wQtdProdRel;

  /*Verifica se j? tem o produto na empresa*/
  SELECT (SELECT PV.BDCODPROD FROM TCADPRO_VINC PV WHERE PV.BDCODPROD = :PRCODPRODNOVO AND PV.BDCODEMP = :wCodEmp) BDCODPRODVINC, /*Produto na empresa*/
         (SELECT FIRST 1 TMP.BDCODPROD FROM TMP_TCADPRO TMP WHERE TMP.BDEDITCHAVE = :wCodProd AND TMP.BDCODEMP <> :wCodEmp) BDCODPRODOUTEMP, /*Produto em outra empresa*/
         (SELECT PV.BDCODPROD FROM TCADPRO_VINC PV WHERE PV.BDCODPROD = :wCodProd AND PV.BDCODEMP = :wCodEmp) BDCODPRODMSMEMP /*Produto antigo na empresa*/
  FROM RDB$DATABASE
  INTO :wCodProdVinc, :wCodProdOutEmp, :wCodProdMsmEmp;

  /*Produto que o usu?rio digitou j? existe na empresa*/
  IF ((:wCodProdVinc IS NOT NULL) AND (:wCodProdVinc > 0)) THEN
    BEGIN
      /*Somente um produto com o mesmo c?digo na grid*/
      IF (:wQtdProdRel = 1) THEN
        BEGIN
          IF ((:wCodProdMsmEmp IS NULL) OR (:wCodProdMsmEmp = 0)) THEN
            BEGIN
              /*Apaga na TMP_TCADPRO o produto da grid(Somente da empresa)*/
              DELETE FROM TMP_TCADPRO TMP WHERE TMP.BDEDITCHAVE = :wCodprod AND TMP.BDCODEMP = :wCodEmp;

              /*Se for produto de entrada apaga na TMP_TCADPRO_PART tamb?m*/
              IF (:wOrigem = :wEntrada) THEN
                BEGIN
                  DELETE FROM TMP_TCADPRO_PART PT
                  WHERE PT.BDEDITCHAVE = :wCodprod
                  AND PT.BDCODENTRADA = :wCodEntrada
                  AND PT.BDDESCPRODBUSCA = :wDescProd
                  AND PT.BDCODTER = :wCodTer;
                END
            END
        END
      ELSE
        BEGIN
          IF (:wOrigem = :wEntrada) THEN
            BEGIN
              UPDATE TMP_TCADPRO_PART PT
              SET PT.BDEDITCHAVE = :PRCODPRODNOVO,
                  PT.BDCODPROD = :PRCODPRODNOVO,
                  PT.BDORDEM = (COALESCE((SELECT MAX(BDORDEM)+1 FROM TMP_TCADPRO_PART WHERE BDEDITCHAVE = :PRCODPRODNOVO), 1))
              WHERE PT.BDEDITCHAVE = :wCodprod
              AND PT.BDCODENTRADA = :wCodEntrada
              AND PT.BDDESCPRODBUSCA = :wDescProd
              AND PT.BDCODTER = :wCodTer;
            END
        END
    END
  ELSE
    BEGIN /*Est? relacionando com um produto que n?o existe na empresa*/
      IF (:wQtdProdRel = 1) THEN
        BEGIN
          UPDATE TMP_TCADPRO TMP SET TMP.BDEDITCHAVE = :PRCODPRODNOVO, TMP.BDCODPROD = :PRCODPRODNOVO WHERE TMP.BDEDITCHAVE = :wCodProd AND TMP.BDCODEMP = :wCodEmp;

          IF (:wOrigem = :wEntrada) THEN
            BEGIN
              UPDATE TMP_TCADPRO_PART PT
              SET PT.BDEDITCHAVE = :PRCODPRODNOVO,
                  PT.BDCODPROD = :PRCODPRODNOVO,
                  PT.BDORDEM = (COALESCE((SELECT MAX(BDORDEM)+1 FROM TMP_TCADPRO_PART WHERE BDEDITCHAVE = :PRCODPRODNOVO), 1))
              WHERE PT.BDEDITCHAVE = :wCodprod
              AND PT.BDCODENTRADA = :wCodEntrada
              AND PT.BDDESCPRODBUSCA = :wDescProd
              AND PT.BDCODTER = :wCodTer;
            END
        END
      ELSE
        BEGIN
          /*Quando tem mais de um produto com o mesmo c?digo, insere um novo na tmp com o c?digo informado pelo usu?rio*/
          INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDORIGEMPROD, BDCODTERLAYOUT, BDCNPJTERLAYOUT, BDCODEMP, BDCODSAIDA,
                                  BDDESCPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODTIPO, BDCODCOMBANP)
          SELECT FIRST 1 :PRSESSAO, :PRCODPRODNOVO, :PRCODPRODNOVO, TMP.BDORIGEMPROD, TMP.BDCODTERLAYOUT, TMP.BDCNPJTERLAYOUT, TMP.BDCODEMP, TMP.BDCODSAIDA,
                         TMP.BDDESCPROD, TMP.BDAPELIDOUNICO, TMP.BDDESCRICAOUNICA, TMP.BDCODIGOEAN, TMP.BDCODTER, TMP.BDCODENTRADA, TMP.BDCODTIPO,
                         TMP.BDCODCOMBANP
          FROM TMP_TCADPRO TMP
          WHERE TMP.BDEDITCHAVE = :wCodProd
          AND TMP.BDCODEMP = :wCodEmp;

          IF (:wOrigem = :wEntrada) THEN
            BEGIN
              UPDATE TMP_TCADPRO_PART PT
              SET PT.BDEDITCHAVE = :PRCODPRODNOVO,
                  PT.BDCODPROD = :PRCODPRODNOVO,
                  PT.BDORDEM = (COALESCE((SELECT MAX(BDORDEM)+1 FROM TMP_TCADPRO_PART WHERE BDEDITCHAVE = :PRCODPRODNOVO), 1))
              WHERE PT.BDEDITCHAVE = :wCodprod
              AND PT.BDCODENTRADA = :wCodEntrada
              AND PT.BDDESCPRODBUSCA = :wDescProd
              AND PT.BDCODTER = :wCodTer;
            END
        END
    END

  IF (((:wCodProdOutEmp IS NULL) OR (:wCodProdOutEmp = 0)) AND ((:wCodProdMsmEmp IS NULL) OR (:wCodProdMsmEmp = 0))) THEN
    DELETE FROM TMP_TCADPRO TMP WHERE TMP.BDEDITCHAVE = :wCodProd AND ((TMP.BDCODEMP IS NULL) OR (TMP.BDCODEMP = 0));

  UPDATE TMP_TCADPRO_TEMP T
  SET T.BDSITUACAO = 1,
      T.BDPRODEXISTEBASE = 'TRUE',
      T.BDEDITCHAVE = :PRCODPRODNOVO
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODEMP = :wCodEmp
  AND T.BDCODPRODVINC = :PRCODPRODVINC;

  /* ** Produto "N?o Relacionado" ou "Cadastro Autom?tico" ** */

  /*1 - OK
    1 - Troca o produto da empresa e apaga o produto unico(verificar na TMP_TCADPRO e TCADPRO) do que est? sendo importado
        EX: 1 - 'ABC' - Null
            1 - 'ABC' - 73
        Produto digitado no grid(2), deve trocar o vinculado para 2 e apagar o unico.
        Trocar produtos por participante para o produto novo tambem


    ** Produto "Relacionado" **

    1 - V?rios iguais no grid
        Verificar quantos produtos vinculados ao c?digo que est? na grid(olhar na TMP_TCADPRO_TEMP),
        se existir mais de um com o mesmo c?digo de produto
        deve fazer um insert select do produto que esta na grid com o c?digo digitado pelo usu?rio.
        Trocar a TMP_TCADPRO_PART usando como filtro o c?digo de entrada do produto que est? sendo trocado no grid.
    
        **S? um igual na grid e troca para um produto unico**
          Se existir s? um desse produto na grid deve trocar ele na TMP da empresa para o novo produto e
          tambem verificar se n?o existe ele em outras empresas na TMP_TCADPRO e n?o existe na TCADPRO,
          se n?o existir em outras empresas apaga o produto unico. Trocar o TMP_TCADPRO_PART tamb?m atrav?s da TMP_TCADPRO_TEMP

    Quando j? tem o produto na pr?pria empresa
    2 - Verificar se j? tem o produto digitado na empresa, se j? existir,
    apaga oque est? na grid(sendo alterado) na TMP_TCADPRO e TMP_TCADPRO_PART da EMPRESA.
    Ver se n?o est? cadastrado em outra empresa(TMP_TCADPRO e TCADPRO), se n?o estiver deve apagar da TMP_TCADPRO.*/

END
^

/* Alter (SP_APURACAO_BLOCOM) */
ALTER PROCEDURE SP_APURACAO_BLOCOM(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODCONFBLOCOM INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WWHEREEMPRESAS VARCHAR(500);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Obt?m a configura??o do Bloco M...
  SELECT BDCODCONFBLOCOM FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :prCODEMP INTO :wCODCONFBLOCOM;

  -- Quando n?o tiver configura??o de Blooo M na empresa, vai buscar uma configura??o padr?o...
  IF (wCODCONFBLOCOM IS NULL) THEN
    SELECT FIRST 1 BDCODCONF FROM VEF_BASE_TCONFBLOCOM WHERE BDPLANOPADRAO = 'TRUE' INTO :wCODCONFBLOCOM;

  wWhereEmpresas = '';
  /* Cria apura??o do Bloco M, necess?rio para os registros abaixo... */
  FOR
      SELECT ex.BDCODEMP
      FROM TEMPRESAS ex
      WHERE ex.BDCODEMP = :prCODEMP
         OR ex.BDCODMATRIZ = :prCODEMP
      INTO :wCODEMP
  DO
   BEGIN
     INSERT INTO VEF_EMP_TBLOCOMGER (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCONF) VALUES (7, :wCODEMP, :prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM);
     wWhereEmpresas = wWhereEmpresas || wCodEmp || ',';
   END

   wWhereEmpresas = ' bdCODEMP IN(' || SUBSTRING(wWhereEmpresas FROM 1 FOR CHARACTER_LENGTH(wWhereEmpresas) -1) ||') ';

  IF (:wCODCONFBLOCOM IS NOT NULL) THEN
    BEGIN
      /* REGISTRO 0111: TABELA DE RECEITA BRUTA MENSAL PARA FINS DE RATEIO DE CR?DITOS COMUNS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_0110 (:prCODEMP, :prREFERENCIA);

      /* REGISTRO M100: CR?DITO DE PIS/PASEP RELATIVO AO PER?ODO
         REGISTRO M500: CR?DITO DE COFINS RELATIVO AO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100_M500 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO 1100: CONTROLE DE CR?DITOS FISCAIS ? PIS/PASEP
         REGISTRO 1500: CONTROLE DE CR?DITOS FISCAIS ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_1100_1500 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO F600: CONTRIBUI??O RETIDA NA FONTE
         REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
         REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_F60013001700 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO M300: CONTRIBUI??O DE PIS/PASEP DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO.
         REGISTRO M700: COFINS DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M300_M700 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);

      /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP
         REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO
         REGISTRO M600: CONSOLIDA??O DA CONTRIBUI??O PARA A SEGURIDADE SOCIAL - COFINS DO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M200_M600 (:prCODEMP, :prREFERENCIA,:wWhereEmpresas);

      /* Gera ?ltimos ajustes da apura??o */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_DADOSFINAIS (:prCODEMP, :prREFERENCIA);
      
      /* Cria a contabiliza??o */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE (:prCODEMP, :prREFERENCIA);

      /* Apaga os dados das tabelas tempor?rias, faz isso pq se apura-se mais de uma vez, somava todos os valores */
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_0110_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_0111_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_TCONF_CONTAS_ONLINE_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
    END
  ELSE
    BEGIN
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC) VALUES
                                   (7, :prCODEMP, :prCODEMP, :prREFERENCIA,
                                    COALESCE((SELECT MAX(x.BDCODBLOCOM)+1 FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA),1),
                                    NULL, NULL, NULL, NULL, 5);
    END
    
END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM for: SP_APURACAO_BLOCOM_0110 */
ALTER PROCEDURE SP_APURACAO_BLOCOM(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_0110) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_0110(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,2);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,2);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,2);
DECLARE VARIABLE WRBCUM NUMERIC(15,2);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Incid?ncia tribut?ria
  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  -- Obt?m os valores das formulas apuradas
  wSQL =       'SELECT ';
  IF (:wINCTRIB IN (1,3)) THEN
    wSQL = wSQL||'       COALESCE(BDRBNCUMTRIBMI, 0) as BDRBNCUMTRIBMI, COALESCE(BDRBNCUMNTMI, 0) as BDRBNCUMNTMI, COALESCE(BDRBNCUMEXP, 0) as BDRBNCUMEXP, ';
  ELSE
    wSQL = wSQL||'       0 as BDRBNCUMTRIBMI, 0 as BDRBNCUMNTMI, 0 as BDRBNCUMEXP, ';

  IF (:wINCTRIB IN (2,3)) THEN
    wSQL = wSQL||'       COALESCE(BDRBCUM, 0) as BDRBCUM ';
  ELSE
    wSQL = wSQL||'       0 as BDRBCUM ';

  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_0110_TEMP aux ';
  wSQL = wSQL||'WHERE aux.BDCODEMP = '||:prCODEMP;
  wSQL = wSQL||'  AND aux.BDREFERENCIA = '||:prREFERENCIA;

  EXECUTE STATEMENT ( wSQL )
  INTO :wRBNCUMTRIBMI, :wRBNCUMNTMI, :wRBNCUMEXP, :wRBCUM;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 1, COALESCE(:wRBNCUMTRIBMI,0));

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 2, COALESCE(:wRBNCUMNTMI,0));

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 3, COALESCE(:wRBNCUMEXP,0));

  /* 35 - Contribui??o cumulativa */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 35, 1, COALESCE(:wRBCUM,0));

  /* 36 - Contribui??o Total (Valores n?o cumulativos + cumulativos) */
  -- Obt?m os valores das formulas apuradas
  SELECT SUM(BDVALOR)
  FROM VEF_EMP_TBLOCOMGERREG aux
  WHERE (aux.BDCODQUADRO IN (34,35)) /* 34 - Contribui??o n?o cumulativa / 35 - Contribui??o cumulativa */
    AND aux.BDCODEMP = :prCODEMP
    AND aux.BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 36, 1, COALESCE(:wRBNCUMTRIBMI,0));

END
^

/* Alter (SP_APURACAO_BLOCOM_1100_1500) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_1100_1500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDCREDITOSPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wCREDITOSPERANT;

  /* Caso tenha saldos no per?odo anterior a apura??o, vai carregar estes valores para a apura??o atual */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM) ';
  wSQL = wSQL||'SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = aux.BDCODQUADRO AND x.BDCODPERIODO = aux.BDCODPERIODO AND x.BDCODEMP = aux.BDCODEMP AND x.BDREFERENCIA = aux.BDREFERENCIA), ';
  wSQL = wSQL||       'aux.BDCODCRE_4_3_6, aux.BDPER_APU_CRED, aux.BDORIG_CRED, aux.BDCNPJ_SUC, ';
  wSQL = wSQL||       'SUM(COALESCE(aux.BDVL_CRED_APU,0)) as BDVL_CRED_APU, SUM(COALESCE(aux.BDVL_CRED_DESC_EFD,0)) as BDVL_CRED_DESC_EFD, SUM(COALESCE(aux.BDSLD_CRED_FIM,0)) as BDSLD_CRED_FIM ';
  wSQL = wSQL||'FROM ( ';
  --IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
    BEGIN
                         /* Saldos periodos anteriores a apura??o */
      wSQL = wSQL||      'SELECT m.BDCODQUADRO, m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, m.BDCODCRE_4_3_6, m.BDPER_APU_CRED, m.BDORIG_CRED, ';
      wSQL = wSQL||             'm.BDCNPJ_SUC, m.BDSLD_CRED_FIM AS BDVL_CRED_APU, 0 AS BDVL_CRED_DESC_EFD, m.BDSLD_CRED_FIM ';
      wSQL = wSQL||      'FROM VEF_EMP_TBLOCOM1100_1500 m ';
      wSQL = wSQL||      'WHERE (m.BDCODMATRIZ = '||:prCODEMP||') ';
      wSQL = wSQL||        'AND (m.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA ';
      wSQL = wSQL||                               'FROM VEF_EMP_TBLOCOM1100_1500 x ';
      wSQL = wSQL||                               'WHERE x.BDCODEMP = '||:prCODEMP||' ';
      wSQL = wSQL||                                 'AND x.BDREFERENCIA < '||:prREFERENCIA||' ';
      wSQL = wSQL||                                'ORDER BY x.BDREFERENCIA DESC)) ';
      wSQL = wSQL||        'AND m.BDSLD_CRED_FIM > 0 ';
    
      wSQL = wSQL||      'UNION ALL ';
    END
                     /* Saldos de PIS lan?ados */
  wSQL = wSQL||      'SELECT 52 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL||             's.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDCODCRE_4_3_6, s.BDREFAPUSALDO as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             's.BDCNPJCEDENTE as BDCNPJ_SUC, s.BDVLRCREPIS as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, s.BDVLRCREPIS as BDSLD_CRED_FIM ';
  wSQL = wSQL||      'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCREPIS > 0 ';

  wSQL = wSQL||      'UNION ALL ';
                     /* Saldos de Cofins lan?ados */
  wSQL = wSQL||      'SELECT 53 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL||             's.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDCODCRE_4_3_6, s.BDREFAPUSALDO as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             's.BDCNPJCEDENTE as BDCNPJ_SUC, s.BDVLRCRECOFINS as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, s.BDVLRCRECOFINS as BDSLD_CRED_FIM ';
  wSQL = wSQL||      'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCRECOFINS > 0 ';

  wSQL = wSQL||      ') aux ';
  wSQL = wSQL||'GROUP BY aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODCRE_4_3_6, ';
  wSQL = wSQL||         'aux.BDPER_APU_CRED, aux.BDORIG_CRED, aux.BDCNPJ_SUC';

  EXECUTE STATEMENT ( wSQL );
        
END
^

/* Alter (SP_APURACAO_BLOCOM_CONTABILIZAR) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_CONTABILIZAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRULTCHAVE INTEGER,
PRUSUARIO INTEGER,
PRULTTRANSACAO INTEGER)
 AS
BEGIN
  -- Atualiza as chaves da contabiliza??o...
  UPDATE TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  SET t.bdCHAVE = :prULTCHAVE-COALESCE((SELECT COUNT(1)
                                        FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP x
                                        WHERE x.bdCHAVE IS NULL
                                          AND x.bdCODMATRIZ = :prCODEMP
                                          AND x.bdREFERENCIA = :prREFERENCIA), 1)+1,
      t.bdTRANSACAO = :prULTTRANSACAO-COALESCE((SELECT COUNT(1)
                                                FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP x
                                                WHERE x.bdTRANSACAO IS NULL
                                                  AND x.bdCODMATRIZ = :prCODEMP
                                                  AND x.bdREFERENCIA = :prREFERENCIA), 1)+1
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA;

  -- Caso a data esteja "NULL", poem ela no primeiro dia da refer?ncia...
  UPDATE TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  SET t.bdDATA = CAST(SUBSTRING(t.bdREFERENCIA FROM 5 FOR 2)||'-'||-- M?s
                 CASE -- Dia
                   WHEN (CAST(SUBSTRING(t.bdREFERENCIA FROM 5 FOR 2) as INTEGER) IN (1,3,5,7,8,10,12)) THEN '31-'
                   WHEN (CAST(SUBSTRING(t.bdREFERENCIA FROM 5 FOR 2) as INTEGER) IN (2)) THEN IIF((MOD(CAST(SUBSTRING(t.bdREFERENCIA FROM 1 FOR 4) as INTEGER), 4) = 0),'29-','28-') -- Anos bissexto
                 ELSE '30-'
                 END||
                 SUBSTRING(t.bdREFERENCIA FROM 1 FOR 4) AS DATE) -- Ano
  WHERE t.bdDATA IS NULL
    AND t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA;

  -- Grava a contabiliza??o...
  INSERT INTO VSUC_EMPRESAS_TLAN(bdCODEMP, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, BDDATALANINICIAL, BDHORALANINICIAL)
  SELECT t.bdCODMATRIZ, t.bdCHAVE, t.bdCODPLAPADRAO, :prUSUARIO, t.bdDEBITO, t.bdCREDITO, t.bdCOMPL, t.bdDATA, t.bdVALOR, t.bdTIPOLAN, t.bdDCTO, t.bdTRANSACAO, t.bdTRANFECHADA, t.bdCODTPHI, CURRENT_DATE, CURRENT_TIME
  FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA
  ORDER BY t.bdCODMATRIZ, t.bdCHAVE, t.bdTRANSACAO;

  -- Grava a contabiliza??o...
  INSERT INTO TOL_VEF_EMP_TBLOCOMGER (bdCHAVE, bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA)
  SELECT t.bdCHAVE, 7 as bdCODPERIODO, t.bdCODMATRIZ as bdCODEMP, t.bdCODMATRIZ, t.bdREFERENCIA
  FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA
  ORDER BY t.bdCODMATRIZ, t.bdCHAVE, t.bdTRANSACAO;

  -- Deleta os registros da tabela da contabiliza??o...
  DELETE FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA;

END
^

/* Alter (SP_APURACAO_BLOCOM_DADOSFINAIS) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_DADOSFINAIS(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
BEGIN
  /* Caso tenham "COD_CRED" que tenham sido aproveitados todo cr?dito e n?o tenham gerados registros 1100/1500,
     ? necess?rio pois precisa consolidar estes registros na exporta??o. */
  INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
  SELECT IIF((m.BDCODQUADRO = 11), 52, 53),
         m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE+1), 1)
          FROM VEF_EMP_TBLOCOM1100_1500 x
          WHERE x.BDCODQUADRO = IIF((m.BDCODQUADRO = 11), 52, 53)
            AND x.BDCODPERIODO = m.BDCODPERIODO
            AND x.BDCODEMP = m.BDCODEMP
            AND x.BDCODMATRIZ = m.BDCODMATRIZ
            AND x.BDREFERENCIA = m.BDREFERENCIA),
         m.BDCODCRE_4_3_6, m.BDREFERENCIA, m.BDIND_CRED_ORI, '  .   .   /    -', m.BDVL_CRED_DISP, m.BDVL_CRED_DESC, m.BDSLD_CRED
  FROM VEF_EMP_TBLOCOM100_500 m
  WHERE m.BDCODMATRIZ = :prCODEMP
    AND m.BDREFERENCIA = :prREFERENCIA
    AND (NOT EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM1100_1500 s
                    WHERE s.BDCODEMP = m.BDCODEMP
                      AND s.BDCODMATRIZ = m.BDCODMATRIZ
                      AND s.BDREFERENCIA = m.BDREFERENCIA
                      AND s.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND s.BDORIG_CRED = m.BDIND_CRED_ORI
                      AND s.BDCODQUADRO = IIF((m.BDCODQUADRO = 11), 52, 53) ));

END
^

/* Alter (SP_APURACAO_BLOCOM_F60013001700) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_F60013001700(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WTIPOAPURACAORET INTEGER;
DECLARE VARIABLE WINDNATPJ INTEGER;
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wRETPISCOFPERANT;

  SELECT BDTIPOAPURACAORET FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :prCODEMP
  INTO :wTIPOAPURACAORET;

  SELECT BDINDNATPJ FROM VW_VEF_BASE_TEMPPARFED WHERE BDCODEMP = :prCODEMP
  INTO :wINDNATPJ;

  wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_F600_1300 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDREFAPUSALDO, BDCODTER, BDCNPJEMP, BDDATAEMISSAO, BDVLRCONTAB, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDIND_DEC, BDCODRECPIS, BDCODRECCOFINS, BDVLRPISRET, BDVLRCOFINSRET) ';
                     /* Saldos de PIS e/ou Cofins lan?ados */
  wSQL = wSQL||'SELECT s.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDREFAPUSALDO, 0 as BDCODTER, emp.BDCNPJEMP, ';
  wSQL = wSQL||       'CAST(SUBSTRING(s.BDREFERENCIA from 1 for 4)||''-''|| SUBSTRING(s.BDREFERENCIA from 5 for 2)||''-01'' as date) as BDDATAEMISSAO, ';
  wSQL = wSQL||       '0 as BDVLRCONTAB, s.BDCODIND_NAT_RET, s.BDTIPONATREC, 0 as BDIND_DEC, ';
  wSQL = wSQL||       'null as BDCODRECPIS, null as BDCODRECCOFINS, ';
  wSQL = wSQL||       'COALESCE(s.BDVLRRETPIS, 0) as BDVLRPISRET, COALESCE(s.BDVLRRETCOFINS, 0) as BDVLRCOFINSRET ';
  wSQL = wSQL||'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||'WHERE ((s.BDVLRRETPIS > 0) or (s.BDVLRRETCOFINS > 0)) ';
  wSQL = wSQL||        'AND (s.BDCREDRETIDOS = ''TRUE'') ';
  wSQL = wSQL||        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';

  wSQL = wSQL||'UNION ALL ';

               -- Solicita??o 4962
  wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDREFAPUSALDO, aux.BDCODTER, emp.BDCNPJEMP,  ';
  wSQL = wSQL||       'aux.BDDATAEMISSAO, aux.BDVLRCONTAB, nat.BDCODIND_NAT_RET, aux.BDTIPONATREC, aux.BDIND_DEC, ';
  wSQL = wSQL||       'aux.BDCODRECPIS, aux.BDCODRECCOFINS, aux.BDVLRPISRET, aux.BDVLRCOFINSRET ';
  wSQL = wSQL||'FROM ( ';
                     -- Demais documentos
  wSQL = wSQL||      'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN as BDREFERENCIA, dem.BDREFLAN as BDREFAPUSALDO, dem.BDCODTER, indoper.BDINDICADOR,';
  wSQL = wSQL||             'dem.BDDT_OPER as BDDATAEMISSAO, dem.BDVL_OPER as BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
  wSQL = wSQL||             'ret.BDVLRPIS as BDVLRPISRET, ret.BDVLRCOFINS as BDVLRCOFINSRET,';
  wSQL = wSQL||             'case when dem.BDIND_OPER = 1 then 1 else 0 end as BDIND_DEC '; -- Aquisi??o
  wSQL = wSQL||      'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
  wSQL = wSQL||      'JOIN VEF_BASE_TAB_TIPO_OPERACAO indoper on (indoper.BDIND_OPER = dem.BDIND_OPER) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
  wSQL = wSQL||      'WHERE dem.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND (CAST(SUBSTRING(dem.BDDT_OPER FROM 1 for 4)||SUBSTRING(dem.BDDT_OPER FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
    
  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||        'AND (dem.BDCONDPGTO <> 1) ';
    
  -- Caso incid?ncia tribut?ria 2 = regime cumulativo. Sped lucro presumido somente os lan?amentos de saidas(receitas) ent?o somente os lan?amentos com tipos 1 e 2.
  IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente aquisi??o e receita n?o sujeita ao pagamento de contribui??o
    wSQL = wSQL||        'AND (dem.BDIND_OPER <> 0) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||      'UNION ALL ';
                         -- Demais documentos - Pagamentos
      wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(EMP.BDCODMATRIZ, MOV.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, indoper.BDINDICADOR,';
      wSQL = wSQL||             'pgto.BDDATAPGTOPAR as BDDATAEMISSAO,';
      wSQL = wSQL||             '((pgto.BDVALORPGTOPAR)+';
      wSQL = wSQL||              '(COALESCE(pgto.BDVALORRETPIS, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCOFINS,0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCSLL, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETIRRF, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETISSQN, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETINSS, 0))) as BDVLRCONTAB,';
      wSQL = wSQL||             'ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
      wSQL = wSQL||             'pgto.BDVALORRETPIS as BDVLRPISRET, pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||             'case when mov.BDIND_OPER = 1 then 1 else 0 end as BDIND_DEC '; -- Aquisi??o
      wSQL = wSQL||      'FROM (';
      wSQL = wSQL||            'SELECT * ';
      wSQL = wSQL||            'FROM ( ';
      wSQL = wSQL||                  'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDIND_OPER, x.BDCODCSTPIS, x.BDCODCSTCOF ';
      wSQL = wSQL||                  'FROM VEF_EMP_TMOVDEMAISDOC_F100 x ';
      wSQL = wSQL||                  'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente aquisi??o e receita n?o sujeita ao pagamento de contribui??o
        wSQL = wSQL||                   'AND (x.BDIND_OPER <> 0) ';
      wSQL = wSQL||                  ') aux ';
      wSQL = wSQL||            'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                     'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||            ') mov ';
      wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVF100PARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||      'JOIN VEF_BASE_TAB_TIPO_OPERACAO INDOPER on (indoper.BDIND_OPER = mov.BDIND_OPER) ';
      wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = mov.BDCODEMP and ret.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||      'WHERE ((mov.BDCODCSTPIS is not null) or (mov.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||        'AND (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||        'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||      'UNION ALL ';
                     -- Lan?amentos de compensa??o de reten??es de servi?os emitidos
  wSQL = wSQL||      'SELECT ret.BDCODEMP, COALESCE(emp.BDCODMATRIZ, ret.BDCODEMP) as BDCODMATRIZ, ret.BDREFERENCIA, ret.BDREFERENCIA as BDREFAPUSALDO, ret.BDCODTER, ';
  wSQL = wSQL||             '0 AS BDINDICADOR, ret.BDDATALAN AS BDDATAEMISSAO, ret.BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             '0 as BDIND_DEC ';
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT r.BDCODEMP, r.BDCODTER, r.BDREFLAN AS BDREFERENCIA, r.BDDATALAN, r.BDVLRCONTAB, r.BDCODIND_NAT_RET, r.BDCODRECPIS, ';
  wSQL = wSQL||                   'r.BDCODRECCOFINS, r.BDVLRPIS, r.BDVLRCOFINS, r.BDTIPONATREC ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVCOMPRET r ';
  wSQL = wSQL||            'WHERE r.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (CAST(SUBSTRING(r.BDDATALAN FROM 1 for 4)||SUBSTRING(r.BDDATALAN FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
  wSQL = wSQL||            ') ret ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = ret.BDCODEMP) ';

  wSQL = wSQL||      'UNION ALL ';
                     -- Servi?o
  wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFERENCIA, mov.BDREFERENCIA as BDREFAPUSALDO, mov.BDCODTER, ';
  wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, mov.BDDATAEMISSAO, mov.BDVALORNOTA AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             'case when mov.BDTIPLAN = 1 then 1 else 0 end as BDIND_DEC '; -- Recebidos
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT ser.BDCODEMP, ser.BDCHAVE, ser.BDCODTER, ser.BDDATAEMISSAO, ser.BDVALORNOTA, ser.BDTIPLAN, ser.BDREFLAN AS BDREFERENCIA ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVSER ser ';
  wSQL = wSQL||            'WHERE ser.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (ser.BDREFLAN = '||:prREFERENCIA||') ';
  wSQL = wSQL||              'AND (ser.BDCODSITNF not in (2,3,4,5)) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
  -- caso incid?ncia tribut?ria 2 = regime cumulativo, exportar somente emitidos
  IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente servi?os emitidos
    wSQL = wSQL||              'AND (ser.BDTIPLAN = 0) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||              'AND (ser.BDCONDPGTO <> 1) ';

  wSQL = wSQL||            ') mov ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSERRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||      'UNION ALL ';
     
      wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, ';
      wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, pgto.BDDATAPGTOPAR as BDDATAEMISSAO, ';
      wSQL = wSQL||             '((pgto.BDVALORPGTOPAR)+ ';
      wSQL = wSQL||              '(COALESCE(pgto.BDVALORRETPIS,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
      wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ';
      wSQL = wSQL||             'pgto.BDVALORRETPIS as BDVLRPISRET,';
      wSQL = wSQL||             'pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||             'case when mov.BDTIPLAN = 1 then 1 else 0 end as BDIND_DEC '; -- Recebidos
      wSQL = wSQL||      'FROM ( ';
      wSQL = wSQL||            'SELECT * ';
      wSQL = wSQL||            'FROM ( ';
      wSQL = wSQL||                  'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDTIPLAN, x.BDCODSITNF, x.BDDATAEMISSAO ';
      wSQL = wSQL||                  'FROM VEF_EMP_TMOVSER x ';
      wSQL = wSQL||                  'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente servi?os emitidos
        wSQL = wSQL||                    'AND (x.BDTIPLAN = 0) ';
      wSQL = wSQL||                  ') aux ';
    
      wSQL = wSQL||            'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                    'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND aux.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
      wSQL = wSQL||           ') mov ';
      wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERPARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||      'WHERE (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||        'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||      'UNION ALL ';
                     -- Sa?das
  wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFERENCIA, mov.BDREFERENCIA as BDREFAPUSALDO, mov.BDCODTER, ';
  wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, mov.BDDATAEMISSAO, mov.BDVALORNOTA AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             '0 as BDIND_DEC ';
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT sai.BDCODEMP, sai.BDCHAVE, sai.BDCODTER, sai.BDDATAEMISSAO, sai.BDVALORNOTA, sai.BDTIPLAN, sai.BDREFLAN AS BDREFERENCIA ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVSAI sai ';
  wSQL = wSQL||            'WHERE sai.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (CAST(SUBSTRING(sai.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(sai.BDDATAEMISSAO FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
  wSQL = wSQL||              'AND sai.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||              'AND (sai.BDCONDPGTO <> 1) ';

  wSQL = wSQL||            ') mov ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSAIRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||            'UNION ALL ';
    
      wSQL = wSQL||            'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, ';
      wSQL = wSQL||                   'mov.BDTIPLAN AS BDINDICADOR, pgto.BDDATAPGTOPAR as BDDATAEMISSAO, ';
      wSQL = wSQL||                   '((pgto.BDVALORPGTOPAR)+ ';
      wSQL = wSQL||                    '(COALESCE(pgto.BDVALORRETPIS,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
      wSQL = wSQL||                   'ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
      wSQL = wSQL||                   'pgto.BDVALORRETPIS as BDVLRPISRET,';
      wSQL = wSQL||                   'pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||                   '0 as BDIND_DEC ';
      wSQL = wSQL||             'FROM ( ';
      wSQL = wSQL||                   'SELECT * ';
      wSQL = wSQL||                   'FROM ( ';
      wSQL = wSQL||                          'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDTIPLAN, x.BDCODSITNF, x.BDDATAEMISSAO ';
      wSQL = wSQL||                          'FROM VEF_EMP_TMOVSAI x ';
      wSQL = wSQL||                          'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                         ') aux ';
      wSQL = wSQL||                   'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                           'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||                     'AND aux.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
    
      wSQL = wSQL||                 ') mov ';
      wSQL = wSQL||            'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIPARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||            'WHERE (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||              'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||    ') aux ';
  wSQL = wSQL||'JOIN TEMPRESAS emp on (aux.BDCODEMP = emp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TIND_NAT_RET nat on (nat.BDCODIND_NAT_RET = aux.BDCODIND_NAT_RET) ';
  wSQL = wSQL||'LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.BDCODTER = aux.BDCODTER) ';
  wSQL = wSQL||'WHERE (nat.BDREGEXP in (''01'',''02'',''03'',''04'',''05'',''99'')) ';
  wSQL = wSQL||' AND (CHAR_LENGTH(ter.BDCGCTER) >= 18) ';
  --wSQL = wSQL||'ORDER BY aux.BDCODMATRIZ, aux.BDCODEMP ';

  EXECUTE STATEMENT ( wSQL );

  -- REGISTRO F600: CONTRIBUI??O RETIDA NA FONTE
  INSERT INTO VEF_EMP_TBLOCOMF600 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODREC, BDCODIND_NAT_RET, BDDT_RET, BDVL_BC_RET, BDVL_RET, BDCNPJPART, BDNOMEPART, BDVL_RET_PIS, BDVL_RET_COFINS, BDIND_DEC, BDIND_NAT_REC)
  SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOMF600 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = aux.BDCODMATRIZ AND x.BDCODQUADRO = 48 AND x.BDREFERENCIA = aux.BDREFERENCIA) AS BDCHAVE,
         aux.BDCODREC,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN aux.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE aux.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         aux.BDCODIND_NAT_RET,
         aux.BDDT_RET,
         SUM(aux.BDVL_BC_RET) AS BDVL_BC_RET, SUM(aux.BDVL_RET) AS BDVL_RET,
         ter.BDCGCTER AS BDCNPJPART, ter.BDNOME AS BDNOMEPART,
         SUM(aux.BDVL_RET_PIS) AS BDVL_RET_PIS, SUM(aux.BDVL_RET_COFINS) AS BDVL_RET_COFINS,
         aux.BDIND_DEC, aux.BDCOD_NAT_REC AS BDIND_NAT_REC
  FROM (-- PIS
        SELECT 48 AS BDCODQUADRO, 7 AS BDCODPERIODO,
               tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODTER, tmp.BDCODRECPIS AS BDCODREC, tmp.BDCODIND_NAT_RET, tmp.BDDATAEMISSAO AS BDDT_RET,
               tmp.BDVLRCONTAB AS BDVL_BC_RET, tmp.BDVLRPISRET AS BDVL_RET, tmp.BDVLRPISRET AS BDVL_RET_PIS, 0 AS BDVL_RET_COFINS, tmp.BDIND_DEC, tmp.BDCOD_NAT_REC
        FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
        WHERE tmp.BDCODRECPIS IS NOT NULL
          AND tmp.BDVLRPISRET IS NOT NULL
          AND tmp.BDCODMATRIZ = :prCODEMP
          AND tmp.BDREFERENCIA = :prREFERENCIA
        UNION ALL
        -- COFINS
        SELECT 48 AS BDCODQUADRO, 7 AS BDCODPERIODO,
               tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODTER, tmp.BDCODRECCOFINS AS BDCODREC, tmp.BDCODIND_NAT_RET, tmp.BDDATAEMISSAO AS BDDT_RET,
               IIF((tmp.BDCODRECPIS = tmp.BDCODRECCOFINS), 0, tmp.BDVLRCONTAB) AS BDVL_BC_RET, -- Caso seja mesmo c?digo de receita, j? trouxe o valor no PIS, da? n?o soma novamente aqui...
               tmp.BDVLRCOFINSRET AS BDVL_RET, 0 AS BDVL_RET_PIS, tmp.BDVLRCOFINSRET AS BDVL_RET_COFINS, tmp.BDIND_DEC, tmp.BDCOD_NAT_REC
        FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
        WHERE tmp.BDCODRECCOFINS IS NOT NULL
          AND tmp.BDVLRCOFINSRET IS NOT NULL
          AND tmp.BDCODMATRIZ = :prCODEMP
          AND tmp.BDREFERENCIA = :prREFERENCIA
        ) aux
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.BDCODTER = aux.BDCODTER)
  WHERE aux.BDCODMATRIZ = :prCODEMP
    AND aux.BDREFERENCIA = :prREFERENCIA
  GROUP BY aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODREC,
           aux.BDCODIND_NAT_RET, aux.BDDT_RET, aux.BDIND_DEC, aux.BDCOD_NAT_REC, ter.BDCGCTER, ter.BDNOME;

  /* Saldos de reten??es de per?odos anteriores */
  --IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Verifica o par?metro "Aproveitar AS reten??es de PIS e Cofins de per?odos anteriores", caso n?o esteja habilita, apenas busca a reten??o atual...
    BEGIN 
      -- REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
      -- REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS
      INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
      SELECT ant.BDCODQUADRO, ant.BDCODPERIODO, ant.BDCODEMP, ant.BDCODMATRIZ, :prREFERENCIA as BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1)
              FROM VEF_EMP_TBLOCOM1300_1700 x
              WHERE x.BDCODPERIODO = ant.BDCODPERIODO
                AND x.BDCODEMP = ant.BDCODEMP
                AND x.BDCODMATRIZ = ant.BDCODMATRIZ
                AND x.BDCODQUADRO = ant.BDCODQUADRO
                AND x.BDREFERENCIA = :prREFERENCIA ) AS BDCHAVE,
             ant.BDCODIND_NAT_RET, ant.BDCOD_NAT_REC, ant.BDPR_REC_RET, ant.BDSLD_RET as BDVL_RET_APU, 0 as BDVL_RET_DED, 0 as BDVL_RET_PER, 0 as BDVL_RET_DCOMP, ant.BDSLD_RET as BDSLD_RET
      FROM VEF_EMP_TBLOCOM1300_1700 ant
      WHERE ant.BDSLD_RET > 0
        AND ant.BDCODMATRIZ = :prCODEMP
        AND ant.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA
                                FROM VEF_EMP_TBLOCOM1300_1700 x
                                WHERE x.BDCODMATRIZ = :prCODEMP
                                  AND x.BDREFERENCIA < :prREFERENCIA
                                  AND x.BDCODPERIODO = 7
                                ORDER BY x.BDREFERENCIA DESC);
    END

  -- REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
  INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
  SELECT 49 AS BDCODQUADRO, 7 AS BDCODPERIODO,
         tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM1300_1700 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDCODQUADRO = 49 AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCHAVE,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN tmp.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE tmp.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         tmp.BDCODIND_NAT_RET,
         tmp.BDCOD_NAT_REC,
         --(CAST(SUBSTRING(tmp.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(tmp.BDDATAEMISSAO FROM 6 for 2) AS INTEGER)) AS BDPR_REC_RET,
         tmp.BDREFAPUSALDO AS BDPR_REC_RET,
         SUM(COALESCE(tmp.BDVLRPISRET, 0)) AS BDVL_RET_APU,
         0 AS BDVL_RET_DED,
         0 AS BDVL_RET_PER, 0 AS BDVL_RET_DCOMP, SUM(COALESCE(tmp.BDVLRPISRET,0)) AS BDSLD_RET
  FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
  WHERE tmp.BDCODMATRIZ = :prCODEMP
    AND tmp.BDREFERENCIA = :prREFERENCIA
    AND tmp.BDVLRPISRET > 0
  GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODIND_NAT_RET, tmp.BDCOD_NAT_REC, tmp.BDDATAEMISSAO, tmp.BDREFAPUSALDO;

  -- REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS
  INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
  SELECT 50 AS BDCODQUADRO, 7 AS BDCODPERIODO,
         tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM1300_1700 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDCODQUADRO = 50 AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCHAVE,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN tmp.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE tmp.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         tmp.BDCODIND_NAT_RET,
         tmp.BDCOD_NAT_REC,
         --(CAST(SUBSTRING(tmp.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(tmp.BDDATAEMISSAO FROM 6 for 2) AS INTEGER)) AS BDPR_REC_RET,
         tmp.BDREFAPUSALDO AS BDPR_REC_RET,
         SUM(COALESCE(tmp.BDVLRCOFINSRET,0)) AS BDVL_RET_APU,
         0 AS BDVL_RET_DED,
         0 AS BDVL_RET_PER, 0 AS BDVL_RET_DCOMP, SUM(COALESCE(tmp.BDVLRCOFINSRET,0)) AS BDSLD_RET
  FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
  WHERE tmp.BDCODMATRIZ = :prCODEMP
    AND tmp.BDREFERENCIA = :prREFERENCIA
    AND tmp.BDVLRCOFINSRET > 0
  GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODIND_NAT_RET, tmp.BDCOD_NAT_REC, tmp.BDDATAEMISSAO, tmp.BDREFAPUSALDO;

END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M100_M500 for: SP_APURACAO_BLOCOM_M100 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_M100) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WMETODOAPRO INTEGER;
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,4);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configura??o da empresa na refer?ncia da apura??o...
  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDMETODOAPRO+1 -- M?todo de apropria??o
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 1
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 2
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMNTMI;

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 3
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMEXP;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      /* REGISTRO M100: CR?DITO DE PIS/PASEP RELATIVO AO PER?ODO */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM100_500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDIND_CRED_ORI, BDVL_BC, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CRED,';
      wSQL = wSQL||                                    'BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CRED_DIF, BDVL_CRED_DISP, BDIND_DESC_CRED, BDVL_CRED_DESC, BDSLD_CRED) ';
      wSQL = wSQL||'SELECT 11 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7) AS BDCHAVE,';
      wSQL = wSQL||       't436.BDCODCRE_4_3_6, 0 AS BDIND_CRED_ORI, SUM(COALESCE(tmp.BDBCPIS,0)) AS BDVL_BC, COALESCE(tmp.BDALIQPIS,0) AS BDALIQ,';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC, COALESCE(tmp.BDALIQPIS_QUANT,0) AS BDALIQ_QUANT,';
      wSQL = wSQL||       '(((SUM(COALESCE(tmp.BDBCPIS,0))*COALESCE(tmp.BDALIQPIS,1))/100)+(SUM(COALESCE(tmp.BDBCPIS_QUANT,0))*COALESCE(tmp.BDALIQPIS_QUANT,1))) AS BDVL_CRED,';
      wSQL = wSQL||       '0 AS BDVL_AJUS_ACRES, 0 AS BDVL_AJUS_REDUC, 0 AS BDVL_CRED_DIF, 0 AS BDVL_CRED_DISP,';
      wSQL = wSQL||       'NULL AS BDIND_DESC_CRED, 0 AS BDVL_CRED_DESC, 0 AS BDSLD_CRED ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED,';
      wSQL = wSQL||             'x.BDALIQPIS,';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT,';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT,';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED,';
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||            'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100  AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCPIS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
          wSQL = wSQL||             'x.BDCOD_CRED as BDCOD_CRED,';
          wSQL = wSQL||             'x.BDBCPIS ';
        END
      wSQL = wSQL||             'AS BDBCPIS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTPIS and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';
      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCPIS > 0) OR (tmp.BDBCPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQPIS > 0) OR (tmp.BDALIQPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ')';
      wSQL = wSQL||       ') ';
      --wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, t436.BDCODCRE_4_3_6, tmp.BDALIQPIS, tmp.BDALIQPIS_QUANT; ';

      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M105: DETALHAMENTO DA BASE DE CALCULO DO CR?DITO APURADO NO PER?ODO ? PIS/PASEP */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM105_M505 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCSTPIS, BDCODCSTCOF, BDCODNATBC, BDCODCRE_4_3_6,';
      wSQL = wSQL||                                     'BDVL_BC_TOT, BDVL_BC_CUM, BDVL_BC_NC, BDVL_BC, BDQUANT_BC_TOT, BDQUANT_BC, BDDESC_CRED, BDALIQ) ';
      wSQL = wSQL||'SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 11 AS BDCODQUADRO, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQPIS) OR (x.BDALIQ_QUANT = tmp.BDALIQPIS_QUANT))) AS BDCHAVE,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDORDEM)+1,1)';
      wSQL = wSQL||        'FROM VEF_EMP_TBLOCOM105_M505 x ';
      wSQL = wSQL||        'WHERE x.BDCODPERIODO = 7 ';
      wSQL = wSQL||          'AND x.BDCODEMP = tmp.BDCODEMP ';
      wSQL = wSQL||          'AND x.BDCODMATRIZ = tmp.BDCODMATRIZ ';
      wSQL = wSQL||          'AND x.BDCODQUADRO = 11 ';
      wSQL = wSQL||          'AND x.BDREFERENCIA = tmp.BDREFERENCIA ';
      wSQL = wSQL||          'AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 ';
      wSQL = wSQL||          'AND x.BDALIQ = COALESCE(tmp.BDALIQPIS,tmp.BDALIQPIS_QUANT) ';
      wSQL = wSQL||          'AND x.BDCHAVE = (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQPIS) OR (x.BDALIQ_QUANT = tmp.BDALIQPIS_QUANT))) ';
      wSQL = wSQL||        ') AS BDORDEM, ';
      wSQL = wSQL||       'tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED AS BDCODNATBC, t436.BDCODCRE_4_3_6, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPISTOTAL,0)) AS BDVL_BC_TOT, 0 AS BDVL_BC_CUM, /*(Campo 04 ? Campo 05)*/SUM(COALESCE(tmp.BDBCPISTOTAL,0)-0) AS BDVL_BC_NC, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPIS,0)) AS BDVL_BC, SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC_TOT,  SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC, NULL AS BDDESC_CRED, COALESCE(tmp.BDALIQPIS,tmp.BDALIQPIS_QUANT,0) AS BDALIQ ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED, ';
      wSQL = wSQL||             'x.BDALIQPIS, x.BDBCPIS as BDBCPISTOTAL, ';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT, ';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT, ';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED,';
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||            'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100  AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCPIS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
          wSQL = wSQL||             'x.BDCOD_CRED as BDCOD_CRED, ';
          wSQL = wSQL||             'x.BDBCPIS ';
        END
      wSQL = wSQL||             'AS BDBCPIS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTPIS and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';
      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCPIS > 0) OR (tmp.BDBCPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQPIS > 0) OR (tmp.BDALIQPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED, t436.BDCODCRE_4_3_6, tmp.BDALIQPIS, tmp.BDALIQPIS_QUANT; ';

      EXECUTE STATEMENT ( wSQL );
   
      /* REGISTRO M110: AJUSTES DO CR?DITO DE PIS/PASEP APURADO */
      INSERT INTO VEF_EMP_TBLOCOM110_M510 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, BDDESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) as BDCODMATRIZ, 11 as BDCODQUADRO, m.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = m.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) AND x.BDCODQUADRO = 11 AND x.BDREFERENCIA = m.BDREFERENCIA AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6 AND ((x.BDALIQ = m.BDALIQPIS) OR (x.BDALIQ_QUANT = m.BDALIQPIS))) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM+1),1)
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 11
                AND x.BDCODEMP = m.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                AND x.BDREFERENCIA = m.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM100_500 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODQUADRO = 11 
                                   AND x.BDCODEMP = m.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                                   AND x.BDREFERENCIA = m.BDREFERENCIA
                                   AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                                   AND ((x.BDALIQ = m.BDALIQPIS) OR (x.BDALIQ_QUANT = m.BDALIQPIS))) ) as BDORDEM,
             m.BDCODAJUEFDC, m.BDTIPOAJUSTE as BDIND_AJ, SUM(m.BDVLRAJUPIS) as BDVL_AJ, m.BDNUMERODOC as BDNUM_DOC, m.BDDESCRICAO as BDDESCR_AJ, m.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TCREDAJU_M110_M510 m
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m.BDCODEMP)
      WHERE m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM100_500 m100
                    WHERE m100.BDCODPERIODO = 7
                      AND m100.BDCODQUADRO = 11
                      AND m100.BDCODEMP = m.BDCODEMP
                      AND m100.BDREFERENCIA = m.BDREFERENCIA
                      AND m100.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND ((m100.BDALIQ = m.BDALIQPIS) OR (m100.BDALIQ_QUANT = m.BDALIQPIS)) ))
      GROUP BY m.BDCODEMP, emp.BDCODMATRIZ, m.BDREFERENCIA, m.BDCODAJUEFDC, m.BDTIPOAJUSTE, m.BDNUMERODOC, m.BDDESCRICAO, m.BDDATAREF, m.BDCODCRE_4_3_6, m.BDALIQPIS;
   
      /* REGISTRO M115: DETALHAMENTO DOS AJUSTES DO CR?DITO DE PIS/PASEP APURADO */
      INSERT INTO VEF_EMP_TBLOCOM115_M515 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM15, BDCODCSTCOF, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m115.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP) as BDCODMATRIZ, 11 as BDCODQUADRO, m110.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDCODQUADRO = 11
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDNUM_DOC = m110.BDNUMERODOC
                AND x.BDDESCR_AJ = m110.BDDESCRICAO
                AND x.BDDT_REF = m110.BDDATAREF ) as BDCHAVE,
             (SELECT x.BDORDEM
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDCODQUADRO = 11
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDNUM_DOC = m110.BDNUMERODOC
                AND x.BDDESCR_AJ = m110.BDDESCRICAO
                AND x.BDDT_REF = m110.BDDATAREF ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM15+1),1)
              FROM VEF_EMP_TBLOCOM115_M515 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 11
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m115.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                                   AND x.BDCODQUADRO = 11
                                   AND x.BDREFERENCIA = m110.BDREFERENCIA
                                   AND x.BDNUM_DOC = m110.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m110.BDDESCRICAO
                                   AND x.BDDT_REF = m110.BDDATAREF)
                AND x.BDORDEM = (SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m115.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                                   AND x.BDCODQUADRO = 11
                                   AND x.BDREFERENCIA = m110.BDREFERENCIA
                                   AND x.BDNUM_DOC = m110.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m110.BDDESCRICAO
                                   AND x.BDDT_REF = m110.BDDATAREF) ) as BDORDEM15,
             m115.BDCODCSTCOF, m115.BDCODCSTPIS, m115.BDCODPLAPADRAO, m115.BDCODTPLA, SUM(m110.BDVLRAJUPIS) as BDDET_VALOR_AJ, SUM(m115.BDBCPIS) as BDDET_BC_CRED,
             m115.BDALIQPIS as BDDET_ALIQ, m115.BDDATAOPEPIS as BDDT_OPER_AJ, m115.BDDESCRICAOAJU as BDDESC_AJ, m115.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TCREDAJU_M110_M510 m110
      JOIN VEF_EMP_TDETAJU_M115_M515 m115 on (m115.BDCODEMP = m110.BDCODEMP AND m115.BDCHAVE = m110.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m110.BDCODEMP)
      WHERE m115.BDCODEMP IS NOT NULL
        AND m115.BDBCPIS > 0
        AND m110.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m110.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM110_M510 x
                    WHERE x.BDCODPERIODO = 7
                      AND x.BDCODEMP = m115.BDCODEMP
                      AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                      AND x.BDCODQUADRO = 11
                      AND x.BDREFERENCIA = m110.BDREFERENCIA
                      AND x.BDNUM_DOC = m110.BDNUMERODOC
                      AND x.BDDESCR_AJ = m110.BDDESCRICAO
                      AND x.BDDT_REF = m110.BDDATAREF ))
      GROUP BY m115.BDCODEMP, emp.BDCODMATRIZ, m110.BDREFERENCIA, m110.BDCODCRE_4_3_6,  m115.BDCODCSTCOF, m115.BDCODCSTPIS, m115.BDCODPLAPADRAO, m115.BDCODTPLA,
               m115.BDALIQPIS, m115.BDDATAOPEPIS, m115.BDDESCRICAOAJU, m115.BDINFCOMP,
               m110.BDNUMERODOC, m110.BDDESCRICAO, m110.BDDATAREF;
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M100_M500) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WMETODOAPRO INTEGER;
DECLARE VARIABLE WRBNCUMTRIBMI VARCHAR(10000);
DECLARE VARIABLE WRBNCUMNTMI VARCHAR(10000);
DECLARE VARIABLE WRBNCUMEXP VARCHAR(10000);
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCRE_4_3_6 INTEGER;
DECLARE VARIABLE WALIQ NUMERIC(7,4);
DECLARE VARIABLE WQTD INTEGER;
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configura??o da empresa na refer?ncia da apura??o...
  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDMETODOAPRO+1 -- M?todo de apropria??o
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  /* 34 - Contribui??o n?o cumulativa */
  SELECT BDRBNCUMTRIBMI, /* Tributada no mercado interno */
         BDRBNCUMNTMI,   /* N?o Tributada no mercado interno */
         BDRBNCUMEXP     /* Exporta??o */
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wRBNCUMTRIBMI, :wRBNCUMNTMI, :wRBNCUMEXP;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      -- Preenche a tabela tempor?ria numa SP auxiliar...
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100_M500AUX(:prCODEMP, :prREFERENCIA,:prWHEREEMPRESAS);

      /* Lan?amentos com CSTs de rateio sem tem cofingura??o de rateio preparada. #Inconsist?ncias# */
      SELECT COUNT(*)
      FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp
      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF)
      WHERE ((cstpis.BDCSTPIS IN ('53','54','55','56','63','64','65','66')) OR
             (cstcof.BDCSTCOF IN ('53','54','55','56','63','64','65','66')))
      INTO :wQTD;

      IF (((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) AND -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
          (:wQTD >= 1) AND -- Existem lan?amentos com AS CSTs de rateio, mas n?o tem as configura??es de rateio preparadas...
          (((:wRBNCUMTRIBMI IS NULL) OR (:wRBNCUMTRIBMI = '')) OR  -- Tributada no Mercado Interno
           ((:wRBNCUMNTMI IS NULL) OR (:wRBNCUMNTMI = '')) OR    -- N?o Tributada no Mercado Interno
           ((:wRBNCUMEXP IS NULL) OR (:wRBNCUMEXP = '')) )) THEN -- Exporta??o
        BEGIN
          INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC) VALUES
                 (7, :prCODEMP, :prCODEMP, :prREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA), NULL, NULL, NULL, NULL, 1);
        END
      ELSE
        BEGIN
          /* REGISTRO M100: CR?DITO DE PIS/PASEP RELATIVO AO PER?ODO */
          EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100 (:prCODEMP, :prREFERENCIA);
    
          /* REGISTRO M500: CR?DITO DE COFINS RELATIVO AO PER?ODO */
          EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M500 (:prCODEMP, :prREFERENCIA);
        END

      /* Atualiza os valores ap?s inserir, n?o faz no INSERT/SELECT acima para n?o matriciar */
      FOR
          SELECT x.BDCODPERIODO, x.BDCODEMP, x.BDCODMATRIZ, x.BDCODQUADRO, x.BDREFERENCIA, x.BDCHAVE, x.BDCODCRE_4_3_6, x.BDALIQ
          FROM VEF_EMP_TBLOCOM100_500 x
          WHERE x.BDCODMATRIZ = :prCODEMP
            AND x.BDREFERENCIA = :prREFERENCIA
          INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCODCRE_4_3_6, :wALIQ
      DO
        BEGIN
          /* Verifica o quadros para pegar os campos corretos, PIS ou Cofins */
          /* Quando alterar os SELECTs dos campos, n?o esquecer de atualizar os SELECTs dos campos 12 e 14... */
          UPDATE VEF_EMP_TBLOCOM100_500 x
          SET -- 09 - VL_AJUS_ACRES - Valor total dos ajustes de acr?scimo
              x.BDVL_AJUS_ACRES = (COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 1 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0)),
              -- 10 - VL_AJUS_REDUC - Valor total dos ajustes de redu??o
              x.BDVL_AJUS_REDUC = (COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 0 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0)),
              -- 11 - VL_CRED_DIF - Valor total do cr?dito diferido no per?od
              x.BDVL_CRED_DIF   = (COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRCREDEFPIS,0), COALESCE(x.BDVLRCREDEPCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 x WHERE x.BDCODEMP =:wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6  AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0)),
              -- 12 - VL_CRED_DISP - Valor Total do Cr?dito Dispon?vel relativo ao Per?odo (08 + 09 ? 10 ? 11)
              x.BDVL_CRED_DISP  = ( /*08*/COALESCE(x.BDVL_CRED,0)
                                   +/*09*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 1 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   -/*10*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 0 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   -/*11*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRCREDEFPIS,0), COALESCE(x.BDVLRCREDEPCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 x WHERE x.BDCODEMP =:wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6  AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   ),
              -- 13 - IND_DESC_CRED - Indicador de op??o de utiliza??o do cr?dito dispon?vel no per?odo: 0 ? Utiliza??o do valor total para desconto da contribui??o apurada no per?odo, no Registro M200; 1 ? Utiliza??o de valor parcial para desconto da contribui??o apurada no per?odo, no Registro M200.
              x.BDIND_DESC_CRED = 0, -- Por padr?o vai levar sempre como "0", por?m caso utilize parcialmente, vai atualizar na apura??o do M200/M600.
              -- 14 - VL_CRED_DESC - Valor do Cr?dito dispon?vel, descontado da contribui??o apurada no pr?prio per?odo.
              --    Se IND_DESC_CRED=0, informar o valor total do Campo 12;
              --    Se IND_DESC_CRED=1, informar o valor parcial do Campo 12.
              x.BDVL_CRED_DESC  = ( /*08*/COALESCE(x.BDVL_CRED,0)
                                   +/*09*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 1 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   -/*10*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 0 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   -/*11*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRCREDEFPIS,0), COALESCE(x.BDVLRCREDEPCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 x WHERE x.BDCODEMP =:wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6  AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   ),
              -- 15 - SLD_CRED - Saldo de cr?ditos a utilizar em per?odos futuros (12 ? 14)
              x.BDSLD_CRED      = 0
          WHERE x.BDCODPERIODO = :wCODPERIODO
            AND x.BDCODEMP = :wCODEMP
            AND x.BDCODMATRIZ = :wCODMATRIZ
            AND x.BDCODQUADRO = :wCODQUADRO
            AND x.BDREFERENCIA = :wREFERENCIA
            AND x.BDCHAVE = :wCHAVE;
        END

      /* 08 - Lan?amento sem natureza do cr?dito informada.  #Inconsist?ncia# */
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
      SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCODBLOCOM, tmp.BDCODTP, tmp.BDCHAVE, tmp.BDORDEM, tmp.BDORDEMPRO, 8 AS BDCODINC
      FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp
      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF)
      LEFT OUTER JOIN VEF_EMP_TMOVPROENT ent on (ent.BDCODEMP = tmp.BDCODEMP and ent.BDCHAVE = tmp.BDCHAVE and ent.BDORDEM = tmp.BDORDEM and ent.BDORDEMPRO = tmp.BDORDEMPRO and 1 = tmp.BDCODTP)
      LEFT OUTER JOIN VEF_EMP_TMOVSER ser on (ser.BDCODEMP = tmp.BDCODEMP and ser.BDCHAVE = tmp.BDCHAVE and 3 = tmp.BDCODTP)
      LEFT OUTER JOIN VEF_EMP_TA170 a170 on (a170.BDCODEMP = tmp.BDCODEMP AND a170.BDCHAVE = tmp.BDCHAVE AND a170.BDORDEM = tmp.BDORDEM and a170.BDNUM_ITEM = tmp.BDORDEMPRO and 3 = tmp.BDCODTP)
      LEFT OUTER JOIN VEF_EMP_TMOVDEMAISDOC_F100 dem on (dem.BDCODEMP = tmp.BDCODEMP and dem.BDCHAVE = tmp.BDCHAVE and 4 = tmp.BDCODTP)
      LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = tmp.BDCODEMP and d100.BDCHAVE = tmp.BDCHAVE and 10 = tmp.BDCODTP)
      LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = tmp.BDCODEMP and d500.BDCHAVE = tmp.BDCHAVE and 11 = tmp.BDCODTP)
      LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = tmp.BDCODEMP and c500.BDCHAVE = tmp.BDCHAVE and 12 = tmp.BDCODTP)
      --LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO f200 on (f200.BDCODEMP = tmp.BDCODEMP and f200.BDCODBEM = tmp.BDCHAVE and 14 = tmp.BDCODTP)
      LEFT OUTER JOIN EMPRESAS_TBEM bem on (bem.BDCODEMP = tmp.BDCODEMP and bem.BDCODBEM = tmp.BDCHAVE and 15 = tmp.BDCODTP)
      WHERE ((cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) OR (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)))
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (((tmp.BDCODTP = 1) and (ent.BDCODNATBC IS NULL)) or -- Entradas
             ((tmp.BDCODTP = 3) and (ser.BDTIPLAN = 1) and (a170.BDNAT_BC_CRED IS NULL)) or -- Servi?os Recebidos
             ((tmp.BDCODTP = 4) and (dem.BDIND_OPER = 1) and (dem.BDNAT_BC_CRED IS NULL)) or -- Demais documentos, Opera??o Representativa de Aquisi??o...
             ((tmp.BDCODTP = 10) and (d100.BDCODNATBC IS NULL)) or -- Entradas - Transporte (D100)
             ((tmp.BDCODTP = 11) and (d500.BDCODNATBC IS NULL)) or -- Entradas - Servi?o de comunica??o e telecomunica??o (D500)
             ((tmp.BDCODTP = 12) and (c500.BDCODNATBC IS NULL)) or -- Entradas - Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
             --((tmp.BDCODTP = 14) and (f200.BDCODNATBC IS NULL)) or -- Baixa do F200, aqui joga fixo...
             ((tmp.BDCODTP = 15) and (bem.BDTIPOAPROCRED IS NULL)) ); -- Bens

      /* 09 - Natureza da base de calculo do cr?dito inv?lida para CFOP lan?ada.  #Inconsist?ncia# */
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
      SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCODBLOCOM, tmp.BDCODTP, tmp.BDCHAVE, tmp.BDORDEM, tmp.BDORDEMPRO, 9 AS BDCODINC
      FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp
      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF)
      LEFT OUTER JOIN VEF_EMP_TMOVSER ser ON (ser.BDCODEMP = tmp.BDCODEMP AND ser.BDCHAVE = tmp.BDCHAVE AND 3 = tmp.BDCODTP)
      WHERE ((cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) OR (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)))
        AND (tmp.BDNAT_BC_CRED IS NOT NULL)
        AND (tmp.BDCODTP = 1) -- Apenas deve filtrar os lan?amentos de produtos...
        AND (-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
             ((tmp.BDNAT_BC_CRED <> 01) AND -- Aquisi??o de Bens para Revenda
              (tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR
             ((tmp.BDNAT_BC_CRED <> 02) AND -- Aquisi??o de Bens Utilizados como Insumo
              (tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR
             ((tmp.BDNAT_BC_CRED <> 03) AND -- Aquisi??o de Servi?os Utilizados como Insumo
              (tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR
             ((tmp.BDNAT_BC_CRED <> 12) AND -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
              (tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR
             ((tmp.BDNAT_BC_CRED <> 13) AND -- Outras Opera??es com Direito a Cr?dito
              (tmp.BDPREFIXONAT IN (1922,2922)))
             )
        AND tmp.BDCODEMP = :prCODEMP
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA;

    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M100_M500AUX) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WMOD_COMTELE VARCHAR(10);
DECLARE VARIABLE WMOD_ENERGAS VARCHAR(10);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
DECLARE VARIABLE WMOD_PROD VARCHAR(50);
DECLARE VARIABLE wMOD_COD_CRED_8 VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
-- Concatena todos os modelos anteriores, usar "NOT IN"...
wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;
-- Modelos que geram "Tipo de Cr?dito" com final 8, exporta??o...
wMOD_COD_CRED_8 = '1,100,4,55,65';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDCODCRIT    -- Crit?rio de escritura??o (cumulativo)
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR (:prCODEMP, :prREFERENCIA, :prWHEREEMPRESAS);

      wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M100_M500 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDPREFIXONAT, BDVL_ITEM, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCPIS_QUANT, BDALIQPIS_QUANT, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT, BDNAT_BC_CRED, BDCOD_CRED) ';

      wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDPREFIXONAT, aux.BDVL_ITEM, aux.BDCODCTA, aux.BDCODCSTPIS, aux.BDBCPIS,';
      wSQL = wSQL||       'aux.BDALIQPIS, aux.BDVLRPIS, aux.BDBCPIS_QUANT, aux.BDALIQPIS_QUANT, aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, aux.BDBCCOFINS_QUANT, aux.BDALIQCOFINS_QUANT, ';
      wSQL = wSQL||       'aux.BDNAT_BC_CRED,';

      wSQL = wSQL||       'Coalesce(aux.BDCOD_CRED,';
      wSQL = wSQL||                '(CASE WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 108 '; -- 108 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 208 '; -- 208 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 201 '; -- 201 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 202 '; -- 202 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
 
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 308 '; -- 308 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 301 '; -- 301 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 302 '; -- 302 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
 
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 202 '; -- 202 - Quando for al?quota diferente da b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 301 '; -- 301 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for al?quota b?sica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 302 '; -- 302 - Quando for aliquota for diferente da basica.  Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for al?quota for diferente da  b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 208 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da segunda linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 202 '; -- 202 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando ? usado CFOP do exterior que tem cr?dito. E a empresa usa rateio para este c?digo deve ser verificado o percentual relativo a primeira linha do 0111 com rela??o a ultima e calcular o montante do cr?dito da CFOP do exterior com CST 56 para este c?digo.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 60) OR (aux.BDCODCSTCOF = 60)) THEN 106 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 61) OR (aux.BDCODCSTCOF = 61)) THEN 206 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 62) OR (aux.BDCODCSTCOF = 62)) THEN 306 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 63) OR (aux.BDCODCSTCOF = 63)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 64) OR (aux.BDCODCSTCOF = 64)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 65) OR (aux.BDCODCSTCOF = 65)) THEN 206 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 66) OR (aux.BDCODCSTCOF = 66)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                 'else NULL end)';
      wSQL = wSQL||               ') AS BDCOD_CRED ';
      wSQL = wSQL||'FROM ( ';
                          /* Entradas - Produtos */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 1 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'p.BDVLRITEM AS BDVL_ITEM, p.BDCODCTA, p.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||              'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                'AND (e.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROENT p on (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'WHERE p.BDCODPROD is not null ';
      wSQL = wSQL||         'AND ((p.BDCODCSTPIS is not null) OR (p.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Servi?o de comunica??o e telecomunica??o (D500) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, d500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'd500.BDVLRSER AS BDVL_ITEM, d500.BDCODCTA, d500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'd500.BDCODCSTPIS, d500.BDVL_BC_PIS AS BDBCPIS, d500.BDALIQ_PIS AS BDALIQPIS, d500.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'd500.BDCODCSTCOF, d500.BDVL_BC_COF AS BDBCCOFINS, d500.BDALIQ_COF AS BDALIQCOFINS, d500.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_COMTELE||')) '; -- Servi?o de comunica??o e telecomunica??o
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||               'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||               'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = mov.BDCODEMP AND d500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE d500.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((d500.BDCODCSTPIS is not null) OR (d500.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'c500.BDVLRCONSFOR AS BDVL_ITEM, NULL AS BDCODCTA, c500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'c500.BDCODCSTPIS, c500.BDVL_BC_PIS AS BDBCPIS, c500.BDALIQ_PIS AS BDALIQPIS, c500.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'c500.BDCODCSTCOF, c500.BDVL_BC_COF AS BDBCCOFINS, c500.BDALIQ_COF AS BDALIQCOFINS, c500.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_ENERGAS||')) '; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||            ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = mov.BDCODEMP AND c500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE c500.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((c500.BDCODCSTPIS is not null) OR (c500.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Transporte (D100) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, d100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'mov.BDVALORNOTA AS BDVL_ITEM, d100.BDCODCTA, d100.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDVALORNOTA, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE d100.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((d100.BDCODCSTPIS is not null) OR (d100.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Demais documentos */
      wSQL = wSQL||       'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN AS BDREFERENCIA, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
      wSQL = wSQL||              'dem.BDVL_OPER AS BDVL_ITEM, NULL AS BDCODCTA, dem.BDNAT_BC_CRED, ';
      wSQL = wSQL||              'CASE WHEN ((dem.BDCODCSTPIS = 60) or (dem.BDCODCSTCOF = 60)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 61) or (dem.BDCODCSTCOF = 61)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 62) or (dem.BDCODCSTCOF = 62)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 307 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 63) or (dem.BDCODCSTCOF = 63)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 64) or (dem.BDCODCSTCOF = 64)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 65) or (dem.BDCODCSTCOF = 65)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 66) or (dem.BDCODCSTCOF = 66)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||              'ELSE NULL ';
      wSQL = wSQL||              'END AS BDCOD_CRED,';
      wSQL = wSQL||              'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM  VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||       'WHERE ((dem.BDCODCSTPIS is not null) OR (dem.BDCODCSTCOF is not null)) ';
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||         'AND (dem.BDIND_OPER <> 1) '; -- Opera??o Representativa de Aquisi??o...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||         'AND (dem.BDCONDPGTO <> 1) ';
      wSQL = wSQL||           'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND dem.BDREFLAN = '||:prREFERENCIA||' ';

      wSQL = wSQL||       'union all ';
                          /* Servi?os tomados(Recebidos), tipolan = 1 */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL as BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'a.BDVL_ITEM, NULL AS BDCODCTA, a.BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||                'AND (s.BDTIPLAN = 0) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TA170 a on (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'WHERE a.BDCODPROD is not null ';
      wSQL = wSQL||         'AND ((a.BDCODCSTPIS is not null) OR (a.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT bem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, bem.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA,';
      wSQL = wSQL||               'bem.BDCODBEM AS BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
--Sol. 22905 Gabriel Ariel (27/02/2018) - Buscar primeiro o valor da depreciacao
      wSQL = wSQL||                'bem.BDVL_ITEM, ';
      wSQL = wSQL||                'bem.BDCODTPLA AS BDCODCTA,';

      wSQL = wSQL||               'CASE bem.BDTIPOAPROCRED ';
      wSQL = wSQL||                 'WHEN 0 THEN ''10'' ';
      wSQL = wSQL||                 'WHEN 1 THEN ''09'' ';
      wSQL = wSQL||                 'WHEN 2 THEN ''11'' ';
      wSQL = wSQL||               'end AS BDNAT_BC_CRED, ';

      wSQL = wSQL||               'case ';
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 50) or (bem.BDCODCSTCOF = 50)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 51) or (bem.BDCODCSTCOF = 51)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 203 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 52) or (bem.BDCODCSTCOF = 52)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 303 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 53) or (bem.BDCODCSTCOF = 53)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 54) or (bem.BDCODCSTCOF = 54)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 55) or (bem.BDCODCSTCOF = 55)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 203 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 56) or (bem.BDCODCSTCOF = 56)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||               'else 101 ';
      wSQL = wSQL||               'end as BDCOD_CRED, ';

      wSQL = wSQL||               'bem.BDCODCSTPIS,';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDBCPIS,';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, bem.BDALIQPIS) AS BDALIQPIS,'; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)

      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDVLRPIS, ';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM), NULL)) AS BDBCPIS_QUANT, ';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), bem.BDALIQPIS, NULL) AS BDALIQPIS_QUANT,';
      wSQL = wSQL||               'bem.BDCODCSTCOF,';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) AS BDBCCOFINS,';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, bem.BDALIQCOFINS) AS BDALIQCOFINS,'; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)

      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDVLRCOFINS, ';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM), NULL)) as BDBCCOFINS_QUANT, ';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), bem.BDALIQCOFINS, NULL) AS BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT tbem.*, ';
      wSQL = wSQL||                'coalesce((select cast(coalesce(PRDEPRECIACAOPERIODO, 0) as numeric(15,2)) PRDEPRECIACAOPERIODO ';
      wSQL = wSQL||                           'from SP_CONS_CALC_DEP('||:PRCODEMP||', TBEM.BDCODBEM, (substring('||:prREFERENCIA||' from 5 for 2) || ''/01/'' || substring('||:prREFERENCIA||' from 1 for 4)), (substring('||:prREFERENCIA||' from 5 for 2) || ''/'' ||(select ULTDIA ';
      wSQL = wSQL||                                                                                                                                                                                                ' from ULTIMO_DIA_MES(cast(substring('||:prREFERENCIA||' from 5 for 2) as integer), cast(substring('||:prREFERENCIA||' from 1 for 4) as integer))) || ''/'' || substring('||:prREFERENCIA||' from 1 for 4)), 0, 0) ';
      wSQL = wSQL||                           'where exists (select dep.bdcodemp from EMPRESAS_TDEPRECIACAO dep where dep.bdcodemp = TBEM.BDCODEMP and dep.bdcodbem = TBEM.BDCODBEM) and TBEM.BDTIPOAPROCRED <> 0), ';
--      wSQL = wSQL||                           'where PRDEPRECIACAOPERIODO > 0), ';
      wSQL = wSQL||               '(case TBEM.BDTIPOAPROCRED ';
      wSQL = wSQL||                  'when 0 then (TBEM.BDBCCALC/COALESCE(case Tbem.BDCODNRPARC '; -- F130 n?o deve abater a exclus?o
      wSQL = wSQL||                                                               'when 0 then 1 ';  -- 1 - Integral
      wSQL = wSQL||                                                               'when 1 then 12 '; -- 2 - 12 Meses
      wSQL = wSQL||                                                               'when 2 then 24 '; -- 3 - 24 Meses
      wSQL = wSQL||                                                               'when 3 then 48 '; -- 4 - 48 Meses
      wSQL = wSQL||                                                               'when 4 then 6 ';  -- 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                                                         'when 5 then COALESCE(Tbem.BDNUMPARC, 1) '; -- 9 - Outra periodicidade definida em Lei. #OBS.: Nesses casos pega o n?mero de parcelas do campo "Quantidade" da aba EFD - PIS/Cofins
      wSQL = wSQL||                                                             'end, 1)) ';
      wSQL = wSQL||                  'else (TBEM.BDBCCALC)-(Tbem.BDEXCBASE/COALESCE(Tbem.BDNUMPARC,1)) '; -- F120 deve abater a exclus?o
      wSQL = wSQL||                  'end)) as BDVL_ITEM ';
      wSQL = wSQL||              'FROM (SELECT TBEM.*, ';     
  --Sol. 22905 - Faz a proporcao para o primeiro e ultimo mes, que depender? dos par?metros do bem
      wSQL = wSQL||               'CASE WHEN ((BDDEPDIARIA = ''TRUE'') and (TBEM.BDTIPOAPROCRED <> 0)) THEN CASE WHEN ('||:PRREFERENCIA||' = extract(year from BDDTINI) || LPAD(extract(month from BDDTINI),2,''0'')) then cast(cast(TBEM.BDBASECALC * (iif(BDNUMDIAS <= 1, 30, (select ULTDIA  from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) - iif((BDNUMDIAS <= 1) and ((extract(day from BDDTINI) ) > 30), 30, (extract(day from BDDTINI) ))) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) as numeric(15,2))';
      wSQL = wSQL||               '                                                                              WHEN ('||:PRREFERENCIA||' = extract(year from BDDTFIM) || LPAD(extract(month from BDDTFIM),2,''0'')) then cast(cast(TBEM.BDBASECALC * (iif((BDNUMDIAS <= 1) and (extract(day from BDDTFIM) > 30), 30, extract(day from BDDTFIM) )) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTFIM), extract(year from BDDTFIM)))) as numeric(15,2))';
      wSQL = wSQL||               '                                                                         ELSE TBEM.BDBASECALC ';
      wSQL = wSQL||               '                                         END ';
      wSQL = wSQL||               '     ELSE TBEM.BDBASECALC ';
      wSQL = wSQL||               'END BDBCCALC ';
      wSQL = wSQL||                'FROM (SELECT TBEM.*, ';           
  --Sol. 22905 - Pega a data da primeira e ultima parcela, para verificar se o bem est? no primeiro ou ?ltimo m?s, onde o c?lculo ? diferente
      wSQL = wSQL||                    'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end))BDDTFIM,';
      wSQL = wSQL||                    'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end))BDDTINI ';
      Wsql = wSQL||                 'FROM EMPRESAS_TBEM tbem ';
      wSQL = wSQL||                'WHERE tbem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND ((tbem.BDCODCSTPIS is not null) OR (tbem.BDCODCSTCOF is not null)) ';
                                   -- sol:15691 - deve trazer os registros sem data de baixa OU
                                   --             (se tiver baixa) todos que a baixa seja posterior ao periodo de apura??o OU
                                   --             (se a baixa for menor que a data final da apura??o) os registros em que o mes da baixa seja igual ao da apura??o E estiver parametrizado para depreciar no mes da baixa
      wSQL = wSQL||                'AND ((tbem.BDDATABAIXA is null) OR ';
      wSQL = wSQL||                     '(Cast(SubString(tbem.BDDATABAIXA FROM 1 for 4)||SubString(tbem.BDDATABAIXA FROM 6 for 2) AS Integer) > '||:prREFERENCIA||') OR ';
      wSQL = wSQL||                     '((tbem.BDDEPMESBAIXABEM = ''TRUE'') AND (LPAD(EXTRACT(MONTH FROM tbem.BDDATABAIXA), 2, ''0'') = SubString('||:prREFERENCIA||' FROM 5 for 2)) AND ';
      wSQL = wSQL||                      '(tbem.BDTIPOAPROCRED <> 0))) '; -- sol:15691 - n?o levar no mes da baixa se for bdtipoaprocred = 0(10), que ? do F130
                                   -- sol:15691 - obedecer o parametro BDDEPMESAQUIBEM que diz se deve depreciar no mes da aquisi??o ou no pr?ximo
      wSQL = wSQL||                'AND (';
      wSQL = wSQL||                     '(Cast(SubString((CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC - 1 + 1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end) FROM 1 for 4)||';
      wSQL = wSQL||                           'SubString((CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC - 1 + 1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end) FROM 6 for 2) AS Integer) >= '||:prREFERENCIA||') AND ';
      wSQL = wSQL||                     '((Cast(SubString((CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end) FROM 1 for 4)||';
      wSQL = wSQL||                            'SubString((CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end) FROM 6 for 2) AS Integer) <= '||:prREFERENCIA||')) ';
      wSQL = wSQL||                     ') ';
                                   -- sol:15653 - somente se cst for diferente de 70
      wSQL = wSQL||                'AND (tbem.BDCODCSTPIS <> 70) AND (tbem.BDCODCSTCOF <> 70) ';
      wSQL = wSQL||              ')TBEM ';
      wSQL = wSQL||           ')TBEM ';
      wSQL = wSQL||             ') bem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = bem.BDCODEMP) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, (cast(substring(pgto.BDDATAPGTO FROM 1 for 4)||substring(pgto.BDDATAPGTO FROM 6 for 2) AS integer)) AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, pgto.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVLRTOTRECPAR AS BDVL_ITEM, NULL AS BDCODCTA, 109 AS BDNAT_BC_CRED, 109 AS BDCOD_CRED,';
      wSQL = wSQL||              'f205.BDCODCSTPIS, f205.BDBASEPIS AS BDBCPIS, f205.BDALIQPIS, f205.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'f205.BDCODCSTCOF, f205.BDBASECOFINS AS BDBCCOFINS, f205.BDALIQCOFINS, f205.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT f.* FROM VEF_EMP_TMOVOPIMOBI_F200_PGTO f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND (cast(substring(f.BDDATAPGTO FROM 1 for 4)||substring(f.BDDATAPGTO FROM 6 for 2) AS integer) = '||:prREFERENCIA||') ';
      wSQL = wSQL||             ') pgto ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVOPIMOBCUSINCOR f205) f205 on (f205.BDCODEMP = pgto.BDCODEMP AND f205.BDCHAVE = pgto.BDCHAVE AND f205.BDORDEMPGTO = pgto.BDORDEMPGTO) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, (cast(substring(pgto.BDDATAPGTO FROM 1 for 4)||substring(pgto.BDDATAPGTO FROM 6 for 2) AS integer)) AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, pgto.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVLRTOTRECPAR AS BDVL_ITEM, NULL AS BDCODCTA, 109 AS BDNAT_BC_CRED, 109 AS BDCOD_CRED,';
      wSQL = wSQL||              'f210.BDCODCSTPIS, f210.BDBASEPIS AS BDBCPIS, f210.BDALIQPIS, f210.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'f210.BDCODCSTCOF, f210.BDBASECOFINS AS BDBCCOFINS, f210.BDALIQCOFINS, f210.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT f.* FROM VEF_EMP_TMOVOPIMOBI_F200_PGTO f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND (cast(substring(f.BDDATAPGTO FROM 1 for 4)||substring(f.BDDATAPGTO FROM 6 for 2) AS integer) = '||:prREFERENCIA||') ';
      wSQL = wSQL||             ') pgto ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVOPIMOBCUSORCA f210) f210 on (f210.BDCODEMP = pgto.BDCODEMP AND f210.BDCHAVE = pgto.BDCHAVE AND f210.BDORDEMPGTO = pgto.BDORDEMPGTO) ';

      wSQL = wSQL||      ') aux ';
      wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS not in (4,6,7,8,9)) or ((aux.BDCODCSTPIS = 5) and ((aux.BDALIQPIS = 0) or (aux.BDALIQCOFINS = 0)))) '; -- CSTs que n?o geram regitros M100/500...

      EXECUTE STATEMENT ( wSQL );

    END

END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M100_M500AUX for: SP_APURACAO_BLOCOM_M100_M500PAR */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_M100_M500PAR) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WMOD_COMTELE VARCHAR(10);
DECLARE VARIABLE WMOD_ENERGAS VARCHAR(10);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
DECLARE VARIABLE WMOD_PROD VARCHAR(50);
DECLARE VARIABLE wMOD_COD_CRED_8 VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
-- Concatena todos os modelos anteriores, usar "NOT IN"...
wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;
-- Modelos que geram "Tipo de Cr?dito" com final 8, exporta??o...
wMOD_COD_CRED_8 = '1,100,4,55,65';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDCODCRIT    -- Crit?rio de escritura??o (cumulativo)
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M100_M500 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDPREFIXONAT, BDVL_ITEM, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCPIS_QUANT, BDALIQPIS_QUANT, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT, BDNAT_BC_CRED, BDCOD_CRED) ';
    
          wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDPREFIXONAT, aux.BDVL_ITEM, aux.BDCODCTA, aux.BDCODCSTPIS, aux.BDBCPIS,';
          wSQL = wSQL||       'aux.BDALIQPIS, aux.BDVLRPIS, aux.BDBCPIS_QUANT, aux.BDALIQPIS_QUANT, aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, aux.BDBCCOFINS_QUANT, aux.BDALIQCOFINS_QUANT, ';
          wSQL = wSQL||       'aux.BDNAT_BC_CRED,';

          wSQL = wSQL||       'Coalesce(aux.BDCOD_CRED,';
          wSQL = wSQL||                '(CASE WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 108 '; -- 108 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 208 '; -- 208 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 201 '; -- 201 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 202 '; -- 202 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
     
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 308 '; -- 308 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 301 '; -- 301 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 302 '; -- 302 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
     
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 202 '; -- 202 - Quando for al?quota diferente da b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 301 '; -- 301 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for al?quota b?sica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 302 '; -- 302 - Quando for aliquota for diferente da basica.  Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for al?quota for diferente da  b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 208 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da segunda linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 202 '; -- 202 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando ? usado CFOP do exterior que tem cr?dito. E a empresa usa rateio para este c?digo deve ser verificado o percentual relativo a primeira linha do 0111 com rela??o a ultima e calcular o montante do cr?dito da CFOP do exterior com CST 56 para este c?digo.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 60) OR (aux.BDCODCSTCOF = 60)) THEN 106 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 61) OR (aux.BDCODCSTCOF = 61)) THEN 206 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 62) OR (aux.BDCODCSTCOF = 62)) THEN 306 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 63) OR (aux.BDCODCSTCOF = 63)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 64) OR (aux.BDCODCSTCOF = 64)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 65) OR (aux.BDCODCSTCOF = 65)) THEN 206 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 66) OR (aux.BDCODCSTCOF = 66)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

          wSQL = wSQL||                 'else NULL end)';
          wSQL = wSQL||               ') AS BDCOD_CRED ';
          wSQL = wSQL||'FROM ( ';

          wSQL = wSQL||'SELECT ent.BDCODEMP, COALESCE(emp.BDCODMATRIZ, ent.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 1 AS BDCODTP, ent.BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||      '(CAST(ROUND(('; -- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                   '(IIF(qtdepro.BDQTDEPRO < 1, pgto.bdvalorpgtopar,'; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                              '((COALESCE(pgto.bdvalorpgtopar,0)*(( COALESCE(movpro.BDVLRITEM,0)/i.BDVLRCONTAB)))) ))+';
          wSQL = wSQL||                   '(IIF(qtdepro.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETINSS,0) ),+';
          wSQL = wSQL||                                             '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) )))';
          wSQL = wSQL||                   ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM,';
          wSQL = wSQL||      'movpro.BDCODCTA, movpro.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||      'movpro.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'movpro.BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'movpro.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'movpro.BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||      'WHERE (e.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||        'AND (e.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||        'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||              'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') ent ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = ent.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVENTPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = ent.BDCODEMP AND x.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTPAR par on (par.BDCODEMP = ent.BDCODEMP AND par.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVENTPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = ent.BDCODEMP AND i.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, Count(*) AS BDQTDEPRO FROM VEF_EMP_TMOVPROENT p group by p.BDCODEMP, p.BDCHAVE, p.BDORDEM) qtdepro on ';
          wSQL = wSQL||                                             '(qtdepro.BDCODEMP = i.BDCODEMP AND qtdepro.BDCHAVE = i.BDCHAVE AND qtdepro.BDORDEM = i.BDORDEM) ';
          wSQL = wSQL||'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODNATBC, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||             'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVPROENT p) movpro on (i.BDCODEMP = movpro.BDCODEMP AND i.BDCHAVE = movpro.BDCHAVE AND i.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||'WHERE ((movpro.BDCODCSTPIS is not null) OR (movpro.BDCODCSTCOF is not null)) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT ent.BDCODEMP, ent.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, ent.BDCHAVE, ent.BDORDEM, ent.BDORDEMPRO, ent.BDCODTP, ent.BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||         '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETINSS,0) ) AS BDVL_ITEM,';

          wSQL = wSQL||      'ent.BDCODCTA, ent.BDNAT_BC_CRED, ent.BDCOD_CRED,';
          wSQL = wSQL||      'ent.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'ent.BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'ent.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'ent.BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
                             /* Entradas - Servi?o de comunica??o e telecomunica??o (D500) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'd500.BDVLRSER AS BDVL_ITEM, d500.BDCODCTA, d500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'd500.BDCODCSTPIS, d500.BDVL_BC_PIS AS BDBCPIS, d500.BDALIQ_PIS AS BDALIQPIS, d500.BDVLRPIS,';
          wSQL = wSQL||             'd500.BDCODCSTCOF, d500.BDVL_BC_COF AS BDBCCOFINS, d500.BDALIQ_COF AS BDALIQCOFINS, d500.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM (';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_COMTELE||' )) '; -- Servi?o de comunica??o e telecomunica??o
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||              'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                    'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = mov.BDCODEMP AND d500.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE d500.BDCHAVE is not null ';
      
          wSQL = wSQL||      'union all ';
                             /* Entradas - Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'c500.BDVLRCONSFOR AS BDVL_ITEM, NULL AS BDCODCTA, c500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'c500.BDCODCSTPIS, c500.BDVL_BC_PIS AS BDBCPIS, c500.BDALIQ_PIS AS BDALIQPIS, c500.BDVLRPIS,';
          wSQL = wSQL||             'c500.BDCODCSTCOF, c500.BDVL_BC_COF AS BDBCCOFINS, c500.BDALIQ_COF AS BDALIQCOFINS, c500.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM ( ';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_ENERGAS||')) '; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||             'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                   'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = mov.BDCODEMP AND c500.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE c500.BDCHAVE is not null ';
      
          wSQL = wSQL||      'union all ';
                             /* Entradas - Transporte (D100) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'd100.BDVLR_FCP_UF_DEST AS BDVL_ITEM, d100.BDCODCTA, d100.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
          wSQL = wSQL||             'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM ( ';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||             'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                   'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE d100.BDCHAVE is not null ';

          wSQL = wSQL||    ') ent ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVENTPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = ent.BDCODEMP AND x.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTPAR par on (par.BDCODEMP = ent.BDCODEMP AND par.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVENTPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = ent.BDCODEMP AND i.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||'WHERE ((ent.BDCODCSTPIS is not null) OR (ent.BDCODCSTCOF is not null)) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL as BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||      '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||      'NULL AS BDCODCTA, a170.BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||      'a170.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'a170.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||      'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||        'AND (s.BDTIPLAN = 0) ';
          wSQL = wSQL||        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||              'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') mov ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||' )) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVSERITENS i on (mov.BDCODEMP = i.BDCODEMP AND mov.BDCHAVE = i.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TA170 a170 on (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND i.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit on (mov.BDCODSITNF = sit.BDCODSITNF) ';
          wSQL = wSQL||'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
          wSQL = wSQL||       '(pgto.bdvalorpgtopar +(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||       'NULL AS BDCODCTA, mov.BDNAT_BC_CRED, ';
          wSQL = wSQL||       'CASE WHEN ((mov.BDCODCSTPIS = 60) or (mov.BDCODCSTCOF = 60)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 61) or (mov.BDCODCSTCOF = 61)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 62) or (mov.BDCODCSTCOF = 62)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 307 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 63) or (mov.BDCODCSTCOF = 63)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 64) or (mov.BDCODCSTCOF = 64)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 65) or (mov.BDCODCSTCOF = 65)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 66) or (mov.BDCODCSTCOF = 66)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||       'ELSE NULL ';
          wSQL = wSQL||       'END AS BDCOD_CRED,';
          wSQL = wSQL||       'mov.BDCODCSTPIS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||       'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||       'NULL as BDBCPIS_QUANT, 0 as BDALIQPIS_QUANT,';
          wSQL = wSQL||       'mov.BDCODCSTCOF,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||       'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||       'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT dem.BDCODEMP, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.BDIND_ORIG_CRED, dem.BDNAT_BC_CRED,';
          wSQL = wSQL||             'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||             'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||      'WHERE ((dem.BDCODCSTPIS is not null) OR (dem.BDCODCSTCOF is not null)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||        'AND (dem.BDIND_OPER <> 1) '; -- Opera??o Representativa de Aquisi??o...
          wSQL = wSQL||        'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||             ' WHERE e.BDCODEMP = dem.BDCODEMP AND e.BDREFEMP <= dem.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') mov ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'WHERE ((mov.BDCODCSTPIS is not null) OR (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||  'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||      ') aux ';
          wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS not in (4,6,7,8,9)) or ((aux.BDCODCSTPIS = 5) and ((aux.BDALIQPIS = 0) or (aux.BDALIQCOFINS = 0)))) '; -- CSTs que n?o geram regitros M100/500...

          EXECUTE STATEMENT ( wSQL );
          
        END
    END

END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M200_M600 for: SP_APURACAO_BLOCOM_M200 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M200_M600(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_M200) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M200(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WVLRAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRUP NUMERIC(15,2);
DECLARE VARIABLE WVLRUPAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRSLD NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT_ORIGINAL NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT_TOTAL NUMERIC(15,2);
DECLARE VARIABLE WINTAUX INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WPER_APU_CRED INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCRE_4_3_6 INTEGER;
DECLARE VARIABLE WIND_CRED_ORI INTEGER;
DECLARE VARIABLE WCOD_NAT_REC INTEGER;
DECLARE VARIABLE WCHAVEAUX INTEGER;
DECLARE VARIABLE WORDENACAO INTEGER;
DECLARE VARIABLE WIND_DESC_CRED INTEGER;
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCREDITOSPERANT, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCREDITOSPERANT, :wRETPISCOFPERANT;

  /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  /* 1 - Exclusivamente no regime n?o-cumulativo */
  IF (wINCTRIB IN (1,3)) THEN
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      wVLRTOTCONT = 0;
      SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR
      FROM VEF_EMP_TBLOCOM210_M610 m
      LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL)
      WHERE (t435.BDCODCSOCIALEXP IN (01,02,03,04,32,71))
        AND (m.BDCODQUADRO = 19) -- M210 - Detalhamento da contribui??o para o PIS/PASEP
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRTOTCONT;

      wVLRTOTCONT_ORIGINAL = wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 2, COALESCE(:wVLRTOTCONT,0));

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100)
         Caso esteja configurado para usar saldo do per?odo anterior, deve descontar ele primeiro, antes do cr?dito do per?odo atual... */
      wVLRCREDPERANT = 0;
      wVLRCREDPERANT_TOTAL = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 52) -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL = wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
              END
          END
        END

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      SELECT COUNT(m.BDCHAVE) as BDQTD
      FROM VEF_EMP_TBLOCOM100_500 m
      WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO wQTD;

      IF ((wQTD = 0) OR (wVLRTOTCONT = 0) OR (wVLRTOTCONT IS NULL))  THEN -- Caso n?o tenha dados no M100/M500 ou o valor do cr?dito seja zerado...
        BEGIN
          UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                               VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, 0)
                                             MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
            UPDATE VEF_EMP_TBLOCOM100_500 m
            SET m.BDIND_DESC_CRED = 1,
                m.BDVL_CRED_DESC  = 0,
                m.BDSLD_CRED      = m.BDVL_CRED_DISP
            WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA;

            /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
            SELECT COUNT(*)
            FROM VEF_EMP_TBLOCOM1100_1500 m
            WHERE m.BDCODPERIODO = 7
              AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA
              AND m.BDPER_APU_CRED = :prREFERENCIA
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDORIG_CRED = :wIND_CRED_ORI
            INTO :wQTD;
  
            IF (:wQTD > 0) THEN
              BEGIN
                /* Caso tenha registros atualiza */
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                    m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                    m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
      ELSE
        BEGIN
                /* Caso n?o tenha lan?amento de saldos insere */
                INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                              VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                      (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                      7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
              END
          END
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            IF (:wVLRTOTCONT > 0) THEN
              BEGIN
                /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
                IF (:wVLR < :wVLRTOTCONT) THEN
                  BEGIN
                    wVLRSLD        = 0;
                    wVLRTOTCONT    = :wVLRTOTCONT - :wVLR;
                    wIND_DESC_CRED = 0; -- 0 ? Utiliza??o do valor total para desconto da contribui??o apurada no per?odo, no Registro M200;
                  END
                ELSE
                  BEGIN
                    /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                    wVLRSLD        = :wVLR - :wVLRTOTCONT;
                    wVLR           = :wVLR - :wVLRSLD;
                    wVLRTOTCONT    = 0;
                    wIND_DESC_CRED = 1; -- 1 ? Utiliza??o de valor parcial para desconto da contribui??o apurada no per?odo, no Registro M200.
                  END

                -- Atualiza os cr?ditos descontados do M100...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = :wIND_DESC_CRED,
                    m.BDVL_CRED_DESC  = :wVLR,
                    m.BDSLD_CRED      = :wVLRSLD
                WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDCHAVE = :wCHAVE
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI;

                IF (wVLRSLD > 0) THEN
                  BEGIN
                /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                SELECT COUNT(*)
                FROM VEF_EMP_TBLOCOM1100_1500 m
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI
                INTO :wQTD;
      
                IF (:wQTD > 0) THEN
                  BEGIN
                    /* Caso tenha registros atualiza */
                    UPDATE VEF_EMP_TBLOCOM1100_1500 m
                    SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI;
                  END
                ELSE
                  BEGIN
                    /* Caso n?o tenha lan?amento de saldos insere */
                    INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                  VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                          (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                              7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', (:wVLR + :wVLRSLD) /*:wVLR*/, :wVLR/*0*/, :wVLRSLD/*:wVLR*/);
                  END
              END

                wVLRAUX = 0;
                SELECT COALESCE(BDVALOR, 0)
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
                  AND BDREFERENCIA = :prREFERENCIA
                  AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
                  AND BDNUMCAMPO   = 3
                INTO wVLRAUX;
         
                IF (wVLRAUX IS NULL) THEN
                  wVLRAUX = 0;
         
                UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, COALESCE(:wVLR+:wVLRAUX,0))
                                                   MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

                  END
                ELSE
                  BEGIN
                -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = 1,
                    m.BDVL_CRED_DESC  = 0,
                    m.BDSLD_CRED      = m.BDVL_CRED_DISP
                WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDCHAVE = :wCHAVE;
          
                    /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                    SELECT COUNT(*)
                    FROM VEF_EMP_TBLOCOM1100_1500 m
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI
                    INTO :wQTD;
          
                    IF (:wQTD > 0) THEN
                      BEGIN
                        /* Caso tenha registros atualiza */
                        UPDATE VEF_EMP_TBLOCOM1100_1500 m
                        SET m.BDVL_CRED_APU = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                        WHERE m.BDCODPERIODO = 7
                          AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                          AND m.BDCODEMP = :wCODEMP
                          AND m.BDCODMATRIZ = :wCODMATRIZ
                          AND m.BDREFERENCIA = :prREFERENCIA
                          AND m.BDPER_APU_CRED = :prREFERENCIA
                          AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                          AND m.BDORIG_CRED = :wIND_CRED_ORI;
                      END
                    ELSE
                      BEGIN
                        /* Caso n?o tenha lan?amento de saldos insere */
                        INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                      VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                              (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                          7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
                      END
                          END
                          END
                      END

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      wVLR = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          wVLR = wVLRCREDPERANT_TOTAL;
        END
      ELSE
        BEGIN
          wVLRCREDPERANT_TOTAL = 0;
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 52) -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END
    
                wVLRCREDPERANT_TOTAL =  wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
          END

          wVLR = wVLRCREDPERANT_TOTAL;
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 4, COALESCE(:wVLR,0));

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (2))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (3,4))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP,  :prCODEMP, :prREFERENCIA, 15, 5, COALESCE(:wVLR,0));

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';
    
      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
              AND BDNUMCAMPO   = 6
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END


      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRPIS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 1 -- 0 - Dedu??o de Natureza N?o Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 7, COALESCE(:wVLR,0));

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR) as BDVALOR, SUM(aux.BDVLRSUB) as BDVALORSUB
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (5))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (6,7))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR, :wVLRAUX;

      IF ((wVLR - wVLRAUX) >= 0) THEN -- Se tiver valor de contribbui??o, calcula os campos a somar e subtrair...
        wVLR = (wVLR - wVLRAUX);
      ELSE
      /* Se o valor do campo 5(Valor Total da Contribui??o) menos o valor do campo 6(Valor Retido na Fonte) for menor que zero, ent?o este valor deve ser levado como saldo no registro 1300. */
      IF ((wVLR - wVLRAUX) < 0) THEN -- Se n?o tiver valor de contribbui??o, leva zerado...
        BEGIN
          /* Atualiza o valor do campo 6, Valor Retido na Fonte, s? pode usar aquilo que abater e n?o o total... */
          UPDATE VEF_EMP_TBLOCOMGERREG
          SET BDVALOR = :wVLR
          WHERE BDCODMATRIZ  = :prCODEMP
            AND BDREFERENCIA = :prREFERENCIA
            AND BDCODQUADRO  = 15
            AND BDNUMCAMPO   = 6;

          /* Caso tenha lan?amentos, desconta o valor da contribui??o deles */
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, COALESCE(m.BDVL_RET_APU, 0)
              FROM VEF_EMP_TBLOCOM1300_1700 m
              WHERE (m.BDCODQUADRO = 49) -- 1300 - Ficha de reten??o do PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUP
          DO
            BEGIN
              IF (wVLR > 0) THEN
                BEGIN
                  /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                  IF (:wVLRUP < :wVLR) THEN
                    BEGIN
                      wVLRUPAUX = :wVLRUP;
                      wVLRSLD   = 0;
                      wVLR      = :wVLR-:wVLRUP; /* Cr?dito j? descontado vai ser abatido... */
                    END
                  ELSE
                    BEGIN
                      wVLRUPAUX = :wVLR;
                      wVLRSLD   = :wVLRUP - :wVLR;
                    END
    
                  UPDATE OR INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDVL_RET_DED, BDSLD_RET)
                                                          VALUES (:wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUPAUX  , :wVLRSLD)
                                                        MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE);
                END
            END

          wVLR = 0; -- Se n?o tiver valor de contribbui??o, leva zerado...
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 8, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 2, 0);

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, 0);

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 4, 0);

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 5, 0);

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, 0);

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 7, 0);

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 8, 0);
    END

  /* 2 - Exclusivamente no regime cumulativo */
  IF (wINCTRIB IN (2,3)) THEN
    BEGIN
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      wVLRTOTCONT = 0;
      wSQL =        'SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM210_M610 m ';
      wSQL = wSQL|| 'LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL) ';
      IF (wINCTRIB IN (3)) THEN -- Quando ? regime n?o-cumulativo e cumulativo, j? considerou algumas contribui??es no campo 2...
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,51,52,53,54,72)) ';
      ELSE
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,32,51,52,53,54,72)) ';
      wSQL = wSQL|| '  AND (m.BDCODQUADRO = 19) '; -- M210 - Detalhamento da contribui??o para o PIS/PASEP
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 9, COALESCE(:wVLRTOTCONT,0));

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
                  AND BDNUMCAMPO   = 10
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                         VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRPIS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 2 -- 1 - Dedu??o de Natureza Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 11, COALESCE(:wVLR,0));

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (9))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (10,11))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 12, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN -- Joga os valores zerados...
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 9, 0);

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, 0);

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 11, 0);

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 12, 0);
    END

  /* 3 - Regimes n?o-cumulativo e cumulativo */
  /* 13 - VL_TOT_CONT_REC - VALOR TOTAL DA CONTRIBUI??O A RECOLHER/PAGAR NO PER?ODO (08 + 12) */
  WVLR = 0;
  SELECT SUM(COALESCE(M.BDVALOR,0)) AS BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG M
  WHERE (M.BDCODQUADRO = 15)
    AND (M.BDNUMCAMPO IN (8,12))
    AND M.BDCODMATRIZ = :PRCODEMP
    AND M.BDREFERENCIA = :PRREFERENCIA
  INTO :WVLR;
 
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, 15, 13, COALESCE(:WVLR,0));

END
^

/* Alter (SP_APURACAO_BLOCOM_M200_M600) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M200_M600(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  /* REGISTRO M210: DETALHAMENTO DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO
     REGISTRO M610: DETALHAMENTO DA CONTRIBUI??O PARA A SEGURIDADE SOCIAL - COFINS DO PER?ODO */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M210_M610 (:prCODEMP, :prREFERENCIA, :prWhereEmpresas);

  /* REGISTRO M220: AJUSTES DA CONTRIBUI??O PARA O PIS/PASEP APURADA
     REGISTRO M620: AJUSTES DA COFINS APURADA */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M220_M620 (:prCODEMP, :prREFERENCIA);

  /* REGISTRO M230: INFORMA??ES ADICIONAIS DE DIFERIMENTO
     REGISTRO M630: INFORMA??ES ADICIONAIS DE DIFERIMENTO */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M230_M630 (:prCODEMP, :prREFERENCIA);

  /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M200 (:prCODEMP, :prREFERENCIA);

  /* REGISTRO M600: CONSOLIDA??O DA CONTRIBUI??O PARA A SEGURIDADE SOCIAL - COFINS DO PER?ODO */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M600 (:prCODEMP, :prREFERENCIA);

END
^

/* Alter (SP_APURACAO_BLOCOM_M210_M610) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M210_M610(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32000);
declare variable WMOD_TRANSPORTE varchar(30);
declare variable WMOD_PROD varchar(50);
declare variable WALIQ_PIS_IT_1 varchar(5);
declare variable WALIQ_COF_IT_1 varchar(5);
declare variable WALIQ_PIS_IT_2 varchar(5);
declare variable WALIQ_COF_IT_2 varchar(5);
BEGIN
/* ***** Constantes das CFOPs que geram "NAT_BC_CRED" da tabela 4.3.7. ***** */
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
--wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
--wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
--wMOD_CFe = '59'; -- CF-e
-- Concatena todos os modelos anteriores, usar "NOT IN"...
--wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;--||','||wMOD_CFe;
wMOD_PROD = wMOD_TRANSPORTE;--||','||wMOD_CFe;

--wCST_NAO_CUM = '1,2,3,4,32,71'; -- CSTs do regime n?o cumulativo
--wCST_CUM = '31,32,51,52,53,54,72'; -- CSTs do regime cumulativo

/* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
wALIQ_PIS_IT_1 = '1.65';
wALIQ_COF_IT_1 = '7.60';
/* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
wALIQ_PIS_IT_2 = '0.65';
wALIQ_COF_IT_2 = '3.00';
/*****************************************************************************/
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
--      IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
--        wCST = wCST_NAO_CUM; -- CSTs do regime n?o cumulativo
--      ELSE
--      IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
--        wCST = wCST_CUM; -- CSTs do regime cumulativo
--      ELSE
--      IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
--        wCST = wCST_NAO_CUM||','||wCST_CUM; -- CSTs do regime n?o cumulativo e cumulativo

      wSQL =        'INSERT INTO TMP_VEF_EMP_TBLOCOM_M210_M610 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDCODCSTPIS, BDCODCSTCOF, BDCOD_CONT_PIS, BDCOD_CONT_COF, BDVL_REC_BRT, BDVL_BC_CONT_PIS, BDVL_BC_CONT_COF, BDALIQ_PIS, BDALIQ_COF, BDQUANT_BC_PIS, BDQUANT_BC_COF, BDALIQ_QUANT_PIS, BDALIQ_QUANT_COF) ';

      wSQL = wSQL|| 'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDCODCSTPIS, aux.BDCODCSTCOF, ';
      IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                        'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))), 01, null) ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                        'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))), 01, null) ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_1||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      ELSE
      IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                       'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 51, null) ';
          wSQL = wSQL||                                       'WHEN 2 THEN 52 ';
          wSQL = wSQL||                                       'WHEN 3 THEN 53 ';
          wSQL = wSQL||                                       'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                       'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 51, null) ';
          wSQL = wSQL||                                       'WHEN 2 THEN 52 ';
          wSQL = wSQL||                                       'WHEN 3 THEN 53 ';
          wSQL = wSQL||                                       'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      ELSE
      IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                        'WHEN 1 THEN ';
          wSQL = wSQL||                                           'CASE CAST(aux.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 01 ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 51 ';
          wSQL = wSQL||                                           'END ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                        'WHEN 1 THEN ';
          wSQL = wSQL||                                           'CASE CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 01 ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 51 ';
          wSQL = wSQL||                                           'END ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      wSQL = wSQL||        'aux.BDVL_ITEM AS BDVL_REC_BRT,';
      /* Se tiver campo de valor da base de calculo por quandtidade e al?quota em R$, leva os mesmo, caso contr?rio, verifica pela CST, se for = 3, vai nas quantidades e al?quotas em R$... */
      wSQL = wSQL||        'iif(((aux.BDQUANT_BC_PIS is null) AND (AUX.BDCODCSTPIS = 3)), 0, AUX.BDBCPIS) AS BDVL_BC_CONT_PIS,';
      wSQL = wSQL||        'iif(((aux.BDQUANT_BC_COF is null) AND (AUX.BDCODCSTCOF = 3)), 0, AUX.BDBCCOFINS) AS BDVL_BC_CONT_COF,';
      wSQL = wSQL||        'iif(((aux.BDALIQ_PIS_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQPIS) AS BDALIQ_PIS,';
      wSQL = wSQL||        'iif(((aux.BDALIQ_COF_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQCOFINS) AS BDALIQ_COF,';
      wSQL = wSQL||        'COALESCE(aux.BDQUANT_BC_PIS, iif(aux.BDCODCSTPIS = 3, aux.BDBCPIS, 0)) AS BDQUANT_BC_PIS,';
      wSQL = wSQL||        'COALESCE(aux.BDQUANT_BC_COF, iif(AUX.BDCODCSTCOF = 3, AUX.BDBCCOFINS, 0)) AS BDQUANT_BC_COF,';
      wSQL = wSQL||        'COALESCE(aux.BDALIQ_PIS_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQPIS, 0)) AS BDALIQ_QUANT_PIS,';
      wSQL = wSQL||        'COALESCE(aux.BDALIQ_COF_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQCOFINS, 0)) AS BDALIQ_QUANT_COF ';
      wSQL = wSQL|| 'FROM ( ';

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 2 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||              '(CAST(ROUND(( '; -- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                     '(IIF(mov.BDQTDEPRO < 1, pgto.bdvalorpgtopar, '; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                                '((COALESCE(pgto.bdvalorpgtopar,0)*((CAST( COALESCE(movpro.BDVLRITEM,0) AS NUMERIC(15,6))/i.BDVLRCONTAB)))) ))+ ';
          wSQL = wSQL||                     '(IIF(mov.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETINSS,0) ),+ ';
          wSQL = wSQL||                                               '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) ))) ';
          wSQL = wSQL||                     ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM, ';
          wSQL = wSQL||              'movpro.BDCODCSTPIS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS, ';
          wSQL = wSQL||              'movpro.BDALIQPIS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS, ';
          wSQL = wSQL||              'movpro.BDCODCSTCOF, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS, ';
          wSQL = wSQL||              'movpro.BDALIQCOFINS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT, ';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM ( ';
          wSQL = wSQL||                'SELECT aux.BDCODEMP, aux.BDCHAVE, aux.BDREFLAN, SUM(aux.BDQTDEPRO) AS BDQTDEPRO, SUM(aux.BDQTDEPARC) AS BDQTDEPARC ';
          wSQL = wSQL||                'FROM ( ';
          wSQL = wSQL||                       'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, COUNT(pro.bdCODEMP) AS BDQTDEPRO, 0 AS BDQTDEPARC ';
          wSQL = wSQL||                       'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE) ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVPROSAI pro ON (pro.bdCODEMP = i.bdCODEMP AND pro.bdCHAVE = i.bdCHAVE AND pro.bdORDEM = i.bdORDEM) ';
          wSQL = wSQL||                       'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                        'AND (s.'||TRIM(:prWHEREEMPRESAS)||') ';
          wSQL = wSQL||                        'AND (s.BDMODELO not in ('||wMOD_PROD||')) ';  -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                       'GROUP BY s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||                       'UNION ALL ';
          wSQL = wSQL||                       'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, 0 AS BDQTDEPRO, COUNT(par.bdCODEMP) AS BDQTDEPARC ';
          wSQL = wSQL||                       'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVSAIPAR par ON (par.bdCODEMP = s.bdCODEMP AND par.bdCHAVE = s.bdCHAVE) ';
          wSQL = wSQL||                       'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                         'AND (s.'||TRIM(:prWHEREEMPRESAS)||') ';
          wSQL = wSQL||                         'AND (s.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                       'GROUP BY s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||                      ') aux ';
          wSQL = wSQL||                'WHERE ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                        'WHERE p.BDCODEMP = aux.BDCODEMP AND p.BDREFEMP <= aux.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||                'GROUP BY aux.BDCODEMP, aux.BDCHAVE, aux.BDREFLAN ';
          wSQL = wSQL||              ') mov ';
          wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIPAR par on (par.BDCODEMP = mov.BDCODEMP AND par.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||              'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                 'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||        'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||                      'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS ';
          wSQL = wSQL||               'FROM VEF_EMP_TMOVPROSAI p ';
          wSQL = wSQL||               'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              ') movpro on (i.BDCODEMP = movpro.BDCODEMP AND i.BDCHAVE = movpro.BDCHAVE AND i.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||        'WHERE (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, mov.BDORDEM, mov.BDORDEMPRO, mov.BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||                '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETINSS,0) ) AS BDVL_ITEM,';
          wSQL = wSQL||                'mov.BDCODCSTPIS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||                'mov.BDALIQPIS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||                'mov.BDCODCSTCOF,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||                'mov.BDALIQCOFINS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||                'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||                'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
                                      /* Sa?das - Transporte (D100) */
          wSQL = wSQL||               'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 16 AS BDCODTP,';
          wSQL = wSQL||                      'mov.BDVALORNOTA AS BDVL_ITEM,';
          wSQL = wSQL||                      'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
          wSQL = wSQL||                      'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS ';
          wSQL = wSQL||               'FROM (';
          wSQL = wSQL||                      'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
          wSQL = wSQL||                      'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                      'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||                        'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
          wSQL = wSQL||                        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                        'AND s.BDREFLAN = '||:prREFERENCIA;
          wSQL = wSQL||                        'AND ((SELECT first 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                              'FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                              'WHERE p.BDCODEMP = s.BDCODEMP ';
          wSQL = wSQL||                                'AND p.BDREFEMP <= s.BDREFLAN ';
          wSQL = wSQL||                              'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||                      ') mov ';
          wSQL = wSQL||               'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||               'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||               'WHERE d100.BDCHAVE is not null ';

          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = mov.BDCODEMP AND x.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIPAR par on (par.BDCODEMP = mov.BDCODEMP AND par.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||              'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||          ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||        'WHERE (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||               '(COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'a170.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'a170.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||             'AND (s.BDTIPLAN = 0) ';
          wSQL = wSQL||               'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT FIRST 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                     'FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP ';
          wSQL = wSQL||                       'AND e.BDREFEMP <= s.BDREFLAN ';
          wSQL = wSQL||                     'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||                'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                 ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||' )) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSERITENS i on (mov.BDCODEMP = i.BDCODEMP AND mov.BDCHAVE = i.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TA170 a170 on (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND i.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit on (mov.BDCODSITNF = sit.BDCODSITNF) ';
          wSQL = wSQL||        'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||               '(pgto.bdvalorpgtopar +';
          wSQL = wSQL||                '(COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||               'mov.BDCODCSTPIS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||               'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||               'mov.BDCODCSTCOF,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||               'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
          wSQL = wSQL||              'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.BDNAT_BC_CRED,';
          wSQL = wSQL||                     'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||                     'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
          wSQL = wSQL||              ' WHERE DEM.'||TRIM(:prWHEREEMPRESAS)||' ';

          if (wINCTRIB = 2) then
            wSQL = wSQL||              ' AND (dem.BDIND_OPER <> 1) '; -- Opera??o de Aquisi??o...
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                      'FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = dem.BDCODEMP ';
          wSQL = wSQL||                        'AND e.BDREFEMP <= dem.BDREFLAN ';
          wSQL = wSQL||                      'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||               'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'WHERE ((mov.BDCODCSTPIS is not null) or (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||          'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';
        END
                           /* Sa?das - Produtos */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, mov.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 2 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'p.BDVLRITEM AS BDVL_ITEM,';
      wSQL = wSQL||               'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS,';
      wSQL = wSQL||               'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                 'AND (s.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||               'AND (s.BDCONDPGTO <> 1) ';
       wSQL = wSQL||                'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 'AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVPROSAI p on (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||        'WHERE (p.BDCODPROD is not null) ';

      wSQL = wSQL||        'union all ';
                           /* Sa?das - Transporte (D100) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 16 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'mov.BDVALORNOTA AS BDVL_ITEM,';
      wSQL = wSQL||               'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
      wSQL = wSQL||               'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                 'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                   'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 ' AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'WHERE (d100.BDCHAVE is not null) ';

      wSQL = wSQL||        'union all ';
                           /* Demais documentos - Receita */
      wSQL = wSQL||        'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN AS BDREFERENCIA, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'dem.BDVL_OPER AS BDVL_ITEM,';
      wSQL = wSQL||               'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS,';
      wSQL = wSQL||               'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||        'WHERE DEM.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         ' AND dem.BDREFLAN = '||:prREFERENCIA;
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||        'AND (dem.BDIND_OPER <> 1) '; -- Opera??o de Aquisi??o...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||          'AND (dem.BDCONDPGTO <> 1) ';

      wSQL = wSQL||        ' union all ';
                           /* Servi?os tomados(Emitidos) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'a.BDVL_ITEM, ';
      wSQL = wSQL||               'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS,';
      wSQL = wSQL||               'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM ( ';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||                 'AND (s.BDTIPLAN = 0) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                 'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 ' AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TA170 a on (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||        'WHERE (a.BDCODPROD is not null) ';

      wSQL = wSQL||        'union all ';
                           /* C425 - Varias al?quotas */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMICMS AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE,  r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZVARALIQ aliq on (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425ALIQ c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE AND c425.BDORDEMICMS = aliq.BDORDEMICMS) ';

      wSQL = wSQL||        'union all ';
                           /* C425 */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMTOT AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 6 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE, r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425 c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||        'union all ';
                           /* C470 */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c470.BDCHAVE, c470.BDORDEMDOCECF AS BDORDEM, c470.BDORDEMITEM AS BDORDEMPRO, 8 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c470.BDVLRTOTPRO AS BDVL_ITEM,';
      wSQL = wSQL||               'c470.BDCODCSTPIS, c470.BDVL_BC_PIS AS BDBCPIS, c470.BDALIQ_PIS AS BDALIQPIS, c470.BDVLRPIS,';
      wSQL = wSQL||               'c470.BDCODCSTCOF, c470.BDVL_BC_COFINS AS BDBCCOFINS, c470.BDALIQ_COFINS AS BDALIQCOFINS, c470.BDVLRCOFINS,';
      wSQL = wSQL||               'c470.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c470.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c470.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c470.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE, r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TDOCECF c460 on (c460.BDCODEMP = mov.BDCODEMP AND c460.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TITEMDOCECF c470 on (c470.BDCODEMP = c460.BDCODEMP AND c470.BDCHAVE = c460.BDCHAVE AND c470.BDORDEMDOCECF = c460.BDORDEMDOCECF) ';

      wSQL = wSQL||        'union all ';
                           /* Lan?amento de opera??es imobili?rias(F200) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, Cast((SubString(i.BDDATAPGTO FROM 1 for 4)||SubString(i.BDDATAPGTO FROM 6 for 2)) AS Integer) AS BDREFERENCIA, ';
      wSQL = wSQL||               'i.BDCHAVE, i.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, ';
      IF (wINCTRIB = 1) THEN
        BEGIN
          wSQL = wSQL||             'iif(((i.BDCODCSTPIS = 1) AND (CAST(i.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)))), 4, null) AS BDCOD_CONT_PIS, ';
          wSQL = wSQL||             'iif(((i.BDCODCSTCOF = 1) AND (CAST(i.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)))), 4, null) AS BDCOD_CONT_COF, ';
        END
      ELSE
      IF (wINCTRIB = 2) THEN
        BEGIN
          wSQL = wSQL||             'iif(((i.BDCODCSTPIS = 1) AND (CAST(i.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)))), 54, null) AS BDCOD_CONT_PIS, ';
          wSQL = wSQL||             'iif(((i.BDCODCSTCOF = 1) AND (CAST(i.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)))), 54, null) AS BDCOD_CONT_COF, ';
        END
      ELSE
      IF (wINCTRIB = 3) THEN
        BEGIN
          wSQL = wSQL||           'CASE i.BDCODCSTPIS ';
          wSQL = wSQL||             'WHEN 1 THEN CASE CAST(i.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 04 ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE null ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'WHEN 5 THEN CASE CAST(i.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE 32 ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'ELSE null ';
          wSQL = wSQL||           'END AS BDCOD_CONT_PIS, ';

          wSQL = wSQL||           'CASE i.BDCODCSTCOF ';
          wSQL = wSQL||             'WHEN 1 THEN CASE CAST(i.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 04 ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE null ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'WHEN 5 THEN CASE CAST(i.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE 32 ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'ELSE null ';
          wSQL = wSQL||           'END AS BDCOD_CONT_COF, ';
        END
      wSQL = wSQL||               'i.BDVLRTOTRECPAR AS BDVL_ITEM,';
      wSQL = wSQL||               'i.BDCODCSTPIS, i.BDBASEPIS AS BDBCPIS, i.BDALIQPIS, i.BDVLRPIS,';
      wSQL = wSQL||               'i.BDCODCSTCOF, i.BDBASECOFINS AS BDBCCOFINS, i.BDALIQCOFINS, i.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT f.BDCODEMP, f.BDCHAVE ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 f ';
      wSQL = wSQL||               'WHERE F.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'WHERE (i.BDDATAPGTO is not null) ';
      wSQL = wSQL||          'AND (Cast((SubString(i.BDDATAPGTO FROM 1 for 4)||SubString(i.BDDATAPGTO FROM 6 for 2)) AS Integer) = '||:prREFERENCIA||') ';

      wSQL = wSQL||        'union all ';
                           /* I100 */
      wSQL = wSQL||        'SELECT i100.BDCODEMP, COALESCE(emp.BDCODMATRIZ, i100.BDCODEMP) as BDCODMATRIZ, i100.BDREFERENCIA, i100.BDCHAVE, NULL as BDORDEM,';
--      wSQL = wSQL||               'NULL as BDORDEMPRO, 9 as BDCODTP, NULL as BDCOD_CONT_PIS, NULL as BDCOD_CONT_COF, (i100.BDVLRREC-i100.BDVLRTOTDEDGER-i100.BDVLRTOTDEDESP) as BDVL_ITEM,';
      wSQL = wSQL||               'NULL as BDORDEMPRO, 9 as BDCODTP, NULL as BDCOD_CONT_PIS, NULL as BDCOD_CONT_COF, i100.BDVLRREC as BDVL_ITEM,';
      wSQL = wSQL||               'i100.BDCODCSTPISCOF as BDCODCSTPIS, i100.BDBASEPIS as BDBCPIS, i100.BDALIQPIS, i100.BDVLRPIS,';
      wSQL = wSQL||               'i100.BDCODCSTPISCOF as BDCODCSTCOF, i100.BDBASECOFINS as BDBCCOFINS, i100.BDALIQCOFINS, i100.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL as BDQUANT_BC_PIS, NULL as BDALIQ_PIS_QUANT, NULL as BDQUANT_BC_COF, NULL as BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM VEF_EMP_TMOVFINI100 i100 ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = i100.BDCODEMP) ';
      wSQL = wSQL||        'WHERE i100.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         ' AND i100.BDREFERENCIA = '||:prREFERENCIA||' ';

      wSQL = wSQL||        ') aux ';
--      wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS in (1,2,3,5)) OR (aux.BDCODCSTCOF in (1,2,3,5))) '; -- CSTs que geram regitros M200/600...

      EXECUTE STATEMENT ( wSQL );

      /* Insere os valores no nas tabelas do M210 e M610, pois j? atingiu o tamanho m?ximo da SP */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX (:prCODEMP, :prREFERENCIA);

    END

END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M210_M610 for: SP_APURACAO_BLOCOM_M210_M610AUX */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M210_M610(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_M210_M610AUX) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCSOCIAL INTEGER;
DECLARE VARIABLE WINDNATPJ INTEGER;
DECLARE VARIABLE WALIQ_PIS_IT_1 VARCHAR(5);
DECLARE VARIABLE WALIQ_COF_IT_1 VARCHAR(5);
DECLARE VARIABLE WALIQ_PIS_IT_2 VARCHAR(5);
DECLARE VARIABLE WALIQ_COF_IT_2 VARCHAR(5);
BEGIN
  /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
  wALIQ_PIS_IT_1 = '1.65';
  wALIQ_COF_IT_1 = '7.60';
  /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
  wALIQ_PIS_IT_2 = '0.65';
  wALIQ_COF_IT_2 = '3.00';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  SELECT BDINDNATPJ FROM VW_VEF_BASE_TEMPPARFED WHERE BDCODEMP = :prCODEMP INTO :wINDNATPJ;

  /* REGISTRO M210: DETALHAMENTO DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER) ';
  wSQL = wSQL||'SELECT 19 as BDCODQUADRO, 7 as BDCODPERIODO, tmp.BDCODEMP, COALESCE(emp.BDCODMATRIZ, tmp.BDCODEMP) as BDCODMATRIZ, tmp.BDREFERENCIA, ';
  wSQL = wSQL||'       (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7) as BDCHAVE, ';
  wSQL = wSQL||'       t435.BDCODCSOCIAL, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDVL_REC_BRT,0)) as BDVL_REC_BRT, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDVL_BC_CONT_PIS,0)) as BDVL_BC_CONT, tmp.BDALIQ_PIS as BDALIQ, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDQUANT_BC_PIS,0)) as BDQUANT_BC, tmp.BDALIQ_QUANT_PIS as BDALIQ_QUANT, ';
  wSQL = wSQL||'       (SUM(IIF(COALESCE(tmp.BDVL_BC_CONT_PIS,0) > 0, tmp.BDVL_BC_CONT_PIS, COALESCE(tmp.BDQUANT_BC_PIS, 0))*IIF(COALESCE(tmp.BDALIQ_PIS,0) > 0, tmp.BDALIQ_PIS, COALESCE(tmp.BDALIQ_QUANT_PIS,1)))) as BDVL_CONT_APUR, ';
  wSQL = wSQL||'       0 as BDVL_AJUS_ACRES, ';
  wSQL = wSQL||'       0 as BDVL_AJUS_REDUC, ';
  wSQL = wSQL||'       0 as BDVL_CONT_DIFER, ';
  wSQL = wSQL||'       0 as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||'       0 as BDVL_CONT_PER ';
  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = tmp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIALEXP = tmp.BDCOD_CONT_PIS) ';
  wSQL = wSQL||'WHERE (((tmp.BDVL_BC_CONT_PIS > 0) or (tmp.BDALIQ_PIS > 0)) or ';
  wSQL = wSQL||'       ((tmp.BDQUANT_BC_PIS > 0) or (tmp.BDALIQ_QUANT_PIS > 0))) ';
  wSQL = wSQL||'  AND (tmp.BDCODCSTPIS in (1,2,3,5)) '; -- CSTs que geram regitros M200/600...
  wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS <> 5) OR ((tmp.BDCODCSTPIS = 5) and ((tmp.BDALIQ_PIS > 0) or (tmp.BDALIQ_QUANT_PIS > 0)))) '; -- CST 05 com al?quota zerada vai no M400/M800...
  wSQL = wSQL||'  AND ((tmp.BDCODTP NOT IN (3,10,11,16)) OR '; -- Lan?amentos de transporte com CST inv?lida, tem inconsist?ncia...
  wSQL = wSQL||'       ((tmp.BDCODTP IN (3,10,11,16)) AND (tmp.BDCODCSTPIS <> (03))) ) ';
  wSQL = wSQL||'  AND (tmp.BDCOD_CONT_PIS IS NOT NULL) ';
  wSQL = wSQL||'  AND (t435.BDCODCSOCIAL IS NOT NULL) ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))) ) ';
     END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) ) ';
     END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Exclusivamente no regime n?o-cumulativo / Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       ((CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))) OR (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4)))) ) ';
     END
   wSQL = wSQL||'GROUP BY tmp.BDCODEMP, emp.BDCODMATRIZ, tmp.BDREFERENCIA, t435.BDCODCSOCIAL, tmp.BDALIQ_PIS, tmp.BDALIQ_QUANT_PIS; ';

   EXECUTE STATEMENT ( wSQL );

  /* REGISTRO M610: DETALHAMENTO DA CONTRIBUI??O PARA A SEGURIDADE SOCIAL - COFINS DO PER?ODO */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER) ';
  wSQL = wSQL||'SELECT 37 as BDCODQUADRO, 7 as BDCODPERIODO, tmp.BDCODEMP, COALESCE(emp.BDCODMATRIZ, tmp.BDCODEMP) as BDCODMATRIZ, tmp.BDREFERENCIA, ';
  wSQL = wSQL||'      (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7) as BDCHAVE, ';
  wSQL = wSQL||'      t435.BDCODCSOCIAL, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDVL_REC_BRT,0)) as BDVL_REC_BRT, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDVL_BC_CONT_COF,0)) as BDVL_BC_CONT, tmp.BDALIQ_COF as BDALIQ, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDQUANT_BC_COF,0)) as BDQUANT_BC, tmp.BDALIQ_QUANT_COF as BDALIQ_QUANT, ';
  wSQL = wSQL||'      (SUM(IIF(COALESCE(tmp.BDVL_BC_CONT_COF,0) > 0, tmp.BDVL_BC_CONT_COF, COALESCE(tmp.BDQUANT_BC_COF, 0))*IIF(COALESCE(tmp.BDALIQ_COF,0) > 0, tmp.BDALIQ_COF, COALESCE(tmp.BDALIQ_QUANT_COF,1)))) as BDVL_CONT_APUR, ';
  wSQL = wSQL||'      0 as BDVL_AJUS_ACRES, ';
  wSQL = wSQL||'      0 as BDVL_AJUS_REDUC, ';
  wSQL = wSQL||'      0 as BDVL_CONT_DIFER, ';
  wSQL = wSQL||'      0 as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||'      0 as BDVL_CONT_PER ';
  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = tmp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIALEXP = tmp.BDCOD_CONT_COF) ';
  wSQL = wSQL||'WHERE (((tmp.BDVL_BC_CONT_COF > 0) or (tmp.BDALIQ_COF > 0)) or ';
  wSQL = wSQL||'       ((tmp.BDQUANT_BC_COF > 0) or (tmp.BDALIQ_QUANT_COF > 0))) ';
  wSQL = wSQL||'  AND (tmp.BDCODCSTCOF in (1,2,3,5)) '; -- CSTs que geram regitros M200/600...
  wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF <> 5) OR ((tmp.BDCODCSTCOF = 5) and ((tmp.BDALIQ_COF > 0) or (tmp.BDALIQ_QUANT_COF > 0)))) '; -- CST 05 com al?quota zerada vai no M400/M800...
  wSQL = wSQL||'  AND ((tmp.BDCODTP NOT IN (3,10,11,16)) OR '; -- Lan?amentos de transporte com CST inv?lida, tem inconsist?ncia...
  wSQL = wSQL||'       ((tmp.BDCODTP IN (3,10,11,16)) AND (tmp.BDCODCSTCOF <> (03))) ) ';
  wSQL = wSQL||'  AND (tmp.BDCOD_CONT_COF IS NOT NULL) ';
  wSQL = wSQL||'  AND (t435.BDCODCSOCIAL IS NOT NULL) ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(7.60 as NUMERIC(7,4))) ) ';
    END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(3.00 as NUMERIC(7,4))) ) ';
    END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Exclusivamente no regime n?o-cumulativo / Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       ((CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(7.60 as NUMERIC(7,4))) OR (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(3.00 as NUMERIC(7,4)))) ) ';
    END
   wSQL = wSQL||'GROUP BY tmp.BDCODEMP, emp.BDCODMATRIZ, tmp.BDREFERENCIA, t435.BDCODCSOCIAL, tmp.BDALIQ_COF, tmp.BDALIQ_QUANT_COF; ';

  EXECUTE STATEMENT ( wSQL );
   
  /* Atualiza os valores ap?s inserir, n?o faz no insert/select acima para n?o matriciar */
  FOR
      SELECT BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL
      FROM VEF_EMP_TBLOCOM210_M610 x
      WHERE x.BDCODMATRIZ = :prCODEMP
        AND x.BDREFERENCIA = :prREFERENCIA
      INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCODCSOCIAL
  DO
    BEGIN
      /* Verifica o quadros para pegar os campos corretos, PIS ou Cofins */
      /* Quando alterar os Selects dos campos, n?o esquecer de atualizar os Selects do campos 13... */
      UPDATE VEF_EMP_TBLOCOM210_M610 x
      SET -- 04 - VL_BC_CONT - Valor da Base de C?lculo da Contribui??o
          -- Se a empresa for sociedade cooperativa, vai descontar os lan?amentos de ajuste do M211...
          x.BDVL_BC_CONT = IIF(:wINDNATPJ IN (1,4),
--                               (IIF(((COALESCE(x.BDVL_BC_CONT,0) > 0) OR (x.BDCODCSOCIAL = 3)), COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))- -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
                               (x.BDVL_BC_CONT-
                                COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0)+COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0)+COALESCE(m211.BDVLREXCLUBCCOFINS,0) ))
                                          FROM VEF_EMP_TSOCCOOPM211M611 m211
                                          WHERE m211.BDCODEMP = x.BDCODEMP
                                            AND m211.BDREFERENCIA = x.BDREFERENCIA
                                            AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                            AND (((x.BDCODQUADRO = 19) AND (m211.BDALIQPIS = x.BDALIQ)) OR
                                                 ((x.BDCODQUADRO = 37) AND (m211.BDALIQCOFINS = x.BDALIQ)))),0)
                                        ),
--                               IIF(((COALESCE(x.BDVL_BC_CONT,0) > 0) OR (x.BDCODCSOCIAL = 3)), COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))), -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
                               x.BDVL_BC_CONT), -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
          -- 08 - VL_CONT_APUR - Valor total da contribui??o social apurada
          x.BDVL_CONT_APUR = (((IIF(:wINDNATPJ IN (1,4),
                                    (IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))-
                                     COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19),COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) FROM VEF_EMP_TSOCCOOPM211M611 m211
                                     WHERE m211.BDCODEMP = x.BDCODEMP
                                       AND m211.BDREFERENCIA = x.BDREFERENCIA
                                       AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                                 AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT))) OR
                                                      ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))))),0) ),
                                    IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0)))
                                )*IIF(COALESCE(x.BDALIQ,0) > 0, COALESCE(x.BDALIQ,0), COALESCE(x.BDALIQ_QUANT,1)))/IIF(COALESCE(x.BDALIQ,0) > 0, 100, 1)), -- Caso seja por quantidade, multiplica sem al?quota....
          -- 09 - VL_AJUS_ACRES - Valor total dos ajustes de acr?scimo
          x.BDVL_AJUS_ACRES = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 1 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 10 - VL_AJUS_REDUC - Valor total dos ajustes de redu??o
          x.BDVL_AJUS_REDUC = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 0 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 11 - VL_CONT_DIFER - Valor da contribui??o a diferir no per?odo
          x.BDVL_CONT_DIFER = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m230.BDVLRCONDEFPIS,0), COALESCE(m230.BDVLRCONDEFCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 m230 WHERE m230.BDCODEMP = x.BDCODEMP AND m230.BDREFERENCIA = x.BDREFERENCIA AND m230.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m230.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m230.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 12 - VL_CONT_DIFER_ANT - Valor da contribui??o diferida em per?odos anteriores
          x.BDVL_CONT_DIFER_ANT = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), (COALESCE(m300.BDVLRCONTRIPIS,0)-COALESCE(m300.BDVLRCREPIS,0)), (COALESCE(m300.BDVLRCONTRICOFINS,0)-COALESCE(m300.BDVLRCRECOFINS,0)))) FROM VEF_EMP_TINFADIDEFM300M700 m300 WHERE m300.BDCODEMP = x.BDCODEMP AND m300.BDREFERENCIA = x.BDREFERENCIA AND m300.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m300.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m300.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 13 - VL_CONT_PER - Valor Total da Contribui??o do Per?odo (08 + 09 ? 10 ? 11 + 12)
          x.BDVL_CONT_PER = (
          /*   08 - VL_CONT_APUR */       (((IIF(:wINDNATPJ IN (1,4),
                                                 (IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))-
                                                  COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19),COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) FROM VEF_EMP_TSOCCOOPM211M611 m211
                                                  WHERE m211.BDCODEMP = x.BDCODEMP
                                                    AND m211.BDREFERENCIA = x.BDREFERENCIA
                                                    AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                                              AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT))) OR
                                                                   ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))))),0) ),
                                                 IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0)))
                                             )*IIF(COALESCE(x.BDALIQ,0) > 0, COALESCE(x.BDALIQ,0), COALESCE(x.BDALIQ_QUANT,1)))/IIF(COALESCE(x.BDALIQ,0) > 0, 100, 1)) -- Caso seja por quantidade, multiplica sem al?quota....
          /* + 09 - VL_AJUS_ACRES */     +(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 1 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* ? 10 - VL_AJUS_REDUC */     -(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 0 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* ? 11 - VL_CONT_DIFER */     -(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m230.BDVLRCONDEFPIS,0), COALESCE(m230.BDVLRCONDEFCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 m230 WHERE m230.BDCODEMP = x.BDCODEMP AND m230.BDREFERENCIA = x.BDREFERENCIA AND m230.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m230.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m230.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* + 12 - VL_CONT_DIFER_ANT */ +(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), (COALESCE(m300.BDVLRCONTRIPIS,0)-COALESCE(m300.BDVLRCREPIS,0)), (COALESCE(m300.BDVLRCONTRICOFINS,0)-COALESCE(m300.BDVLRCRECOFINS,0)))) FROM VEF_EMP_TINFADIDEFM300M700 m300 WHERE m300.BDCODEMP = x.BDCODEMP AND m300.BDREFERENCIA = x.BDREFERENCIA AND m300.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m300.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m300.BDALIQCOFINS = x.BDALIQ))) ),0))
                             )
      WHERE x.BDCODPERIODO = :wCODPERIODO
        AND x.BDCODEMP = :wCODEMP
        AND x.BDCODMATRIZ = :wCODMATRIZ
        AND x.BDCODQUADRO = :wCODQUADRO
        AND x.BDREFERENCIA = :wREFERENCIA
        AND x.BDCHAVE = :wCHAVE;

  IF (:wINDNATPJ IN (1,4)) THEN -- Apenas se a empresa for "01 ? Sociedade cooperativa" ou "04 ? Sociedade cooperativa participante de SCP como s?cia ostensiva"
    BEGIN
          /* REGISTRO M211: SOCIEDADES COOPERATIVAS ? COMPOSI??O DA BASE DE CALCULO ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM211_M611 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDTIPOSOCCOOP, BDVL_BC_CONT_ANT_EXC, BDVL_EXC_COOP_GER, BDVL_EXC_ESP_COOP, BDVL_BC_CONT)
      SELECT :wCODPERIODO AS BDCODPERIODO, m211.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m211.BDCODEMP) AS BDCODMATRIZ, :wCODQUADRO AS BDCODQUADRO, m211.BDREFERENCIA, :wCHAVE AS BDCHAVE,
                 (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
                  FROM VEF_EMP_TBLOCOM211_M611 x
                  WHERE x.BDCODPERIODO = :wCODPERIODO
                    AND x.BDCODEMP = :wCODEMP
                    AND x.BDCODMATRIZ = :wCODMATRIZ
                    AND x.BDCODQUADRO = :wCODQUADRO
                    AND x.BDREFERENCIA = :wREFERENCIA
                    AND x.BDCHAVE = :wCHAVE) AS BDORDEM,
             m211.BDTIPOSOCCOOP,
             -- 03 - VL_BC_CONT_ANT_EXC_COOP - Valor da Base de C?lculo da Contribui??o, conforme Registros escriturados nos Blocos A, C, D e F, antes das Exclus?es das Cooperativas.
                 (SELECT ( SUM(x.BDVL_BC_CONT)+
                           -- Como j? abateu as exclus?es no select complementar acima, adiciona esses valores aqui...
                           SUM(IIF((x.BDCODQUADRO = 19), COALESCE(SUM(m211.BDVLREXCLUGERPIS),0)+COALESCE(SUM(m211.BDVLREXCLUBCPIS),0),
                                                         COALESCE(SUM(m211.BDVLREXCLUGERCOFINS),0)+COALESCE(SUM(m211.BDVLREXCLUBCCOFINS),0) )) ) as BDVL_BC_CONT


                  FROM VEF_EMP_TBLOCOM210_M610 x
                  WHERE x.BDCODPERIODO = :wCODPERIODO
                    AND x.BDCODEMP = :wCODEMP
                    AND x.BDCODMATRIZ = :wCODMATRIZ
                    AND x.BDCODQUADRO = :wCODQUADRO
                    AND x.BDREFERENCIA = :wREFERENCIA
                    AND x.BDCHAVE = :wCHAVE
                    AND x.BDCODCSOCIAL = :wCODCSOCIAL
                    AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT)) ) OR
                         ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))) ) ) AS BDVL_BC_CONT_ANT_EXC,
             -- 04 - VL_EXC_COOP_GER - Valor de Exclus?o Especifica das Cooperativas em Geral, decorrente das Sobras Apuradas na DRE, destinadas a constitui??o do Fundo de Reserva e do FATES.
             SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0))) AS BDVL_EXC_COOP_GER,
             -- 05 - VL_EXC_ESP_COOP - Valor das Exclus?es da Base de C?lculo Especifica do Tipo da Sociedade Cooperativa, conforme Campo 02 (IND_TIP_COOP).
             SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) AS BDVL_EXC_ESP_COOP,
             -- 06 - VL_BC_CONT - Valor da Base de C?lculo, Ap?s as Exclus?es Especificas da Sociedade Cooperativa (04 ? 05 ? 06) ? Transportar para M210.
                 /* 03 - VL_BC_CONT_ANT_EXC_COOP */ ( (SELECT SUM(x.BDVL_BC_CONT) as BDVL_BC_CONT
                                                       FROM VEF_EMP_TBLOCOM210_M610 x
                                                       WHERE x.BDCODPERIODO = :wCODPERIODO
                                                         AND x.BDCODEMP = :wCODEMP
                                                         AND x.BDCODMATRIZ = :wCODMATRIZ
                                                         AND x.BDCODQUADRO = :wCODQUADRO
                                                         AND x.BDREFERENCIA = :wREFERENCIA
                                                         AND x.BDCHAVE = :wCHAVE
                                                         AND x.BDCODCSOCIAL = :wCODCSOCIAL)
                 -- J? abateu as exclus?es no select complementar acima...
                 --/* 04 - VL_EXC_COOP_GER */          -SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0)))
                 --/* 05 - VL_EXC_ESP_COOP */          -SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0)))
                                                      ) AS BDVL_BC_CONT
      FROM VEF_EMP_TSOCCOOPM211M611 m211
      LEFT OUTER JOIN TEMPRESAS emp ON (emp.BDCODEMP = m211.BDCODEMP)
      WHERE m211.BDCODEMP = :wCODEMP
        AND m211.BDREFERENCIA = :wREFERENCIA
            AND m211.BDCODCSOCIAL = :wCODCSOCIAL
            AND ( ((:wCODQUADRO = 19) AND ((m211.BDALIQPIS > 0) OR (m211.BDVLREXCLUGERPIS > 0) OR (m211.BDVLREXCLUBCPIS > 0))) OR
                  ((:wCODQUADRO = 37) AND ((m211.BDALIQCOFINS > 0) OR (m211.BDVLREXCLUGERCOFINS > 0) OR (m211.BDVLREXCLUBCCOFINS > 0))) )
            AND (EXISTS(SELECT *
                        FROM VEF_EMP_TBLOCOM210_M610 x
                        WHERE x.BDCODEMP = m211.BDCODEMP
                          AND x.BDREFERENCIA = m211.BDREFERENCIA
                          AND x.BDCODCSOCIAL = m211.BDCODCSOCIAL
                          AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT)) ) OR
                               ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))) )
                        ))
          GROUP BY m211.BDCODEMP, emp.BDCODMATRIZ, m211.BDREFERENCIA, m211.BDTIPOSOCCOOP, m211.BDALIQPIS, m211.BDALIQCOFINS;
        END

  END
  
  /* Aliquota diferente do padr?o nos lan?amentos do M210 e M610 #Inconsist?ncia# */
  wSQL =       'INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC) ';
  wSQL = wSQL||'SELECT aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = aux.BDCODMATRIZ AND x.BDREFERENCIA = '||:prREFERENCIA||') AS BDCODBLOCOM, ';
  wSQL = wSQL||       'aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODINC ';
  wSQL = wSQL||'FROM ( ';
  -- PIS/PASEP
  wSQL = wSQL||       'SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '       aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 6 AS BDCODINC ';
  wSQL = wSQL||       'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux ';
  wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
  --wSQL = wSQL||       'WHERE (aux.BDCODCSTPIS NOT IN (02,03,05)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||       'WHERE (aux.BDCODCSTPIS IN (01)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||         'AND aux.BDCODEMP in (SELECT ex.BDCODEMP ';
  wSQL = wSQL||                              'FROM TEMPRESAS ex ';
  wSQL = wSQL||                              'WHERE ex.BDCODEMP = '||:prCODEMP||' ';
  wSQL = wSQL||                                 'OR ex.BDCODMATRIZ = '||:prCODEMP||') ';
  wSQL = wSQL||         'AND (aux.BDREFERENCIA = '||:prREFERENCIA||') ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))) ';
     END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))) ';
     END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
     BEGIN
      wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))) AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)))) ';
     END

  wSQL = wSQL||       'UNION ALL ';
  -- Cofins
  wSQL = wSQL||       'SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '       aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 7 AS BDCODINC ';
  wSQL = wSQL||       'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux ';
  wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
  --wSQL = wSQL||       'WHERE (aux.BDCODCSTCOF NOT IN (02,03,05)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||       'WHERE (aux.BDCODCSTCOF IN (01)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||         'AND aux.BDCODEMP in (SELECT ex.BDCODEMP ';
  wSQL = wSQL||                              'FROM TEMPRESAS ex ';
  wSQL = wSQL||                              'WHERE ex.BDCODEMP = '||:prCODEMP||' ';
  wSQL = wSQL||                                 'OR ex.BDCODMATRIZ = '||:prCODEMP||') ';
  wSQL = wSQL||         'AND (aux.BDREFERENCIA = '||:prREFERENCIA||') ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))) ';
    END
  ELSE
  IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))) ';
    END
  ELSE
  IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
    BEGIN
      wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))) AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)))) ';
    END

   wSQL = wSQL||      ') aux ';

   EXECUTE STATEMENT ( wSQL );

  /* CST 03 n?o permitida nos lan?amentos "A100/A170, C600/C601,D200/D201,D300,D600/D601" #Inconsist?ncia# */
  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
  SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
         aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 4 AS BDCODINC
  FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux
  WHERE ((aux.BDCODCSTPIS IN (03)) OR (aux.BDCODCSTCOF IN (03)))
    AND (aux.BDCODTP IN (3,10,11,16))
    AND (aux.BDCODMATRIZ = :prCODEMP)
    AND (aux.BDREFERENCIA = :prREFERENCIA);

  /* CST diferente de 01, a ?nica permitida nos lan?amentos de opera??es imobili?rias  #Inconsist?ncia# */
  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
  SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
         aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 10 AS BDCODINC
  FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux
  WHERE ((aux.BDCODCSTPIS <> 01) OR (aux.BDCODCSTCOF <> 01))
    AND (aux.BDCODTP IN (14))
    AND (aux.BDCODMATRIZ = :prCODEMP)
    AND (aux.BDREFERENCIA = :prREFERENCIA);

  IF (:wINDNATPJ IN (1,4)) THEN -- Apenas se a empresa for "01 ? Sociedade cooperativa" ou "04 ? Sociedade cooperativa participante de SCP como s?cia ostensiva"
    BEGIN
      /* Registros de M210/M610 sem M211/M611 respectivo #Inconsist?ncia# */
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDREPLACES)
      SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
             NULL as BDCODTP, NULL as BDCHAVE, NULL as BDORDEM, NULL as BDORDEMPRO, 11 AS BDCODINC,
             aux.BDCODCSOCIAL||'?'||CASE WHEN aux.BDCODQUADRO = 19 THEN 'PIS' ELSE 'Cofins' END||'?'||IIF(aux.BDALIQ > 0, aux.BDALIQ, aux.BDALIQ_QUANT) as BDREPLACES
      FROM VEF_EMP_TBLOCOM210_M610 aux
      WHERE (aux.BDCODMATRIZ = :prCODEMP)
        AND (aux.BDREFERENCIA = :prREFERENCIA)
        AND (NOT EXISTS(SELECT *
                        FROM VEF_EMP_TBLOCOM211_M611 m211
                        WHERE m211.BDCODPERIODO = aux.BDCODPERIODO
                          AND m211.BDCODEMP = aux.BDCODEMP
                          AND m211.BDCODMATRIZ = aux.BDCODMATRIZ
                          AND m211.BDCODQUADRO = aux.BDCODQUADRO
                          AND m211.BDREFERENCIA = aux.BDREFERENCIA
                          AND m211.BDCHAVE = aux.BDCHAVE ));
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M220_M620) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M220_M620(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  -- INSERE A COMPET?NCIA DA APURA??O...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT;

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* REGISTRO M220: AJUSTES DA CONTRIBUI??O PARA O PIS/PASEP APURADA */
      INSERT INTO VEF_EMP_TBLOCOM220_M620 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, DESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m220.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m220.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m220.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m220.BDCODEMP AND x.BDREFERENCIA = m220.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) ) as BDORDEM,
             m220.BDCODAJUEFDC, m220.BDTIPOAJUSTE as BDIND_AJ, m220.BDVLRAJUPIS as BDVL_AJ, m220.BDNUMERODOC as BDNUM_DOC, m220.BDDESCRICAO as DESCR_AJ, m220.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TAJUAPUPCM220620 m220
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m220.BDCODEMP)
      WHERE m220.BDVLRAJUPIS > 0
        AND m220.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m220.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m220.BDCODEMP
                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL));

      /* REGISTRO M225: DETALHAMENTO DOS AJUSTES DA CONTRIBUI??O PARA O PIS/PASEP APURADA */
      INSERT INTO VEF_EMP_TBLOCOM225_M625 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM25, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCSTPIS, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m220.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m220.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m220.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m220.BDCODEMP AND x.BDREFERENCIA = m220.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) as BDCHAVE,
             (SELECT FIRST 1 x.BDORDEM
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDNUM_DOC = m220.BDNUMERODOC
                AND x.DESCR_AJ  = m220.BDDESCRICAO
                AND x.BDDT_REF  = m220.BDDATAREF
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM25)+1, 1)
              FROM VEF_EMP_TBLOCOM225_M625 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL)
                AND x.BDORDEM = (SELECT FIRST 1 x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM220_M620 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDNUM_DOC = m220.BDNUMERODOC
                                   AND x.DESCR_AJ  = m220.BDDESCRICAO
                                   AND x.BDDT_REF  = m220.BDDATAREF
                                   AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                                    FROM VEF_EMP_TBLOCOM210_M610 x
                                                    WHERE x.BDCODEMP = m220.BDCODEMP
                                                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                                                      AND x.BDCODQUADRO = 19
                                                      AND x.BDCODPERIODO = 7
                                                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL)) ) as BDORDEM25,
             m625.BDCODCSTCOF, m625.BDCODPLAPADRAO, m625.BDCODTPLA, m625.BDCODCSTPIS, m625.BDVALORPIS as BDDET_VALOR_AJ, m625.BDBCPIS as BDDET_BC_CRED, m625.BDALIQPIS as BDDET_ALIQ,
             m625.BDDATAOPEPIS as BDDT_OPER_AJ, m625.BDDESCRICAOAJU as BDDESC_AJ, m625.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TAJUAPUPCM220620 m220
      JOIN VEF_EMP_TDETAJUM225625 m625 on (m220.BDCODEMP = m625.BDCODEMP AND m220.BDCHAVE = m625.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m220.BDCODEMP)
      WHERE m220.BDVLRAJUPIS > 0
        AND m220.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m220.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m220.BDCODEMP
                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL));

      /* REGISTRO M620: AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM220_M620 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, DESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m620.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m620.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m620.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m620.BDCODEMP AND x.BDREFERENCIA = m620.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) ) as BDORDEM,
             m620.BDCODAJUEFDC, m620.BDTIPOAJUSTE as BDIND_AJ, m620.BDVLRAJUCOFINS as BDVL_AJ, m620.BDNUMERODOC as BDNUM_DOC, m620.BDDESCRICAO as DESCR_AJ, m620.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TAJUAPUPCM220620 m620
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m620.BDCODEMP)
      WHERE m620.BDVLRAJUCOFINS > 0
        AND m620.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m620.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m620.BDCODEMP
                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL));

      /* REGISTRO M625: DETALHAMENTO DOS AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM225_M625 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM25, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCSTPIS, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m620.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m620.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m620.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m620.BDCODEMP AND x.BDREFERENCIA = m620.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) as BDCHAVE,
             (SELECT FIRST 1 x.BDORDEM
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDNUM_DOC = m620.BDNUMERODOC
                AND x.DESCR_AJ  = m620.BDDESCRICAO
                AND x.BDDT_REF  = m620.BDDATAREF
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM25)+1, 1)
              FROM VEF_EMP_TBLOCOM225_M625 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL)
                AND x.BDORDEM = (SELECT FIRST 1 x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM220_M620 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDNUM_DOC = m620.BDNUMERODOC
                                   AND x.DESCR_AJ  = m620.BDDESCRICAO
                                   AND x.BDDT_REF  = m620.BDDATAREF
                                   AND x.BDCHAVE = (SELECT x.BDCHAVE
                                                    FROM VEF_EMP_TBLOCOM210_M610 x
                                                    WHERE x.BDCODEMP = m620.BDCODEMP
                                                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                                                      AND x.BDCODQUADRO = 37
                                                      AND x.BDCODPERIODO = 7
                                                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL)) ) as BDORDEM25,
             m625.BDCODCSTCOF, m625.BDCODPLAPADRAO, m625.BDCODTPLA, m625.BDCODCSTPIS, m625.BDVALORCOFINS as BDDET_VALOR_AJ, m625.BDBCCOFINS as BDDET_BC_CRED, m625.BDALIQCOFINS as BDDET_ALIQ,
             m625.BDDATAOPECOFINS as BDDT_OPER_AJ, m625.BDDESCRICAOAJU as BDDESC_AJ, m625.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TAJUAPUPCM220620 m620
      JOIN VEF_EMP_TDETAJUM225625 m625 on (m620.BDCODEMP = m625.BDCODEMP AND m620.BDCHAVE = m625.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m620.BDCODEMP)
      WHERE m620.BDVLRAJUCOFINS > 0
        AND m620.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m620.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m620.BDCODEMP
                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL));
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M230_M630) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M230_M630(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  -- INSERE A COMPET?NCIA DA APURA??O...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT;

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* REGISTRO M230: INFORMA??ES ADICIONAIS DE DIFERIMENTO */
      INSERT INTO VEF_EMP_TBLOCOM230_M630 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCRE_4_3_6, BDCNPJ, BDVL_VEND, BDVL_NAO_RECEB, BDVL_CONT_DIF, BDVL_CRED_DIF)
      SELECT 7 as BDCODPERIODO, m230.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m230.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m230.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m230.BDCODEMP AND x.BDREFERENCIA = m230.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM230_M630 x
              WHERE x.BDCODEMP = m230.BDCODEMP
                AND x.BDREFERENCIA = m230.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m230.BDCODEMP
                                   AND x.BDREFERENCIA = m230.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL) ) as BDORDEM,
             m230.BDCODCRE_4_3_6, m230.BDCNPJPJRELACIONADA as BDCNPJ,
             m230.BDVLRVENDAPIS as BDVL_VEND, m230.BDVLRNRECPIS as BDVL_NAO_RECEB, m230.BDVLRCONDEFPIS as BDVL_CONT_DIF, m230.BDVLRCREDEFPIS as BDVL_CRED_DIF
      FROM VEF_EMP_TINFADIDEFM230630 m230
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m230.BDCODEMP)
      WHERE m230.BDALIQPIS > 0
        AND m230.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m230.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m230.BDCODEMP
                      AND x.BDREFERENCIA = m230.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL));

      /* REGISTRO M630: INFORMA??ES ADICIONAIS DE DIFERIMENTO */
      INSERT INTO VEF_EMP_TBLOCOM230_M630 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCRE_4_3_6, BDCNPJ, BDVL_VEND, BDVL_NAO_RECEB, BDVL_CONT_DIF, BDVL_CRED_DIF)
      SELECT 7 as BDCODPERIODO, m630.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m630.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m630.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m630.BDCODEMP AND x.BDREFERENCIA = m630.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM230_M630 x
              WHERE x.BDCODEMP = m630.BDCODEMP
                AND x.BDREFERENCIA = m630.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m630.BDCODEMP
                                   AND x.BDREFERENCIA = m630.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL) ) as BDORDEM,
             m630.BDCODCRE_4_3_6, m630.BDCNPJPJRELACIONADA as BDCNPJ,
             m630.BDVLRVENDACOFINS as BDVL_VEND, m630.BDVLRNRECCOFINS as BDVL_NAO_RECEB, m630.BDVLRCONDEFCOFINS as BDVL_CONT_DIF, m630.BDVLRCREDEPCOFINS as BDVL_CRED_DIF
      FROM VEF_EMP_TINFADIDEFM230630 m630
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m630.BDCODEMP)
      WHERE m630.BDALIQCOFINS > 0
        AND m630.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m630.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m630.BDCODEMP
                      AND x.BDREFERENCIA = m630.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL));

    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M300_M700) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M300_M700(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  /*
    REGISTRO M300: CONTRIBUI??O DE PIS/PASEP DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO.
    REGISTRO M700: COFINS DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO
  */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM300_M700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_CONT_APUR_DIFER, BDNAT_CRED_DESC, BDVL_CRED_DESC_DIFER, BDVL_CONT_DIFER_ANT, BDALIQ, BDPER_APUR, BDDT_RECEB) ';
  wSQL = wSQL||'SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE+1),1) FROM VEF_EMP_TBLOCOM300_M700 x WHERE x.BDCODPERIODO = aux.BDCODPERIODO AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) AND x.BDCODQUADRO = aux.BDCODQUADRO AND x.BDREFERENCIA = aux.BDREFERENCIA) AS BDCHAVE, ';
  wSQL = wSQL||       'aux.BDCODCSOCIAL, aux.BDVL_CONT_APUR_DIFER, aux.BDNAT_CRED_DESC, aux.BDVL_CRED_DESC_DIFER, aux.BDVL_CONT_DIFER_ANT, aux.BDALIQ, aux.BDPER_APUR, aux.BDDT_RECEB ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||      'SELECT 24 as BDCODQUADRO, '; -- M300 - Diferimentos Per?odos Anteriores de PIS/PASEP
  wSQL = wSQL||             '7 as BDCODPERIODO, m300.BDCODEMP, m300.BDREFERENCIA, m300.BDCODCSOCIAL, m300.BDVLRCONTRIPIS as BDVL_CONT_APUR_DIFER, ';
  wSQL = wSQL||             'm300.BDCODNATDEF as BDNAT_CRED_DESC, m300.BDVLRCREPIS as BDVL_CRED_DESC_DIFER, (m300.BDVLRCONTRIPIS-m300.BDVLRCREPIS) as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||             'm300.BDALIQPIS as BDALIQ, m300.BDREFERENCIA as BDPER_APUR, m300.BDDATAREC as BDDT_RECEB ';
  wSQL = wSQL||      'FROM VEF_EMP_TINFADIDEFM300M700 m300 ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 soc ON (soc.BDCODCSOCIAL = m300.BDCODCSOCIAL) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABNATCREDEF nat ON (nat.BDCODNATDEF = m300.BDCODNATDEF) ';
  wSQL = wSQL||      'WHERE m300.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND m300.BDREFERENCIA = '||:prREFERENCIA||' ';
  
  wSQL = wSQL||      ' UNION ALL ';
  
  wSQL = wSQL||      'SELECT 42 as BDCODQUADRO, '; -- M700 - Diferimentos Per?odos Anteriores de Cofins
  wSQL = wSQL||             '7 as BDCODPERIODO, m700.BDCODEMP, m700.BDREFERENCIA, m700.BDCODCSOCIAL, m700.BDVLRCONTRICOFINS as BDVL_CONT_APUR_DIFER, ';
  wSQL = wSQL||             'm700.BDCODNATDEF as BDNAT_CRED_DESC, m700.BDVLRCRECOFINS as BDVL_CRED_DESC_DIFER, (m700.BDVLRCONTRICOFINS-m700.BDVLRCRECOFINS) as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||             'm700.BDALIQCOFINS as BDALIQ, m700.BDREFERENCIA as BDPER_APUR, m700.BDDATAREC as BDDT_RECEB ';
  wSQL = wSQL||      'FROM VEF_EMP_TINFADIDEFM300M700 m700 ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 soc ON (soc.BDCODCSOCIAL = m700.BDCODCSOCIAL) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABNATCREDEF nat ON (nat.BDCODNATDEF = m700.BDCODNATDEF) ';
  wSQL = wSQL||      'WHERE m700.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND m700.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||      ') aux ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP); ';

  EXECUTE STATEMENT wSQL;

  /* REGISTRO M350: PIS/PASEP ? FOLHA DE SAL?RIOS */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M350 (:prCODEMP, :prREFERENCIA);
  
END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M300_M700 for: SP_APURACAO_BLOCOM_M350 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M300_M700(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_M350) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M350(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WALIQ NUMERIC(15,6);
DECLARE VARIABLE WCODIMP INTEGER;
DECLARE VARIABLE WVLRBRUTO NUMERIC(15,2);
DECLARE VARIABLE WVLRPIS NUMERIC(15,2);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT FIRST 1 i.BDCODIMP, i.BDALIQIMPOSTO
  FROM VW_TEMPRESAIMPOSTO e
  LEFT OUTER JOIN TIMPOSTO i ON (i.BDCODIMP = e.BDCODIMP)
  WHERE e.BDCODEMP = :prCODEMP
    AND i.BDCLASSIMP LIKE '01.01.01.04.%' -- "Classifica??o" PIS - Programa integra??o social
    AND i.BDCODSIS = 2 -- "Sistema" Folha
    AND i.BDDOCARRECADACAO = 1 -- "Documento arrecada??o" DARF
    AND i.BDCODTIPIMP = 6 -- "Tipo de imposto" PIS/Pasep
    AND i.BDTIPOIMPDOC = 2 -- "Tipo c?lculo imposto" PIS
    AND i.BDTIPORETENCAO = 1 -- "Reten??o" PIS
  INTO :wCODIMP, :wALIQ;

  IF (wALIQ IS NOT NULL) THEN -- A empresa deve ter o imposto cadastrado na empresa, caso contr?rio, n?o obriga...
    BEGIN
      SELECT --calc.BDCODEMP,calc.BDREFFN,
             SUM(CASE WHEN vr.BDTIPOCODVER = 0 THEN COALESCE(calc.BDVALVFN,0) ELSE 0 END) AS BDVLRBRUTO
             --SUM(CASE WHEN vr.BDPISVER = 'TRUE' THEN calc.BDVALVFN ELSE 0 END) AS BDVLRPIS -- Apenas verbas cadastradas como PIS
      FROM (
            SELECT fn.BDCODEMP, fn.BDCODCOL, fn.BDREFFN, fn.BDCODVER, fn.BDVALVFN
            FROM VRHF_EMP_TVERBAFN fn -- Folha normal
            WHERE fn.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND fn.BDREFFN = :prREFERENCIA
      
            UNION ALL
      
            SELECT rh.BDCODEMP, ad.BDCODCOL, ad.BDREFCOMP, ad.BDCODVER, ad.BDVALVFC
            FROM VRHF_EMP_TVERBAFC ad -- Folha normal complementar
            JOIN VW_VRHF_EMPRESAS_REF_ATUAL rh ON (ad.BDCODEMP = rh.BDCODEMP)
            WHERE (rh.BDCALCFCNAFNEMP <> 'TRUE')
              AND ad.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ad.BDREFCOMP = :prREFERENCIA
      
            UNION ALL
      
            SELECT ft.BDCODEMP, ft.BDCODCOL, ft.BDREFTOMADOR, ft.BDCODVER, ft.BDVALVFT
            FROM VRHF_EMP_TVERBATOMADOR ft -- Folha por tomador
            WHERE ft.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ft.BDREFTOMADOR = :prREFERENCIA
      
            UNION ALL
      
            SELECT ad.BDCODEMP, ad.BDCODCOL, ad.BDREFCOMP, ad.BDCODVER, ad.BDVALVFC
            FROM VRHF_EMP_TVERBAFCTOMADOR ad -- Folha por tomador complementar
            JOIN VW_VRHF_EMPRESAS_REF_ATUAL rh ON (ad.BDCODEMP = rh.BDCODEMP)
            WHERE (rh.BDCALCFCNAFNEMP <> 'TRUE')
              AND ad.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ad.BDREFCOMP = :prREFERENCIA
      
            UNION ALL
      
            SELECT dt.BDCODEMP, dt.BDCODCOL, dt.BDREF13, dt.BDCODVER, dt.BDVALV13
            FROM VRHF_EMP_TVERBA13 dt -- 13?
            WHERE dt.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND dt.BDREF13 = :prREFERENCIA
      
            UNION ALL
      
            SELECT cdt.BDCODEMP, cdt.BDCODCOL, cdt.BDREFC13, cdt.BDCODVER, cdt.BDVALVC13
            FROM VRHF_EMP_TVERBAC13 cdt -- Complemento 13o
            WHERE cdt.BDCODEMP in (SELECT ex.BDCODEMP
                                   FROM TEMPRESAS ex
                                   WHERE ex.BDCODEMP = :prCODEMP
                                      OR ex.BDCODMATRIZ = :prCODEMP)
              AND cdt.BDREF13 = :prREFERENCIA
            ) calc
      JOIN VW_VRH_EMP_TCOLCON_VINC col ON (col.BDCODEMP = calc.BDCODEMP AND col.BDCODCOL = calc.BDCODCOL)
      JOIN VRH_BASE_TCLASSE cla ON (col.BDCODCLA = cla.BDCODCLA)
      JOIN VW_VERBAS_REF_ATUAL vr ON (vr.BDCODVER = calc.BDCODVER)
      --GROUP BY calc.BDCODEMP, calc.BDREFFN
      INTO :wVLRBRUTO;--, :wVLRPIS;

      /* Caso n?o tenha apura??o da folha #Inconsist?ncia# */
      --IF (:wVLRBRUTO IS NULL) THEN
      --  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
      --                        VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA), NULL, NULL, NULL, NULL, 3);

      SELECT SUM(COALESCE(d.BDBASEIMP,0)) as BDBASEIMP
      FROM TDARFPADRAO d
      WHERE d.BDCODIMP = :wCODIMP
        AND d.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND d.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRPIS;

      /* Caso n?o tenha apura??o do Darf PIS #Inconsist?ncia# */
      IF (:wVLRPIS IS NULL) THEN
        INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
                              VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA), NULL, NULL, NULL, NULL, 12);

    END

  IF ((wALIQ IS NULL) OR (wVLRBRUTO IS NULL) OR (wVLRPIS IS NULL)) THEN
    EXIT;

  /* 02 - VL_TOT_FOL - Valor Total da Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 2, :wVLRBRUTO);

  /* 03 - VL_EXC_BC - Valor Total das Exclus?es ? Base de C?lculo */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 3, (:wVLRBRUTO - :wVLRPIS));

  /* 04 - VL_TOT_BC - Valor Total da Base de C?lculo */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 4, :wVLRPIS);

  IF ((wVLRBRUTO = 0) AND (wVLRPIS = 0)) THEN -- Caso venham valores zerados, leva tudo zerado...
    wALIQ = 0;

  /* 05 - ALIQ_PIS_FOL - Al?quota do PIS/PASEP ? Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 5, :wALIQ);

  /* 06 - VL_TOT_CONT_FOL - Valor Total da Contribui??o Social sobre a Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 6, ((:wVLRPIS*:wALIQ)/100) );

END
^

/* Alter (SP_APURACAO_BLOCOM_M400_M800) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX (:prCODEMP, :prREFERENCIA, :prWHEREEMPRESAS);

      /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM400_M800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODCSTPIS, BDVL_TOT_REC, BDDESC_COMPL)
      SELECT 26 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM400_M800 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 26) AS BDCHAVE,
             tmp.BDCODCSTCOF, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTPIS, SUM(COALESCE(tmp.BDVL_ITEM,0)) AS BDVL_TOT_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTPIS > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

      /* REGISTRO M410: DETALHAMENTO DAS RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM410_M810 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODNATREC, BDVL_REC, BDDESC_COMPL)
      SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 26 AS BDCODQUADRO, tmp.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM400_M800 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                AND x.BDCODQUADRO = 26
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                ) AS BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1,1) FROM VEF_EMP_TBLOCOM410_M810 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 26
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                AND x.BDCHAVE = (SELECT z.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM400_M800 z
                                 WHERE z.BDCODEMP = tmp.BDCODEMP
                                   AND z.BDCODMATRIZ = tmp.BDCODMATRIZ
                                   AND z.BDREFERENCIA = tmp.BDREFERENCIA
                                   AND z.BDCODCSTCOF = tmp.BDCODCSTCOF
                                   AND z.BDCODCSTPIS = tmp.BDCODCSTPIS
                                   AND z.BDCODQUADRO = 26
                                   AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                                   AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
                                   ) AS BDORDEM,
             tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODNATREC, SUM(tmp.BDVL_ITEM) AS BDVL_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTPIS > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM400_M800 x
                    WHERE x.BDCODEMP = tmp.BDCODEMP
                      AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                      AND x.BDREFERENCIA = tmp.BDREFERENCIA
                      AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                      AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                      AND x.BDCODQUADRO = 26
                      AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                      AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))) ))
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODNATREC, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

      /* REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      INSERT INTO VEF_EMP_TBLOCOM400_M800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODCSTCOF, BDVL_TOT_REC, BDDESC_COMPL)
      SELECT 43 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM400_M800 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 43) AS BDCHAVE,
             tmp.BDCODCSTPIS, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, SUM(COALESCE(tmp.BDVL_ITEM,0)) AS BDVL_TOT_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTCOF > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF;

      /* REGISTRO M810: DETALHAMENTO DAS RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      INSERT INTO VEF_EMP_TBLOCOM410_M810 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODNATREC, BDVL_REC, BDDESC_COMPL)
      SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 43 AS BDCODQUADRO, tmp.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM400_M800 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                AND x.BDCODQUADRO = 43
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                ) AS BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1,1) FROM VEF_EMP_TBLOCOM410_M810 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 43
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                AND x.BDCHAVE = (SELECT z.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM400_M800 z
                                 WHERE z.BDCODEMP = tmp.BDCODEMP
                                   AND z.BDCODMATRIZ = tmp.BDCODMATRIZ
                                   AND z.BDREFERENCIA = tmp.BDREFERENCIA
                                   AND z.BDCODCSTPIS = tmp.BDCODCSTPIS
                                   AND z.BDCODCSTCOF = tmp.BDCODCSTCOF
                                   AND z.BDCODQUADRO = 43
                                   AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                                   AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
                                   ) AS BDORDEM,
             tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODNATREC, SUM(tmp.BDVL_ITEM) AS BDVL_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTCOF > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM400_M800 x
                    WHERE x.BDCODEMP = tmp.BDCODEMP
                      AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                      AND x.BDREFERENCIA = tmp.BDREFERENCIA
                      AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                      AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                      AND x.BDCODQUADRO = 26
                      AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                      AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))) ))
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODNATREC, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

    END

   /* Lan?amentos sem natureza da base de c?lculo  #Inconsist?ncia# */
   INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
   SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCODBLOCOM, tmp.BDCODTP, tmp.BDCHAVE, tmp.BDORDEM, tmp.BDORDEMPRO, 2 AS BDCODINC
   FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
   WHERE tmp.BDCODNATREC IS NULL
     AND tmp.BDCODMATRIZ = :prCODEMP
     AND tmp.BDREFERENCIA = :prREFERENCIA;

END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M400_M800 for: SP_APURACAO_BLOCOM_M400_M800AUX */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_M400_M800AUX) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP
           REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR (:prcodemp,  :prREFERENCIA, :prWHEREEMPRESAS);

      wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA) ';

      wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
      wSQL = wSQL||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
      wSQL = wSQL||       'aux.BDCODCSTPIS, aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
      wSQL = wSQL||       'aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
      wSQL = wSQL||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA ';
      wSQL = wSQL||'FROM (';
                          /* Sa?das - Produtos */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 2 AS BDCODTP, ';
      wSQL = wSQL||              'p.BDVLRITEM AS BDVL_ITEM, p.BDCODNATREC, p.BDCODCTA, ';
      wSQL = wSQL||              'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS,';
      wSQL = wSQL||              'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROSAI p ON (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = COALESCE(p.BDCODPLAPADRAO,lan.BDCODPLAPADRAO) and ccl.BDCODTPLA = COALESCE(p.BDCODTPLA,lan.BDCREDITO)) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = COALESCE(p.BDCODPLAPADRAO,lanrat.BDCODPLAPADRAO) and cclrat.BDCODTPLA = COALESCE(p.BDCODTPLA,lanrat.BDCREDITO)) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Sa?das - Transporte (D100) */
      wSQL = wSQL||       'select mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL as BDORDEM,';
      wSQL = wSQL||              'NULL as BDORDEMPRO, 16 as BDCODTP, mov.BDVALORNOTA as BDVL_ITEM, d100.BDCODNATREC, NULL as BDCODCTA,';
      wSQL = wSQL||              'd100.BDCODCSTPIS, d100.BDVL_BC_PIS as BDBCPIS, d100.BDALIQ_PIS as BDALIQPIS, d100.BDVLRPIS,';
      wSQL = wSQL||              'd100.BDCODCSTCOF, d100.BDVL_BC_COF as BDBCCOFINS, d100.BDALIQ_COF as BDALIQCOFINS, d100.BDVLRCOFINS,';
      wSQL = wSQL||              'COALESCE(CCL.BDCODPLAPADRAO, CCLRAT.BDCODPLAPADRAO) as BDCODPLAPADRAO,';
      wSQL = wSQL||              'COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Servi?o */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, ';
      wSQL = wSQL||              'a.BDVL_ITEM, a.BDCODNATREC, NULL AS BDCODCTA, ';
      wSQL = wSQL||              'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS,';
      wSQL = wSQL||              'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||              'WHERE s.BDTIPLAN = 0 '; -- Servi?os Emitidos
      wSQL = wSQL||                'AND (s.BDCODSITNF not in (2,3,4,5)) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TA170 a ON (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESER, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSER GROUP BY BDCODEMP, BDCHAVESER, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESER = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSER GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Demais documentos */
      wSQL = wSQL||       'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, ';
      wSQL = wSQL||              'dem.BDVL_OPER AS BDVL_ITEM, dem.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS, dem.BDVLR_PIS AS BDVLRPIS,';
      wSQL = wSQL||              'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(dem.bdCODPLAPADRAO, lan.bdCODPLAPADRAO) AS bdCODPLAPADRAO, COALESCE(dem.bdCODTPLA, lan.bdCREDITO) AS bdCODTPLA ';
      wSQL = wSQL||       'FROM ( ';
      wSQL = wSQL||               'SELECT dem.BDCODEMP, dem.BDREFLAN, dem.BDCHAVE, dem.bdIND_OPER, dem.BDVL_OPER, dem.BDCODNATREC, dem.bdCODPLAPADRAO, dem.bdCODTPLA, '; -- Caso tenha v?rios lan?amentos na contabiliza??o, vai buscar apenas a primeira conta...
      wSQL = wSQL||                      'dem.BDCODCSTPIS, dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS, ';
      wSQL = wSQL||                      'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||               'WHERE dem.bdIND_OPER IN (2,3) '; -- Opera??o Representativa de Receita
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (dem.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND dem.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||       ' ) dem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT tol.bdCODEMP, tol.bdCHAVEDEMDOC, lan.bdCODPLAPADRAO, MIN(lan.bdDATA) AS bdDATA, MIN(lan.bdREFERENCIA) AS bdREFERENCIA, MIN(lan.bdCREDITO) AS bdCREDITO, MIN(lan.bdDEBITO) AS bdDEBITO ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVDEMAISDOC tol ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = tol.bdCODEMP AND lan.bdCHAVE = tol.bdCHAVE) ';
      wSQL = wSQL||                        'GROUP BY bdCODEMP, bdCHAVEDEMDOC, bdCODPLAPADRAO) lan ON (lan.bdCODEMP = dem.bdCODEMP AND lan.bdCHAVEDEMDOC = dem.bdCHAVE) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Redu??o Z */
      wSQL = wSQL||       'SELECT redz.BDCODEMP, redz.BDCODMATRIZ, redz.BDREFLAN, redz.BDCHAVE, redz.BDORDEM, redz.BDORDEMPRO, redz.BDCODTP,  ';
      wSQL = wSQL||              'redz.BDVL_ITEM, redz.BDCODNATREC, redz.BDCODCTA,';
      wSQL = wSQL||              'redz.BDCODCSTPIS, redz.BDBCPIS, redz.BDALIQPIS, redz.BDVLRPIS,';
      wSQL = wSQL||              'redz.BDCODCSTCOF, redz.BDBCCOFINS, redz.BDALIQCOFINS, redz.BDVLRCOFINS, ';
      wSQL = wSQL||              'ccl.BDCODPLAPADRAO, ccl.BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, c425.BDCHAVE, c425.BDORDEMTOT AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 6 AS BDCODTP, ';
      wSQL = wSQL||                     'c425.BDVLRACU AS BDVL_ITEM, c425.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||                     'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425 c425 ON (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL ';

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, aliq.BDCHAVE, aliq.BDORDEMICMS AS BDORDEM, aliq.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, ';
      wSQL = wSQL||                     'aliq.BDVLRACU AS BDVL_ITEM, aliq.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'aliq.BDCODCSTPIS, aliq.BDVL_BC_PIS AS BDBCPIS, aliq.BDALIQ_PIS AS BDALIQPIS, aliq.BDVLRPIS,';
      wSQL = wSQL||                     'aliq.BDCODCSTCOF, aliq.BDVL_BC_COFINS AS BDBCCOFINS, aliq.BDALIQ_COFINS AS BDALIQCOFINS, aliq.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425ALIQ aliq ON (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL ';

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, i.BDCHAVE, i.BDORDEMDOCECF AS BDORDEM, i.BDORDEMITEM AS BDORDEMPRO, 8 AS BDCODTP, ';
      wSQL = wSQL||                     'i.BDVLRTOTPRO AS BDVL_ITEM, i.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'i.BDCODCSTPIS, i.BDVL_BC_PIS AS BDBCPIS, i.BDALIQ_PIS AS BDALIQPIS, i.BDVLRPIS AS BDVLRPIS,';
      wSQL = wSQL||                     'i.BDCODCSTCOF, i.BDVL_BC_COFINS AS BDBCCOFINS, i.BDALIQ_COFINS AS BDALIQCOFINS, i.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TDOCECF doc ON (doc.BDCODEMP = mov.BDCODEMP AND doc.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TITEMDOCECF i ON (i.BDCODEMP = doc.BDCODEMP AND i.BDCHAVE = doc.BDCHAVE AND i.BDORDEMDOCECF = doc.BDORDEMDOCECF) ';
      wSQL = wSQL||            ') redz ';
      wSQL = wSQL||       'LEFT OUTER JOIN (';
      wSQL = wSQL||                         'SELECT v.BDCODEMP, v.BDCHAVECFOP,';
      wSQL = wSQL||                                '(SELECT FIRST 1 x.BDCHAVE FROM TOL_VEF_EMP_TREDZVARCFOP x WHERE x.BDCODEMP = v.BDCODEMP AND x.BDCHAVECFOP = v.BDCHAVECFOP) as BDCHAVE ';
      wSQL = wSQL||                         'FROM TOL_VEF_EMP_TREDZVARCFOP v ';
      wSQL = wSQL||                         'WHERE v.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                         'GROUP BY v.BDCODEMP, v.BDCHAVECFOP ';
      wSQL = wSQL||                         ') tol on (tol.BDCODEMP = redz.BDCODEMP and tol.BDCHAVECFOP = redz.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* I100 */
      wSQL = wSQL||       'SELECT i100.BDCODEMP, COALESCE(emp.BDCODMATRIZ, i100.BDCODEMP) as BDCODMATRIZ, i100.BDREFERENCIA AS BDREFLAN, i100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 9 AS BDCODTP, ';
      --wSQL = wSQL||              '(i100.BDVLRREC-i100.BDVLRTOTDEDGER-i100.BDVLRTOTDEDESP) AS BDVL_ITEM, i100.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'i100.BDVLRREC AS BDVL_ITEM, i100.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'i100.BDCODCSTPISCOF AS BDCODCSTPIS, i100.BDBASEPIS AS BDBCPIS, i100.BDALIQPIS, i100.BDVLRPIS,';
      wSQL = wSQL||              'i100.BDCODCSTPISCOF AS BDCODCSTCOF, i100.BDBASECOFINS AS BDBCCOFINS, i100.BDALIQCOFINS, i100.BDVLRCOFINS, ';
      wSQL = wSQL||              'i200.BDCODPLAPADRAO, i200.BDCODTPLA ';
      wSQL = wSQL||       'FROM VEF_EMP_TMOVFINI100 i100 ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = i100.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN ( SELECT i.BDCODEMP, i.BDCHAVE, i.BDORDEMI200 as BDORDEMI200, i.BDCODPLAPADRAO, i.BDCODTPLA ';
      wSQL = wSQL||                         'FROM VEF_EMP_TMOVFIN_I200 i ';
      wSQL = wSQL||                         'WHERE i.BDORDEMI200 = (SELECT FIRST 1 x.BDORDEMI200 ';
      wSQL = wSQL||                                                'FROM VEF_EMP_TMOVFIN_I200 x ';
      wSQL = wSQL||                                                'WHERE x.BDCODEMP = i.BDCODEMP ';
      wSQL = wSQL||                                                  'AND x.BDCHAVE = i.BDCHAVE ';
      wSQL = wSQL||                                                  'AND x.BDCODPLAPADRAO IS NOT NULL ';
      wSQL = wSQL||                                                  'AND x.BDCODTPLA IS NOT NULL) ) i200 on (i200.BDCODEMP = i100.BDCODEMP and i200.BDCHAVE = i100.BDCHAVE) ';
      wSQL = wSQL||       'WHERE i100.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND i100.BDREFERENCIA = '||:prREFERENCIA||' ';

      wSQL = wSQL||     ') aux ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
      wSQL = wSQL||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
      wSQL = wSQL||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';

      EXECUTE STATEMENT ( wSQL );

    END

END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M400_M800AUX for: SP_APURACAO_BLOCOM_M400_M800PAR */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_M400_M800PAR) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA) ';
          wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
          wSQL = wSQL||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
          wSQL = wSQL||       'aux.BDCODCSTPIS, aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
          wSQL = wSQL||       'aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
          wSQL = wSQL||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA ';
          wSQL = wSQL||'FROM (';
                              /* Sa?das - Produtos */
          wSQL = wSQL||       'SELECT sai.BDCODEMP, COALESCE(emp.BDCODMATRIZ, sai.BDCODEMP) as BDCODMATRIZ, sai.BDREFLAN, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 2 AS BDCODTP, ';
          wSQL = wSQL||              '(CAST(ROUND((';-- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                           '(IIF(qtdepro.BDQTDEPRO < 1, pgto.bdvalorpgtopar,'; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                                      '((COALESCE(pgto.bdvalorpgtopar,0)*((CAST( COALESCE(movpro.BDVLRITEM,0) AS NUMERIC(15,6))/itens.BDVLRCONTAB)))) ))+';
          wSQL = wSQL||                           '(IIF(qtdepro.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETINSS,0) ),+';
          wSQL = wSQL||                                                     '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) )))';
          wSQL = wSQL||                           ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM,';
          wSQL = wSQL||              'movpro.BDCODNATREC, movpro.BDCODCTA, movpro.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'movpro.BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'movpro.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'movpro.BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') SAI ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = sai.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x ON (sai.BDCODEMP = x.BDCODEMP AND sai.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (sai.BDCODEMP = par.BDCODEMP AND sai.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (sai.BDCODEMP = itens.BDCODEMP AND sai.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, Count(*) AS BDQTDEPRO FROM VEF_EMP_TMOVPROSAI p group by p.BDCODEMP, p.BDCHAVE, p.BDORDEM) qtdepro ON ';
          wSQL = wSQL||                                                    '(qtdepro.BDCODEMP = itens.BDCODEMP AND qtdepro.BDCHAVE = itens.BDCHAVE AND qtdepro.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODNATREC, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||                    'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS, p.BDCODPLAPADRAO, p.BDCODTPLA ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVPROSAI p) movpro ON (itens.BDCODEMP = movpro.BDCODEMP AND itens.BDCHAVE = movpro.BDCHAVE AND itens.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = movpro.BDCODCSTPIS) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = movpro.BDCODCSTCOF) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = COALESCE(movpro.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) and ccl.BDCODTPLA = COALESCE(movpro.BDCODTPLA, lan.BDCREDITO)) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = COALESCE(movpro.BDCODPLAPADRAO, lanrat.BDCODPLAPADRAO) and cclrat.BDCODTPLA = COALESCE(movpro.BDCODTPLA, lanrat.BDCREDITO)) ';
          wSQL = wSQL||       'WHERE ((movpro.BDCODCSTPIS is not null) OR (movpro.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wSQL = wSQL||         'AND ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (movpro.BDALIQPIS = 0)) OR ';
          wSQL = wSQL||              '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (movpro.BDALIQCOFINS = 0))) ';

          wSQL = wSQL||       'UNION ALL ';
                              /* Sa?das - Transporte (D100) */
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, d100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'd100.BDCODNATREC, d100.BDCODCTA, d100.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'd100.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(cast((COALESCE(d100.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'd100.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'd100.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x ON (x.BDCODEMP = mov.BDCODEMP AND x.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TD100SAI d100 ON (mov.BDCODEMP = d100.BDCODEMP AND mov.BDCHAVE = d100.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((d100.BDCODCSTPIS is not null) OR (d100.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, d500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'd500.BDCODNATREC,d500.BDCODCTA,d500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'd500.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'd500.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'd500.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS numeric(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5))';
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TD500SAI x ';
          wSQL = wSQL||             'WHERE not exists(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||             ') d500 ON (mov.BDCODEMP = d500.BDCODEMP AND mov.BDCHAVE = d500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((d500.BDCODCSTPIS is not null) OR (d500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, c500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'c500.BDCODNATREC, NULL AS BDCODCTA, c500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(c500.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'c500.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(c500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'c500.BDCODCSTCOF,';
          wSQL = wSQL||              'CAST((COALESCE(c500.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8)) AS BDBCCOFINS,';
          wSQL = wSQL||              'c500.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              'CAST((COALESCE(c500.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8)) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TC500SAI x ';
          wSQL = wSQL||             'WHERE not exists(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||             ') c500 ON (mov.BDCODEMP = C500.BDCODEMP AND mov.BDCHAVE = C500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((C500.BDCODCSTPIS is not null) OR (C500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, f500.BDCHAVE, f500.BDORDEM, f500.BDORDEMF500 AS BDORDEMPRO, 13 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'f500.BDCODNATREC, NULL AS BDCODCTA, f500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDBASEPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'f500.BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'f500.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDBASECOF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'f500.BDALIQCOF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDVLRCOF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||              ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT X.* FROM VEF_EMP_TF500SAI X ';
          wSQL = wSQL||             'WHERE not exists(SELECT Y.BDCODEMP, Y.BDCHAVE FROM VEF_EMP_TMOVPROSAI Y WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCHAVE = Y.BDCHAVE) ';
          wSQL = wSQL||             ') F500 ON (mov.BDCODEMP = F500.BDCODEMP AND mov.BDCHAVE = F500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((F500.BDCODCSTPIS is not null) OR (F500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'a170.BDCODNATREC, NULL AS BDCODCTA, a170.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'a170.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP, aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSERPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSERITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TA170 a170 ON (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND itens.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit ON (mov.BDCODSITNF = sit.BDCODSITNF) ';

          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESER, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSER GROUP BY BDCODEMP, BDCHAVESER, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESER = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSER GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';

          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.bdvalorpgtopar +(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'mov.BDCODNATREC, NULL AS BDCODCTA, mov.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'mov.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'ccl.BDCODPLAPADRAO, COALESCE(mov.bdCODTPLA, ccl.bdCODTPLA) as bdCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT dem.BDCODEMP, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.bdCODTPLA, ';
          wSQL = wSQL||                    'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||                    'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||             'WHERE dem.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = dem.BDCODEMP AND e.BDREFEMP <= dem.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVF100PAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT tol.bdCODEMP, tol.bdCHAVEDEMDOC, lan.bdCODPLAPADRAO, MIN(lan.bdDATA) AS bdDATA, MIN(lan.bdREFERENCIA) AS bdREFERENCIA, MIN(lan.bdCREDITO) AS bdCREDITO, MIN(lan.bdDEBITO) AS bdDEBITO ';
          wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVDEMAISDOC tol ';
          wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = tol.bdCODEMP AND lan.bdCHAVE = tol.bdCHAVE) ';
          wSQL = wSQL||                        'GROUP BY bdCODEMP, bdCHAVEDEMDOC, bdCODPLAPADRAO) lan ON (lan.bdCODEMP = mov.bdCODEMP AND lan.bdCHAVEDEMDOC = mov.bdCHAVE) ';

          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((mov.BDCODCSTPIS is not null) OR (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

         wSQL = wSQL||     ') aux ';
         wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
         wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
         wSQL = wSQL||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
         wSQL = wSQL||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';
   
         EXECUTE STATEMENT ( wSQL );

        END

    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M500) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WMETODOAPRO INTEGER;
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,4);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configura??o da empresa na refer?ncia da apura??o...
  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDMETODOAPRO+1 -- M?todo de apropria??o
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 1
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 2
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMNTMI;

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 3
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMEXP;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      /* REGISTRO M500: CR?DITO DE COFINS RELATIVO AO PER?ODO */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM100_500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDIND_CRED_ORI, BDVL_BC, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CRED,';
      wSQL = wSQL||                                    'BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CRED_DIF, BDVL_CRED_DISP, BDIND_DESC_CRED, BDVL_CRED_DESC, BDSLD_CRED) ';
      wSQL = wSQL||'SELECT 29 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7) AS BDCHAVE,';
      wSQL = wSQL||       't436.BDCODCRE_4_3_6, 0 AS BDIND_CRED_ORI, SUM(COALESCE(tmp.BDBCCOFINS,0)) AS BDVL_BC, COALESCE(tmp.BDALIQCOFINS,0) AS BDALIQ,';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC, COALESCE(tmp.BDALIQCOFINS_QUANT,0) AS BDALIQ_QUANT,';
      wSQL = wSQL||       '(((SUM(COALESCE(tmp.BDBCCOFINS,0))*COALESCE(tmp.BDALIQCOFINS,1))/100)+(SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0))*COALESCE(tmp.BDALIQCOFINS_QUANT,1))) AS BDVL_CRED,';
      wSQL = wSQL||       '0 AS BDVL_AJUS_ACRES, 0 AS BDVL_AJUS_REDUC, 0 AS BDVL_CRED_DIF, 0 AS BDVL_CRED_DISP,';
      wSQL = wSQL||       'NULL AS BDIND_DESC_CRED, 0 AS BDVL_CRED_DESC, 0 AS BDSLD_CRED ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED,';
      wSQL = wSQL||             'x.BDALIQCOFINS,';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT,';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT,';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                    -- Rateio
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||             'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED, ';
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||             'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
         wSQL = wSQL||          'x.BDCOD_CRED as BDCOD_CRED, ';
         wSQL = wSQL||          'x.BDBCCOFINS ';
        END
      wSQL = wSQL||             'AS BDBCCOFINS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTCOF and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';

      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCCOFINS > 0) OR (tmp.BDBCCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQCOFINS > 0) OR (tmp.BDALIQCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      --wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, t436.BDCODCRE_4_3_6, tmp.BDALIQCOFINS, tmp.BDALIQCOFINS_QUANT; ';
 
      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M505: DETALHAMENTO DA BASE DE CALCULO DO CR?DITO APURADO NO PER?ODO ? COFINS */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM105_M505 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCSTPIS, BDCODCSTCOF, BDCODNATBC, BDCODCRE_4_3_6,';
      wSQL = wSQL||                                     'BDVL_BC_TOT, BDVL_BC_CUM, BDVL_BC_NC, BDVL_BC, BDQUANT_BC_TOT, BDQUANT_BC, BDDESC_CRED, BDALIQ) ';
      wSQL = wSQL||'SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 29 AS BDCODQUADRO, tmp.BDREFERENCIA, ';
      wSQL = wSQL||       '(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQCOFINS) OR (x.BDALIQ_QUANT = tmp.BDALIQCOFINS_QUANT))) AS BDCHAVE, ';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDORDEM)+1,1)';
      wSQL = wSQL||        'FROM VEF_EMP_TBLOCOM105_M505 x ';
      wSQL = wSQL||        'WHERE x.BDCODPERIODO = 7 ';
      wSQL = wSQL||          'AND x.BDCODEMP = tmp.BDCODEMP ';
      wSQL = wSQL||          'AND x.BDCODMATRIZ = tmp.BDCODMATRIZ ';
      wSQL = wSQL||          'AND x.BDCODQUADRO = 29 ';
      wSQL = wSQL||          'AND x.BDREFERENCIA = tmp.BDREFERENCIA ';
      wSQL = wSQL||          'AND x.BDCHAVE = (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQCOFINS) OR (x.BDALIQ_QUANT = tmp.BDALIQCOFINS_QUANT)))) AS BDORDEM, ';
      wSQL = wSQL||       'tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED AS BDCODNATBC, t436.BDCODCRE_4_3_6, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINSTOTAL,0)) AS BDVL_BC_TOT, 0 AS BDVL_BC_CUM, /*(Campo 04 ? Campo 05)*/SUM(COALESCE(tmp.BDBCCOFINSTOTAL,0)-0) AS BDVL_BC_NC, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINS,0)) AS BDVL_BC, SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC_TOT, SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC, NULL AS BDDESC_CRED, COALESCE(tmp.BDALIQCOFINS,tmp.BDALIQCOFINS_QUANT) AS BDALIQ ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT, ';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED, ';
      wSQL = wSQL||             'x.BDALIQCOFINS, x.BDBCCOFINS as BDBCCOFINSTOTAL, ';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT, ';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT, ';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED, ';
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||             'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
         wSQL = wSQL||          'x.BDCOD_CRED as BDCOD_CRED, ';
         wSQL = wSQL||          'x.BDBCCOFINS ';
        END
      wSQL = wSQL||             'AS BDBCCOFINS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTCOF and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';

      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCCOFINS > 0) OR (tmp.BDBCCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQCOFINS > 0) OR (tmp.BDALIQCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '('; -- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED, t436.BDCODCRE_4_3_6, tmp.BDALIQCOFINS, tmp.BDALIQCOFINS_QUANT; ';
 
      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M510: AJUSTES DO CR?DITO DE COFINS APURADO */
      INSERT INTO VEF_EMP_TBLOCOM110_M510 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, BDDESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) as BDCODMATRIZ,  29 as BDCODQUADRO, m.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = m.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) AND x.BDCODQUADRO = 29 AND x.BDREFERENCIA = m.BDREFERENCIA AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6 AND ((x.BDALIQ = m.BDALIQCOFINS) OR (x.BDALIQ_QUANT = m.BDALIQCOFINS))) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM+1),1)
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 29
                AND x.BDCODEMP = m.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                AND x.BDREFERENCIA = m.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM100_500 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDCODEMP = m.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                                   AND x.BDREFERENCIA = m.BDREFERENCIA
                                   AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                                   AND ((x.BDALIQ = m.BDALIQCOFINS) OR (x.BDALIQ_QUANT = m.BDALIQCOFINS))) ) as BDORDEM,
             m.BDCODAJUEFDC, m.BDTIPOAJUSTE as BDIND_AJ, SUM(m.BDVLRAJUCOFINS) as BDVL_AJ, m.BDNUMERODOC as BDNUM_DOC, m.BDDESCRICAO as BDDESCR_AJ, m.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TCREDAJU_M110_M510 m
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m.BDCODEMP)
      WHERE m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM100_500 m100
                    WHERE m100.BDCODPERIODO = 7
                      AND m100.BDCODQUADRO = 29
                      AND m100.BDCODEMP = m.BDCODEMP
                      AND m100.BDREFERENCIA = m.BDREFERENCIA
                      AND m100.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND ((m100.BDALIQ = m.BDALIQCOFINS) OR (m100.BDALIQ_QUANT = m.BDALIQCOFINS)) ))
      GROUP BY m.BDCODEMP, emp.BDCODMATRIZ, m.BDREFERENCIA, m.BDCODAJUEFDC, m.BDTIPOAJUSTE, m.BDNUMERODOC, m.BDDESCRICAO, m.BDDATAREF, m.BDCODCRE_4_3_6, m.BDALIQCOFINS;
 
      /* REGISTRO 515: DETALHAMENTO DOS AJUSTES DO CR?DITO DE COFINS APURADO */
      INSERT INTO VEF_EMP_TBLOCOM115_M515 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM15, BDCODCSTCOF, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m515.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP) as BDCODMATRIZ, 29 as BDCODQUADRO, m510.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDCODQUADRO = 29
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDNUM_DOC = m510.BDNUMERODOC
                AND x.BDDESCR_AJ = m510.BDDESCRICAO
                AND x.BDDT_REF = m510.BDDATAREF ) as BDCHAVE,
             (SELECT x.BDORDEM
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDCODQUADRO = 29
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDNUM_DOC = m510.BDNUMERODOC
                AND x.BDDESCR_AJ = m510.BDDESCRICAO
                AND x.BDDT_REF = m510.BDDATAREF ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM15+1),1)
              FROM VEF_EMP_TBLOCOM115_M515 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 29
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF )
                AND x.BDORDEM = (SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF ) ) as BDORDEM15,
             m515.BDCODCSTCOF, m515.BDCODCSTPIS, m515.BDCODPLAPADRAO, m515.BDCODTPLA, SUM(m510.BDVLRAJUCOFINS) as BDDET_VALOR_AJ, SUM(m515.BDBCCOFINS) as BDDET_BC_CRED,
             m515.BDALIQCOFINS as BDDET_ALIQ, m515.BDDATAOPECOFINS as BDDT_OPER_AJ, m515.BDDESCRICAOAJU as BDDESC_AJ, m515.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TCREDAJU_M110_M510 m510
      JOIN VEF_EMP_TDETAJU_M115_M515 m515 on (m515.BDCODEMP = m510.BDCODEMP AND m515.BDCHAVE = m510.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m510.BDCODEMP)
      WHERE m515.BDCODEMP IS NOT NULL
        AND m515.BDBCCOFINS > 0
        AND m510.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m510.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF ))
      GROUP BY m515.BDCODEMP, emp.BDCODMATRIZ, m510.BDREFERENCIA, m510.BDCODCRE_4_3_6,  m515.BDCODCSTCOF, m515.BDCODCSTPIS, m515.BDCODPLAPADRAO, m515.BDCODTPLA,
               m515.BDALIQCOFINS, m515.BDDATAOPECOFINS, m515.BDDESCRICAOAJU, m515.BDINFCOMP, m510.BDNUMERODOC, m510.BDDESCRICAO, m510.BDDATAREF;
 
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M600) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M600(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WVLRAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRUP NUMERIC(15,2);
DECLARE VARIABLE WVLRUPAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRSLD NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT_ORIGINAL NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT_TOTAL NUMERIC(15,2);
DECLARE VARIABLE WINTAUX INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WPER_APU_CRED INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCRE_4_3_6 INTEGER;
DECLARE VARIABLE WIND_CRED_ORI INTEGER;
DECLARE VARIABLE WCOD_NAT_REC INTEGER;
DECLARE VARIABLE WCHAVEAUX INTEGER;
DECLARE VARIABLE WORDENACAO INTEGER;
DECLARE VARIABLE WIND_DESC_CRED INTEGER;
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCREDITOSPERANT, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCREDITOSPERANT, :wRETPISCOFPERANT;

  /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  /* 1 - Exclusivamente no regime n?o-cumulativo */
  IF (wINCTRIB IN (1,3)) THEN
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M610, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      wVLRTOTCONT = 0;
      SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR
      FROM VEF_EMP_TBLOCOM210_M610 m
      LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL)
      WHERE (t435.BDCODCSOCIALEXP IN (01,02,03,04,32,71))
        AND (m.BDCODQUADRO = 37) -- M610 - Detalhamento da contribui??o para o Cofins
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRTOTCONT;

      wVLRTOTCONT_ORIGINAL = wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 2, COALESCE(:wVLRTOTCONT,0));

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100)
         Caso esteja configurado para usar saldo do per?odo anterior, deve descontar ele primeiro, antes do cr?dito do per?odo atual... */
      wVLRCREDPERANT = 0;
      wVLRCREDPERANT_TOTAL = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 53) -- 1500 - Controle de cr?ditos fiscais Cofins
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL = wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
              END
          END
        END

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      SELECT COUNT(m.BDCHAVE) as BDQTD
      FROM VEF_EMP_TBLOCOM100_500 m
      WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO wQTD;

      IF ((wQTD = 0) OR (wVLRTOTCONT = 0) OR (wVLRTOTCONT IS NULL)) THEN -- Caso n?o tenha dados no M100/M500 ou o valor do cr?dito seja zerado...
        BEGIN
          UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                               VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, 0)
                                             MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
            UPDATE VEF_EMP_TBLOCOM100_500 m
            SET m.BDIND_DESC_CRED = 1,
                m.BDVL_CRED_DESC  = 0,
                m.BDSLD_CRED      = m.BDVL_CRED_DISP
            WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA;
 
            /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
            SELECT COUNT(*)
            FROM VEF_EMP_TBLOCOM1100_1500 m
            WHERE m.BDCODPERIODO = 7
              AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA
              AND m.BDPER_APU_CRED = :prREFERENCIA
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDORIG_CRED = :wIND_CRED_ORI
            INTO :wQTD;
  
            IF (:wQTD > 0) THEN
              BEGIN
                /* Caso tenha registros atualiza */
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                    m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                    m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
      ELSE
        BEGIN
                /* Caso n?o tenha lan?amento de saldos insere */
                INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                              VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                      (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA),
                                                      7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
              END
          END
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            IF (:wVLRTOTCONT > 0) THEN
              BEGIN
                /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
                IF (:wVLR < :wVLRTOTCONT) THEN
                  BEGIN
                    wVLRSLD        = 0;
                    wVLRTOTCONT    = wVLRTOTCONT - wVLR;
                    wIND_DESC_CRED = 0; -- 0 ? Utiliza??o do valor total para desconto da contribui??o apurada no per?odo, no Registro M200;
                  END
                ELSE
                  BEGIN
                    /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                    wVLRSLD        = :wVLR - :wVLRTOTCONT;
                    wVLR           = :wVLR - :wVLRSLD;
                    wVLRTOTCONT    = 0;
                    wIND_DESC_CRED = 1; -- 1 ? Utiliza??o de valor parcial para desconto da contribui??o apurada no per?odo, no Registro M200.
                  END
    
                -- Atualiza os cr?ditos descontados do M500...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = :wIND_DESC_CRED,
                    m.BDVL_CRED_DESC  = :wVLR,
                    m.BDSLD_CRED      = :wVLRSLD
                WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDCHAVE = :wCHAVE
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI;

                IF (wVLRSLD > 0) THEN
                  BEGIN
                /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                SELECT COUNT(*)
                FROM VEF_EMP_TBLOCOM1100_1500 m
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI
                INTO :wQTD;
      
                IF (:wQTD > 0) THEN
                  BEGIN
                    /* Caso tenha registros atualiza */
                    UPDATE VEF_EMP_TBLOCOM1100_1500 m
                    SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI;
                  END
                ELSE
                  BEGIN
                    /* Caso n?o tenha lan?amento de saldos insere */
                    INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                  VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                              (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                              7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', (:wVLR + :wVLRSLD) /*:wVLR*/, :wVLR/*0*/, :wVLRSLD/*:wVLR*/);
                  END
              END

                wVLRAUX = 0;
                SELECT COALESCE(BDVALOR, 0)
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
                  AND BDREFERENCIA = :prREFERENCIA
                  AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
                  AND BDNUMCAMPO   = 3
                INTO wVLRAUX;
         
                IF (wVLRAUX IS NULL) THEN
                  wVLRAUX = 0;
         
                UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, COALESCE(:wVLR+:wVLRAUX,0))
                                                   MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

                  END
                ELSE
                  BEGIN
                -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = 1,
                    m.BDVL_CRED_DESC  = 0,
                    m.BDSLD_CRED      = m.BDVL_CRED_DISP
                WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDCHAVE = :wCHAVE;
          
                    /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                    SELECT COUNT(*)
                    FROM VEF_EMP_TBLOCOM1100_1500 m
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI
                    INTO :wQTD;
          
                    IF (:wQTD > 0) THEN
                      BEGIN
                        /* Caso tenha registros atualiza */
                        UPDATE VEF_EMP_TBLOCOM1100_1500 m
                        SET m.BDVL_CRED_APU = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                        WHERE m.BDCODPERIODO = 7
                          AND m.BDCODQUADRO = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                          AND m.BDCODEMP = :wCODEMP
                          AND m.BDCODMATRIZ = :wCODMATRIZ
                          AND m.BDREFERENCIA = :prREFERENCIA
                          AND m.BDPER_APU_CRED = :prREFERENCIA
                          AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                          AND m.BDORIG_CRED = :wIND_CRED_ORI;
                      END
                    ELSE
                      BEGIN
                        /* Caso n?o tenha lan?amento de saldos insere */
                        INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                      VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                          (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                          7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
                      END
                          END
                          END
                      END

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      wVLR = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          wVLR = wVLRCREDPERANT_TOTAL;
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 53) -- 1500 - Controle de cr?ditos fiscais Cofins
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL =  wVLRCREDPERANT_TOTAL + wVLR;
    
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
          END

          wVLR = wVLRCREDPERANT_TOTAL;
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 4, COALESCE(:wVLR,0));

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (2))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (3,4))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 5, COALESCE(:wVLR,0));

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1700. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
              AND BDNUMCAMPO   = 6
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRCOFINS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 1 -- 0 - Dedu??o de Natureza N?o Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 7, COALESCE(:wVLR,0));

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR) as BDVALOR, SUM(aux.BDVLRSUB) as BDVALORSUB
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (5))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (6,7))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR, wVLRAUX;

      IF ((wVLR - wVLRAUX) >= 0) THEN -- Se tiver valor de contribbui??o, calcula os campos a somar e subtrair...
        wVLR = (wVLR - wVLRAUX);
      ELSE
      /* Se o valor do campo 5(Valor Total da Contribui??o) menos o valor do campo 6(Valor Retido na Fonte) for menor que zero, ent?o este valor deve ser levado como saldo no registro 1300. */
      IF ((wVLR - wVLRAUX) < 0) THEN -- Se n?o tiver valor de contribbui??o, leva zerado...
        BEGIN
          /* Atualiza o valor do campo 6, Valor Retido na Fonte, s? pode usar aquilo que abater e n?o o total... */
          UPDATE VEF_EMP_TBLOCOMGERREG
          SET BDVALOR = :wVLR
          WHERE BDCODMATRIZ  = :prCODEMP
            AND BDREFERENCIA = :prREFERENCIA
            AND BDCODQUADRO  = 33
            AND BDNUMCAMPO   = 6;

          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, COALESCE(m.BDVL_RET_APU, 0)
              FROM VEF_EMP_TBLOCOM1300_1700 m
              WHERE (m.BDCODQUADRO = 50) -- 1700 - Ficha de reten??o do Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUP
          DO
            BEGIN
              IF (wVLR > 0) THEN
                BEGIN
                  /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                  IF (:wVLRUP < :wVLR) THEN
                    BEGIN
                      wVLRUPAUX = :wVLRUP;
                      wVLRSLD   = 0;
                      wVLR      = :wVLR-:wVLRUP; /* Cr?dito j? descontado vai ser abatido... */
                    END
                  ELSE
                    BEGIN
                      wVLRUPAUX = :wVLR;
                      wVLRSLD   = :wVLRUP - :wVLR;
                    END
    
                  UPDATE OR INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDVL_RET_DED, BDSLD_RET)
                                                          VALUES (:wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUPAUX  , :wVLRSLD)
                                                        MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE);
                END
            END

          wVLR = 0; -- Se n?o tiver valor de contribbui??o, leva zerado...
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 8, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 2, 0);

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, 0);

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 4, 0);

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 5, 0);

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, 0);

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 7, 0);

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 8, 0);
    END

  /* 2 - Exclusivamente no regime cumulativo */
  IF (wINCTRIB IN (2,3)) THEN
    BEGIN
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      wVLRTOTCONT = 0;
      wSQL =        'SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM210_M610 m ';
      wSQL = wSQL|| 'LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL) ';
      IF (wINCTRIB IN (3)) THEN -- Quando ? regime n?o-cumulativo e cumulativo, j? considerou algumas contribui??es no campo 2...
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,51,52,53,54,72)) ';
      ELSE
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,32,51,52,53,54,72)) ';
      wSQL = wSQL|| '  AND (m.BDCODQUADRO = 37) '; -- M610 - Detalhamento da contribui??o para o Cofins
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 9, COALESCE(:wVLRTOTCONT,0));

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1700. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
                  AND BDNUMCAMPO   = 10
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                         VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRCOFINS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 2 -- 1 - Dedu??o de Natureza Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 11, COALESCE(:wVLR,0));

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (9))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (10,11))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 12, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN -- Joga os valores zerados...
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 9, 0);

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, 0);

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 11, 0);

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 12, 0);
    END

  /* 3 - Regimes n?o-cumulativo e cumulativo */
  /* 13 - VL_TOT_CONT_REC - Valor Total da Contribui??o a Recolher/Pagar no Per?odo (08 + 12) */
  wVLR = 0;
  SELECT SUM(COALESCE(m.BDVALOR,0)) as BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG m
  WHERE (m.BDCODQUADRO = 33)
    AND (m.BDNUMCAMPO in (8,12))
    AND m.BDCODMATRIZ = :prCODEMP
    AND m.BDREFERENCIA = :prREFERENCIA
  INTO :wVLR;

  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 13, COALESCE(:wVLR,0));

END
^

/* Alter (SP_APURACAO_BLOCOM_ONLINE) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
BEGIN
  -- Limpa a tabela de contabiliza??o do Bloco M
  DELETE FROM TMP_TCONF_CONTAS_ONLINE_TEMP WHERE bdCODMATRIZ = :prCODEMP AND bdREFERENCIA = :prREFERENCIA;

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Incid?ncia tribut?ria
  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  IF (:wINCTRIB IN (1,3)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo e 3 - Regimes n?o-cumulativo e cumulativo
    BEGIN
      -- Valida as contas da contabiliza??o da apura??o do Bloco M...
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDAONLINE (:prCODEMP, :prREFERENCIA);
    
      -- Verifica se possui alguma inconsist?ncia de contas online...
      SELECT FIRST 1 i.bdCODINC
      FROM VEF_INCON_BLOCOM i
      WHERE i.bdCODMATRIZ = :prCODEMP
        AND i.bdREFERENCIA = :prREFERENCIA
        -- "Outras Dedu??es" n?o ? um campo obrigat?rio
        AND i.bdCODINC IN (13,/*"Cr?dito" do PIS*/    14,/*"D?bito" do PIS*/    /*15,/*"Outras Dedu??es" do PIS*/    16,/*"Compensa??o" do PIS*/
                           17,/*"Cr?dito" do Cofins*/ 18,/*"D?bito" do Cofins*/ /*19,/*"Outras Dedu??es" do Cofins*/ 20,/*"Compensa??o" do Cofins*/
                           21/*Inconsist?ncias gen?rica da contabiliza??o detalhada*/)
      INTO :wCODINC;
    
      -- Deleta os registros da tabela da contabiliza??o, caso exista algum lan?amento
      DELETE FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
      WHERE t.bdCODMATRIZ = :prCODEMP
        AND t.bdREFERENCIA = :prREFERENCIA;

      IF (:wCODINC IS NULL) THEN
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO (:prCODEMP, :prREFERENCIA);
    END
 
END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_ONLINE for: SP_APURACAO_BLOCOM_ONLINE_CONSO */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_ONLINE_CONSO) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCONTDETALHADA VARCHAR(5);
BEGIN
  /* PIS */
  /****************************************************************************/
  /********************************** Cr?ditos ********************************/
  -- "Cr?dito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS');
  -- "Cr?dito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 247);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED');
  /********************************** D?bitos *********************************/
  -- "D?bito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS');
  -- "D?bito Detalhado"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 248);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED');

          -- "Outras Dedu??es"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de PIS Outras Dedu??es - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, g.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 249)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
            AND g.bdNUMCAMPO  = 07 -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
            AND g.bdVALOR > 0;

          -- "Compensa??o"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de PIS Compensa??o - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, SUM(g.bdVALOR) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 250)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
    AND (
         (g.bdNUMCAMPO  = 03) OR -- VL_TOT_CRED_DESC - Valor do Cr?dito Descontado
                 (g.bdNUMCAMPO  = 04) OR -- VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior
                 (g.bdNUMCAMPO  = 06) OR -- VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo
                 (g.bdNUMCAMPO  = 07)    -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
                 )
            AND g.bdVALOR > 0
  GROUP BY g.bdCODMATRIZ, g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdORDENACAO;
  /****************************************************************************/

  /****************************************************************************/
  /********************************** Cr?ditos ********************************/
          /* Cofins */
  -- "Cr?dito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins');
  -- "Cr?dito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 251);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED');
  /********************************** D?bitos *********************************/
  -- "D?bito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins');
  -- "D?bito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 252);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED');

          -- "Outras Dedu??es"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de Cofins Outras Dedu??es - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, g.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 253)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 33 -- M600 - Consolida??o da contribui??o para o Cofins
            AND g.bdNUMCAMPO  = 07 -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
            AND g.bdVALOR > 0;

          -- "Compensa??o"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de Cofins Compensa??o - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, SUM(g.bdVALOR) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 254)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 33 -- M600 - Consolida??o da contribui??o para o Cofins
    AND (
         (g.bdNUMCAMPO  = 03) OR -- VL_TOT_CRED_DESC - Valor do Cr?dito Descontado
                 (g.bdNUMCAMPO  = 04) OR -- VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior
                 (g.bdNUMCAMPO  = 06) OR -- VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo
                 (g.bdNUMCAMPO  = 07)   -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
                 )
            AND g.bdVALOR > 0
  GROUP BY g.bdCODMATRIZ, g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdORDENACAO;
  /****************************************************************************/
END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_ONLINE_CONSO for: SP_APURACAO_BLOCOM_ONLINE_CRED */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_APURACAO_BLOCOM_ONLINE_CRED) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRTIPO VARCHAR(6),
PRDEBCRED VARCHAR(5) = '')
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCONTDETALHADA VARCHAR(5);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WSQLAUX VARCHAR(1000);
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WCODQUADROSALDO INTEGER;
DECLARE VARIABLE WCODITEMONLINE INTEGER;
BEGIN
  IF (UPPER(:prTIPO) = 'PIS') THEN
    BEGIN
      wCODQUADRO      = 15; -- M200 - Consolida??o da contribui??o para o PIS/PASEP
      wCODQUADROSALDO = 52; -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
      wCODITEMONLINE  = 247;
    END
  ELSE
  IF (UPPER(:prTIPO) = 'COFINS') THEN
    BEGIN
      wCODQUADRO      = 33; -- M600 - Consolida??o da contribui??o para o Cofins
      wCODQUADROSALDO = 53; -- 1500 - Controle de cr?ditos fiscais Cofins
      wCODITEMONLINE  = 251;
    END

  IF (:prDEBCRED <> '') THEN
    BEGIN
      wSQLAUX =                         '(COALESCE((SELECT SUM(COALESCE(t.bdVALOR, 0)) ';
      wSQLAUX = wSQLAUX||                          'FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t ';
      wSQLAUX = wSQLAUX||                          'WHERE t.bdCODMATRIZ = g.bdCODMATRIZ ';
      wSQLAUX = wSQLAUX||                            'AND t.bdREFERENCIA = g.bdREFERENCIA ';
      wSQLAUX = wSQLAUX||                            'AND t.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                            'AND POSITION('''||:wCODITEMONLINE||''', t.bdORDENACAO) > 0 ';
      wSQLAUX = wSQLAUX||                            'AND ((POSITION(''.00000'', t.bdORDENACAO) = 0) ';
      IF (UPPER(:prDEBCRED) = 'DEB') THEN
        wSQLAUX = wSQLAUX||                   'AND t.bdDEBITO IS NULL)),0)) ';
      ELSE
      IF (UPPER(:prDEBCRED) = 'CRED') THEN
        wSQLAUX = wSQLAUX||                   'AND t.bdCREDITO IS NULL)),0)) ';
    END
  ELSE
    BEGIN
      wSQLAUX =               '(COALESCE(m1100.bdSLD_CRED_FIM,0)+COALESCE(g.bdVALOR,0)-COALESCE((SELECT SUM(o.bdVALOR) ';
      wSQLAUX = wSQLAUX||                                                                       'FROM TMP_TCONF_CONTAS_ONLINE_TEMP o ';
      wSQLAUX = wSQLAUX||                                                                       'WHERE o.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                                                                         'AND o.bdCODITEMONLINE = '||:wCODITEMONLINE;
      wSQLAUX = wSQLAUX||                                                                         'AND o.bdCODMATRIZ = G.BDCODMATRIZ ';
      wSQLAUX = wSQLAUX||                                                                         'AND o.bdREFERENCIA = G.BDREFERENCIA ';
      wSQLAUX = wSQLAUX||                                                                         'AND o.bdFORMULA IS NOT NULL '; -- Contabiliza??o detalhada
      wSQLAUX = wSQLAUX||                                                                         'AND o.bdVALOR > 0 ),0) ';
      wSQLAUX = wSQLAUX||                                                                       ') ';
    END

  -- "Cr?dito Principal"
  wSQL =       'INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO) ';
  wSQL = wSQL||'SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU,  ';
  IF (:prDEBCRED <> '') THEN
    BEGIN
      IF (UPPER(:prDEBCRED) = 'DEB') THEN
        wSQL = wSQL||'c.bdCONTADEBPROV as bdDEBITO, NULL as bdCREDITO, ';
      ELSE
      IF (UPPER(:prDEBCRED) = 'CRED') THEN
        wSQL = wSQL||'NULL as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO, ';
    END
  ELSE
    wSQL = wSQL||'c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO, ';
  wSQL = wSQL||      ' ''Valor de '||:prTIPO||' Cr?dito - Ref:''||substring(g.bdREFERENCIA FROM 5 for 2)||''/''||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL, ';
  wSQL = wSQL||      'NULL as bdDATA, ';
  wSQL = wSQL||      wSQLAUX||' as bdVALOR, ';
  wSQL = wSQL||      '100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO ';
  wSQL = wSQL||'FROM VEF_EMP_TBLOCOMGERREG g ';
  wSQL = wSQL||'JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP) ';
  wSQL = wSQL||'JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = '||:wCODITEMONLINE||') ';
  wSQL = wSQL||'LEFT OUTER JOIN (';
  wSQL = wSQL||                  'SELECT sld.bdCODPERIODO, sld.bdCODMATRIZ, sld.bdREFERENCIA, sld.bdCODQUADRO, SUM(COALESCE(sld.bdSLD_CRED_FIM,0)) as bdSLD_CRED_FIM ';
  wSQL = wSQL||                  'FROM VEF_EMP_TBLOCOM1100_1500 sld ';
  wSQL = wSQL||                  'WHERE sld.bdCODMATRIZ = '||:prCODEMP;
  wSQL = wSQL||                    'AND sld.bdREFERENCIA = '||:prREFERENCIA;
  wSQL = wSQL||                    'AND sld.bdPER_APU_CRED = '||:prREFERENCIA; -- Apenas o saldo do m?s atual, os per??iodos anteriores j? usou o campo 04 na "Compen??o"
  wSQL = wSQL||                    'AND sld.bdCODQUADRO = '||:wCODQUADROSALDO;
  wSQL = wSQL||                  'GROUP BY sld.bdCODPERIODO, sld.bdCODMATRIZ, sld.bdREFERENCIA, sld.bdCODQUADRO ';
  wSQL = wSQL||                 ') m1100 ON (m1100.bdCODPERIODO = g.bdCODPERIODO and m1100.bdCODMATRIZ = g.bdCODMATRIZ and m1100.bdREFERENCIA = g.bdREFERENCIA) ';
  wSQL = wSQL||'WHERE g.bdCODMATRIZ = '||:prCODEMP||' ';
  wSQL = wSQL||  'AND g.bdREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||  'AND g.bdCODQUADRO = '||:wCODQUADRO||' ';
  wSQL = wSQL||  'AND g.bdNUMCAMPO  = 03 '; -- VL_TOT_CRED_DESC - Valor do Cr?dito Descontado
  wSQL = wSQL||  'AND c.bdFORMULA IS NULL '; -- Para n?o carregar as contas detalhadas
  wSQL = wSQL||  ' AND ('||wSQLAUX||') > 0 ';

  EXECUTE STATEMENT wSQL;

END
^

/* Alter (SP_APURACAO_BLOCOM_ONLINE_DEB) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRTIPO VARCHAR(6),
PRDEBCRED VARCHAR(5) = '')
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCONTDETALHADA VARCHAR(5);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WSQLAUX VARCHAR(5000);
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WCODITEMONLINE INTEGER;
BEGIN
  IF (UPPER(:prTIPO) = 'PIS') THEN
    BEGIN
      WCODQUADRO      = 15; -- M200 - Consolida??o da contribui??o para o PIS/PASEP
      WCODITEMONLINE  = 248;
    END
  ELSE
  IF (UPPER(:prTIPO) = 'COFINS') THEN
    BEGIN
      WCODQUADRO      = 33; -- M600 - Consolida??o da contribui??o para o Cofins
      WCODITEMONLINE  = 252;
    END

  IF (:prDEBCRED <> '') THEN
    BEGIN
      wSQLAUX =                         '(COALESCE((SELECT SUM(COALESCE(t.bdVALOR, 0)) ';
      wSQLAUX = wSQLAUX||                           'FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t ';
      wSQLAUX = wSQLAUX||                           'WHERE t.bdCODMATRIZ = g.bdCODMATRIZ ';
      wSQLAUX = wSQLAUX||                             'AND t.bdREFERENCIA = g.bdREFERENCIA ';
      wSQLAUX = wSQLAUX||                             'AND t.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                             'AND POSITION('''||:wCODITEMONLINE||''', t.bdORDENACAO) > 0 ';
      wSQLAUX = wSQLAUX||                             'AND ((POSITION(''.00000'', t.bdORDENACAO) = 0) ';
      IF (UPPER(:prDEBCRED) = 'DEB') THEN
        wSQLAUX = wSQLAUX||                   'AND t.bdDEBITO IS NULL)),0)) ';
      ELSE
      IF (UPPER(:prDEBCRED) = 'CRED') THEN
        wSQLAUX = wSQLAUX||                   'AND t.bdCREDITO IS NULL)),0)) ';
    END
  ELSE
        BEGIN
      wSQLAUX =          'COALESCE(COALESCE(g.bdVALOR,0)-COALESCE((SELECT SUM(o.bdVALOR) ';
      wSQLAUX = wSQLAUX||                                         'FROM TMP_TCONF_CONTAS_ONLINE_TEMP o ';
      wSQLAUX = wSQLAUX||                                         'WHERE o.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdCODITEMONLINE = '||:wCODITEMONLINE;
      wSQLAUX = wSQLAUX||                                           'AND o.bdCODMATRIZ = g.bdCODMATRIZ ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdREFERENCIA = g.bdREFERENCIA ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdFORMULA IS NOT NULL ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdVALOR > 0),0),0)';
        END

  wSQL =       'INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO) ';
  wSQL = wSQL||'SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, ';
  IF (:prDEBCRED <> '') THEN
        BEGIN
      IF (UPPER(:prDEBCRED) = 'DEB') THEN
        wSQL = wSQL||'c.bdCONTADEBPROV as bdDEBITO, NULL as bdCREDITO, ';
      ELSE
      IF (UPPER(:prDEBCRED) = 'CRED') THEN
        wSQL = wSQL||'NULL as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO, ';
        END
  ELSE
  wSQL = wSQL||'c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO, ';
  wSQL = wSQL||'      ''Valor de '||:prTIPO||' D?bito - Ref:''||substring(g.bdREFERENCIA FROM 5 for 2)||''/''||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL, NULL as bdDATA, ';
  wSQL = wSQL||       wSQLAUX||', ';
  wSQL = wSQL||'      100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO ';
  wSQL = wSQL||'FROM VEF_EMP_TBLOCOMGERREG g ';
  wSQL = wSQL||'JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP) ';
  wSQL = wSQL||'JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = '||:wCODITEMONLINE||') ';
  wSQL = wSQL||'WHERE g.bdCODMATRIZ = '||:prCODEMP;
  wSQL = wSQL||'  AND g.bdREFERENCIA = '||:prREFERENCIA;
  wSQL = wSQL||'  AND g.bdCODQUADRO = '||wCodQuadro; -- M200 - Consolida??o da contribui??o para o PIS/PASEP
  wSQL = wSQL||'  AND g.bdNUMCAMPO  = 02 '; -- VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo
  wSQL = wSQL||'  AND c.bdFORMULA IS NULL '; -- Para n?o carregar as contas detalhadas
  wSQL = wSQL||'  AND ('||:wSQLAux||') > 0; ';

  EXECUTE STATEMENT wSQL;

END
^

/* Alter (SP_APURACAO_BLOCOM_ONLINE_DETAL) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRCODITEMONLINE INTEGER)
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCONTDETALHADA VARCHAR(5);
BEGIN
  /* Insere os valores do Cr?ditos e D?bitos */
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
  SELECT t.bdCODMATRIZ, t.bdREFERENCIA, NULL as bdCHAVE, t.bdCODPLAPADRAO, NULL as bdCODUSU, t.bdCONTADEBPROV as bdDEBITO, t.bdCONTACREDPROV as bdCREDITO,
         'Valor de '||
         TRIM(CASE
                WHEN t.bdFORMULA LIKE '%PIS%' THEN 'PIS'
                WHEN t.bdFORMULA LIKE '%COFINS%' THEN 'Cofins'
              ELSE ''
              END)||
         ' '||
         TRIM(CASE
                WHEN t.bdFORMULA LIKE '%CREDDESC%' THEN 'Cr?dito '
                WHEN t.bdFORMULA LIKE '%DEBITO%' THEN 'D?bito '
              ELSE ''
              END)||
          ' "'||COALESCE(cred.bdREGEXP||' - '||cred.bdDESCRICAO, deb.bdCODCSOCIALEXP||' - '||deb.bdDESCRICAO)||'"'||
          ' - Ref:'||substring(t.bdREFERENCIA FROM 5 for 2)||'/'||substring(t.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, t.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, t.bdORDENACAO
  FROM TMP_TCONF_CONTAS_ONLINE_TEMP t
  LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS cred ON (cred.bdREGEXP = CASE
                                                                      WHEN t.bdFORMULA LIKE '%CREDDESC%' THEN SUBSTRING(t.bdFORMULA FROM (POSITION('(', t.bdFORMULA)-2) FOR 2)
                                                                    ELSE '' END)
  LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 deb ON (deb.bdCODCSOCIALEXP = CASE
                                                                             WHEN t.bdFORMULA LIKE '%DEBITO%' THEN SUBSTRING(t.bdFORMULA FROM (POSITION('(', t.bdFORMULA)-2) FOR 2)
                                                                           ELSE '' END)
  WHERE t.bdCODITEMONLINE IN (:prCODITEMONLINE) -- "Cr?ditos" e "D?bitos"...
    AND t.bdFORMULA IS NOT NULL
    AND t.bdVALOR > 0
  ORDER BY t.bdCODMATRIZ, t.bdREFERENCIA, t.bdORDENACAO;

END
^

/* Alter (SP_APURACAO_BLOCOM_VALIDA_DETAL) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_VALIDA_DETAL(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRCODCONFBLOCOM INTEGER,
PRCODPLANOONLINE INTEGER,
PRCODQUADRO INTEGER,
PRCODNATBC INTEGER,
PRVALOR NUMERIC(15,2))
 AS
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCONTADEBPROV INTEGER;
DECLARE VARIABLE WCONTACREDPROV INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(100);
DECLARE VARIABLE WCODITEMONLINE INTEGER;
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WREPLACE01 VARCHAR(10);
DECLARE VARIABLE WREPLACE02 VARCHAR(200);
DECLARE VARIABLE WREPLACE03 VARCHAR(10);
DECLARE VARIABLE WORD INTEGER;
BEGIN
  -- Busca as contas do lan?amento cont?bi, primeiro a especifica, caso n?o exista, busca a padr?o...
  SELECT FIRST 1 bdCODPLAPADRAO, bdCONTADEBPROV, bdCONTACREDPROV, bdCLASSIFICACAO, bdCODITEMONLINE, bdFORMULA,
         TRIM(CASE
                WHEN :prCODQUADRO IN (11,29) THEN 'Cr?dito'
                WHEN :prCODQUADRO IN (19,37) THEN 'D?bito'
              END) as bdREPLACE01,
         COALESCE(cred.bdREGEXP||' - '||cred.bdDESCRICAO, deb.bdCODCSOCIALEXP||' - '||deb.bdDESCRICAO) as bdREPLACE02,
         TRIM(CASE
                WHEN :prCODQUADRO IN (11,19) THEN 'PIS'
                WHEN :prCODQUADRO IN (29,37) THEN 'COFINS'
              END) as bdREPLACE03,
         COALESCE(cred.bdREGEXP, deb.bdCODCSOCIALEXP) as bdORD
  FROM (
         SELECT o.bdCODPLAPADRAO, o.bdCODITEMONLINE, o.bdCONTADEBPROV, o.bdCONTACREDPROV, o.bdCLASSIFICACAO, o.bdFORMULA
         FROM TCONF_CONTAS_ONLINE o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdFORMULA = 'BLOCOM'||
                             TRIM(CASE
                                    WHEN :prCODQUADRO IN (11,29) THEN 'CREDDESC'
                                    WHEN :prCODQUADRO IN (19,37) THEN 'DEBITO'
                                  END)||
                             TRIM(CASE
                                    WHEN :prCODQUADRO IN (11,19) THEN 'PIS'
                                    WHEN :prCODQUADRO IN (29,37) THEN 'COFINS'
                                  END)||
                             '.'||LPAD(:prCODNATBC, 6, '0')||'('||:prCODCONFBLOCOM||')'
--           AND ((o.bdCONTADEBPROV IS NOT NULL) AND (o.bdCONTACREDPROV IS NOT NULL))
         UNION ALL
         SELECT o.bdCODPLAPADRAO, o.bdCODITEMONLINE, o.bdCONTADEBPROV, o.bdCONTACREDPROV, o.bdCLASSIFICACAO, o.bdFORMULA
         FROM TCONF_CONTAS_ONLINE o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdFORMULA = 'BLOCOM'||
                             TRIM(CASE
                                    WHEN :prCODQUADRO IN (11,29) THEN 'CREDDESC'
                                    WHEN :prCODQUADRO IN (19,37) THEN 'DEBITO'
                                  END)||
                             TRIM(CASE
                                    WHEN :prCODQUADRO IN (11,19) THEN 'PIS'
                                    WHEN :prCODQUADRO IN (29,37) THEN 'COFINS'
                                  END)||
                             '.T.'||LPAD(:prCODNATBC, 6, '0')||'('||:prCODCONFBLOCOM||')'
        ) c
  LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS cred ON (cred.bdREGEXP = CASE
                                                                      WHEN c.bdFORMULA LIKE '%CREDDESC%' THEN SUBSTRING(c.bdFORMULA FROM (POSITION('(', c.bdFORMULA)-2) FOR 2)
                                                                    ELSE '' END)
  LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 deb ON (deb.bdCODCSOCIALEXP = CASE
                                                                             WHEN c.bdFORMULA LIKE '%DEBITO%' THEN SUBSTRING(c.bdFORMULA FROM (POSITION('(', c.bdFORMULA)-2) FOR 2)
                                                                           ELSE '' END)
  INTO :wCODPLAPADRAO, :wCONTADEBPROV, :wCONTACREDPROV, :wCLASSIFICACAO, :wCODITEMONLINE, :wFORMULA, :wREPLACE01, :wREPLACE02, :wREPLACE03, wORD;

  -- Grava as contas do que acabou de buscar, caso n?o existam, insere a inconsist?ncia...
--  IF ((:wCODPLAPADRAO IS NOT NULL) AND (:wCONTADEBPROV IS NOT NULL) AND (:wCONTACREDPROV IS NOT NULL)) THEN
  IF ((:wCODPLAPADRAO IS NOT NULL) AND ((:wCONTADEBPROV IS NOT NULL) OR (:wCONTACREDPROV IS NOT NULL))) THEN
    BEGIN
      INSERT INTO TMP_TCONF_CONTAS_ONLINE_TEMP (bdCODMATRIZ,  bdREFERENCIA,  bdCODPLANOONLINE, bdCODPLAPADRAO, bdCODITEMONLINE, bdCONTADEBPROV, bdCONTACREDPROV, bdFORMULA,  bdVALOR, bdORDENACAO)
                                        VALUES (  :prCODEMP, :prREFERENCIA, :prCODPLANOONLINE, :wCODPLAPADRAO, :wCODITEMONLINE,
                                                  :wCONTADEBPROV, :wCONTACREDPROV, :wFORMULA, :prVALOR, LPAD(:wCODITEMONLINE, 5, '0')||'.'||LPAD(:wORD, 5, '0'));
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_VALIDACONTAS) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRCODCONFBLOCOM INTEGER,
PRCODPLANOONLINE INTEGER,
PRCODITEMONLINE INTEGER,
PRCODINC INTEGER)
 AS
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCONTADEBPROV INTEGER;
DECLARE VARIABLE WCONTACREDPROV INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(100);
DECLARE VARIABLE WCODITEMONLINE INTEGER;
BEGIN
  -- Busca as contas do lan?amento cont?bi, primeiro a especifica, caso n?o exista, busca a padr?o...
  SELECT FIRST 1 bdCODPLAPADRAO, bdCONTADEBPROV, bdCONTACREDPROV, bdCLASSIFICACAO, bdCODITEMONLINE
  FROM (
         SELECT o.bdCODPLAPADRAO, o.bdCODITEMONLINE, o.bdCONTADEBPROV, o.bdCONTACREDPROV, o.bdCLASSIFICACAO
         FROM TCONF_CONTAS_ONLINE o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdCODITEMONLINE = :prCODITEMONLINE -- Busca a conta espec?f?ca...
           AND ((o.bdCONTADEBPROV IS NOT NULL) AND (o.bdCONTACREDPROV IS NOT NULL))
           AND (o.bdCODCONFBLOCOM = :prCODCONFBLOCOM) -- Configura??o especifica
         UNION ALL
         SELECT o.bdCODPLAPADRAO, o.bdCODITEMONLINE, o.bdCONTADEBPROV, o.bdCONTACREDPROV, o.bdCLASSIFICACAO
         FROM TCONF_CONTAS_ONLINE o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdCODITEMONLINE = :prCODITEMONLINE -- Busca a conta padr?o...
           --AND ((o.bdCONTADEBPROV IS NOT NULL) AND (o.bdCONTACREDPROV IS NOT NULL))
           AND (o.bdCODCONFBLOCOM IS NULL) -- Configura??o padr?o
        ) c
  --WHERE ((c.bdCONTADEBPROV IS NOT NULL) AND (c.bdCONTACREDPROV IS NOT NULL))
  INTO :wCODPLAPADRAO, :wCONTADEBPROV, :wCONTACREDPROV, :wCLASSIFICACAO, :wCODITEMONLINE;

  -- Grava as contas do que acabou de buscar, caso n?o existam, insere a inconsist?ncia...
  IF ((:wCODPLAPADRAO IS NOT NULL) AND (:wCONTADEBPROV IS NOT NULL) AND (:wCONTACREDPROV IS NOT NULL)) THEN
    BEGIN
      INSERT INTO TMP_TCONF_CONTAS_ONLINE_TEMP (bdCODMATRIZ,  bdREFERENCIA,  bdCODPLANOONLINE, bdCODPLAPADRAO,  bdCODITEMONLINE, bdCONTADEBPROV, bdCONTACREDPROV, bdORDENACAO)
                                        VALUES (  :prCODEMP, :prREFERENCIA, :prCODPLANOONLINE, :wCODPLAPADRAO, :prCODITEMONLINE, :wCONTADEBPROV, :wCONTACREDPROV, LPAD(:wCODITEMONLINE, 5, '0')||'.'||LPAD('', 5, '0'));
        END
  ELSE
  IF ( --(:wCONTADEBPROV IS NULL) AND (:wCONTACREDPROV IS NULL) AND
       (:prCODINC NOT IN (15,19)) ) THEN -- Conta "Outras Dedu??es" n?o vai obrigar ou lan?ar inconsist?ncias...
    BEGIN
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDREPLACES)
                            VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA,
                                    (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1)
                                     FROM VEF_INCON_BLOCOM x
                                     WHERE x.BDCODPERIODO = 7
                                       AND x.BDCODEMP = :prCODEMP
                                       AND x.BDCODMATRIZ = :prCODEMP
                                       AND x.BDREFERENCIA = :prREFERENCIA),
                                    NULL, NULL, NULL, NULL, :prCODINC, :prCODPLANOONLINE||'?'||COALESCE(:wCLASSIFICACAO,'03.002')||'?'||:prCODPLANOONLINE); -- Caso n?o tenha conta por n?o ter atualizado o plano, joga o padr?o para abrir a tela e mostrar que n?o tem comnfigura??o das contas...
    END
 
END
^

/* Alter (SP_APURACAO_BLOCOM_VALIDAONLINE) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_VALIDAONLINE(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODCONFBLOCOM INTEGER;
DECLARE VARIABLE WCODPLANOONLINE INTEGER;
DECLARE VARIABLE WTIPOINTPIS INTEGER;
DECLARE VARIABLE WTIPOINTCOFINS INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WCODNATBC INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(15,2);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Obt?m a configura??o de Bloco M
  SELECT COALESCE(tot.bdCODCONFBLOCOM, confPadrao.bdCODCONF) AS bdCODCONFBLOCOM
  FROM VW_EMP_REF_TOTAL tot
  LEFT OUTER JOIN (
                    SELECT FIRST 1 x.bdCODCONF, x.bdPLANOPADRAO
                    FROM VEF_BASE_TCONFBLOCOM x
                    WHERE x.bdPLANOPADRAO = 'TRUE'
                   ) confPadrao ON (confPadrao.bdPLANOPADRAO = 'TRUE')
  WHERE  tot.bdCODEMP = :prCODEMP
  ORDER BY tot.bdCODCONFBLOCOM, tot.bdCODEMP
  INTO :wCODCONFBLOCOM;

  -- Obt?m o plano online
  SELECT r.bdCODPLANOONLINE
  FROM VW_TEMPRESAS_REF r
  WHERE r.bdCODEMP = :prCODEMP
  INTO :wCODPLANOONLINE;

  -- Verifica se deve ou n?o contabilizar o PIS e Cofins...
  SELECT bdTIPOINTPIS, bdTIPOINTCOFINS
  FROM TPLANO_CONF_ONLINE
  WHERE bdCODPLANOONLINE = :wCODPLANOONLINE
  INTO :wTIPOINTPIS, :wTIPOINTCOFINS;

  IF ((:wCODCONFBLOCOM > 0) AND (:wCODPLANOONLINE > 0)) THEN
    BEGIN
      IF ((:wTIPOINTPIS = 1) OR (:wTIPOINTCOFINS = 1)) THEN -- Valores da apura??o
        BEGIN
          /* Contabiliza detalhadamente nas contas especificas... */
          FOR
            SELECT /*m.bdCODMATRIZ, m.bdREFERENCIA,*/ m.bdCODQUADRO, m.bdCODNATBC, m.bdVALOR
            FROM (
                   SELECT /*m.bdCODMATRIZ, m.bdREFERENCIA,*/ m.bdCODQUADRO, m.bdCODNATBC, SUM((COALESCE(m.bdVL_BC,0)*COALESCE(m.bdALIQ,1))/100) AS bdVALOR
                   FROM VEF_EMP_TBLOCOM105_M505 m
                   WHERE m.bdCODMATRIZ = :prCODEMP
                     AND m.bdREFERENCIA = :prREFERENCIA
                   GROUP BY m.bdCODMATRIZ, m.bdREFERENCIA, m.bdCODQUADRO, m.bdCODNATBC
                   UNION ALL
                   SELECT /*m.bdCODMATRIZ, m.bdREFERENCIA,*/ m.bdCODQUADRO, m.bdCODCSOCIAL, SUM(COALESCE(m.bdVL_CONT_PER,0)) AS bdVALOR
                   FROM VEF_EMP_TBLOCOM210_M610 m
                   WHERE m.bdCODMATRIZ = :prCODEMP
                     AND m.bdREFERENCIA = :prREFERENCIA
                   GROUP BY m.bdCODMATRIZ, m.bdREFERENCIA, m.bdCODQUADRO, m.bdCODCSOCIAL
                  ) m
            INTO /*:wCODMATRIZ, :wREFERENCIA,*/ :wCODQUADRO, :wCODNATBC, :wVALOR
          DO
            BEGIN
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDA_DETAL (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, :wCODQUADRO, :wCODNATBC, :wVALOR);
            END
          /********************************************************/

          /* Contabiliza nas contas principais... */
          IF (:wTIPOINTPIS = 1) THEN -- Valores da apura??o
            BEGIN
              -- 247 - Cr?dito - PIS
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 247, 13);
              -- 248 - D?bito - PIS
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 248, 14);
              -- 249 - Outras Dedu??es - PIS
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 249, 15);
              -- 250 - Compensa??o - PIS
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 250, 16);
            END
    
          IF (:wTIPOINTCOFINS = 1) THEN -- Valores da apura??o
            BEGIN
              -- 251 - Cr?dito - Cofins
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 251, 17);
              -- 252 - D?bito - Cofins
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 252, 18);
              -- 253 - Outras Dedu??es - Cofins
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 253, 19);
              -- 254 - Compensa??o - Cofins
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 254, 20);
            END
          /****************************************/
        END
    END

END
^

/* Alter (SP_APURADOS_VALTRANS) */
ALTER PROCEDURE SP_APURADOS_VALTRANS(PRCODEMP VARCHAR(25000),
PRCOLABORADOR VARCHAR(32700),
PRCOMPETENCIA INTEGER,
PRNRVIAS INTEGER)
 RETURNS(BDNRVIA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODITI INTEGER,
BDCOMPETENCIA INTEGER,
BDQUANTIDADE INTEGER,
BDTPAPURACAO INTEGER,
BDDTINICIAL DATE,
BDDTFINAL DATE,
BDNOMCOL DM_BDNOMCOL,
BDNOMCOLUPPER DM_BDNOMCOL,
BDRGCOL VARCHAR(20),
BDCPFCOL VARCHAR(14),
BDDESCITI VARCHAR(40),
BDLINHAITI VARCHAR(20),
BDVALUNI NUMERIC(18,6),
BDVALCUSTOEMP NUMERIC(18,6),
BDVALDESCONTO NUMERIC(18,6),
BDQTDITINERARIOS INTEGER,
BDFECHAMENTOVT INTEGER,
BDFECHAMENTO INTEGER)
 AS
declare variable WVIA integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDCODITI integer;
declare variable WBDCOMPETENCIA integer;
declare variable WBDQUANTIDADE integer;
declare variable WBDTAPURACAO integer;
declare variable WBDDTINICIAL date;
declare variable WBDDTFINAL date;
declare variable WBDNOMCOL DM_BDNOMCOL;
declare variable WBDNOMCOLUPPER DM_BDNOMCOL;
declare variable WBDRGCOL varchar(20);
declare variable WBDCPFCOL varchar(30);
declare variable WBDDESCITI varchar(50);
declare variable WBDLINHAITI varchar(20);
declare variable WBDVALUNI numeric(18,6);
declare variable WBDVALCUSTOEMP numeric(18,6);
declare variable WBDVALDESCONTO numeric(18,6);
declare variable WBDQTDITINERARIOS integer;
declare variable WSQL varchar(30000);
declare variable WSQLDATA varchar(10000);
declare variable WWHERE varchar(10000);
declare variable WBDDATAADMCOL date;
declare variable WBDDATARESCISAO date;
declare variable WSQLCUSTOEMP varchar(2000);
declare variable WFECHAVTEMP integer;
declare variable WFECHAEMP integer;
declare variable WULTDIA integer;
BEGIN
  WBDQTDITINERARIOS = 0;
  WVIA = 1;

  WSQL = 'select ValeTrans.*, cast (null as Date) BDDTINICIAL, cast(null as Date) BDDTFINAL, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, DOCREF.BDRGCOL, ColCon.BDCPFCOL, Iti.BDDESCITI, '||
        'Iti.BDLINHAITI, Iti.BDVALITI BDVALUNI, 0 BDVALCUSTOEMP, 0 BDVALDESCONTO, ColCon.BDDATAADMCOL, Resc.BDDATARESCISAO '||
        'from VRHF_EMP_TAPVALTRANS ValeTrans '||
        'left outer join VRH_EMP_TCOLCON ColCon on (ColCon.BDCODEMP = ValeTrans.BDCODEMP and ColCon.BDCODCOL = ValeTrans.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = VALETRANS.BDCODEMP and COLCAD.BDCODCOL = VALETRANS.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = VALETRANS.BDCODEMP and DOCREF.BDCODCOL = VALETRANS.BDCODCOL) '||
        'left outer join VRH_EMP_TCOLCON_DOC ColConDoc on (ColConDoc.BDCODEMP = ValeTrans.BDCODEMP and ColConDoc.BDCODCOL = ValeTrans.BDCODCOL) '||
        'left outer join VW_VRHF_BASE_TITINERARIOS_REF Iti on (Iti.BDCODITI = ValeTrans.BDCODITI) '||
        'left outer join VW_RESCISAO Resc on (Resc.BDCODEMP = ValeTrans.BDCODEMP and Resc.BDCODCOL = ValeTrans.BDCODCOL) ';

  WWHERE = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     BEGIN
      WWHERE = ' where '||PRCODEMP||' ';

      IF (PRCOLABORADOR IS NOT NULL AND PRCOLABORADOR <> '') THEN
         WWHERE = WWHERE||' and '||PRCOLABORADOR||' ';
     END

   IF (PRCOMPETENCIA IS NOT NULL AND PRCOMPETENCIA <> 0) THEN
      BEGIN
        IF (WWHERE = '') THEN
           WWHERE = WWHERE||' where ValeTrans.BDCOMPETENCIA = '||PRCOMPETENCIA;
        ELSE
           WWHERE = WWHERE||' and ValeTrans.BDCOMPETENCIA = '||PRCOMPETENCIA;
      END

   WSQL = WSQL||WWHERE||' order by ValeTrans.BDCODEMP, ValeTrans.BDCODCOL, ValeTrans.BDCODITI, ValeTrans.BDCOMPETENCIA';

   EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(prcompetencia FROM 5 FOR 2)||', '||SUBSTRING(prcompetencia FROM 1 FOR 4)||')' INTO :wultdia;

   FOR EXECUTE STATEMENT WSQL INTO
     WBDCODEMP,
     WBDCODCOL,
     WBDCODITI,
     WBDCOMPETENCIA,
     WBDQUANTIDADE,
     WBDTAPURACAO,
     WBDDTINICIAL,
     WBDDTFINAL,
     WBDNOMCOL,
     WBDNOMCOLUPPER,
     WBDRGCOL,
     WBDCPFCOL,
     WBDDESCITI,
     WBDLINHAITI,
     WBDVALUNI,
     WBDVALCUSTOEMP,
     WBDVALDESCONTO,
     WBDDATAADMCOL,
     WBDDATARESCISAO
   DO
   BEGIN
     WVIA = 1;
     BDVALCUSTOEMP = 0;
     WHILE (WVIA <= PRNRVIAS) DO
       BEGIN
         BDNRVIA = WVIA;
         BDCODEMP = WBDCODEMP;
         BDCODCOL = WBDCODCOL;
         BDCODITI = WBDCODITI;
         BDCOMPETENCIA = WBDCOMPETENCIA;
         BDQUANTIDADE = WBDQUANTIDADE;
         BDTPAPURACAO = WBDTAPURACAO;

         --Sol. 19620 - Bruno L. R. - 28/07/2017
         EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRCOMPETENCIA);

         WSQLDATA = 'select BDFECHAVTEMP, BDFECHAMESEMP from VW_VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP;
         WFECHAVTEMP = null;
         EXECUTE STATEMENT WSQLDATA INTO :WFECHAVTEMP, :WFECHAEMP;
    
         BDFECHAMENTOVT = wfechavtemp;
         BDFECHAMENTO   = wfechaemp;

         if ((coalesce(wfechavtemp, 0) = 0) or (wfechavtemp > wultdia)) then
            begin
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);

              if (coalesce(wfechavtemp, 0) = 0) then
                 WBDDTFINAL = null;
              else
                 WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||wultdia|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
            end
         else
            begin
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTINICIAL = DATEADD(DAY, 1, DATEADD(MONTH, -1, WBDDTFINAL));
            end
         --Sol. 19620 - Bruno L. R. - 28/07/2017
    
         IF (WBDDTINICIAL < WBDDATAADMCOL) THEN
            BEGIN
              WBDDTINICIAL = WBDDATAADMCOL;
            END
    
         IF (((SUBSTRING(WBDDATARESCISAO FROM 1 FOR 4) || SUBSTRING(WBDDATARESCISAO FROM 6 FOR 2)) = BDCOMPETENCIA) AND (WBDDTFINAL > WBDDATARESCISAO)) THEN
            BEGIN
              WBDDTFINAL = WBDDATARESCISAO;
            END
    
         BDDTINICIAL = WBDDTINICIAL;
         BDDTFINAL = WBDDTFINAL;


         WSQLCUSTOEMP = 'select distinct (ValTrans.BDQUANTIDADE * Iti.BDVALITI) from VRHF_EMP_TAPVALTRANS ValTrans '||
            'left outer join VW_VRHF_BASE_TITINERARIOS_REF Iti on (Iti.BDCODITI = ValTrans.BDCODITI) '||
            'left outer join VWRH_UNION_FN_FT_MES Val on (Val.BDREFFN = ValTrans.BDCOMPETENCIA and Val.BDCODEMP = ValTrans.BDCODEMP and Val.BDCODCOL = ValTrans.BDCODCOL) '||
            'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = Val.BDCODVER) '||
         'where ValTrans.BDCODEMP='||BDCODEMP||' and ValTrans.BDCODCOL='||BDCODCOL||' and ValTrans.BDCOMPETENCIA='||PRCOMPETENCIA;

         FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALCUSTOEMP = BDVALCUSTOEMP + WBDVALCUSTOEMP;
           END

         BDNOMCOL = WBDNOMCOL;
         BDNOMCOLUPPER = WBDNOMCOLUPPER;
         BDRGCOL = WBDRGCOL;
         BDCPFCOL = WBDCPFCOL;
         BDDESCITI = WBDDESCITI;
         BDLINHAITI = WBDLINHAITI;
         BDVALUNI = WBDVALUNI;
         BDVALDESCONTO = WBDVALDESCONTO;
         WBDQTDITINERARIOS = WBDQTDITINERARIOS + 1;
         BDQTDITINERARIOS = WBDQTDITINERARIOS;

         WVIA = WVIA + 1;
         SUSPEND;
         BDVALCUSTOEMP = 0;

       END
   END
END
^

/* Alter (SP_ATI_SEM_AFAST_MES_INT) */
ALTER PROCEDURE SP_ATI_SEM_AFAST_MES_INT(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
declare variable WSQL varchar(1000);
declare variable WSQL2 varchar(2000);
declare variable WCODSIT integer;
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';

  -- Admiss?es
  wsql = wsql||'where COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescis?es e Transfer?ncias
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataini||''')) ';

  -- Situa??es
  wsql = wsql||' and not exists (select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
         'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
         'where Y.BDCODEMP = COLCON.BDCODEMP and Y.BDCODCOL = COLCON.BDCODCOL and Y.BDDATAINISIT <= '''||prdataini||''' and '||
     '(Y.BDDATAFIMSIT is null or Y.BDDATAFIMSIT >= '''||prdatafim||''') and Z.BDCODVER is not null)  ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
    begin
      wsql2 = 'select first 1 SIT.BDCODSIT from VRH_EMP_TSITCOL SIT '||
              'left outer join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
              'where SIT.BDCODEMP = '||bdcodemp||' and BDCODCOL = '||bdcodcol||' and SIT.BDDATAINISIT <= '''||prdataini||''' and '||
                    '((SIT.BDDATAFIMSIT is null) or (SIT.BDDATAFIMSIT >= '''||prdatafim||''')) and PSIT.BDCODVER is not null ';
      wcodsit = null;

      execute statement wsql2 into :wcodsit;

      if (wcodsit is null) then
        SUSPEND;
    end
END
^

/* Alter (SP_ATI_SEM_DEM_COM_TRANSF) */
ALTER PROCEDURE SP_ATI_SEM_DEM_COM_TRANSF(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
declare variable WSQL varchar(2000);
declare variable WTIPORESC integer;
declare variable WDATARESC date;
declare variable WSQL2 varchar(2000);
declare variable WCODCOL integer;
begin
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COALESCE(PRES.BDTIPOMOV,0), RESC.BDDATARESCISAO from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql||'left outer join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = RESC.BDCODPRES) ';

  -- Admiss?es
  wsql = wsql||'where COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescis?es e Transfer?ncias
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataini||''')) ';


  /*#Alt:18469. Precisa retornar os que não foram demitidos ou os que foram transferidos no período informado
     - Foi trocado a view VW_DEMITIDOS para utilizar direto a tabela porque na view já existe um controle com os colaboradores transferidos. Mas para o correto
       funcionamento desse SQL precisamos tratar os transferidos de outra forma.
     - Foi adicionado o comando "between" para o SQL utilizado na view VW_TRANSFERIDOS para retornar apenas os transferidos dentro do período informado.

  wsql = wsql||' and (not exists (select X.BDCODEMP, X.BDCODCOL from VW_DEMITIDOS X where X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL and X.BDDATARESCISAO <= '''||prdatafim||''') or '||
         '(exists (select W.BDCODEMP, W.BDCODCOL from VW_TRANSFERIDOS W where W.BDCODEMP = COLCON.BDCODEMP and W.BDCODCOL = COLCON.BDCODCOL and W.BDDATARESCISAO < '''||prdataini||''')))'; */

  for execute statement wsql
  into
    :BDCODEMP,
    :BDCODCOL,
    :wtiporesc,
    :wdataresc
  do
    begin
      if (wdataresc is null) then
         suspend;
      else
      if (wtiporesc = 0 and wdataresc > prdatafim) then
         suspend;
      else
      if (wtiporesc = 1 and wdataresc >= prdataini) then
         begin
           wsql2 = 'select first 1 BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPORIG = '||bdcodemp||' and BDCODCOLORIG = '||bdcodcol;
           wcodcol = null;
           execute statement wsql2 into :wcodcol;
           if (wcodcol is not null) then
              SUSPEND;
         end
    end
end
^

/* Alter (SP_ATIVOS_SEM_DEMITIDOS_MES) */
ALTER PROCEDURE SP_ATIVOS_SEM_DEMITIDOS_MES(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';

  -- Admiss?es
  wsql = wsql||'where COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescis?es e Transfer?ncias
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO > '''||prdatafim||'''))';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END
^

/* Alter (SP_ATU_CATEGORIA) */
ALTER PROCEDURE SP_ATU_CATEGORIA AS
DECLARE VARIABLE wcontrol INTEGER;
DECLARE VARIABLE waux VARCHAR(3000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wcol INTEGER;
DECLARE VARIABLE wanomes INTEGER;
DECLARE VARIABLE wcat INTEGER;
DECLARE VARIABLE wauxins VARCHAR(3000);
BEGIN
  /* Procedure Text */
--  suspend;
/*  waux = 'select x.bdcodemp,x.bdcodcol, x.bdrefcol, x.bdcategoriacol from VRHF_EMP_TCOLCON_FGTSGPS x';

  wauxins = 'delete from TCATEGORIATEMP';
  execute statement wauxins;

  for execute statement waux into
    :wemp,:wcol,:wanomes,:wcat
  do
    begin
      if (wcat is null) then
        wauxins = 'insert into TCATEGORIATEMP values('||wemp||','||wcol||','||wanomes||',null)';
      else
        wauxins = 'insert into TCATEGORIATEMP values('||wemp||','||wcol||','||wanomes||','||wcat||')';

      execute statement wauxins;
    end

  waux = 'update VRHF_EMP_TCOLCON_FGTSGPS x set x.bdcategoriacol = null';

  execute statement waux;*/

  waux = 'select x.bdcodemp,x.bdcodcol,x.bdanomes,x.bdcategoria,y.bdcontrcol from tcategoriatemp x'||
         ' left outer join vrh_emp_tcolcon y on (x.bdcodemp = y.bdcodemp and x.bdcodcol = y.bdcodcol)';

  FOR EXECUTE STATEMENT waux INTO
    :wemp,:wcol,:wanomes,:wcat, :wcontrol
  DO
    BEGIN
/*      if (wcontrol = 0) then
         begin
           if (wcat = 0) then
              wcat = 1; -- '1 - Empregado';
           else if (wcat = 1) then
              wcat = 2; -- '2 - Trabalhador avulso';
           else if (wcat = 2) then
              wcat = 3; -- '3 - Empregado afastado por prestar servi?o militar';
           else if (wcat = 3) then
              wcat = 4; -- '4 - Empregado sob contrato de trabalho por prazo determinado';
           else if (wcat = 4) then
              wcat = 5; -- '5 - Diretor n?o empregado com FGTS (empres?rio)';
           else if (wcat = 5) then
              wcat = 6; -- '6 - Empregado dom?stico';
           else if (wcat = 6) then
              wcat = 7; -- '7 - Trabalhador de 14 a 24 com contrato aprendizagem';
           else
              wcat = 1;
         end
      else
         begin
           if (wcat = 0) then
              wcat = 5; -- '05 - Diretor n?o empregado com FGTS (empres?rio)';
           else if (wcat = 1) then
              wcat = 11; -- '11 - Diretor n?o empregado sem FGTS';
           else if (wcat = 2) then
              wcat = 12; -- '12 - Agente p?blico';
           else if (wcat = 3) then
              wcat = 13; -- '13 - Trab. aut?nomo equip. contrib. remunera??o';
           else if (wcat = 4) then
              wcat = 14; -- '14 - Trab. aut?nomo equip. contrib. sal?rio-base';
           else if (wcat = 5) then
              wcat = 15; -- '15 - Transp. aut?nomo contrib remunera??o';
           else if (wcat = 6) then
              wcat = 16; -- '16 - Transp. aut?nomo contrib. sal?rio-base';
           else if (wcat = 7) then
              wcat = 17; -- '17 - Contribuinte individual cooperado';
           else if (wcat = 8) then
              wcat = 18; -- '18 - Contribuinte individual transportador cooperado';
           else if (wcat = 9) then
              wcat = 19; -- '19 - Agente pol?tico';
           else if (wcat = 10) then
              wcat = 20; -- '20 - Servidor p?blico tempor?rio';
           else if (wcat = 11) then
              wcat = 21; -- '21 - Servidor p?blico titular';
           else if (wcat = 12) then
              wcat = 22; -- '22 - Contrib. individual contratado por contrib indiv.';
           else if (wcat = 13) then
              wcat = 23; -- '23 - Contrib. individual transportador aut?nomo';
           else if (wcat = 14) then
              wcat = 24; -- '24 - Contrib. indiv. cooperado prestador de servi?os';
           else if (wcat = 15) then
              wcat = 25; -- '25 - Contrib. indiv. transp. cooperado - beneficente';
           else
              wcat = 13;
         end*/

      wauxins = 'update VRHF_EMP_TCOLCON_FGTSGPS x set x.bdcategoriacol = '||wcat||
              ' where x.bdcodemp = '||wemp||' and x.bdcodcol = '||wcol||' and x.bdrefcol = '||wanomes;

      EXECUTE STATEMENT wauxins;
    END
END
^

/* Alter (SP_ATU_CODREC) */
ALTER PROCEDURE SP_ATU_CODREC(PRCODREC DM_CODRECOF)
 AS
DECLARE VARIABLE WCODREC DM_CODRECOF;
BEGIN
  wcodrec = NULL;
  SELECT BDCODRECOF FROM TCODREC WHERE TRIM(BDCODRECOF) = :prcodrec INTO :wcodrec;
  IF (wcodrec IS NULL) THEN
     BEGIN
       INSERT INTO TCODREC (BDDESCREC,BDTIPOIMPOSTO,BDCODRECOF,BDCONFCONTABILIZA) VALUES ('Participa??o nos lucros ou resultados (PLR)', 2, :prcodrec, 'FALSE');
     END
END
^

/* Alter (SP_ATUALIZA_PART_TABLE_DEP) */
ALTER PROCEDURE SP_ATUALIZA_PART_TABLE_DEP(PRID_TERMINAL INTEGER,
PRCODTER INTEGER,
PRFIELD VARCHAR(20),
PRVALUE VARCHAR(100))
 AS
DECLARE VARIABLE WSESSAO INTEGER;
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WSQL VARCHAR(250);
BEGIN
  /*Sol: 14207 Patrick T. S? 16/12/2016.
    Esta sp atualiza o campo cpf/cnpj em outra tabela.
    Exemplo: Ao alterar CPF/CNPJ no cadastro de participante,
    todas as tabelas que tem o participante precisam receber o novo CPF/CNPJ
  */
  PRFIELD = UPPER(:PRFIELD);

  FOR SELECT TRIM(T.RDB$RELATION_NAME), S.BDSESSAO
      FROM RDB$RELATION_FIELDS T
      JOIN TMP_TSESSAO_IMP S ON(S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = TRIM(T.RDB$RELATION_NAME))
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$FIELD_NAME = 'BDALTCODTER'
      INTO :wTable, :wSessao
  DO
    BEGIN
      wSQL = 'UPDATE '||:wTable||' SET ';
      IF (:PRFIELD = 'BDCGCTER') THEN
        wSQL = :wSQL ||' BDCNPJ = '||''''||:PRVALUE||'''';
      ELSE
      IF (:PRFIELD = 'BDSIGLAUFTER') THEN
        wSQL = :wSQL ||' BDSIGLAUFTER = '||''''||:PRVALUE||'''';
      ELSE
      IF (:PRFIELD = 'BDNOMETER') THEN
        wSQL = :wSQL ||' BDNOMETER = '||''''||:PRVALUE||'''';

      wSQL = :wSQL || ' WHERE BDSESSAO = '||:wSessao;
      wSQL = :wSQL || ' AND BDCODTER = '||:PRCODTER;
      EXECUTE STATEMENT :wSQL;

      wSessao = NULL;
    END
END
^

/* empty dependent procedure body */
/* Clear: SP_ATUALIZAR_TMP_BLOCOK210 for: SP_ATUALIZAR_CAMPO_CHAVE_TEMP */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK210(PRSESSAO INTEGER,
PRSESSAOPRO INTEGER,
PRULTCHAVE INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_ATUALIZAR_TMP_BLOCOK230K250 for: SP_ATUALIZAR_CAMPO_CHAVE_TEMP */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK230K250(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRID_TERMINAL INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_ATUALIZAR_TMP_BLOCOK260 for: SP_ATUALIZAR_CAMPO_CHAVE_TEMP */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK260(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRIDTERMINAL INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_ATUALIZAR_TMP_BLOCOK270 for: SP_ATUALIZAR_CAMPO_CHAVE_TEMP */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK270(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRIDTERMINAL INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_ATUALIZAR_TMP_TMOVSAI for: SP_ATUALIZAR_CAMPO_CHAVE_TEMP */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TMOVSAI(PRSESSAO INTEGER,
PRREF INTEGER,
PRCHAVEFIMBASE INTEGER,
PRVALIDARCSTMOVPRO VARCHAR(5),
PRSESSAOPRO INTEGER,
PRSESSAOTER INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_ATUALIZAR_CAMPO_CHAVE_TEMP) */
ALTER PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(PRSESSAO INTEGER,
PRTABLE VARCHAR(50))
 AS
DECLARE VARIABLE WSQL VARCHAR(500);
DECLARE VARIABLE WTABLE VARCHAR(100);
BEGIN
  FOR SELECT RDB$RELATION_NAME BDTABLE
      FROM RDB$RELATION_FIELDS
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$RELATION_NAME <> 'TMP_VEF_EMP_TMOVSAI_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_TTERCEIRO_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_TCADPRO_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_TUNIDADEMEDIDA_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_VEF_BASE_TEQUIPASAT_TEMP'     
      AND RDB$RELATION_NAME <> 'TMP_TCADPRO_INSUMOS_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_VEF_EMP_TAJUICMSE115_TEMP' -- ALT.: 11938 - N?o pode incluir a tabela de lan?amento de ajuste do E115
      AND RDB$RELATION_NAME <> ''||:PRTABLE||''
      AND RDB$FIELD_NAME = 'BDEDITCHAVE'
      INTO :wTable
  DO
    BEGIN
      wSql =         'UPDATE '||:wTable||' T ';
      wSql = wSql || 'SET T.BDEDITCHAVE = ( ';
      wSql = wSql || '                     SELECT BDEDITCHAVE ';
      wSql = wSql || '                     FROM '||:PRTABLE||' S ';
      wSql = wSql || '                     WHERE S.BDSESSAO = T.BDSESSAO ';
      wSql = wSql || '                     AND S.BDCODEMP = T.BDCODEMP';
      wSql = wSql || '                     AND S.BDCHAVE = T.BDCHAVE ';
      wSql = wSql || '                    ) ';
      wSql = wSql || 'WHERE T.BDSESSAO = '||:PRSESSAO;
      EXECUTE STATEMENT wSql;
    END
END
^

/* empty dependent procedure body */
/* Clear: SP_ATUALIZAR_TMP_MOVPROSAI_TEMP for: SP_ATUALIZAR_CST_PROD */
ALTER PROCEDURE SP_ATUALIZAR_TMP_MOVPROSAI_TEMP(PRSESSAO INTEGER,
PRCODPLANOINCO INTEGER,
PRVALIDARCST VARCHAR(5),
PRSESSAOPRO INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_ATUALIZAR_TMP_TCADPRO for: SP_ATUALIZAR_CST_PROD */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TCADPRO(PRSESSAO INTEGER NOT NULL,
PRLANCAMENTOMANUAL /* DM_BOOLEAN */ VARCHAR(5) NOT NULL,
PRGERARINCONSISTENCIAS /* DM_BOOLEAN */ VARCHAR(5) NOT NULL,
PRREF INTEGER,
PRCODEMP INTEGER,
PRIDTERMINAL INTEGER,
PRALTERARSIT /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_ATUALIZAR_CST_PROD) */
ALTER PROCEDURE SP_ATUALIZAR_CST_PROD(PRSESSAO INTEGER)
 AS
BEGIN
  /*Atualiza as CST's*/
  /*IPI - Entrada*/
  UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTIPIENT = (SELECT FIRST 1 IPI.BDCODCSTIPIENT FROM VEF_BASE_TCSTIPICORENTSAI IPI WHERE IPI.BDCODCSTIPISAI = P.BDCODCSTIPISAI)
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCODCSTIPISAI > 7;

  /*IPI - Sa?da*/
  UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTIPISAI = (SELECT FIRST 1 IPI.BDCODCSTIPISAI FROM VEF_BASE_TCSTIPICORENTSAI IPI WHERE IPI.BDCODCSTIPIENT = P.BDCODCSTIPIENT)
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCODCSTIPIENT <= 7;
    
  /*COFINS - Entrada*/
  UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTCOFENT = (SELECT FIRST 1 COF.BDCODCSTCOFENT FROM VEF_BASE_TCSTCOFCORENTSAI COF WHERE COF.BDCODCSTCOFSAI = P.BDCODCSTCOFSAI)
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCODCSTCOFSAI < 49;

  /*COFINS - Sa?da*/
  UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTCOFSAI = (SELECT FIRST 1 COF.BDCODCSTCOFSAI FROM VEF_BASE_TCSTCOFCORENTSAI COF WHERE COF.BDCODCSTCOFENT = P.BDCODCSTCOFENT)
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCODCSTCOFENT >= 50;
    
  /*PIS - Entrada*/
  UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTPISENT = (SELECT FIRST 1 PIS.BDCODCSTPISENT FROM VEF_BASE_TCSTPISCORENTSAI PIS WHERE PIS.BDCODCSTPISSAI = P.BDCODCSTPISSAI)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDCODCSTPISSAI <= 49) OR (P.BDCODCSTPISSAI = 99));

  /*PIS - Sa?da*/
  UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTPISSAI = (SELECT FIRST 1 PIS.BDCODCSTPISSAI FROM VEF_BASE_TCSTPISCORENTSAI PIS WHERE PIS.BDCODCSTPISENT = P.BDCODCSTPISENT)
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCODCSTPISENT >= 50;

  UPDATE TMP_TCADPRO TP SET TP.BDCODCSTIPIENT = (SELECT FIRST 1 P.BDCODCSTIPIENT FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTIPISAI = (SELECT FIRST 1 P.BDCODCSTIPISAI FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTCOFENT = (SELECT FIRST 1 P.BDCODCSTCOFENT FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTCOFSAI = (SELECT FIRST 1 P.BDCODCSTCOFSAI FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTPISENT = (SELECT FIRST 1 P.BDCODCSTPISENT FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTPISSAI = (SELECT FIRST 1 P.BDCODCSTPISSAI FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA)
  WHERE TP.BDSESSAO = :PRSESSAO;
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK200) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK200(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRIDTERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO AND ((K.BDCHAVEK200 IS NOT NULL) AND (K.BDCHAVEK200 > 0));

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK200_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*22 - Lan?amento j? existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS(
             SELECT K200.BDCHAVE
             FROM VEF_EMP_TMOVK200 K200
             WHERE K200.BDCODEMP = K.BDCODEMP
             AND K200.BDDATAESTFIM = K.BDDATAESTFIM
             AND K200.BDCODPOSSE = K.BDCODPOSSE
             AND K200.BDCODPROD = K.BDALTCODPROD             
            );

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 88 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDQTDESTOQUE <= 0;

  /*17 - Participante n?o informado*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 17 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODPOSSE IN(2, 3)
  AND ((K.BDALTCODTER IS NULL) OR (K.BDALTCODTER = 0));

  /*89 - O c?digo SPED do item informado deve ser 00, 01, 02, 03, 04, 05, 06 ou 10*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 89 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDTIPOITEM IN(1, 2, 3, 4, 5, 6, 7, 11);
  
  /*74 - Participante inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 74 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  JOIN TMP_TTERCEIRO T ON(T.BDEDITCHAVE = K.BDALTCODTER AND T.BDINCONSISTENTE IS NOT NULL AND T.BDINCONSISTENTE NOT IN(0, 2))
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODTER IS NOT NULL) AND (K.BDALTCODTER > 0))
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;  
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK210) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK210(PRSESSAO INTEGER,
PRSESSAOPRO INTEGER,
PRULTCHAVE INTEGER)
 AS
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK WHERE BDSESSAO = :PRSESSAO AND BDCHAVEK210 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK210_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*22 - Lan?amento j? existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT FIRST 1 K210.BDCHAVE
              FROM VEF_EMP_TMOVK210 K210
              WHERE K210.BDCODEMP = K.BDCODEMP
              AND K210.BDREFERENCIA = K.BDREFERENCIA
              AND K210.BDORDEMPROD = K.BDORDEMPROD
              AND K210.BDCODPROD = K.BDALTCODPROD
             );

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));


  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*101 - O c?digo SPED do item informado deve ser 00, 01, 02, 03, 04, 05 ou 10*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDEDITCHAVE = K.BDALTCODPROD AND P.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Est? sendo importado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
    UNION
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  JOIN TCADPRO_VINC V ON(V.BDCODEMP = K.BDCODEMP AND V.BDCODPROD = K.BDALTCODPROD AND V.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*J? gravado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0));

  /*102 - Data de fim do servi?o tem que estar dentro da refer?ncia do lan?amento!*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 102 BDCODINCONSISTENCIA, K.BDDATAFIMPROD,
        K.BDREFERENCIA, CAST((SELECT BDAAAAMM FROM AAAAMM(K.BDDATAFIMPROD)) AS INTEGER) BDREFFIM
        FROM TMP_VEF_EMP_TMOVK210_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDDATAFIMPROD IS NOT NULL
       ) MOV
   WHERE MOV.BDREFFIM <> MOV.BDREFERENCIA;

  /*103 - Data de fim do servi?o n?o pode ser menor que a data de in?cio do servi?o!*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 103 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDDATAFIMPROD IS NOT NULL
  AND K.BDDATAFIMPROD < K.BDDATAINIPROD;

  IF ((:PRULTCHAVE IS NOT NULL) AND (:PRULTCHAVE > 0)) THEN
    EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVK210_TEMP');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK215(:PRSESSAO, :PRSESSAOPRO);
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK215) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK215(PRSESSAO INTEGER,
PRSESSAOPRO INTEGER)
 AS
BEGIN
  /*105 - J? existe um lan?amento de mesmo produto para essa chave na ordem */
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDORDEMK215, BDCODINCONSISTENCIA)
  SELECT K215.BDCODEMP, K215.BDSESSAO, K215.BDCHAVE, K215.BDORDEM, 105 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K215
  WHERE K215.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT K.BDCHAVE
              FROM TMP_VEF_EMP_TMOVK215_TEMP K
              WHERE K.BDSESSAO = K215.BDSESSAO
              AND K.BDCODEMP = K215.BDCODEMP
              AND K.BDCHAVE = K215.BDCHAVE
              AND K.BDALTCODPROD = K215.BDALTCODPROD
              AND K.BDORDEM <> K215.BDORDEM
             );

  /*104 - O produto de destino n?o pode ser igual ao produto de origem*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDORDEMK215, BDCODINCONSISTENCIA)
  SELECT K215.BDCODEMP, K215.BDSESSAO, K215.BDCHAVE, K215.BDORDEM, 104 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K215
  JOIN TMP_VEF_EMP_TMOVK210_TEMP K210 ON(K210.BDSESSAO = K215.BDSESSAO AND K210.BDCODEMP = K215.BDCODEMP AND K210.BDCHAVE = K215.BDCHAVE AND K210.BDALTCODPROD = K215.BDALTCODPROD)
  WHERE K215.BDSESSAO = :PRSESSAO;

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDORDEMK215, BDCODINCONSISTENCIA)
  SELECT K215.BDCODEMP, K215.BDSESSAO, K215.BDCHAVE, K215.BDORDEM, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K215
  WHERE K215.BDSESSAO = :PRSESSAO
  AND ((K215.BDALTCODPROD IS NULL) OR (K215.BDALTCODPROD = 0));
  
  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDORDEMK215, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, BDCODINCONSISTENCIA;

  /*101 - O c?digo SPED do item informado deve ser 00, 01, 02, 03, 04, 05 ou 10*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K
  JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDEDITCHAVE = K.BDALTCODPROD AND P.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Est? sendo importado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
    UNION
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K
  JOIN TCADPRO_VINC V ON(V.BDCODEMP = K.BDCODEMP AND V.BDCODPROD = K.BDALTCODPROD AND V.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*J? gravado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0));
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK220) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK220(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRIDTERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO AND ((K.BDCHAVEK220 IS NOT NULL) AND (K.BDCHAVEK220 > 0));

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*22 - Lan?amento j? existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS(
             SELECT K220.BDCHAVE
             FROM VEF_EMP_TMOVESTOQUEK220 K220
             WHERE K220.BDCODEMP = K.BDCODEMP
             AND K220.BDDATAMOV = K.BDDATAMOV
             AND K220.BDCODPRODORI = K.BDALTCODPROD
             AND K220.BDCODPRODDEST = K.BDALTCODPRODDEST
            );

  /*90 - O produto de origem n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 90 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*91 - O produto de destino n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 91 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPRODDEST IS NULL) OR (K.BDALTCODPRODDEST = 0));

  /*76 - Produto inconsistente - Produto de destino*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPRODDEST)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPRODDEST IS NOT NULL) AND (K.BDALTCODPRODDEST > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 88 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDQTDMOV <= 0;

  /*127 - A Quantidade destino deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 127 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDDEST <= 0) AND (K.BDDATAMOV >= '01/01/2018'));

END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK230K250) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK230K250(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRID_TERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO
  AND (((K.BDCHAVEK230 IS NOT NULL) AND (K.BDCHAVEK230 > 0)) OR ((K.BDCHAVEK250 IS NOT NULL) AND (K.BDCHAVEK250 > 0)));

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK230_K250_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /***************************************************K230************************************************************/
  /*22 - Lan?amento j? existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA,
               K.BDALTCODPROD, K.BDORDEMPROD
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 0 /*K230*/
       ) MOV
  WHERE EXISTS(
               SELECT F.BDCHAVE FROM VEF_EMP_TMOVK230_K250 F
               WHERE F.BDCODEMP = MOV.BDCODEMP
               AND F.BDCODPROD = MOV.BDALTCODPROD
               AND F.BDORDEMPROD = MOV.BDORDEMPROD
              );

  /*92 - Data de in?cio da produ??o deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 92 BDCODINCONSISTENCIA,
               K.BDDATAPRODINI
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 0 /*K230*/
       ) MOV
  WHERE MOV.BDDATAPRODINI IS NULL;

  /*93 - Data de in?cio da produ??o deve ser menor ou igual a data de fim da produ??o.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 93 BDCODINCONSISTENCIA,
               K.BDDATAPRODINI, K.BDDATAPRODFIN
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 0 /*K230*/
       ) MOV
  WHERE MOV.BDDATAPRODFIN IS NOT NULL
  AND MOV.BDDATAPRODINI IS NOT NULL
  AND MOV.BDDATAPRODINI > MOV.BDDATAPRODFIN;

  /*94 - A ordem de produ??o deve ter no m?ximo 30 caracteres.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 94 BDCODINCONSISTENCIA,
               COALESCE(CHAR_LENGTH(TRIM(K.BDORDEMPROD)), 0) BDQTDCARAC
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 0 /*K230*/
       ) MOV
  WHERE MOV.BDQTDCARAC > 30;

  /***************************************************K250************************************************************/
  /*22 - Lan?amento j? existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA,
               K.BDALTCODPROD, K.BDDATAPRODINI
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 1 /*K250*/
       ) MOV
  WHERE EXISTS(
               SELECT F.BDCHAVE FROM VEF_EMP_TMOVK230_K250 F
               WHERE F.BDCODEMP = MOV.BDCODEMP
               AND F.BDCODPROD = MOV.BDALTCODPROD
               AND F.BDDATAPRODINI = MOV.BDDATAPRODINI
              );

  /***********************************************K230 E K250*********************************************************/
  /*BDINDUSTRIALIZADOCAO = 0 ent?o ? K230, = 1 ? K250*/

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, IIF(MOV.BDTIPOREG = 0, MOV.BDCHAVE, NULL), IIF(MOV.BDTIPOREG = 1, MOV.BDCHAVE, NULL),
         MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA,
               K.BDALTCODPROD, K.BDINDUSTRIALIZADOCAO BDTIPOREG
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
       ) MOV
  WHERE ((MOV.BDALTCODPROD IS NULL) OR (MOV.BDALTCODPROD = 0));

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, IIF(MOV.BDTIPOREG = 0, MOV.BDCHAVE, NULL), IIF(MOV.BDTIPOREG = 1, MOV.BDCHAVE, NULL),
         MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 88 BDCODINCONSISTENCIA,
               K.BDQTDPROD, K.BDINDUSTRIALIZADOCAO BDTIPOREG
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
       ) MOV
  WHERE ((MOV.BDQTDPROD IS NULL) OR (MOV.BDQTDPROD = 0));

  /*95 - O c?digo de item SPED deve ser 03 ou 04.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, IIF(MOV.BDTIPOREG = 0, MOV.BDCHAVE, NULL), IIF(MOV.BDTIPOREG = 1, MOV.BDCHAVE, NULL),
         MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 95 BDCODINCONSISTENCIA,
               K.BDCODTIPOSER, K.BDINDUSTRIALIZADOCAO BDTIPOREG
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
       ) MOV
  WHERE MOV.BDCODTIPOSER NOT IN(4, 5);

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, IIF(MOV.BDTIPOREG = 0, MOV.BDCHAVE, NULL), IIF(MOV.BDTIPOREG = 1, MOV.BDCHAVE, NULL),
         MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA, K.BDINDUSTRIALIZADOCAO BDTIPOREG
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
        WHERE K.BDSESSAO = :PRSESSAO
        AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
        AND PRO.BDCODINCONSISTENCIA IS NOT NULL
        GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA, BDTIPOREG
       ) MOV;

  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVK230_K250_TEMP');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK235K255(:PRSESSAO, :PRID_TERMINAL);
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK235K255) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK235K255(PRSESSAO INTEGER,
PRID_TERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  /*BDCODREG = 0 - K235
               1 - K255*/
  DELETE FROM VEF_INCON_TMOVBLOCOK I WHERE I.BDSESSAO = :PRSESSAO AND ((I.BDORDEMK235 IS NOT NULL) OR (I.BDORDEMK255 IS NOT NULL));               

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_TCADPRO_INSUMOS_TEMP' INTO :wSessaoPro;

  /*67 - C?digo do produto insumo n?o informado!*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         67 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  /*76 - Produto inconsistente - insumo*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA;

  /*111 - Produto substituto inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         111 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPRODSUB)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPRODSUB IS NOT NULL) AND (K.BDALTCODPRODSUB > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA;

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         88 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDQTDCONSUMIDA <= 0;

  /*96 - O substituto deve constar no cadastro de insumo.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         96 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDCODSAIDASUB IS NOT NULL) AND (K.BDCODSAIDASUB <> ''))
  AND NOT EXISTS(
                 /*Seleciona os insumos que est?o consistentes*/
                 SELECT I.BDCODPROD
                 FROM TMP_TCADPRO_INSUMOS_TEMP I
                 WHERE I.BDSESSAO = :wSessaoPro
                 AND NOT EXISTS(
                                SELECT INCO.BDCODSAIDA
                                FROM VEF_INCON_TCADPRO_INSUMO INCO
                                WHERE INCO.BDSESSAO = I.BDSESSAO
                                AND INCO.BDCODEMP = I.BDCODEMP
                                AND INCO.BDCODSAIDA = I.BDCODSAIDA
                                AND INCO.BDORDEM = INCO.BDORDEM
                               )
                 AND I.BDCODSAIDAPROD = K.BDCODSAIDASUB
                );

  /********************************************************K235********************************************************/
  /*97 - Insumo ou substituto igual ao produto.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         97 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODREG = 0 /*K235*/
  AND ((K.BDCODSAIDA = K.BDCODSAIDAK230K250) OR (K.BDCODSAIDASUB = K.BDCODSAIDAK230K250)) ;

  /*98 - Data de sa?da ? obrigat?ria.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         98 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODREG = 0 /*K235*/
  AND K.BDDATASAIDA IS NULL;

  /********************************************************K255********************************************************/
  /*99 - Insumo n?o pode ser igual ao item produzido.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         99 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODREG = 1 /*K255*/
  AND K.BDCODSAIDA = K.BDCODSAIDAK230K250;
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK260) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK260(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRIDTERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK WHERE BDSESSAO = :PRSESSAO AND BDCHAVEK260 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK260_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*22 - Lan?amento j? existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT FIRST 1 K260.BDCHAVE
              FROM VEF_EMP_TMOVK260 K260
              WHERE K260.BDCODEMP = K.BDCODEMP
              AND K260.BDREFERENCIA = K.BDREFERENCIA
              AND K260.BDORDEMPROD = K.BDORDEMPROD
              AND K260.BDCODPROD = K.BDALTCODPROD
             );

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*98 - Data de sa?da ? obrigat?ria.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 98 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDDATAINIPROD IS NULL;

  /*106 - Data de retorno ao estoque tem que estar dentro da refer?ncia do lan?amento */
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 106 BDCODINCONSISTENCIA, K.BDDATAFIMPROD,
        K.BDREFERENCIA, CAST((SELECT BDAAAAMM FROM AAAAMM(K.BDDATAFIMPROD)) AS INTEGER) BDREFFIM
        FROM TMP_VEF_EMP_TMOVK260_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDDATAFIMPROD IS NOT NULL
       ) MOV
   WHERE MOV.BDREFFIM <> MOV.BDREFERENCIA;

  /*107 - A Ordem de produ??o dever? ser informada caso a data de retorno n?o esteja preenchida*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 107 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDORDEMPROD IS NULL) OR (K.BDORDEMPROD = ''))
  AND K.BDDATAFIMPROD IS NULL;

  /*108 - O campo quantidade de retorno ? obrigat?rio quando o campo data de retorno ao estoque estiver preenchido!*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 108 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDRETORNO IS NULL) OR (K.BDQTDRETORNO = 0))
  AND K.BDDATAFIMPROD IS NOT NULL;
  
  IF (:PRULTCHAVE > 0) THEN
    EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVK260_TEMP');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK265(:PRSESSAO, :wSessaoPro);
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK265) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK265(PRSESSAO INTEGER,
PRSESSAOPRO INTEGER)
 AS
BEGIN
  /*105 - J? existe um lan?amento de mesmo produto para essa chave na ordem */
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 105 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  WHERE K265.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT K.BDCHAVE
              FROM TMP_VEF_EMP_TMOVK265_TEMP K
              WHERE K.BDSESSAO = K265.BDSESSAO
              AND K.BDCODEMP = K265.BDCODEMP
              AND K.BDCHAVE = K265.BDCHAVE
              AND K.BDALTCODPROD = K265.BDALTCODPROD
              AND K.BDORDEM <> K265.BDORDEM
             );

  /*104 - O produto de destino n?o pode ser igual ao produto de origem*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 104 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  JOIN TMP_VEF_EMP_TMOVK260_TEMP K260 ON(K260.BDSESSAO = K265.BDSESSAO AND K260.BDCODEMP = K265.BDCODEMP AND K260.BDCHAVE = K265.BDCHAVE AND K260.BDALTCODPROD = K265.BDALTCODPROD)
  WHERE K265.BDSESSAO = :PRSESSAO;

  /*109 - ? preciso preencher pelo menos um dos campos de quantidade.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 109 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  WHERE K265.BDSESSAO = :PRSESSAO
  AND ((K265.BDQTDCONSUMIDA IS NULL) OR (K265.BDQTDCONSUMIDA = 0))
  AND ((K265.BDQTDRETORNADA IS NULL) OR (K265.BDQTDRETORNADA = 0));

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  WHERE K265.BDSESSAO = :PRSESSAO
  AND ((K265.BDALTCODPROD IS NULL) OR (K265.BDALTCODPROD = 0));

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K265.BDCODEMP AND PRO.BDCODPROD = K265.BDALTCODPROD)
  WHERE K265.BDSESSAO = :PRSESSAO
  AND ((K265.BDALTCODPROD IS NOT NULL) AND (K265.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, BDCODINCONSISTENCIA;

END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK270) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK270(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRIDTERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO AND K.BDCHAVEK270 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK270_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*110 - A origem deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 110 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDCODIGO = 0) OR (K.BDCODIGO IS NULL));

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*112 - Data de fim da produ??o tem que ser menor que a refer?ncia do lan?amento.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 112 BDCODINCONSISTENCIA,
               (SELECT A.BDAAAAMM FROM AAAAMM(K.BDDATAFIMPROD) A) BDREFFIM,
               K.BDREFERENCIA
        FROM TMP_VEF_EMP_TMOVK270_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDDATAFIMPROD IS NOT NULL
       ) K
  WHERE K.BDREFFIM >= K.BDREFERENCIA;

  /*113 - Data de in?cio da produ??o tem que ser menor que a refer?ncia do lan?amento.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 113 BDCODINCONSISTENCIA,
               (SELECT A.BDAAAAMM FROM AAAAMM(K.BDDATAINIPROD) A) BDREFFIM,
               K.BDREFERENCIA
        FROM TMP_VEF_EMP_TMOVK270_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDDATAINIPROD IS NOT NULL
       ) K
  WHERE K.BDREFFIM >= K.BDREFERENCIA;

  /*114 - Somente um dos campos de quantidade dever? ser preenchido.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 114 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDPOSITIVA IS NOT NULL) AND (K.BDQTDPOSITIVA > 0))
  AND ((K.BDQTDNEGATIVA IS NOT NULL) AND (K.BDQTDNEGATIVA > 0));

  /*115 - ? preciso preencher um dos campos de quantidade.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 115 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDPOSITIVA IS NULL) OR (K.BDQTDPOSITIVA = 0))
  AND ((K.BDQTDNEGATIVA IS NULL) OR (K.BDQTDNEGATIVA = 0));

  /*22 - Lan?amento j? existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT FIRST 1 K270.BDCHAVE
              FROM VEF_EMP_TMOVK270 K270
              WHERE K270.BDCODEMP = K.BDCODEMP
              AND K270.BDREFERENCIA = K.BDREFERENCIA
              AND K270.BDORDEMPROD = K.BDORDEMPROD
              AND K270.BDCODPROD = K.BDALTCODPROD
              AND K270.BDCODIGO = K.BDCODIGO
             );
             
  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVK270_TEMP');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK275(:PRSESSAO, :wSessaoPro);             
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK275) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK275(PRSESSAO INTEGER,
PRSESSAOPRO INTEGER)
 AS
BEGIN
/*114 - Somente um dos campos de quantidade dever? ser preenchido.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 114 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDPOSITIVAK275 IS NOT NULL) AND (K.BDQTDPOSITIVAK275 > 0))
  AND ((K.BDQTDNEGATIVAK275 IS NOT NULL) AND (K.BDQTDNEGATIVAK275 > 0));

  /*115 - ? preciso preencher um dos campos de quantidade.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 115 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDPOSITIVAK275 IS NULL) OR (K.BDQTDPOSITIVAK275 = 0))
  AND ((K.BDQTDNEGATIVAK275 IS NULL) OR (K.BDQTDNEGATIVAK275 = 0));

  /*22 - Lan?amento j? existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT FIRST 1 K275.BDCHAVE
              FROM VEF_EMP_TMOVK275 K275
              WHERE K275.BDCODEMP = K.BDCODEMP
              AND K275.BDCHAVE = K.BDEDITCHAVE
              AND K275.BDCODPRODITEM = K.BDALTCODPROD
             );

  /*101 - O c?digo SPED do item informado deve ser 00, 01, 02, 03, 04, 05 ou 10.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDEDITCHAVE = K.BDALTCODPROD AND P.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Est? sendo importado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
    UNION
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  JOIN TCADPRO_VINC V ON(V.BDCODEMP = K.BDCODEMP AND V.BDCODPROD = K.BDALTCODPROD AND V.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*J? gravado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0));

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, BDCODINCONSISTENCIA;

  /*111 - Produto substituto inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 111 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPRODSUB)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPRODSUB IS NOT NULL) AND (K.BDALTCODPRODSUB > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, BDCODINCONSISTENCIA;
END
^

/* Alter (SP_ATUALIZAR_TMP_BLOCOK280) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK280(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRID_TERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO AND K.BDCHAVEK280 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK280_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*117 - Data de estoque final ? de preenchimento obrigat?rio.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 117 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDDATAESTOQUE IS NULL;

  /*114 - Somente um dos campos de quantidade dever? ser preenchido.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 114 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDCORPOS IS NOT NULL) AND (K.BDQTDCORPOS > 0))
  AND ((K.BDQTDCORNEG IS NOT NULL) AND (K.BDQTDCORNEG > 0));

  /*115 - ? preciso preencher um dos campos de quantidade.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 115 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDCORPOS IS NULL) OR (K.BDQTDCORPOS = 0))
  AND ((K.BDQTDCORNEG IS NULL) OR (K.BDQTDCORNEG = 0));

  /*116 - Participante ? de preenchimento obrigat?rio para indicador de posse igual a 1 ou 2.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 116 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODPOSSE IN (2, 3)
  AND ((K.BDALTCODTER IS NULL) OR (K.BDALTCODTER = 0));

  /*22 - Lan?amento j? existente na base de dados - Sem participante*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDALTCODTER IS NULL
  AND EXISTS (
              SELECT FIRST 1 K280.BDCHAVE
              FROM VEF_EMP_TMOVK280 K280
              WHERE K280.BDCODEMP = K.BDCODEMP
              AND K280.BDREFERENCIA = K.BDREFERENCIA
              AND K280.BDCODPOSSE = K.BDCODPOSSE
              AND K280.BDCODPROD = K.BDALTCODPROD
             );

  /*22 - Lan?amento j? existente na base de dados - Com participante*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODTER IS NOT NULL) AND (K.BDALTCODTER > 0))
  AND EXISTS (
              SELECT FIRST 1 K280.BDCHAVE
              FROM VEF_EMP_TMOVK280 K280
              WHERE K280.BDCODEMP   = K.BDCODEMP
              AND K280.BDREFERENCIA = K.BDREFERENCIA
              AND K280.BDCODPOSSE   = K.BDCODPOSSE
              AND K280.BDCODPROD    = K.BDALTCODPROD
              AND K280.BDCODTER     = K.BDALTCODTER
             );

  /*87 - Produto n?o informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*74 - Participante inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 74 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  JOIN TMP_TTERCEIRO T ON(T.BDEDITCHAVE = K.BDALTCODTER AND T.BDINCONSISTENTE IS NOT NULL AND T.BDINCONSISTENTE NOT IN(0, 2))
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODTER IS NOT NULL) AND (K.BDALTCODTER > 0))
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;
END
^

/* Alter (SP_ATUALIZAR_TMP_INSUMO_TEMP) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_INSUMO_TEMP(PRSESSAO INTEGER,
PRATUALIZARDADOS DM_BOOLEAN,
PRGERARINCONSISTENCIAS DM_BOOLEAN)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WCODSAIDA VARCHAR(60);
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WQTDCONSUMO NUMERIC(17,6);
DECLARE VARIABLE WPERDA DM_NUMERIC_7_4_ALIQ;
BEGIN
  PRATUALIZARDADOS      = UPPER(:PRATUALIZARDADOS);
  PRGERARINCONSISTENCIAS= UPPER(:PRGERARINCONSISTENCIAS);

  IF (:PRATUALIZARDADOS = 'FALSE') THEN
    BEGIN
      /*Se n?o ? pra atualizar, joga os dados da tabela TCADPRO_INSUMOS pra tabela TEMP, assim quando ficar o insert or update n?o vai alterar o registros da tabela de insumos*/
      FOR SELECT IT.BDCODEMP, IT.BDCODSAIDA, IT.BDORDEM,
                 CI.BDCODPROINSUMO, CI.BDQTDCONSUMO, CI.BDPERDA
          FROM TMP_TCADPRO_INSUMOS_TEMP IT
          LEFT OUTER JOIN TCADPRO_VINC P ON(P.BDCODEMP = IT.BDCODEMP AND P.BDCODPROD = IT.BDCODPROD)
          JOIN TCADPRO_INSUMOS CI ON(CI.BDCODEMP = IT.BDCODEMP AND CI.BDCODPROD = IT.BDCODPROD AND CI.BDREFERENCIA = IT.BDREFERENCIA AND CI.BDQTDCONSUMO = IT.BDQTDCONSUMO AND CI.BDPERDA = IT.BDPERDA)
          WHERE IT.BDSESSAO = :PRSESSAO
          AND IT.BDCODSAIDAPROD = P.BDCODSAIDA
          INTO :WCODEMP, :WCODSAIDA, :WORDEM, :WCODPROD,
               :WQTDCONSUMO, :WPERDA
      DO
        BEGIN
          IF ((:WCODPROD IS NOT NULL) OR (:WCODPROD > 0)) THEN
            BEGIN
              UPDATE TMP_TCADPRO_INSUMOS_TEMP IT SET IT.BDCODPROINSUMO = :WCODPROD, IT.BDQTDCONSUMO = :WQTDCONSUMO, IT.BDPERDA = :WPERDA
              WHERE IT.BDSESSAO    = :PRSESSAO
              AND IT.BDCODEMP      = :WCODEMP
              AND IT.BDCODSAIDAPROD= :WCODSAIDA
              AND IT.BDORDEM       = :WORDEM;
            END
        END
    END

  IF (:PRGERARINCONSISTENCIAS = 'TRUE') THEN
    BEGIN
      DELETE FROM VEF_INCON_TCADPRO_INSUMO D WHERE D.BDSESSAO = :PRSESSAO;

      /*70 - Produto do insumo inconsistente.*/
      /*Quando o produto ? inconsistente torna o insumo inconsistente*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 70 BDCODINCONSISTENCIA, IT.BDSESSAO, IT.BDCODSAIDA, IT.BDCODEMP, IT.BDORDEM, IT.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP IT
      JOIN VEF_INCON_TCADPRO IP ON(IP.BDSESSAO = IT.BDSESSAO AND IP.BDCODPROD = IT.BDCODPROD)
      WHERE IT.BDSESSAO = :PRSESSAO;

      /*67 - C?digo do produto insumo n?o informado!*/
      /*N?o existe produto no insumo, ? obrigat?rio*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 67 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND ((I.BDCODSAIDAPROD IS NULL) OR (I.BDCODSAIDAPROD = ''));

      /*68 - Produto do insumo deve ter o tipo item como 00, 01, 02, 03, 04, 05 ou 10.*/
      /*O produto do insumo tem que ter o tipo item como 00, 01, 02, 03, 04, 05 ou 10*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 68 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDTIPOITEM NOT IN (1, 2, 3, 4, 5, 6, 11);

      /*69 - A quantidade de consumo n?o foi informada*/
      /*O insumo tem que ter quantidade de consumo, ? obrigat?rio*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 69 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND ((I.BDQTDCONSUMO IS NULL) OR (I.BDQTDCONSUMO <= 0));

      /*71 - Insumo inconsistente.*/
      /*Se o produto do insumo ? inconsistente o insumo e o produto tambem devem ser.*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 71 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      JOIN VEF_INCON_TCADPRO IC ON(IC.BDSESSAO = I.BDSESSAO AND IC.BDCODPROD = I.BDCODPROINSUMO)
      WHERE I.BDSESSAO = :PRSESSAO;

      /*72 - Produto inconsistente devido ao insumo ser inconsistente.*/
      /*Se o insumo ? inconsistente, torna o produto inconsistente*/
      FOR SELECT P.BDEDITCHAVE BDCODPROD, IP.BDCODEMP FROM VEF_INCON_TCADPRO_INSUMO IP
          JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = IP.BDSESSAO AND P.BDCODSAIDA = IP.BDCODSAIDA)
          WHERE IP.BDSESSAO = :PRSESSAO
          INTO :WCODPROD, :wCodEmp
      DO
        BEGIN
          INSERT INTO VEF_INCON_TCADPRO (BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP) VALUES (72, :PRSESSAO, :WCODPROD, :WCODEMP);
        END

    END
END
^

/* Alter (SP_ATUALIZAR_TMP_ITEMDOCECF) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_ITEMDOCECF(PRSESSAO INTEGER,
PRSESSAOPRODUTO INTEGER,
PRCODEMP INTEGER)
 AS
BEGIN
  /*Limpando as inconsistencias*/
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET I.BDINCONSISTENTE = NULL WHERE I.BDSESSAO = :PRSESSAO;

  /*Produtos inconsistentes torna o item em inconsistente*/
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET BDINCONSISTENTE = 1
  WHERE I.BDSESSAO = :PRSESSAO
  AND EXISTS(
             SELECT P.BDCODINCONSISTENCIA
             FROM VEF_INCON_TCADPRO P
             WHERE P.BDSESSAO = :PRSESSAOPRODUTO
             AND P.BDCODPROD = I.BDCODPROD
            );

  /*Itens sem produto (N?o conseguiu encontrar o produto)*/
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET I.BDINCONSISTENTE = 1
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDCODPROD = 0) OR (I.BDCODPROD IS NULL));

  /*Cadastro do produto n?o existe na empresa
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET I.BDINCONSISTENTE = 1
  WHERE I.BDSESSAO = :PRSESSAO
  AND I.BDCODPROD NOT IN (
                          SELECT P.BDCODPROD
                          FROM TMP_TCADPRO P
                          LEFT OUTER JOIN TMP_TCADPRO_TEMP PRO ON(P.BDCODEMP = PRO.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD AND PRO.BDSESSAO = :PRSESSAOPRODUTO)
                          WHERE P.BDCODEMP = :PRCODEMP
                          AND (PRO.BDSITUACAO > 0)
                         );*/

  /*Produto est? como n?o relacionado, deixa o lan?amento inconsistente*/
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET I.BDINCONSISTENTE = 1
  WHERE I.BDSESSAO = :PRSESSAO
  AND I.BDCODPROD = (
                     SELECT FIRST 1 P.BDCODPROD
                     FROM TMP_TCADPRO_TEMP P
                     WHERE P.BDSESSAO = :PRSESSAOPRODUTO
                     AND P.bdeditchave = I.BDCODPROD
                     AND ((P.BDSITUACAO IS NULL) OR (P.BDSITUACAO = 0))
                    );
END
^

/* empty dependent procedure body */
/* Clear: SP_ATUALIZAR_TMP_TMOVSAIITENS for: SP_ATUALIZAR_TMP_MOVPROSAI_TEMP */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TMOVSAIITENS(PRCODPLANOONLINE INTEGER,
PRSESSAO INTEGER,
PRCODPLANOINCON INTEGER,
PRUFEMP VARCHAR(2),
PRVALIDARCSTMOVPRO VARCHAR(5),
PRSESSAOPRO INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_ATUALIZAR_TMP_MOVPROSAI_TEMP) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_MOVPROSAI_TEMP(PRSESSAO INTEGER,
PRCODPLANOINCO INTEGER,
PRVALIDARCST VARCHAR(5),
PRSESSAOPRO INTEGER)
 AS
DECLARE VARIABLE WCADPROAUTO VARCHAR(5);
BEGIN
  DELETE FROM VEF_INCON_TMOVSAI INCO
  WHERE INCO.BDSESSAO = :PRSESSAO
  AND INCO.BDCODEMP   IS NOT NULL
  AND INCO.BDCHAVE    IS NOT NULL
  AND INCO.BDORDEM    IS NOT NULL
  AND INCO.BDORDEMPRO IS NOT NULL;

  SELECT UPPER(I.BDCADPROAUTO) FROM VEF_BASE_TACOESINCONS I
  WHERE I.BDCODPLANOINCONS = :PRCODPLANOINCO INTO :wCadProAuto;

  IF (:wCadProAuto = 'TRUE') THEN
    BEGIN
      UPDATE TMP_TCADPRO_TEMP P
      SET P.BDCODCSTIPISAI = (SELECT FIRST 1 M.BDCODCSTIPI  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDCODCSTPISSAI = (SELECT FIRST 1 M.BDCODCSTPIS  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDCODCSTCOFSAI = (SELECT FIRST 1 M.BDCODCSTCOF  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDCODCSTICMS   = (SELECT FIRST 1 M.BDCODCSTICMS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDCODCSTIPIENT = (SELECT FIRST 1 M.BDCODCSTIPI  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDCODCSTPISENT = (SELECT FIRST 1 M.BDCODCSTPIS  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDCODCSTCOFENT = (SELECT FIRST 1 M.BDCODCSTCOF  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDALIQICMS     = (SELECT FIRST 1 M.BDALIQICMS   FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDALIQPIS      = (SELECT FIRST 1 M.BDALIQPIS    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDALIQCOF      = (SELECT FIRST 1 M.BDALIQCOFINS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDALIQPISENT   = (SELECT FIRST 1 M.BDALIQPIS    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDALIQCOFENT   = (SELECT FIRST 1 M.BDALIQCOFINS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDALIQIPI      = (SELECT FIRST 1 M.BDALIQIPI    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
          P.BDALIQICMSST   = (SELECT FIRST 1 M.BDALIQST     FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC)
      WHERE P.BDSESSAO = :PRSESSAOPRO;
  
      EXECUTE PROCEDURE SP_ATUALIZAR_CST_PROD(:PRSESSAOPRO);
    END

  IF (:wCadProAuto <> 'TRUE') THEN
    BEGIN
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro)
      SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDSESSAO, 66 BDCODINCONSISTENCIA, P.BDORDEMPRO
      FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
      LEFT OUTER JOIN TMP_TCADPRO_TEMP CP ON(CP.BDSESSAO = :PRSESSAOPRO AND CP.BDEDITCHAVE = P.BDALTCODPROD)
       WHERE P.BDSESSAO = :PRSESSAO
      AND (CP.BDSITUACAO = 0); /*Produto n?o cadastrado e o usu?rio n?o optou por cadastrar.*/
    END

  /*Inconsistencia do valor de desconto maior do que o valor do item*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro)
  SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDSESSAO, 34 BDCODINCONSISTENCIA, P.BDORDEMPRO
  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND BDVLRDESC > BDVLRITEM;

  PRVALIDARCST = COALESCE(UPPER(:PRVALIDARCST), 'FALSE');

  IF (:PRVALIDARCST = 'TRUE') THEN
    BEGIN
      /*35 - PIS*/
      INSERT INTO VEF_INCON_TMOVSAI(bdsessao, bdcodemp, bdchave, bdordem, bdordempro, bdcodinconsistencia)
      SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDORDEMPRO, 35 BDCODINCONSISTENCIA
      FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = P.BDCODCSTPIS)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDVLRPIS > 0
      AND ((P.BDCODCSTPIS IS NULL) OR (PIS.BDCODCSTPIS IS NULL));

      /*36 - Cofins*/
      INSERT INTO VEF_INCON_TMOVSAI(bdsessao, bdcodemp, bdchave, bdordem, bdordempro, bdcodinconsistencia)
      SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDORDEMPRO, 36 BDCODINCONSISTENCIA
      FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = P.BDCODCSTCOF)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDVLRCOFINS > 0
      AND ((P.BDCODCSTCOF IS NULL) OR (COF.BDCODCSTCOF IS NULL));

      /*37 - IPI*/
      INSERT INTO VEF_INCON_TMOVSAI(bdsessao, bdcodemp, bdchave, bdordem, bdordempro, bdcodinconsistencia)
      SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDORDEMPRO, 37 BDCODINCONSISTENCIA
      FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
      LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = P.BDCODCSTIPI)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDVLRIPI > 0
      AND ((P.BDCODCSTIPI IS NULL) OR (IPI.BDCODCSTIPI IS NULL));
    END

  /*Se a situa??o do produto estiver como 0 - N?o relacionado ele n?o ir? ser importado e tudo que tiver produto deve se tornar inconsistente*/
  --73 - Produto n?o cadastrado.
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDSESSAO, 73 BDCODINCONSISTENCIA, S.BDORDEMPRO
  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP S
  JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDCODPROD = S.BDCODPROD AND COALESCE(P.BDSITUACAO, 0) = 0)
  WHERE S.BDSESSAO = :PRSESSAO;

  /*Se o produto for inconsistente, torna o lan?amento inconsistente tambem*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDSESSAO, 76 BDCODINCONSISTENCIA, S.BDORDEMPRO
  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP S
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = S.BDCODEMP AND PRO.BDCODPROD = S.BDALTCODPROD)
  WHERE S.BDSESSAO = :PRSESSAO
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDSESSAO, BDCODINCONSISTENCIA, S.BDORDEMPRO;

END
^

/* Alter (SP_ATUALIZAR_TMP_TAJUICMSE115) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TAJUICMSE115(PRSESSAO INTEGER,
PRULTCHAVE INTEGER)
 AS
BEGIN
  -- Atualiza o EDITCHAVE para a chave real que vai usar no lan?amento,
  -- vai pegar a ?ltima chave cedida pelo servidor e decrementar do sequ?ncial gerado ao inserir os dados na tabela tempor?ria...
  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TAJUICMSE115_TEMP E
    SET E.BDEDITCHAVE = :PRULTCHAVE - E.BDEDITCHAVE + 1
    WHERE E.BDSESSAO  = :PRSESSAO;
END
^

/* Alter (SP_ATUALIZAR_TMP_TCADPRO) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TCADPRO(PRSESSAO INTEGER NOT NULL,
PRLANCAMENTOMANUAL DM_BOOLEAN NOT NULL,
PRGERARINCONSISTENCIAS DM_BOOLEAN NOT NULL,
PRREF INTEGER,
PRCODEMP INTEGER,
PRIDTERMINAL INTEGER,
PRALTERARSIT DM_BOOLEAN)
 AS
DECLARE VARIABLE WCODORIGEMPROD INTEGER;
DECLARE VARIABLE WCNPJTERLAYOUT VARCHAR(18);
DECLARE VARIABLE WCODTERENCONTRADO INTEGER;
DECLARE VARIABLE WCODENTRADA VARCHAR(60);
DECLARE VARIABLE WCODSAIDA VARCHAR(60);
DECLARE VARIABLE WDESCPRO VARCHAR(200);
DECLARE VARIABLE WCODPROENCONTRADO INTEGER;
DECLARE VARIABLE WEANPROUNICO VARCHAR(20);
DECLARE VARIABLE WDESCPROUNICO VARCHAR(200);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPROVINC INTEGER;
DECLARE VARIABLE WATUPROD DM_BOOLEAN;
DECLARE VARIABLE WCADAUT DM_BOOLEAN;
DECLARE VARIABLE WCODPLANOINCO INTEGER;
DECLARE VARIABLE WCODTIPO INTEGER;
DECLARE VARIABLE WCODATVMUN VARCHAR(20);
DECLARE VARIABLE WCODCIDEMP INTEGER;
DECLARE VARIABLE WCODSAIDAEXISTENTE VARCHAR(60);
DECLARE VARIABLE WCODPERSONALIZACAO INTEGER;
DECLARE VARIABLE WSEQ_PART          INTEGER;
BEGIN
  PRLANCAMENTOMANUAL     = UPPER(:PRLANCAMENTOMANUAL);
  PRGERARINCONSISTENCIAS = UPPER(:PRGERARINCONSISTENCIAS);
  PRALTERARSIT           = UPPER(:PRALTERARSIT);

  SELECT FIRST 1 P.BDCODIGO FROM TPERSONALIZACAO P INTO :wCodPersonalizacao;

  /*Se n?o houver produto na TMP_TCADPRO e/ou TMP_TCADPRO_PART, vai inserir os dados.*/
  --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
  EXECUTE PROCEDURE SP_CARREGAR_TMP_TCADPRO('FALSE');

--  UPDATE TMP_TCADPRO SET BDSEQ_PART = NULL WHERE BDSEQ_PART >= 0/*IS NOT NULL*/;
--  UPDATE TMP_TCADPRO_PART SET BDSEQ_PART = NULL WHERE BDSEQ_PART >= 0/*IS NOT NULL*/;
  UPDATE TMP_TCADPRO SET BDSEQ_PART = NULL WHERE BDSEQ_PART IS NOT NULL;
  UPDATE TMP_TCADPRO_PART SET BDSEQ_PART = NULL WHERE BDSEQ_PART IS NOT NULL;

  IF (:PRLANCAMENTOMANUAL = 'TRUE') THEN
    BEGIN
      wCodProEncontrado = NULL;
      SELECT FIRST 1 V.BDEDITCHAVE, V.BDCODENTRADA, V.BDCNPJTERLAYOUT, V.BDDESCPROD, V.BDORIGEMPROD, V.BDCODTER FROM TMP_TCADPRO_A_VALIDAR V
      INTO :wCodProEncontrado, :wCodEntrada, :wCnpjTerLayout, :wDescPro, :wCodOrigemProd, :wCodTerEncontrado;
      IF ((:wCodProEncontrado IS NOT NULL) AND (:wCodProEncontrado > 0)) THEN
        EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, '', :wCodEntrada, :wCodProEncontrado, COALESCE(:PRCODEMP, 0), :wCodTerEncontrado, :wCnpjTerLayout, :wDescPro, :wCodOrigemProd,  'INUP', 1, 'TRUE');
        
      DELETE FROM TMP_TCADPRO_TEMP WHERE BDSESSAO = 0;        
      EXIT;
    END

  SELECT SP.BDCODPLANOINCONS, SP.BDATUPROD, SP.BDCADPROAUTO
  FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :PRREF) SP
  INTO :wCodPlanoInco, :wAtuProd, :wCadAut;

  SELECT FIRST 1 SP.BDCODCID FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :wCodCidEmp;

  IF (:PRGERARINCONSISTENCIAS = 'TRUE') THEN
    BEGIN
      EXECUTE PROCEDURE SP_GERAR_INCON_TCADPRO(:PRSESSAO, :PRCODEMP, :wCodPlanoInco, :PRREF, :PRIDTERMINAL);

      /*Apaga os registros inconsistentes da TMP
      DELETE FROM TMP_TCADPRO T
      WHERE T.BDSESSAO = :PRSESSAO
      AND EXISTS(
                 SELECT C.BDCODPROD
                 FROM VEF_INCON_TCADPRO C
                 WHERE C.BDSESSAO = T.BDSESSAO
                 AND C.BDCODPROD = T.BDEDITCHAVE
                );*/
    END

  wSeq_Part = 0;
  FOR SELECT COALESCE(V.BDORIGEMPROD, 0),
             COALESCE(V.BDCNPJTERLAYOUT, ''),
             COALESCE(V.BDCODENTRADA, ''),
             COALESCE(V.BDCODSAIDA, ''),
             COALESCE(TRIM(V.BDDESCPROD), ''),
             COALESCE(V.BDCODIGOEAN, ''),
             COALESCE(TRIM(V.BDDESCRICAOUNICA), ''),
             COALESCE(V.BDCODEMP, 0),
             COALESCE(V.BDCODTIPO, 0),
             COALESCE(V.BDCODMUNATVM, '')

      FROM TMP_TCADPRO_A_VALIDAR V
      /*Se j? tem BDEDITCHAVE n?o precisa procurar, o produto j? foi vinculado(se existe) e se n?o existe j? foi gerada uma nova chave*/
      WHERE ((V.BDEDITCHAVE IS NULL) OR (V.BDEDITCHAVE = 0))
      ORDER BY V.BDISPRODUNICO DESC
      INTO :WCODORIGEMPROD,
           :WCNPJTERLAYOUT,
           :WCODENTRADA,
           :WCODSAIDA,
           :WDESCPRO,
           :WEANPROUNICO,
           :WDESCPROUNICO,
           :WCODEMP,
           :wCodTipo,
           :wCodAtvMun
  DO
  BEGIN
    wSeq_Part = :wSeq_Part + 1;

    wCodProVinc = NULL;
    wCodProEncontrado = NULL;

    /* ********************************************************** V?NCULO ********************************************************** */

    /* SERVI?O */
    IF (:wCodTipo IN (118, 119, 120, 121, 122)) THEN
      BEGIN
        SELECT FIRST 1 P.BDCODPROD
        FROM TMP_TCADPRO P
        WHERE P.BDCODSER = (
                            SELECT T.BDCODSER
                            FROM TATVMUNICIPAL T
                            WHERE T.BDCODCID = :wCodCidEmp
                            AND T.BDCODMUNATVM = :wCodAtvMun
                            AND T.BDREFATVM = (SELECT MAX(A.BDREFATVM) FROM TATVMUNICIPAL A WHERE A.BDCODCID = T.BDCODCID AND A.BDCODMUNATVM = T.BDCODMUNATVM)
                           )
        INTO :wCodProEncontrado;
      END

    /* ENTRADA */
    IF (:WCODORIGEMPROD = 0) THEN
      BEGIN
        IF ((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) THEN
          BEGIN
            wCodTerEncontrado = NULL;
            -- TENTA ENCONTRAR O PARTICIPANTE PRIMEIRO
            SELECT FIRST 1 T.BDEDITCHAVE FROM TMP_TTERCEIRO T
            WHERE /*(T.bdcodter = :wCODTERLAYOUT) OR*/ (T.bdcgcter = :WCNPJTERLAYOUT)
            INTO :WCODTERENCONTRADO;

            -- TENDO O C?DIGO DO PARTICIPANTE, PODE TENTAR ENCONTRAR V?NCULO NA TMP_TCADPRO_PART
            IF (:WCODTERENCONTRADO IS NOT NULL) THEN
              BEGIN
                -- PODE TENTAR ENCONTRAR POR C?DIGO DE TERCEIRO, C?DIGO DE ENTRADA E DESCRI??O DO PRODUTO
                IF ((:wDescPro <> '') AND (:wDescPro <> '#')) THEN
                  BEGIN
                    SELECT FIRST 1 P.BDCODPROD
                    FROM TMP_TCADPRO_PART P
                    WHERE P.BDCODTER        = :WCODTERENCONTRADO
                    AND   P.bdcodentrada    = :wCodEntrada
                    AND   P.bddescprodbusca = :wdescpro
                    ORDER BY P.BDCODPROD
                    INTO :wCodProEncontrado;
                  END

                -- E SE N?O CONSEGUIR, PODE TENTAR POR C?DIGO DE TERCEIRO, C?DIGO DE ENTRADA E EAN DO PRODUTO DA TMP_TCADPRO
                IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND (:wEanProUnico <> '') AND (:wEanProUnico <> '#')) THEN
                  BEGIN
                    SELECT FIRST 1 PP.BDCODPROD
                    FROM TMP_TCADPRO_PART PP
                    INNER JOIN TMP_TCADPRO P ON(P.BDCODPROD = PP.BDCODPROD)
                    WHERE PP.bdcodter = :wCodTerEncontrado
                    AND PP.bdcodentrada = :wCodEntrada
                    AND P.BDCODIGOEAN = :wEanProUnico
                    ORDER BY P.BDCODPROD
                    INTO :wCodProEncontrado;
                  END
              END
          END

        -- SE N?O ENCONTROU AT? AGORA, PODE TENTAR ENCONTRAR POR EAN E DESCRI??O
        IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND ((:wEanProUnico <> '') AND (:wEanProUnico <> '#')) AND ((:wDescProUnico <> '') AND (:wDescProUnico <> '#'))) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.bddescricaounica = :wdescprounico
            AND P.BDCODIGOEAN = :wEanProUnico
            AND P.BDCODEMP IS NULL
            INTO :wCodProEncontrado;
          END

        -- AINDA PODE TENTAR ENCONTRAR POR C?DIGO DE EMPRESA E DESCRI??O
        IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND ((:wDescPro <> '') AND (:wDescPro <> '#'))) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDDESCPROD = :wDescPro
            AND ((P.BDCODEMP = :wCodEmp) OR (P.BDCODEMP IS NULL))
            ORDER BY P.BDCODEMP DESC
            INTO :wCodProEncontrado;
          END
          
        -- POR FIM, AINDA PODE TENTAR ENCONTRAR POR DESCRI??O ?NICA
        IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND ((:wDescProUnico <> '') AND (:wDescProUnico <> '#'))) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDDESCRICAOUNICA = :wDescProUnico
            AND ((P.BDCODEMP IS NULL) OR (P.BDCODEMP = 0))
            INTO :wCodProEncontrado;
          END          
      END
    ELSE
      /* SA?DA */
      BEGIN
        -- PODE TENTAR ENCONTRAR DIRETO POR C?DIGO SA?DA e EMPRESA
        IF ((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDCODSAIDA = :wCodSaida
            AND P.BDCODEMP = :wCodEmp
            INTO :wCodProEncontrado;
          END

        -- SE N?O CONSEGUIR, TENTA POR EAN E DESCRI??O
        IF (((:wcodproencontrado IS NULL) OR (:wcodproencontrado = 0)) AND ((:wEanProUnico <> '') AND (:wEanProUnico <> '#')) AND ((:wDescProUnico <> '') AND (:wDescProUnico <> '#'))) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDCODIGOEAN = :wEanProUnico
            AND P.bddescricaounica = :wDescProUnico
            AND ((P.BDCODEMP = :wCodEmp) OR (P.BDCODEMP IS NULL))
            INTO :wCodProEncontrado;
          END

        -- E SE AINDA N?O CONSEGUIR, PODE TENTAR POR DESCRI??O E C?DIGO
        IF (((:wcodproencontrado IS NULL) OR (:wcodproencontrado = 0)) AND ((:wDescPro <> '') AND (:wDescPro <> '#'))) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDDESCPROD = :wDescPro
            AND P.BDCODSAIDA = :wCodSaida
            AND ((P.BDCODEMP = :wCodEmp) OR (P.BDCODEMP IS NULL))
            INTO :wCodProEncontrado;
          END

        -- E POR FIM TENTA BUSCAR UNICAMENTE POR DESCRICAO NO CADASTRO UNICO
        IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND ((:wDescProUnico <> '') AND (:wDescProUnico <> '#'))) THEN
          BEGIN
            /*
              Exemplo: C?d. Sa?da  Descri??o
                       2020270537  ARAME GALVANIZADO N. <- S? vai vincular nesse primeiro, os outros ser?o produtos novos.
                       2020270883  ARAME GALVANIZADO N.
                       2020270853  ARAME GALVANIZADO N.
                       1750010010  ARAME GALVANIZADO N.
            */
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            JOIN TMP_TCADPRO_TEMP T ON(T.BDSESSAO = :PRSESSAO AND T.BDCODSAIDA = :wCodSaida AND UPPER(T.BDISPRODUNICO) = 'TRUE')
            LEFT OUTER JOIN TCADPRO_VINC V ON(V.BDCODEMP = :PRCODEMP AND V.BDCODPROD = P.BDEDITCHAVE)
            WHERE P.BDDESCRICAOUNICA = :wDescProUnico
            AND T.BDCODPROD IS NULL
            AND V.BDCODPROD IS NULL
            INTO :wCodProEncontrado;

            IF ((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) THEN
              BEGIN
                SELECT FIRST 1 P.BDCODPROD
                FROM TMP_TCADPRO P
                /*Se j? tiver vinculado algum produto pela descri??o, os outros s?o diferentes, para n?o vincular tudo no mesmo*/
                LEFT OUTER JOIN TMP_TCADPRO_TEMP T ON(T.BDSESSAO = :PRSESSAO AND T.BDEDITCHAVE = P.BDEDITCHAVE)
                LEFT OUTER JOIN TCADPRO_VINC V ON(V.BDCODEMP = :PRCODEMP AND V.BDCODPROD = P.BDEDITCHAVE)
                WHERE P.BDDESCRICAOUNICA = :wDescProUnico
                AND T.BDSESSAO IS NULL
                AND V.BDCODPROD IS NULL
                INTO :wCodProEncontrado;
              END
          END
      END
    /* ***************************************************************************************************************************** */

    IF ((:wCodPersonalizacao = 9615) AND (:wCodOrigemProd = 0)) THEN /*SOMENTE PARA O 9615 - VANCREIACESSORIA 16836999*/
      BEGIN
        DELETE FROM TCADPRO_PART PP
        WHERE PP.BDCODPROD <> :wCodProEncontrado
        AND PP.BDCODTER = :wCodTerEncontrado
        AND PP.BDCODENTRADA = :wCodEntrada
        AND PP.BDDESCPRODBUSCA = :wDescPro;

        DELETE FROM TMP_TCADPRO_PART PP
        WHERE PP.BDCODPROD <> :wCodProEncontrado
        AND PP.BDCODTER = :wCodTerEncontrado
        AND PP.BDCODENTRADA = :wCodEntrada
        AND PP.BDDESCPRODBUSCA = :wDescPro;
      END

    wCodProVinc = NULL;
    /*Sa?da precisa olhar o codsaida, pois pode ter 2 produtos com a mesma descri??o e c?digos de sa?da
      diferentes cadastrados na empresa*/
    IF (((:wCodProEncontrado IS NOT NULL) AND (:wCodProEncontrado > 0)) AND (:wCodOrigemProd = 1)) THEN /*Sa?da*/
      BEGIN
        SELECT FIRST 1 P.BDCODPROD
        FROM TMP_TCADPRO P
        WHERE P.BDCODPROD = :wCodProEncontrado
        AND P.BDCODEMP = :wCodEmp
        --AND P.BDCODSAIDA = :wCodSaida
        INTO :wCodProVinc;

        /* Esse select a cima verificou se esse produto j? n?o est? cadastrado na empresa.
           Se n?o estiver, verifica se tem algum produto vinculado a esse na empresa.
           Se houver, cria um cadastro unico novo */
        IF ((:wCodProVinc = 0) OR (:wCodProVinc IS NULL)) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDCODPROD = :wCodProEncontrado
            AND P.BDCODEMP = :wCodEmp
            INTO :wCodProVinc;

            IF ((:wCodProVinc IS NOT NULL) AND (:wCodProVinc > 0)) THEN
              wCodProEncontrado = NULL;
          END
      END

    IF ((:wCodProEncontrado IS NOT NULL) AND (:wCodProEncontrado > 0)) THEN /*Encontrou produto*/
      BEGIN
        /*Verifica se j? est? cadastrado na empresa*/

        wCodSaidaExistente = '';
        IF (:wCodOrigemProd = 0) THEN /*Entrada n?o olha o codsaida*/
          BEGIN
            SELECT FIRST 1 P.BDCODPROD, COALESCE(P.BDCODSAIDA, '')
            FROM TCADPRO_VINC P
            WHERE P.BDCODPROD = :wCodProEncontrado
            AND P.BDCODEMP = :wCodEmp
            INTO :wCodProVinc, :wCodSaidaExistente;
          END

        /*Se entrar no if ? porque o produto s? existe no cadastro unico, ent?o deve inserir na TMP_TCADPRO como cadastro vinculado ? empresa*/
        IF ((:wCodProVinc IS NULL) OR (:wCodProVinc = 0)) THEN
          BEGIN
            EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, :wCodSaida, :wCodEntrada, :wCodProEncontrado, 0, :wCodTerEncontrado, :wCNPJTerLayout, :wDescPro, :wCodOrigemProd, 'INS', :wSeq_Part, 'FALSE');
          END
        ELSE /*o else ? se o produto j? existir na empresa, s? verifica se vai atualizar. Se for atualizar, atualiza, sen?o n?o faz nada.*/
          BEGIN
            IF ((:wAtuProd = 'TRUE') AND (:PRGERARINCONSISTENCIAS = 'TRUE')) THEN
              BEGIN /*J? existe na empresa e o usu?rio optou por atualizar os dados*/
                EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, :wCodSaida, :wCodEntrada, :wCodProEncontrado, 0, :wCodTerEncontrado, :wCNPJTerLayout, :wDescPro, :wCodOrigemProd, 'UPT', :wSeq_Part, 'FALSE');
              END
            ELSE
              BEGIN
                IF (:wCodOrigemProd = 0) THEN /*Entrada*/
                  BEGIN
                    wCodProVinc = NULL;
                    SELECT FIRST 1 PART.BDEDITCHAVE
                    FROM TMP_TCADPRO_PART PART
                    WHERE PART.BDEDITCHAVE = :wCodProEncontrado
                    AND PART.BDCODENTRADA = :wCodEntrada
                    AND PART.BDDESCPRODBUSCA = :wDescPro
                    AND PART.BDCODTER = :wCodTerEncontrado
                    INTO :wCodProVinc;

                    IF (:wCodProVinc IS NULL) THEN
                      BEGIN
                        UPDATE OR INSERT INTO TMP_TCADPRO_PART(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODTER, BDCODENTRADA, BDDESCPRODBUSCA, BDCODEMP, BDSEQ_PART)
                        VALUES(:PRSESSAO, :wCodProEncontrado, :wCodProEncontrado, :wCodTerEncontrado, :wCodEntrada, :wDescPro, :wCodEmp, :wSeq_Part) MATCHING(BDCODPROD, BDCODENTRADA, BDCODTER, BDDESCPRODBUSCA);
                      END
                    ELSE
                      UPDATE TMP_TCADPRO_PART SET BDSEQ_PART = :wSeq_Part WHERE BDCODENTRADA = :wCodEntrada AND BDDESCPRODBUSCA = :wDescPro AND BDCODTER = :wCodTerEncontrado;
                  END
              END
          END

        IF (:wCodOrigemProd = 0) THEN /*Entrada*/
          BEGIN
            UPDATE TMP_TCADPRO_TEMP T SET T.BDEDITCHAVE = :wCodProEncontrado, T.BDCODPROD = :wCodProEncontrado, T.BDSITUACAO = 1, T.BDPRODEXISTEBASE = 'TRUE', T.BDCODSAIDA = :wCodSaidaExistente
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODENTRADA = :wCodEntrada
            AND T.BDDESCPROD = :wDescPro
            AND T.BDCNPJTERLAYOUT = :wCnpjTerLayout;
          END
        ELSE
          BEGIN /*Sa?da*/
            UPDATE TMP_TCADPRO_TEMP T SET T.BDEDITCHAVE = :wCodProEncontrado, T.BDCODPROD = :wCodProEncontrado, T.BDSITUACAO = 1, T.BDPRODEXISTEBASE = 'TRUE'
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODSAIDA = :wCodSaida;
          END
      END
    ELSE
      BEGIN
        /*Se n?o encontrou ent?o ? um produto novo e deve inserir na TMP_TCADPRO*/
        EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, :wCodSaida, :wCodEntrada, 0, 0, :wCodTerEncontrado, :wCNPJTerLayout, :wDescPro, :wCodOrigemProd, 'INS', :wSeq_Part, 'TRUE');

        IF (:PRALTERARSIT = 'TRUE') THEN
          BEGIN
        /*Se for pra cadastrar os produtos novos automaticamente, ent?o define a situa??o como 2 - Cadastro autom?tico*/
        IF (:wCodOrigemProd = 0) THEN /*Entrada*/
          BEGIN
            UPDATE TMP_TCADPRO_TEMP T SET T.BDSITUACAO = IIF(:wCadAut = 'TRUE', 2, 0), T.BDPRODEXISTEBASE = 'FALSE'
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODENTRADA = :wCodEntrada
            AND T.BDDESCPROD = :wDescPro
            AND T.BDCNPJTERLAYOUT = :wCnpjTerLayout;
          END
        ELSE
          BEGIN /*Sa?da*/
            UPDATE TMP_TCADPRO_TEMP T SET T.BDSITUACAO = IIF(:wCadAut = 'TRUE', 2, 0), T.BDPRODEXISTEBASE = 'FALSE'
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODENTRADA = :wCodEntrada
            AND T.BDCODSAIDA = :wCodSaida;
          END
      END
  END
  END

  /*Sol: 14207 Patrick T. S? 20/01/2017. Busca o c?digo CEST pela classifica??o CEST caso tenha no arquivo.*/
  /*Formata a classifica??o caso no arquivo s? venha como inteiro*/
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDCODCEST = (
                     SELECT FIRST 1 C.BDCODCEST
                     FROM TCEST C
                     WHERE C.BDCLASSCEST = (SUBSTRING(P.BDCLASSCEST FROM 1 FOR 2)||'.'||SUBSTRING(P.BDCLASSCEST FROM 3 FOR 3)||'.'||SUBSTRING(P.BDCLASSCEST FROM 6 FOR 2))
                    )
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCLASSCEST IS NOT NULL
  AND CHAR_LENGTH(P.BDCLASSCEST) <= 7;

  /*Caso no arquivo venha a classifica??o ent?o n?o formata, s? pesquisa*/
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDCODCEST = (
                     SELECT FIRST 1 C.BDCODCEST
                     FROM TCEST C
                     WHERE C.BDCLASSCEST = P.BDCLASSCEST
                    )
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCLASSCEST IS NOT NULL
  AND CHAR_LENGTH(P.BDCLASSCEST) > 7;

  /*Joga a ordem do produto por participante na TEMP, para quando for gravar o produto por participante tem a ordem*/
--  UPDATE TMP_TCADPRO_TEMP P
--  SET P.BDORDEM = (
--                   SELECT FIRST 1 PP.BDORDEM
--                   FROM TMP_TCADPRO_PART PP
--                   WHERE PP.BDCODENTRADA = P.BDCODENTRADA
--                   AND PP.BDDESCPRODBUSCA = P.BDDESCPROD
--                   AND PP.BDCODTER = P.BDCODTERLAYOUT
--                  )
--  WHERE P.BDSESSAO = :PRSESSAO
--  AND P.BDORIGEMPROD = 0
--  AND P.BDORDEM IS NULL;

  EXECUTE PROCEDURE SP_ATUALIZAR_CST_PROD(:PRSESSAO);

  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_INSUMO_TEMP(:PRSESSAO, :wAtuProd, :PRGERARINCONSISTENCIAS);
END
^

/* Alter (SP_ATUALIZAR_TMP_TEQUIPSAT) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TEQUIPSAT(PRSESSAO INTEGER,
PRULTCHAVE INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODEQUIPSAT INTEGER;
DECLARE VARIABLE WNRSERIE VARCHAR(9) COLLATE WIN_PTBR;
DECLARE VARIABLE WNRCAIXA INTEGER;
DECLARE VARIABLE WDATAINIOBRI DATE;
DECLARE VARIABLE WDATAFIMOBRI DATE;
DECLARE VARIABLE WCODEQUIPSAT_TMP INTEGER;
DECLARE VARIABLE WDATAINIOBRI_TMP DATE;
DECLARE VARIABLE WDATAFIMOBRI_TMP DATE;
BEGIN
  DELETE FROM VEF_INCON_TEQUIPSAT E WHERE E.BDSESSAO = :PRSESSAO;

  /*78 - N?mero de s?rie n?o informado*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 78 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND ((E.BDNRSERIE IS NULL) OR (E.BDNRSERIE = ''));

  /*79 - N?mero do caixa n?o informado*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 79 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND ((E.BDNRCAIXA IS NULL) OR (E.BDNRCAIXA = 0));

  /*80 - Data de in?cio das atividades n?o informada*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 80 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND (E.BDDATAINIOBRI IS NULL);

  FOR SELECT E.BDCODEMP, E.BDCODEQUIPSAT,
             E.BDNRSERIE, E.BDNRCAIXA,
             E.BDDATAINIOBRI, E.BDDATAFIMOBRI
      FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
      LEFT OUTER JOIN VEF_INCON_TEQUIPSAT EI ON(EI.BDSESSAO = E.BDSESSAO AND EI.BDCODEMP = E.BDCODEMP AND EI.BDCODEQUIPSAT = E.BDCODEQUIPSAT)
      WHERE E.BDSESSAO = :PRSESSAO
      AND E.BDCODEMP IS NOT NULL
      AND EI.BDCODINCONSISTENCIA IS NULL
      INTO :wCodEmp, :wCodEquipSat_tmp,
           :wNrSerie, :wNrCaixa,
           :wDataIniObri_tmp, :wDataFimObri_tmp
  DO
    BEGIN
      FOR SELECT EQ.BDCODEQUIPSAT, EQ.BDDATAINIOBRI,
                 EQ.BDDATAFIMOBRI
          FROM VEF_BASE_TEQUIPASAT EQ
          WHERE EQ.BDCODEMP = :wCodEmp
          AND EQ.BDNRSERIE = :wNrSerie
          AND EQ.BDNRCAIXA = :wNrCaixa
          ORDER BY EQ.BDCODEQUIPSAT
          INTO :wCodEquipSat, :wDataIniObri,
               :wDataFimObri
      DO
        BEGIN
          IF (((:wDataIniObri > :wDataIniObri_TMP) AND (((:wDataFimObri_TMP IS NULL) OR (:wDataFimObri_TMP = 0)) OR (:wDataIniObri <= :wDataFimObri_TMP))) OR
              ((:wDataIniObri <= :wDataIniObri_TMP) AND ((:wDataFimObri_TMP > :wDataIniObri) OR ((:wDataFimObri_TMP IS NULL) OR (:wDataFimObri_TMP = 0))))) THEN
            BREAK;
          ELSE
            wCodEquipSat = NULL;
        END

      IF ((:wCodEquipSat IS NOT NULL) AND (:wCodEquipSat > 0)) THEN /*Achou uma m?quina com mesma s?rie e caixa*/
        BEGIN
          IF (:wDataIniObri_tmp > wDataIniObri) THEN
            wDataIniObri_tmp = :wDataIniObri;

          IF (:wDataFimObri IS NOT NULL) THEN
            wDataFimObri_tmp = :wDataFimObri;

          UPDATE TMP_VEF_BASE_TEQUIPASAT_TEMP T
          SET T.BDEDITCHAVE = :wCodEquipSat,
              T.BDDATAINIOBRI = :wDataIniObri_tmp,
              T.BDDATAFIMOBRI = :wDataFimObri_tmp
          WHERE T.BDSESSAO = :PRSESSAO
          AND T.BDCODEQUIPSAT = :wCodEquipSat_tmp;
        END
      ELSE
        BEGIN
          UPDATE TMP_VEF_BASE_TEQUIPASAT_TEMP T SET T.BDEDITCHAVE = :PRULTCHAVE
          WHERE T.BDSESSAO = :PRSESSAO
          AND T.BDCODEQUIPSAT = :wCodEquipSat_tmp;

          PRULTCHAVE = :PRULTCHAVE - 1;
        END
     --alt:#23396 - w80794 - elizeu - 21-3-18 - Maquina com mesmo n?mero de s?rie e nr do caixa diferente uma j? cadastrada e outra n?o

      wCodEquipSat = null;
      wDataIniObri = null;
      wDataFimObri = null;
    END
END
^

/* Alter (SP_ATUALIZAR_TMP_TMOVSAI) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TMOVSAI(PRSESSAO INTEGER,
PRREF INTEGER,
PRCHAVEFIMBASE INTEGER,
PRVALIDARCSTMOVPRO VARCHAR(5),
PRSESSAOPRO INTEGER,
PRSESSAOTER INTEGER)
 AS
DECLARE VARIABLE FCODEMP INTEGER;
DECLARE VARIABLE FENQFED INTEGER;
DECLARE VARIABLE FCODCONFICMSSPED INTEGER;
DECLARE VARIABLE FSQL VARCHAR(1000);
DECLARE VARIABLE FCODPLANOONLINE INTEGER;
DECLARE VARIABLE FUFEMP VARCHAR(2);
DECLARE VARIABLE FCODPLANOINCON INTEGER;
DECLARE VARIABLE FNRNOTASAI VARCHAR(5);
DECLARE VARIABLE FDATAEMISAI VARCHAR(5);
DECLARE VARIABLE FSERIESAI VARCHAR(5);
DECLARE VARIABLE FESPECIESAI VARCHAR(5);
DECLARE VARIABLE FMODELOSAI VARCHAR(5);
DECLARE VARIABLE WCFOPPADRAOCANC INTEGER;
DECLARE VARIABLE WCFOPPADRAO INTEGER;
DECLARE VARIABLE WAJUSTARCFOPPART VARCHAR(5);
DECLARE VARIABLE FCODCONFIRLP INTEGER;
DECLARE VARIABLE FCODSITNF_CANC INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVSAI WHERE BDSESSAO = :PRSESSAO;

  SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP IS NOT NULL INTO :FCodEmp;

  IF (:PRCHAVEFIMBASE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVSAI_TEMP SET BDEDITCHAVE = :PRCHAVEFIMBASE WHERE BDSESSAO = :PRSESSAO AND BDEDITCHAVE IS NULL;

  /*Joga a cidade do participante na capa da nota se n?o vier na importa??o*/
  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP S SET S.BDCODCID = (SELECT FIRST 1
                                                             COALESCE(
                                                                      (SELECT FIRST 1 T.BDCODCID
                                                                       FROM TMP_TTERCEIRO_TEMP T
                                                                       WHERE T.BDSESSAO = :PRSESSAOTER
                                                                       AND T.BDCODTER = S.BDCODTER),
                                                                      (SELECT FIRST 1 VW.BDCODCID
                                                                       FROM VW_TTERCEIRO_SIMPLES VW
                                                                       WHERE VW.BDCGCTER = S.BDCNPJ)
                                                                     )
                                                      FROM RDB$DATABASE)
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDCODCID IS NULL) OR (S.BDCODCID = 0));

  /*Busca dados usados nas inconsistencias do lan?amento e do item*/
  SELECT SP.BDCODCONFICMSSPED, SP.BDCODPLANOONLINE, SP.BDSIGLAUF, SP.BDCODPLANOINCONS, SP.BDCODENQFED, SP.BDCODCONFIRLP
  FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :FCODEMP, NULL) SP INTO :FCODCONFICMSSPED, :FCODPLANOONLINE, :FUFEMP, :FCODPLANOINCON, :FENQFED, :FCODCONFIRLP;

  /*Verifica se n?o existe o lan?amento na base */
  SELECT R.BDNRNOTASAI, R.BDDATAEMISAI, R.BDSERIESAI, R.BDESPECIESAI, R.BDMODELOSAI
  FROM VEF_BASE_TCONFLANCREPETIDOS R INTO :FNRNOTASAI, :FDATAEMISAI, :FSERIESAI, :FESPECIESAI, :FMODELOSAI;
  
  /*Se n?o tem configura??o de lan?amento repetido, usa todos os parametros para comparar.*/
  IF (ROW_COUNT = 0) THEN
    BEGIN
      FNRNOTASAI = 'TRUE';
      FMODELOSAI = 'TRUE';
      FDATAEMISAI= 'TRUE';
      FSERIESAI  = 'TRUE';
      FESPECIESAI= 'TRUE';
    END  

  /* Insere incosist?ncia de lan?amentos repetidos */
  /* Caso a nota seja cancelada e j? exista na base, est? importando evento de cancelamento, apenas vai cancelar a nota existente... */
  FSQL =         ' INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia) ';
  FSQL = FSQL || ' SELECT T.BDCODEMP, T.BDCHAVE, NULL, T.BDSESSAO, 22 BDCODINCONSISTENCIA ';
  FSQL = FSQL || ' FROM TMP_VEF_EMP_TMOVSAI_TEMP T ';
  FSQL = FSQL || ' JOIN VEF_EMP_TMOVSAI S ON (S.BDCODEMP = T.BDCODEMP ';
  IF (UPPER(:FNRNOTASAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND S.BDNUMDOCINI = T.BDNUMDOCINI AND S.BDNUMDOCFIM = T.BDNUMDOCFIM ';
  IF (UPPER(:FMODELOSAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND S.BDMODELO = T.BDMODELO ';
  IF (UPPER(:FDATAEMISAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND S.BDDATAEMISSAO = T.BDDATAEMISSAO ';
  IF (UPPER(:FSERIESAI)   = 'TRUE') THEN
    FSQL = FSQL || ' AND COALESCE(S.BDSERIE, '''') = COALESCE(T.BDSERIE, '''') ';
  IF (UPPER(:FESPECIESAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND COALESCE(S.BDESPECIE, '''') = COALESCE(T.BDESPECIE, '''') ';
  FSQL = FSQL || ') WHERE T.BDSESSAO = '||:PRSESSAO;

  /*Sol: 18928 Patrick T. S? 30/05/2017. CFe valida no comando abaixo*/
  EXECUTE STATEMENT (FSQL || ' AND T.BDMODELO <> 59');

  /*CFe*/
  EXECUTE STATEMENT (FSQL || '  AND T.BDMODELO = 59 AND S.BDCODEQUIPSAT = T.BDCODEQUIPSAT');

  /***********************************Tratamento Nfe's canceladas***********************************/
  /*Patrick T. S? - Todos comandos da solicita??o 18626 foram refeitos porque estavam levando
                    mais de 1 hora para executar no banco da GFisco, ocasionando travamento
                    nos outros terminais que est?o importando*/
  FCODSITNF_CANC = 2; /*2 - Documento cancelado*/

  DELETE FROM TMP_TLANC_REPETIDOS WHERE BDCHAVE IS NOT NULL;

  /*Insere nessa tempor?ria para no update ter os campos chave, ent?o o update usa o indice prim?rio*/
  INSERT INTO TMP_TLANC_REPETIDOS(BDCODEMP, BDCHAVE, BDDATACANC)
  SELECT SAI.BDCODEMP, SAI.BDCHAVE, COALESCE(S.BDDATACANC, SAI.BDDATAEMISSAO) BDDATACANC
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE, S.BDCHAVENFE, S.BDCHAVENFECANC, S.BDDATACANC
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
        AND S.BDCODEMP = :FCODEMP
        AND S.BDCODSITNF = :FCODSITNF_CANC
       ) S
  JOIN VEF_EMP_TMOVSAI SAI ON(SAI.BDCODEMP = S.BDCODEMP AND SAI.BDCHAVENFE = S.BDCHAVENFE AND SAI.BDCHAVENFE = S.BDCHAVENFECANC);

  UPDATE VEF_EMP_TMOVSAI S
  SET S.BDCODSITNF = :FCODSITNF_CANC,
      S.BDDATACANC = (
                      SELECT REP.BDDATACANC
                      FROM TMP_TLANC_REPETIDOS REP
                      WHERE REP.BDCODEMP = S.BDCODEMP
                      AND REP.BDCHAVE = S.BDCHAVE
                     )
  WHERE S.BDCODEMP = :FCODEMP
  AND EXISTS (
              SELECT REP.BDCHAVE
              FROM TMP_TLANC_REPETIDOS REP
              WHERE REP.BDCODEMP = S.BDCODEMP
              AND REP.BDCHAVE = S.BDCHAVE
             );

  DELETE FROM TOL_VEF_EMP_TMOVSAI TOL
  WHERE TOL.BDCODEMP = :FCODEMP
  AND EXISTS(
             SELECT REP.BDCHAVE
             FROM TMP_TLANC_REPETIDOS REP
             WHERE REP.BDCODEMP = TOL.BDCODEMP
             AND REP.BDCHAVE = TOL.BDCHAVESAI
            );
  /*************************************************************************************************/
  /* Alt.: 18626 - Atualiza os movimentos de sa?da em que esteja importando evento de cancelamento */
--  UPDATE VEF_EMP_TMOVSAI s
--  SET s.BDCODSITNF = 2,
--      s.BDDATACANC = COALESCE((SELECT tmp.BDDATACANC
--                               FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
--                               WHERE tmp.BDCODEMP = s.BDCODEMP
--                                 AND tmp.BDSESSAO = :PRSESSAO
--                                 AND tmp.BDCODSITNF = 2
--                                 AND tmp.BDDATACANC IS NOT NULL
--                                 AND tmp.BDCHAVENFE = s.BDCHAVENFE
--                                 AND tmp.BDCHAVENFECANC = s.BDCHAVENFE), s.BDDATAEMISSAO)
--  WHERE (EXISTS(SELECT tmp.BDDATACANC
--                FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
--                WHERE tmp.BDCODEMP = s.BDCODEMP
--                  AND tmp.BDSESSAO = :PRSESSAO
--                  AND tmp.BDCODSITNF = 2
--                  AND tmp.BDCHAVENFECANC = s.BDCHAVENFE));

  /* Alt.: 18626 - Deleta a contabiliza??o das notas de evento de cancelamento */
--  DELETE FROM TOL_VEF_EMP_TMOVSAI tol
--  WHERE (EXISTS(SELECT * FROM VEF_EMP_TMOVSAI s
--                WHERE s.BDCODEMP = tol.BDCODEMP
--                  AND s.BDCHAVE = tol.BDCHAVESAI
--                  AND (EXISTS(SELECT tmp.BDDATACANC
--                              FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
--                              WHERE tmp.BDCODEMP = s.BDCODEMP
--                                AND tmp.BDSESSAO = :PRSESSAO
--                                AND tmp.BDCODSITNF = 2
--                                AND tmp.BDCHAVENFECANC = s.BDCHAVENFE))));

  /* Alt.: 18626 - Caso seja um evento de cancelamento sem nota na base ou importando a nota junto */
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA)
  SELECT tmp.BDCODEMP, tmp.BDCHAVE, NULL, tmp.BDSESSAO, 126 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
  WHERE tmp.BDSESSAO = :PRSESSAO
  AND TMP.BDCODEMP = :FCODEMP
  AND tmp.BDCODSITNF = :FCODSITNF_CANC
  AND tmp.BDDATACANC IS NULL -- Alt.: 18626 - Evento de cancelamento...
  AND tmp.BDNUMDOCINI IS NULL
  AND tmp.BDNUMDOCFIM IS NULL
  AND NOT EXISTS(
                 SELECT s.BDCODEMP
                 FROM VEF_EMP_TMOVSAI s
                 WHERE s.BDCODEMP = tmp.BDCODEMP
                 AND s.BDCHAVENFE = tmp.BDCHAVENFECANC
                 AND s.BDCODSITNF = :FCODSITNF_CANC
                );

  /* Alt.: 18626 - Remove as notas de evento de cancelamento, pois j? aplicou o cancelamento acima... */
  DELETE FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
  WHERE tmp.BDSESSAO = :PRSESSAO
  AND TMP.BDCODEMP = :FCODEMP
  AND tmp.BDCODSITNF = :FCODSITNF_CANC
  AND tmp.BDDATACANC IS NULL -- Evento de cancelamento n?o vai vir a data de cancelamento...
  AND EXISTS(
             SELECT S.BDCHAVE
             FROM VEF_EMP_TMOVSAI s
             WHERE s.BDCODEMP = tmp.BDCODEMP
             AND s.BDCHAVENFE = tmp.BDCHAVENFECANC
             AND s.BDCODSITNF = :FCODSITNF_CANC
            );

  /*Inconsistencia de n?mero do documento vazio(Inicial e final)*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO,
         CASE WHEN ((S.BDNUMDOCINI = 0) OR (S.BDNUMDOCINI IS NULL)) THEN 13 /*NUMDOCINI vazio*/
              WHEN ((S.BDNUMDOCFIM = 0) OR (S.BDNUMDOCFIM IS NULL)) THEN 14 /*NUMDOCFIM vazio*/
              WHEN (S.BDNUMDOCINI > S.BDNUMDOCFIM)                  THEN 16 /*NUMDOCINI maior do que o NUMDOCFIM*/
         END BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND (((S.BDNUMDOCINI = 0) OR (S.BDNUMDOCINI IS NULL)) OR ((S.BDNUMDOCFIM = 0) OR (S.BDNUMDOCFIM IS NULL)) OR (S.BDNUMDOCINI > S.BDNUMDOCFIM))
  AND (s.BDCHAVENFECANC IS NULL); -- Alt.: 18626 - Evento de cancelamento n?o precisa verificar...

  /*************************************************************************************************/

  /*Se a nfe tiver chave, valida a chave*/
  IF (:FCODCONFICMSSPED > 0) THEN
    BEGIN
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
      SELECT MOV.BDCODEMP, MOV.BDCHAVE, NULL, MOV.BDSESSAO, 19 BDCODINCONSISTENCIA
      FROM (
            SELECT S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE_CTE(S.BDCODEMP, S.BDCHAVE))
            FROM TMP_VEF_EMP_TMOVSAI_TEMP S
            WHERE S.BDSESSAO = :PRSESSAO
            AND S.BDMODELO = 55
            AND S.BDCODSITNF <> 5
           ) MOV
      WHERE BDISVALID = 'FALSE';
    END

  /*Inconsistencia dos lan?amentos de modelo 57 que tem chave da nfe vazia ou data de emiss?o maior do que data de saida*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT MOV.BDCODEMP, MOV.BDCHAVE, NULL, MOV.
         BDSESSAO, CASE WHEN ((TRIM(MOV.bdchavenfe) = '') OR (MOV.bdchavenfe IS NULL)) THEN 18
                        WHEN (BDISVALID = 'FALSE')                                     THEN 20
                   END BDCODINCONSISTENCIA
  FROM (
        SELECT S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, S.BDCHAVENFE,
               (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE_CTE(S.BDCODEMP, S.BDCHAVE)), S.BDDATAEMISSAO, S.BDDATASAIDA
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
        AND S.BDMODELO = 57
        AND ((TRIM(s.bdchavenfe) = '') OR (S.bdchavenfe IS NULL))
       ) MOV;

  /*21 - Data da emiss?o n?o pode ser maior que a data de sa?da*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdsessao, bdcodinconsistencia)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 21 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDDATAEMISSAO > S.BDDATASAIDA;

  /*Apartir de agora(08/11/2016) n?o filtra mas por modelo, toda nf tem que ter esse campo preenchido.*/
  /*Inconsistencia para cidade de destino obrigat?ria nos modelos 07, 08, 57 e 8B*/
--  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
--  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 15 BDCODINCONSISTENCIA
--  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
--  WHERE S.BDSESSAO = :prsessao
--  AND ((S.BDCODCID = 0) OR (S.BDCODCID IS NULL));
  
  /*Se n?o tiver participante vinculado o lan?amento ? inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 17 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDALTCODTER IS NULL) OR (S.BDALTCODTER = 0)); /*Este campo deve estar preenchido, ? o c?digo do banco no participante*/
--  AND ((S.BDCODTER IS NULL) OR (S.BDCODTER = 0));

  /*Torna o lan?amento inconsistente se o cadastro do participante est? inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 74 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTER/*S.BDCODTER*/)
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDPARTEXISTENTE IS NULL) OR (S.BDPARTEXISTENTE <> 'TRUE'))
  AND (S.BDCODTER > 0);

  /*75 - Lan?amentos sem item s?o inconsistentes*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 75 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE AND I.BDSESSAO = S.BDSESSAO)
  WHERE S.BDSESSAO = :PRSESSAO
    AND (s.BDCHAVENFECANC IS NULL) -- Alt.: 18626 - Evento de cancelamento n?o precisa verificar...  
  GROUP BY S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, I.BDORDEM
  HAVING COUNT(I.BDORDEM) = 0;

  /***************************************************************************************************************************/
  /*Troca a CFOP dos items aqui, porque se trocar depois de buscar as contas n?o vai mais encontrar porque j? trocou as cfops*/
  /***************************************************************************************************************************/

  /*Busca a sigla da uf do terceiro da tabela de lan?amento para tabela de item*/
  UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I SET I.BDSIGLAUFTER = (SELECT S.BDSIGLAUFTER
                                                               FROM TMP_VEF_EMP_TMOVSAI_TEMP S
                                                               WHERE S.BDCODEMP = I.BDCODEMP
                                                               AND S.BDCHAVE = I.BDCHAVE
                                                               AND S.BDSESSAO = I.BDSESSAO)
  WHERE I.BDSESSAO = :PRSESSAO;

  /*Se a empresa n?o tiver plano de inconsistencia, deve buscar o plano que est? setado como default*/
  IF ((:FCODPLANOINCON = 0) OR (:FCODPLANOINCON IS NULL)) THEN
    SELECT A.BDCODPLANOINCONS, A.BDSAICFOPNCAD, A.BDSAIAJUCFOP, A.BDSAICFOPCANC
    FROM VEF_BASE_TACOESINCONS A
    WHERE UPPER(A.BDPLANODEFAULT) = 'TRUE'
    INTO :FCODPLANOINCON, :wCFOPPADRAO, :wAJUSTARCFOPPART, :wCFOPPADRAOCANC;
  ELSE
    SELECT A.BDCODPLANOINCONS, A.BDSAICFOPNCAD, A.BDSAIAJUCFOP, A.BDSAICFOPCANC
    FROM VEF_BASE_TACOESINCONS A
    WHERE A.BDCODPLANOINCONS = :FCODPLANOINCON
    INTO :FCODPLANOINCON, :wCFOPPADRAO, :wAJUSTARCFOPPART, :wCFOPPADRAOCANC;

 /*S? executa se for para ajustar a cfop de acordo com a regi?o*/
  IF (UPPER(:wAJUSTARCFOPPART) = 'TRUE') THEN
    BEGIN
      DELETE FROM TMP_VEF_BASE_TNATOP_TEMP WHERE bdcodnat IS NOT NULL;
      /*Busca as cfops existentes na importa??o, agrupa e insere na tabela*/
      INSERT INTO TMP_VEF_BASE_TNATOP_TEMP (bdcodnat, BDNAOSOMARSTISEOUT, bdclassificacao, bdCODNATEX, bdCODNATufigual, bdCODNATufdif)
      SELECT I.BDCODNAT, COALESCE(N.BDNAOSOMARSTISEOUT, 'FALSE') BDNAOSOMARSTISEOUT, N.BDCLASSIFICACAO,
             ('7'||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDEXTERIOR,
             ('5'||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDUFIGUAL,
             ('6'||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDUFDIF
      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT)
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDCODNAT IS NOT NULL
      GROUP BY I.BDCODNAT, N.BDNAOSOMARSTISEOUT, N.BDCLASSIFICACAO, BDEXTERIOR, BDUFIGUAL, BDUFDIF;

      /*Muda a cfop se tiver setado para mudar no plano de inconsistencias - troca inicio da cfop para 5, 6 ou 7*/
      /*                  EX                */
      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
      SET BDCODNAT = (
                      SELECT N.BDCODNATEX
                      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP IT
                      LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT)
                      WHERE IT.BDSESSAO = :PRSESSAO
                      AND N.BDCODNATEX IS NOT NULL
                      AND IT.BDSIGLAUFTER = 'EX'
                      AND u.bdcodemp = it.bdcodemp
                      AND u.bdsessao = it.bdsessao
                      AND u.bdchave  = it.bdchave
                      AND u.bdordem  = it.bdordem
                     )
      WHERE U.BDSIGLAUFTER = 'EX'
      AND u.bdsessao = :PRSESSAO;

      /*                UF IGUAL          */
      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
      SET BDCODNAT = (
                      SELECT N.BDCODNATUFIGUAL
                      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP IT
                      LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT)
                      WHERE IT.BDSESSAO = :PRSESSAO
                      AND N.BDCODNATEX IS NOT NULL
                      AND IT.BDSIGLAUFTER = :FUFEMP
                      AND u.bdcodemp = it.bdcodemp
                      AND u.bdsessao = it.bdsessao
                      AND u.bdchave  = it.bdchave
                      AND u.bdordem  = it.bdordem
                     )
      WHERE U.BDSIGLAUFTER = :FUFEMP
      AND u.bdsessao = :PRSESSAO;

      /*                UF DIF            */
      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
      SET BDCODNAT = (
                      SELECT N.BDCODNATUFDIF
                      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP IT
                      LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT)
                      WHERE IT.BDSESSAO = :PRSESSAO
                      AND N.BDCODNATEX IS NOT NULL
                      AND ((IT.BDSIGLAUFTER <> :FUFEMP) AND (IT.BDSIGLAUFTER <> 'EX'))
                      AND u.bdcodemp = it.bdcodemp
                      AND u.bdsessao = it.bdsessao
                      AND u.bdchave  = it.bdchave
                      AND u.bdordem  = it.bdordem
                     )
      WHERE ((U.BDSIGLAUFTER <> :FUFEMP) AND (U.BDSIGLAUFTER <> 'EX'))
      AND u.bdsessao = :PRSESSAO;
    END

  /*Altera para cfop padrao as notas canceladas*/
   IF (:wCFOPPADRAOCANC > 0) THEN
     BEGIN
       UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
       SET U.BDCODNAT = :wCFOPPADRAOCANC
       WHERE U.BDSESSAO = :PRSESSAO
       AND EXISTS(
                  SELECT I.BDCHAVE
                  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                  LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT)
                  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
                  WHERE I.BDSESSAO = U.BDSESSAO
                  AND S.BDCODSITNF IN(2, 3)
                  AND N.BDCODNAT IS NULL
                  AND I.BDCODEMP = U.BDCODEMP
                  AND I.BDCHAVE  = U.BDCHAVE
                  AND I.BDORDEM  = U.BDORDEM
                  AND I.BDSESSAO = U.BDSESSAO
                 );
     END

  /*Altera para cfop padrao as notas n?o canceladas*/
  IF (:wCFOPPADRAO > 0) THEN
    BEGIN
      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
      SET U.BDCODNAT = :wCFOPPADRAO
      WHERE U.BDSESSAO = :PRSESSAO
      AND EXISTS(
                 SELECT I.BDCHAVE
                 FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                 LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT)
                 LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
                 WHERE I.BDSESSAO = U.BDSESSAO
                 AND S.BDCODSITNF NOT IN(2, 3)
                 AND N.BDCODNAT IS NULL
                 AND I.BDCODEMP = U.BDCODEMP
                 AND I.BDCHAVE  = U.BDCHAVE
                 AND I.BDORDEM  = U.BDORDEM
                 AND I.BDSESSAO = U.BDSESSAO
                );
    END

  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDCODCSTIPISAI = (SELECT FIRST 1 M.BDCODCSTIPI  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDCODCSTPISSAI = (SELECT FIRST 1 M.BDCODCSTPIS  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDCODCSTCOFSAI = (SELECT FIRST 1 M.BDCODCSTCOF  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDCODCSTICMS   = (SELECT FIRST 1 M.BDCODCSTICMS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDALIQPIS      = (SELECT FIRST 1 M.BDALIQPIS    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDALIQPISENT   = (SELECT FIRST 1 M.BDALIQPIS    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDALIQCOF      = (SELECT FIRST 1 M.BDALIQCOFINS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDALIQCOFENT   = (SELECT FIRST 1 M.BDALIQCOFINS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDALIQICMS     = (SELECT FIRST 1 M.BDALIQICMS   FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC),
      P.BDALIQIPI      = (SELECT FIRST 1 M.BDALIQIPI    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC)
  WHERE P.BDSESSAO = :PRSESSAOPRO;

  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVSAI_TEMP');
  EXECUTE PROCEDURE SP_VALIDA_CONTA_ONLINE_TEMP(:FCODPLANOONLINE, :PRSESSAO, :FENQFED, :FCODCONFIRLP);
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_TMOVSAIITENS(:FCODPLANOONLINE, :PRSESSAO, :FCODPLANOINCON, :FUFEMP, :PRVALIDARCSTMOVPRO, :PRSESSAOPRO);
  EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO(:PRSESSAO, :FCODPLANOONLINE, :FENQFED, :FCODCONFIRLP);

END
^

/* Alter (SP_ATUALIZAR_TMP_TMOVSAIITENS) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TMOVSAIITENS(PRCODPLANOONLINE INTEGER,
PRSESSAO INTEGER,
PRCODPLANOINCON INTEGER,
PRUFEMP VARCHAR(2),
PRVALIDARCSTMOVPRO VARCHAR(5),
PRSESSAOPRO INTEGER)
 AS
--declare variable WCODENQFED integer;
DECLARE VARIABLE WCOMPLEMENTOHIST BLOB SUB_TYPE 1 SEGMENT SIZE 1000;
DECLARE VARIABLE WIMPVLRCONTABDIFIPI VARCHAR(5);
DECLARE VARIABLE WIMPVLRCONTABDIF VARCHAR(5);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WCONDPGTO INTEGER;
DECLARE VARIABLE WCODITEMONLINE INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
BEGIN
  /*Se a empresa n?o tiver plano de inconsistencia, deve buscar o plano que est? setado como default*/
  IF ((:PRCODPLANOINCON = 0) OR (:PRCODPLANOINCON IS NULL)) THEN
    SELECT A.BDSAIIMPICMSDIF, A.BDSAIIMPIPIDIF FROM VEF_BASE_TACOESINCONS A WHERE UPPER(A.BDPLANODEFAULT) = 'TRUE' INTO :wIMPVLRCONTABDIF, :wIMPVLRCONTABDIFIPI;
  ELSE
    SELECT A.BDSAIIMPICMSDIF, A.BDSAIIMPIPIDIF FROM VEF_BASE_TACOESINCONS A WHERE A.BDCODPLANOINCONS = :PRCODPLANOINCON INTO :wIMPVLRCONTABDIF, :wIMPVLRCONTABDIFIPI;

  /*Se o lan?amento for inconsistente, torna o item inconsistente
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro)
  SELECT IT.BDCODEMP, IT.BDCHAVE, NULL, IT.BDSESSAO, 26 BDCODINCONSISTENCIA, NULL
  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP IT
  JOIN VEF_INCON_TMOVSAI INCO ON(INCO.BDSESSAO = IT.BDSESSAO AND INCO.BDCODEMP = IT.BDCODEMP AND INCO.BDCHAVE = IT.BDCHAVE AND INCO.BDORDEM IS NULL AND INCO.BDORDEMPRO IS NULL)
  WHERE IT.BDSESSAO = :PRSESSAO;*/

  /*Inconsistencia do valor de ipi diferente do valor cont?bil*/
  IF ((UPPER(:wIMPVLRCONTABDIFIPI) = 'FALSE') OR (:wIMPVLRCONTABDIFIPI IS NULL)) THEN
    BEGIN
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
      SELECT mov.BDCODEMP, mov.BDCHAVE, mov.BDORDEM, mov.BDSESSAO, 25 BDCODINCONSISTENCIA
      FROM (
            SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDVLRCONTAB,
                   (COALESCE(I.BDBASEIPI, 0) + COALESCE(I.BDISENTASIPI, 0) + COALESCE(I.BDOUTRASIPI, 0)) BDTOTALIPI
            FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
            WHERE I.BDSESSAO = :PRSESSAO
           ) mov
      WHERE MOV.BDTOTALIPI > 0
      AND MOV.BDTOTALIPI <> mov.BDVLRCONTAB;
    END

  /*Inconsistencia do valor de icms diferente do valor cont?bil*/
  IF ((UPPER(:wIMPVLRCONTABDIF) = 'FALSE') OR (:wIMPVLRCONTABDIF IS NULL)) THEN
    BEGIN
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
      SELECT mov.BDCODEMP, mov.BDCHAVE, mov.BDORDEM, mov.BDSESSAO, 24 BDCODINCONSISTENCIA
      FROM (
            SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDVLRCONTAB,
                   (COALESCE(I.BDBASEICMS, 0) + COALESCE(I.BDISENTASICMS, 0) + COALESCE(I.BDOUTRASICMS, 0) + COALESCE(I.BDOUTROSIMP, 0) + IIF(UPPER(CFOP.BDNAOSOMARSTISEOUT) = 'TRUE', COALESCE(I.BDVLRST, 0), 0)) BDTOTAL
            FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
            LEFT OUTER JOIN VEF_BASE_TNATOP CFOP ON(CFOP.BDCODNAT = I.BDCODNAT)
            WHERE I.BDSESSAO = :PRSESSAO
           ) mov
      WHERE MOV.BDTOTAL > 0
      AND MOV.BDTOTAL <> mov.BDVLRCONTAB;

--      IF (UPPER(:wNAOSOMARSTISEOUT) = 'TRUE') THEN
--        BEGIN
--          INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
--          SELECT mov.BDCODEMP, mov.BDCHAVE, mov.BDORDEM, mov.BDSESSAO, 24 BDCODINCONSISTENCIA
--          FROM (
--                SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDVLRCONTAB,
--                       (COALESCE(I.BDBASEICMS, 0) + COALESCE(I.BDISENTASICMS, 0) + COALESCE(I.BDOUTRASICMS, 0) + COALESCE(I.BDOUTROSIMP, 0) + COALESCE(I.BDVLRST, 0)) BDTOTAL
--                FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
--                WHERE I.BDSESSAO = :PRSESSAO
--               ) mov
--          WHERE MOV.BDTOTAL > 0
--          AND MOV.BDTOTAL <> mov.BDVLRCONTAB;
--        END
--      ELSE
--        BEGIN
--          INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
--          SELECT mov.BDCODEMP, mov.BDCHAVE, mov.BDORDEM, mov.BDSESSAO, 24 BDCODINCONSISTENCIA
--          FROM (
--                SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDVLRCONTAB,
--                       (COALESCE(I.BDBASEICMS, 0) + COALESCE(I.BDISENTASICMS, 0) + COALESCE(I.BDOUTRASICMS, 0) + COALESCE(I.BDOUTROSIMP, 0)) BDTOTAL
--                FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
--                WHERE I.BDSESSAO = :PRSESSAO
--               ) mov
--          WHERE MOV.BDTOTAL > 0
--          AND MOV.BDTOTAL <> mov.BDVLRCONTAB;
--        END
    END


  /*Joga como inconsistente os lan?amentos com cfop n?o cadastrada*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 23 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
  LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT)
  WHERE I.BDSESSAO = :PRSESSAO
  AND N.BDCODNAT IS NULL;

  /*cfop n?o pertence ao estado DO participante*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT CFOP.BDCODEMP, CFOP.BDCHAVE, CFOP.BDORDEM, CFOP.BDSESSAO, CFOP.BDINCONSISTENTE
  FROM (
        SELECT MOV.BDSESSAO, MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDORDEM, MOV.BDSIGLAUFTER, MOV.BDSIGLAUFEMP, MOV.BDCODNAT,
               CASE WHEN MOV.BDMODELO IN (59,65) THEN NULL -- Sol. 21385 notas de modelo 59 e 65 n?o precisam da valida??o
                    WHEN MOV.BDSIGLAUFTER = MOV.BDSIGLAUFEMP THEN IIF(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 1) = '5', NULL, 38)
                    WHEN MOV.BDSIGLAUFTER = 'EX' THEN IIF(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 1) = '7', NULL, 38)
                    ELSE
                      IIF(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 1) = '6', NULL, 38)
               END BDINCONSISTENTE
        FROM (
              SELECT I.BDSESSAO, L.BDMODELO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM,
                     I.BDCODNAT, I.BDSIGLAUFTER, :PRUFEMP BDSIGLAUFEMP, NULL BDINCONSISTENTE
              FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
              LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP L ON (L.BDSESSAO = I.BDSESSAO AND L.BDCODEMP = I.BDCODEMP AND L.BDCHAVE = I.BDCHAVE)
              WHERE I.BDSESSAO = :PRSESSAO
             ) MOV
       ) CFOP
  WHERE CFOP.BDINCONSISTENTE IS NOT NULL;

  /*-----------------------------------------------------------------------------------------------------------------------------*/
  /*---------------------Monta o complemento das contas do valor cont?bil, ICMS, IPI, ICMS ST, PIS e COFINS----------------------*/
  FOR SELECT I.BDCODNAT, CASE WHEN COALESCE(S.BDCONDPGTO, 0) = 0 THEN 50
                              WHEN COALESCE(S.BDCONDPGTO, 0) = 1 THEN 51
                              WHEN COALESCE(S.BDCONDPGTO, 0) = 2 THEN 406
                         END BDCONDPGTO
      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
      WHERE I.BDSESSAO = :PRSESSAO
      GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCODNAT, S.BDCONDPGTO
      INTO :wCodNat, :wCondPgto
  DO
    BEGIN

      /*Complemento de hist?rico do valor cont?bil*/
      SELECT FIRST 1 COALESCE(
                              (
                               /*Busca primeiro o complemento da conta
                               SELECT FIRST 1 H.BDCOMPLEMENTO
                               FROM TCONF_CONTAS_ONLINE O
                               LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = O.BDCODCOMPHISTPROV)
                               WHERE EXISTS(
                                            SELECT I.BDCHAVE
                                            FROM TCONTAS_ONLINE_TEMP I
                                            WHERE ((I.BDCHAVE = O.BDCHAVE) OR (I.BDCHAVECONF = O.BDCHAVE))
                                            AND I.BDCLASS_TITULO = O.BDCLASSIFICACAO
                                            AND I.BDCODNAT = :wCodnat
                                            AND I.BDCODITEMONLINE = CASE WHEN :wCondPgto = 50  THEN 111
                                                                         WHEN :wCondPgto = 51  THEN 117
                                                                         WHEN :wCondPgto = 406 THEN 170
                                                                    END
                                           )
                               AND O.BDCODPLANOONLINE = :PRCODPLANOONLINE*/
                               SELECT T.BDCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP T
                               WHERE T.BDCODNAT = :wCodNat
                               AND T.BDCODTIPOCONTA = :wCondPgto
                               --AND T.BDCODITEMONLINE IN(111, 117, 170) /*Avista, prazo e outras do valor cont?bil*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                               AND (T.BDCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 111 /*Valor cont?bil - A vista*/
                                                             WHEN :wCondPgto =  51 THEN 117 /*Valor cont?bil - Prazo*/
                                                             WHEN :wCondPgto = 406 THEN 170 /*Valor cont?bil - Outras*/
                                                        END)
                              ),
                              (
                               /*Se n?o houver na conta, busca no vinculo de complemento e se l? n?o houver usa o complemento padr?o*/
                               SELECT H.BDCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC HV
                               LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                               WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                               AND HV.BDCODIGOTIPO = 3
                              ),
                              ('*NRDOC - *NOMEPART') /*Default*/
                             ) BDCODCOMPHIST
      FROM TCOMPLEMENTO_HIST_VINC
      INTO :wComplementoHist;

      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      SET I.BDCOMPHIST_VLRCONTAB = :wComplementoHist
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDVLRCONTAB > 0
      AND I.BDCODNAT = :wCodNat
      AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND INCO.BDCHAVE = I.BDCHAVE
                     AND INCO.BDSESSAO = I.BDSESSAO);

      /*---------------------------------------Complemento hist?rico do pis---------------------------------------*/
      wComplementoHist = NULL;
      SELECT FIRST 1 COALESCE(
                              (
                               SELECT T.BDCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP T
                               WHERE T.BDCODNAT = :wCodNat
                               AND T.BDCODTIPOCONTA = :wCondPgto
                               --AND T.BDCODITEMONLINE IN(115, 121, 174) /*Avista, prazo e outras do valor do PIS*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                               AND (T.BDCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 115 /*PIS - A vista*/
                                                             WHEN :wCondPgto =  51 THEN 121 /*PIS - Prazo*/
                                                             WHEN :wCondPgto = 406 THEN 174 /*PIS - Outras*/
                                                        END)
                              ),
                              (
                               /*Se n?o houver na conta, busca no vinculo de complemento e se l? n?o houver usa o complemento padr?o*/
                               SELECT H.BDCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC HV
                               LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                               WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                               AND HV.BDCODIGOTIPO = 19
                              ),
                               ('*NRDOC - *NOMEPART') /*Default*/
                              ) BDCODCOMPHIST
      FROM TCOMPLEMENTO_HIST_VINC
      INTO :wComplementoHist;

      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      SET I.BDCOMPHIST_VLRPIS = :wComplementoHist
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDVLRPIS > 0
      AND I.BDCODNAT = :wCodNat
      AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND INCO.BDCHAVE = I.BDCHAVE
                     AND INCO.BDSESSAO = I.BDSESSAO);
      /*----------------------------------------------------------------------------------------------------------*/
      /*---------------------------------------Complemento de hist?rico de ICMS-----------------------------------*/
      wComplementoHist = NULL;
      SELECT FIRST 1 COALESCE(
                              (
                               SELECT T.BDCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP T
                               WHERE T.BDCODNAT = :wCodNat
                               AND T.BDCODTIPOCONTA = :wCondPgto
                               --AND T.BDCODITEMONLINE IN(112, 118, 171) /*Avista, prazo e outras do valor de ICMS*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                               AND (T.BDCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 112 /*ICMS - A vista*/
                                                             WHEN :wCondPgto =  51 THEN 118 /*ICMS - Prazo*/
                                                             WHEN :wCondPgto = 406 THEN 171 /*ICMS - Outras*/
                                                        END)          
                              ),
                              (
                               /*Se n?o houver na conta, busca no vinculo de complemento e se l? n?o houver usa o complemento padr?o*/
                               SELECT H.BDCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC HV
                               LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                               WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                               AND HV.BDCODIGOTIPO = 9
                              ),
                               ('*NRDOC - *NOMEPART') /*Default*/
                              ) BDCODCOMPHIST
      FROM TCOMPLEMENTO_HIST_VINC
      INTO :wComplementoHist;

      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      SET I.BDCOMPHIST_VLRICMS = :wComplementoHist
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDVLRICMS > 0
      AND I.BDCODNAT = :wCodNat
      AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND INCO.BDCHAVE = I.BDCHAVE
                     AND INCO.BDSESSAO = I.BDSESSAO);
      /*----------------------------------------------------------------------------------------------------------*/
      /*---------------------------------------Complemento hist?rico de ICMS ST-----------------------------------*/
      wComplementoHist = NULL;
      SELECT FIRST 1 COALESCE(
                              (
                               SELECT T.BDCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP T
                               WHERE T.BDCODNAT = :wCodNat
                               AND T.BDCODTIPOCONTA = :wCondPgto
                               --AND T.BDCODITEMONLINE IN(113, 119, 172) /*Avista, prazo e outras do valor de ICMS ST*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                               AND (T.BDCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 113 /*ICMS ST - A vista*/
                                                             WHEN :wCondPgto =  51 THEN 119 /*ICMS ST - Prazo*/
                                                             WHEN :wCondPgto = 406 THEN 172 /*ICMS ST - Outras*/
                                                        END)                    
                              ),
                              (
                               /*Se n?o houver na conta, busca no vinculo de complemento e se l? n?o houver usa o complemento padr?o*/
                               SELECT H.BDCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC HV
                               LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                               WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                               AND HV.BDCODIGOTIPO = 14
                              ),
                               ('*NRDOC - *NOMEPART') /*Default*/
                             ) BDCODCOMPHIST
      FROM TCOMPLEMENTO_HIST_VINC
      INTO :wComplementoHist;

      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      SET I.BDCOMPHIST_VLRICMSST = :wComplementoHist
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDVLRST > 0
      AND I.BDCODNAT = :wCodNat
      AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND INCO.BDCHAVE = I.BDCHAVE
                     AND INCO.BDSESSAO = I.BDSESSAO);
      /*----------------------------------------------------------------------------------------------------------*/
      /*---------------------------------------Complemento hist?rico do IPI---------------------------------------*/
      SELECT FIRST 1 COALESCE(
                              (
                               SELECT T.BDCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP T
                               WHERE T.BDCODNAT = :wCodNat
                               AND T.BDCODTIPOCONTA = :wCondPgto
                               --AND T.BDCODITEMONLINE IN(114, 120, 173) /*Avista, prazo e outras do valor de IPI*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                               AND (T.BDCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 114 /*IPI - A vista*/
                                                             WHEN :wCondPgto =  51 THEN 120 /*IPI - Prazo*/
                                                             WHEN :wCondPgto = 406 THEN 173 /*IPI - Outras*/
                                                        END)
                              ),
                              (
                               /*Se n?o houver na conta, busca no vinculo de complemento e se l? n?o houver usa o complemento padr?o*/
                               SELECT H.BDCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC HV
                               LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                               WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                               AND HV.BDCODIGOTIPO = 16
                              ),
                               ('*NRDOC - *NOMEPART') /*Default*/
                             ) BDCODCOMPHIST
      FROM TCOMPLEMENTO_HIST_VINC
      INTO :wComplementoHist;

      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      SET I.BDCOMPHIST_VLRIPI = :wComplementoHist
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDVLRIPI > 0
      AND I.BDCODNAT = :wCodNat
      AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND INCO.BDCHAVE = I.BDCHAVE
                     AND INCO.BDSESSAO = I.BDSESSAO);
      /*----------------------------------------------------------------------------------------------------------*/
      /*---------------------------------------Complemento hist?rico do Cofins------------------------------------*/
      wComplementoHist = NULL;
      SELECT FIRST 1 COALESCE(
                              (
                               SELECT T.BDCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP T
                               WHERE T.BDCODNAT = :wCodNat
                               AND T.BDCODTIPOCONTA = :wCondPgto
                               --AND T.BDCODITEMONLINE IN(116, 122, 175) /*Avista, prazo e outras do valor do Cofins*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                               AND (T.BDCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 116 /*Cofins - A vista*/
                                                             WHEN :wCondPgto =  51 THEN 122 /*Cofins - Prazo*/
                                                             WHEN :wCondPgto = 406 THEN 175 /*Cofins - Outras*/
                                                        END)
                              ),
                              (
                               /*Se n?o houver na conta, busca no vinculo de complemento e se l? n?o houver usa o complemento padr?o*/
                               SELECT H.BDCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC HV
                               LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                               WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                               AND HV.BDCODIGOTIPO = 25
                              ),
                               ('*NRDOC - *NOMEPART') /*Default*/
                             ) BDCODCOMPHIST
      FROM TCOMPLEMENTO_HIST_VINC
      INTO :wComplementoHist;

      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      SET I.BDCOMPHIST_VLRCOFINS = :wComplementoHist
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDVLRCOFINS > 0
      AND I.BDCODNAT = :wCodNat
      AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND INCO.BDCHAVE = I.BDCHAVE
                     AND INCO.BDSESSAO = I.BDSESSAO);
      /*----------------------------------------------------------------------------------------------------------*/
    END

  /*-----------------------------------------Complemento de hist?rico das reten??es-------------------------------*/
  FOR SELECT C.BDCODITEMONLINE, C.BDCOMPLEMENTO, COALESCE(C.BDCODREC, 0) BDCODREC
      FROM TCONTAS_ONLINE_TEMP C
      WHERE C.BDCODNAT IS NULL
      AND C.BDCODTIPOCONTA IS NULL
      INTO :wCodItemOnline, :wComplementoHist, :wCodRec
  DO
    BEGIN
      /*PIS*/
      IF (:wCodItemOnline = 89) THEN
        BEGIN
          SELECT FIRST 1 COALESCE(:wComplementoHist,
                                  (
                                   SELECT H.BDCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC HV
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                                   WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                                   AND HV.BDCODIGOTIPO = 44
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) BDCODCOMPHIST
          FROM TCOMPLEMENTO_HIST_VINC
          INTO :wComplementoHist;

          UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
          SET BDCOMPHIST_VLRPISRET = :wComplementoHist
          WHERE I.BDSESSAO = :PRSESSAO
          AND EXISTS(
                     SELECT R.BDVLRPIS
                     FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
                     WHERE R.BDVLRPIS > 0
                     AND R.BDCODRECPIS = :wCodRec
                     AND R.BDCODEMP = I.BDCODEMP
                     AND R.BDCHAVE  = I.BDCHAVE
                     AND R.BDSESSAO = I.BDSESSAO
                    )
          AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                         FROM VEF_INCON_TMOVSAI INCO
                         WHERE INCO.BDCODEMP = BDCODEMP
                         AND INCO.BDCHAVE = BDCHAVE
                         AND INCO.BDSESSAO = BDSESSAO);
        END
      ELSE /*COFINS*/
      IF (:wCodItemOnline = 90) THEN
        BEGIN
          SELECT FIRST 1 COALESCE(:wComplementoHist,
                                  (
                                   SELECT H.BDCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC HV
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                                   WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                                   AND HV.BDCODIGOTIPO = 50
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) BDCODCOMPHIST
          FROM TCOMPLEMENTO_HIST_VINC
          INTO :wComplementoHist;

          UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
          SET I.BDCOMPHIST_VLRCOFRET = :wComplementoHist
          WHERE I.BDSESSAO = :PRSESSAO
          AND EXISTS(
                     SELECT R.BDVLRCOFINS
                     FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
                     WHERE R.BDVLRCOFINS > 0
                     AND R.BDCODRECCOFINS = :wCodRec
                     AND R.BDCODEMP = I.BDCODEMP
                     AND R.BDCHAVE  = I.BDCHAVE
                     AND R.BDSESSAO = I.BDSESSAO
                    )
          AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                         FROM VEF_INCON_TMOVSAI INCO
                         WHERE INCO.BDCODEMP = BDCODEMP
                         AND INCO.BDCHAVE = BDCHAVE
                         AND INCO.BDSESSAO = BDSESSAO);
        END
      ELSE /*Contribui??o social*/
      IF (:wCodItemOnline = 91) THEN
        BEGIN
          SELECT FIRST 1 COALESCE(:wComplementoHist,
                                  (
                                   SELECT H.BDCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC HV
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                                   WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                                   AND HV.BDCODIGOTIPO = 56
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) BDCODCOMPHIST
          FROM TCOMPLEMENTO_HIST_VINC
          INTO :wComplementoHist;

          UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
          SET I.BDCOMPHIST_VLRCSRET = :wComplementoHist
          WHERE I.BDSESSAO = :PRSESSAO
          AND EXISTS(
                     SELECT R.BDVLRCSOCIAL
                     FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
                     WHERE R.BDVLRCSOCIAL > 0
                     AND R.BDCODRECCSOCIAL = :wCodRec
                     AND R.BDCODEMP = I.BDCODEMP
                     AND R.BDCHAVE  = I.BDCHAVE
                     AND R.BDSESSAO = I.BDSESSAO
                    )
          AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                         FROM VEF_INCON_TMOVSAI INCO
                         WHERE INCO.BDCODEMP = BDCODEMP
                         AND INCO.BDCHAVE = BDCHAVE
                         AND INCO.BDSESSAO = BDSESSAO);
        END
      ELSE /*IR*/
      IF (:wCodItemOnline = 92) THEN
        BEGIN
          SELECT FIRST 1 COALESCE(:wComplementoHist,
                                  (
                                   SELECT H.BDCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC HV
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                                   WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                                   AND HV.BDCODIGOTIPO = 62
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) BDCODCOMPHIST
          FROM TCOMPLEMENTO_HIST_VINC
          INTO :wComplementoHist;

          UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
          SET I.BDCOMPHIST_VLRIRRET = :wComplementoHist
          WHERE I.BDSESSAO = :PRSESSAO
          AND EXISTS(
                     SELECT R.BDVLRIR
                     FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
                     WHERE R.BDVLRIR > 0
                     AND R.BDCODRECIR = :wCodRec
                     AND R.BDCODEMP = I.BDCODEMP
                     AND R.BDCHAVE  = I.BDCHAVE
                     AND R.BDSESSAO = I.BDSESSAO
                    )
          AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                         FROM VEF_INCON_TMOVSAI INCO
                         WHERE INCO.BDCODEMP = BDCODEMP
                         AND INCO.BDCHAVE = BDCHAVE
                         AND INCO.BDSESSAO = BDSESSAO);
        END
      ELSE /*INSS*/
      IF (:wCodItemOnline = 93) THEN
        BEGIN
          SELECT FIRST 1 COALESCE(:wComplementoHist,
                                  (
                                   SELECT H.BDCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC HV
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                                   WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                                   AND HV.BDCODIGOTIPO = 68
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) BDCODCOMPHIST
          FROM TCOMPLEMENTO_HIST_VINC
          INTO :wComplementoHist;

          UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
          SET I.BDCOMPHIST_VLRINSSRET = :wComplementoHist
          WHERE I.BDSESSAO = :PRSESSAO
          AND EXISTS(
                     SELECT R.BDINSSRET
                     FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
                     WHERE R.BDINSSRET > 0
                     AND R.BDCODRECINSS = :wCodRec
                     AND R.BDCODEMP = I.BDCODEMP
                     AND R.BDCHAVE  = I.BDCHAVE
                     AND R.BDSESSAO = I.BDSESSAO
                    )
          AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                         FROM VEF_INCON_TMOVSAI INCO
                         WHERE INCO.BDCODEMP = BDCODEMP
                         AND INCO.BDCHAVE = BDCHAVE
                         AND INCO.BDSESSAO = BDSESSAO);
        END
      wCodItemOnline   = NULL;
      wComplementoHist = NULL;
      wCodRec          = NULL;
    END

    /*-----------------------------------------Complemento hist?rico do desconto----------------------------------*/
    wComplementoHist = NULL;
    SELECT C.BDCOMPLEMENTO FROM TCONTAS_ONLINE_TEMP C WHERE C.BDCODITEMONLINE = 88 /*Desconto*/ INTO :wComplementoHist;

    SELECT FIRST 1 COALESCE(:wComplementoHist,
                            (
                             SELECT H.BDCOMPLEMENTO
                             FROM TCOMPLEMENTO_HIST_VINC HV
                             LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                             WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                             AND HV.BDCODIGOTIPO = 31
                            ),
                             ('*NRDOC - *NOMEPART') /*Default*/
                           ) BDCODCOMPHIST
          FROM TCOMPLEMENTO_HIST_VINC
          INTO :wComplementohist;

          UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
          SET I.BDCOMPHIST_VLRDESCONTO = :wComplementoHist
          WHERE I.BDSESSAO = :PRSESSAO
          AND EXISTS(
                     SELECT S.BDDESCONTONOTA
                     FROM TMP_VEF_EMP_TMOVSAI_TEMP S
                     WHERE S.BDDESCONTONOTA > 0
                     AND S.BDCODEMP = I.BDCODEMP
                     AND S.BDCHAVE  = I.BDCHAVE
                     AND S.BDSESSAO = I.BDSESSAO
                    )
          AND NOT EXISTS(
                         SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                         FROM VEF_INCON_TMOVSAI INCO
                         WHERE INCO.BDCODEMP = I.BDCODEMP
                         AND INCO.BDCHAVE = I.BDCHAVE
                         AND INCO.BDSESSAO = I.BDSESSAO
                        );

  /*Inconsistencia do lan?amento de produto*/
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_MOVPROSAI_TEMP(:PRSESSAO, :PRCODPLANOINCON, :PRVALIDARCSTMOVPRO, :PRSESSAOPRO);
END
^

/* Alter (SP_ATUALIZAR_TMP_TNCM) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TNCM(PRSESSAO INTEGER)
 AS
BEGIN
  UPDATE TMP_TNCM_TEMP N
  SET N.BDTIPONCM = CASE WHEN N.BDTIPONCMSTR = 'Se??o'      THEN 0
                         WHEN N.BDTIPONCMSTR = 'Cap?tulo'   THEN 1
                         WHEN N.BDTIPONCMSTR = 'Posi??o'    THEN 2
                         WHEN N.BDTIPONCMSTR = 'Subposi??o' THEN 3
                         WHEN N.BDTIPONCMSTR = 'Item'       THEN 4
                         WHEN N.BDTIPONCMSTR = 'Subitem'    THEN 5
                    END
  WHERE N.BDSESSAO = :PRSESSAO;
END
^

/* Alter (SP_ATUALIZAR_TMP_TTERCEIRO) */
ALTER PROCEDURE SP_ATUALIZAR_TMP_TTERCEIRO(PRSESSAO INTEGER NOT NULL,
PRLANCAMENTOMANUAL DM_BOOLEAN NOT NULL,
PRGERARINCONSISTENCIAS DM_BOOLEAN NOT NULL,
PRATUALIZARDADOS DM_BOOLEAN NOT NULL,
PRHUGEFILE DM_BOOLEAN NOT NULL,
PRCODTIPO INTEGER)
 AS
DECLARE VARIABLE WINCONSISTENTE DM_BOOLEAN COLLATE WIN_PTBR;
DECLARE VARIABLE WCODBRASIL INTEGER;
DECLARE VARIABLE WCODCIDENCONTRADO INTEGER;
DECLARE VARIABLE WEDITCHAVE INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCGCTER VARCHAR(18) COLLATE WIN_PTBR;
DECLARE VARIABLE WIETER VARCHAR(20) COLLATE WIN_PTBR;
DECLARE VARIABLE WAPELIDOTER VARCHAR(20);
DECLARE VARIABLE WNOMETER VARCHAR(100) COLLATE WIN_PTBR;
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODPAIS INTEGER;
DECLARE VARIABLE WAPELIDO VARCHAR(20);
DECLARE VARIABLE WCODTEREXIST INTEGER;
BEGIN
  PRLANCAMENTOMANUAL     = UPPER(:PRLANCAMENTOMANUAL);
  PRGERARINCONSISTENCIAS = UPPER(:PRGERARINCONSISTENCIAS);
  PRATUALIZARDADOS       = UPPER(:PRATUALIZARDADOS);
  PRHUGEFILE             = UPPER(:PRHUGEFILE);

  DELETE FROM VEF_INCON_TTERCEIROS WHERE BDSESSAO = :PRSESSAO;

  /* Select para verificar se a tabela TMP_TTERCEIRO est? vazia */
  SELECT FIRST 1 BDCODTER
  FROM TMP_TTERCEIRO
  INTO :WCODTER;

  IF (ROW_COUNT = 0) THEN
  BEGIN
    /* Se for lan?amento manual pode encerrar a execu??o da SP, pois quando for importar algo,
    todos os registros da tabela TTERCEIRO ser?o carregados para a tempor?ria */
    IF (:PRLANCAMENTOMANUAL = 'TRUE') THEN
      EXIT;

    /* Copiar todos os participantes para a tabela tempor?ria */
    INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER, BDAPELIDOTER,
                               BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST, BDREF_MAX)
    SELECT 0 BDSESSAO,
           X.BDCODTER BDEDITCHAVE,
           X.BDCODTER,
           COALESCE(TER.BDCGCTER, '') BDCGCTER,
           COALESCE(REF.BDIETER, '') BDIETER,
           COALESCE(REF.BDAPELIDOTER, '') BDAPELIDOTER,
           COALESCE(REF.BDNOMETER, '') BDNOMETER,
           COALESCE(REF.BDCODCID, 0) BDCODCID,
           COALESCE(REF.BDCODPAIS, 0) BDCODPAIS,
           'TRUE' BDPARTEXIST,
           REF.BDREFEMP
    FROM (SELECT R.BDCODTER,
                 MAX(R.BDREFEMP) BDREFEMP
          FROM TTERCEIRO_REF R
          GROUP BY R.BDCODTER) X
    INNER JOIN TTERCEIRO TER ON TER.BDCODTER = X.BDCODTER
    INNER JOIN TTERCEIRO_REF REF ON REF.BDCODTER = X.BDCODTER AND REF.BDREFEMP = X.BDREFEMP;
  END

  /* Guarda o c?digo de pais do brasil, posteriormente pode ser necess?rio
  verificar se o participante ? do exterior */
  SELECT P.BDCODPAIS
  FROM TPAIS P
  WHERE UPPER(BDDESCPAIS) = 'BRASIL'
  INTO :WCODBRASIL;

  FOR SELECT V.BDEDITCHAVE,
             V.BDCODTER,
             V.BDCGCTER,
             V.BDIETER,
             V.BDAPELIDOTER,
             V.BDNOMETER,
             V.BDCODCID,
             V.BDCODPAIS
      FROM TMP_TTERCEIRO_A_VALIDAR V
      ORDER BY V.BDCODTER
      INTO :WEDITCHAVE,
           :WCODTER,
           :WCGCTER,
           :WIETER,
           :WAPELIDOTER,
           :WNOMETER,
           :WCODCID,
           :WCODPAIS
  DO
  BEGIN
    /* Tratamento de campos a validar */
    WEDITCHAVE  = COALESCE(:WEDITCHAVE, 0);
    WCODTER     = COALESCE(:WCODTER, 0);
    WCGCTER     = COALESCE(:WCGCTER, '');
    WIETER      = COALESCE(:WIETER, '');
    WAPELIDOTER = COALESCE(:WAPELIDOTER, '');
    WNOMETER    = COALESCE(:WNOMETER, '');
    WCODCID     = COALESCE(:WCODCID, 0);
    WCODPAIS    = COALESCE(:WCODPAIS, 0);
    /*Sol: 14207 Patrick T. S? 15/03/2017. Quando ? participante do exterior, n?o tem cpf/cnpj ent?o o apelido ? o nome*/
    wApelido    = IIF(:wCgcTer = '', SUBSTRING(:wNomeTer FROM 1 FOR 20), :wCgcTer);

    /* independente do registro j? existir, precisa verificar se a cidade ? v?lida */
    /* Verificar inconsistencias antes de fazer o update/insert */
    WINCONSISTENTE = 'FALSE';

    /*Quando ? importa??o do Sintegra n?o valida a cidade, pode importar sem.*/
    IF ((:PRATUALIZARDADOS = 'TRUE') AND ((:PRCODTIPO <> 105) AND ((:wCodCid IS NULL) OR (:wCodCid > 0)))) THEN /* > 0 porque se for zerada j? valida na aplica??o*/
      BEGIN
        /* Cidade n?o cadastrada */
        WCODCIDENCONTRADO = NULL;

        SELECT C.BDCODCID
        FROM TCIDADE C
        WHERE C.BDCODCID = :WCODCID
        INTO :WCODCIDENCONTRADO;

        IF ((:WCODCIDENCONTRADO IS NULL) OR (:wCodCidEncontrado = 0)) THEN
          BEGIN
            WINCONSISTENTE = 'TRUE';

            IF (UPPER(:PRGERARINCONSISTENCIAS) = 'TRUE') THEN
              BEGIN
                /* Cidade inv?lida */
                INSERT INTO VEF_INCON_TTERCEIROS (BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
                VALUES (7, :PRSESSAO, :WCODTER);
              END
          END
      END

    /* Se n?o teve inconsistencia, faz update/insert do registro */
    IF (:WINCONSISTENTE <> 'TRUE') THEN
    BEGIN
      /* Se j? tem edit chave, ? uma altera??o de registro existente na tabela */
      IF (:WEDITCHAVE > 0) THEN
      BEGIN
        wCodTerExist = 0;
        SELECT FIRST 1 T.BDCODTER FROM TTERCEIRO T WHERE T.BDCODTER = :wEditChave INTO :wCodTerExist;
        wCodTerExist = COALESCE(:wCodTerExist, 0);

        /* Verifica se o apelido j? est? cadastrado, mas n?o deve marcar como inconsistente ainda...*/
        WINCONSISTENTE = 'FALSE';

        IF (:WINCONSISTENTE <> 'TRUE') THEN
        BEGIN
          IF (:PRATUALIZARDADOS = 'TRUE') THEN
          BEGIN
            UPDATE OR INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER,
                                                 BDAPELIDOTER, BDNOMETER, BDCODCID, BDCODPAIS,BDPARTEXIST)
            VALUES (:PRSESSAO, :WEDITCHAVE, :WCODTER, :WCGCTER, :WIETER, :WAPELIDO, :WNOMETER,
                    :WCODCID, :WCODPAIS, 'TRUE')
            MATCHING (BDEDITCHAVE);
          END
          ELSE
          BEGIN
            UPDATE TMP_TTERCEIRO
            SET BDSESSAO = :PRSESSAO,
                BDCODTER = :WCODTER,
                BDPARTEXIST = IIF(:wCodTerExist > 0, 'TRUE', 'FALSE')
            WHERE BDEDITCHAVE = :WEDITCHAVE;

            IF (ROW_COUNT = 0) THEN
            BEGIN
              INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER,
                                         BDAPELIDOTER, BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST)
              VALUES (:PRSESSAO, :WEDITCHAVE, :WCODTER, :WCGCTER, :WIETER, :WAPELIDO, :WNOMETER,
                      :WCODCID, :WCODPAIS, 'FALSE');
            END

          END
        END
      END
      ELSE
      BEGIN
        /* NOVO REGISTRO (EDITCHAVE=0) */
        /* Primeiro procurar pelo CNPJ e IE */
        IF ((:wCGCTER IS NOT NULL) AND (:WCGCTER <> '')) THEN
          BEGIN
            IF (:PRATUALIZARDADOS = 'TRUE') THEN
            BEGIN
              UPDATE TMP_TTERCEIRO T
              SET T.BDSESSAO = :PRSESSAO,
                  T.BDEDITCHAVE = COALESCE(T.BDEDITCHAVE, :WEDITCHAVE),
                  T.BDCODTER = :WCODTER,
                  T.BDCGCTER = :WCGCTER,
                  T.BDIETER = :WIETER,
                  T.BDAPELIDOTER = :WAPELIDO,
                  T.BDNOMETER = :WNOMETER,
                  T.BDCODCID = :WCODCID,
                  T.BDCODPAIS = :WCODPAIS,
                  T.BDPARTEXIST = 'TRUE'
              WHERE (T.BDCGCTER = :WCGCTER) AND
                    (T.BDIETER = :WIETER) AND
                    (T.BDCODPAIS = :wCodBrasil)
              ROWS 1 TO 1;
            END
            ELSE
            BEGIN
              UPDATE TMP_TTERCEIRO T
              SET T.BDSESSAO = :PRSESSAO,
                  T.BDCODTER = :WCODTER,
                  T.BDPARTEXIST = 'TRUE'
              WHERE (T.BDCGCTER = :WCGCTER) AND
                    (T.BDIETER = :WIETER) AND
                    (T.BDCODPAIS = :wCodBrasil)
              ROWS 1 TO 1;
            END
          END

        /* Se n?o achou pelo CNPJ e IE, pode ser participante do exterior,
        ent?o ? procurado pelo NOME e PAIS */
        --IF (ROW_COUNT = 0) THEN #Alt:21995 - N?o estava importando/alterando participantes do exterior
        IF ((ROW_COUNT = 0) or
            ((:wCGCTER IS NULL) or (:wCGCTER = ''))) THEN
        BEGIN
          IF ((:wCGCTER IS NULL) OR (:WCGCTER = '')) THEN
            BEGIN
              IF (:PRATUALIZARDADOS = 'TRUE') THEN
              BEGIN
                UPDATE TMP_TTERCEIRO T
                SET T.BDSESSAO = :PRSESSAO,
                    T.BDEDITCHAVE = COALESCE(T.BDEDITCHAVE, :WEDITCHAVE),
                    T.BDCODTER = :WCODTER,
                    T.BDCGCTER = :WCGCTER,
                    T.BDIETER = :WIETER,
                    T.BDAPELIDOTER = :WAPELIDO,
                    T.BDNOMETER = :WNOMETER,
                    T.BDCODCID = :WCODCID,
                    T.BDCODPAIS = :WCODPAIS,
                    T.BDPARTEXIST = 'TRUE'
                WHERE (T.BDNOMETER = :WNOMETER) AND
                      ((T.BDCODPAIS <> :WCODBRASIL) AND
                      (T.BDCGCTER = ''))
                ROWS 1 TO 1;
              END
              ELSE
              BEGIN
                UPDATE TMP_TTERCEIRO T
                SET T.BDSESSAO = :PRSESSAO,
                    T.BDCODTER = :WCODTER,
                    T.BDPARTEXIST = 'TRUE'
                WHERE (T.BDNOMETER = :WNOMETER) AND
                      ((T.BDCODPAIS <> :WCODBRASIL) AND
                      (T.BDCGCTER = ''))
                ROWS 1 TO 1;
              END
            END
          ELSE
            BEGIN /*02/05/2017 Vincula somente pelo CNPJ/CGC/CPF se n?o encontrar por CPF/CNPJ/CGC e I.E*/
              IF (:PRATUALIZARDADOS = 'TRUE') THEN
                BEGIN
                  UPDATE TMP_TTERCEIRO T
                  SET T.BDSESSAO = :PRSESSAO,
                      T.BDEDITCHAVE = COALESCE(T.BDEDITCHAVE, :WEDITCHAVE),
                      T.BDCODTER = :WCODTER,
                      T.BDCGCTER = :WCGCTER,
                      T.BDIETER = :WIETER,
                      T.BDAPELIDOTER = :WAPELIDO,
                      T.BDNOMETER = :WNOMETER,
                      T.BDCODCID = :WCODCID,
                      T.BDCODPAIS = :WCODPAIS,
                      T.BDPARTEXIST = 'TRUE'
                  WHERE (T.BDCGCTER = :wCGCTER)
                  AND (T.BDCODPAIS = :wCodBrasil)
                  ROWS 1 TO 1;
                END
              ELSE
                BEGIN
                  UPDATE TMP_TTERCEIRO T
                  SET T.BDSESSAO = :PRSESSAO,
                      T.BDCODTER = :WCODTER,
                      T.BDPARTEXIST = 'TRUE'
                  WHERE (T.BDCGCTER = :wCGCTER)
                  AND (T.BDCODPAIS = :wCodBrasil)
                  ROWS 1 TO 1;
                END
            END

          /* Se ainda n?o achou, ser? inserido um novo participante */

          IF (ROW_COUNT = 0) THEN
          BEGIN
            /* Verifica se o apelido j? est? cadastrado, mas n?o deve marcar como inconsistente ainda...*/
            WINCONSISTENTE = 'FALSE';

            /*Se chegar aqui ? porque o participante ? novo, ent?o deve validar a cidade, se for inv?lida nem insere na tmp*/
            IF ((:PRCODTIPO <> 105) AND ((:wCodCid IS NULL) OR (:wCodCid = 0))) THEN
              BEGIN
                /* Cidade n?o cadastrada */
                WCODCIDENCONTRADO = NULL;
        
                SELECT C.BDCODCID FROM TCIDADE C WHERE C.BDCODCID = :WCODCID INTO :WCODCIDENCONTRADO;
        
                IF ((:WCODCIDENCONTRADO IS NULL) OR (:wCodCidEncontrado = 0)) THEN
                  BEGIN
                    WINCONSISTENTE = 'TRUE';
        
                    IF (UPPER(:PRGERARINCONSISTENCIAS) = 'TRUE') THEN
                      BEGIN
                        /* Cidade inv?lida */
                        INSERT INTO VEF_INCON_TTERCEIROS (BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
                        VALUES (7, :PRSESSAO, :WCODTER);
                      END
                  END
              END

--            IF (:wInconsistente = 'FALSE') THEN
--              BEGIN
--                WAPELIDOENCONTRADO = NULL;
    
--                SELECT FIRST 1 T.BDAPELIDOTER
--                FROM TMP_TTERCEIRO T
--                WHERE T.BDAPELIDOTER = :WAPELIDOTER
--                INTO :WAPELIDOENCONTRADO;
    

                INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER,
                                           BDAPELIDOTER, BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST)
                VALUES (:PRSESSAO, :WEDITCHAVE, :WCODTER, :WCGCTER, :WIETER, :WAPELIDO, :WNOMETER,
                        :WCODCID, :WCODPAIS, 'FALSE');

    
                UPDATE TMP_TTERCEIRO_TEMP T SET T.BDAPELIDOTER = :WAPELIDO WHERE (T.bdcodter = :WCODTER);
--              END
          END
        END
      END
    END
    /* Caso o registro esteja inconsistente, e tenha editchave deve ser eliminado */
    IF ((:WINCONSISTENTE = 'TRUE') AND (:WEDITCHAVE > 0)) THEN
    BEGIN
      DELETE FROM TMP_TTERCEIRO
      WHERE BDEDITCHAVE = :WEDITCHAVE;
    END
  END

  /*Todos os participantes novos tem como apelido o CPF/CNPJ/CEI*/
  UPDATE TMP_TTERCEIRO T SET T.BDAPELIDOTER = IIF(T.BDCGCTER = '', SUBSTRING(T.BDNOMETER FROM 1 FOR 20), T.BDCGCTER)
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDAPELIDOTER <> T.BDCGCTER
  AND T.BDEDITCHAVE = 0;

  IF (:PRHUGEFILE = 'TRUE') THEN
    BEGIN
      UPDATE TMP_TTERCEIRO_TEMP T SET T.BDAPELIDOTER = T.BDCGCTER
      WHERE T.BDSESSAO = :PRSESSAO
      AND ((T.BDCGCTER IS NOT NULL) OR (T.BDCGCTER <> ''));

      UPDATE TMP_TTERCEIRO_TEMP T SET T.BDAPELIDOTER = SUBSTRING(T.BDNOMETER FROM 1 FOR 20)
      WHERE T.BDSESSAO = :PRSESSAO
      AND ((T.BDCGCTER IS NULL) OR (T.BDCGCTER = ''));
    END
END
^

/* Alter (SP_ATUALIZAR_UNIDADE_MEDIDA) */
ALTER PROCEDURE SP_ATUALIZAR_UNIDADE_MEDIDA(PRSESSAO INTEGER,
PRULTCHAVE INTEGER)
 AS
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WCODUNIMED INTEGER;
BEGIN

  IF (:PRULTCHAVE IS NULL) THEN
    BEGIN
      /*Atualiza a chave das unidades de medida j? existentes no banco*/
      UPDATE TMP_TUNIDADEMEDIDA_TEMP UN
      SET UN.BDEDITCHAVE = (
                            SELECT FIRST 1 U.BDCODUNIMED FROM TUNIDADEMEDIDA U
                            WHERE U.BDAPEUNIMED = UN.BDAPEUNIMED
                            AND U.BDCODUNIMED IS NOT NULL
                            ORDER BY U.BDCODUNIMED
                           )
      WHERE UN.BDSESSAO = :PRSESSAO;

      UPDATE TMP_TUNIDADEMEDIDA_TEMP UN
      SET UN.BDCODUNIMED = UN.BDEDITCHAVE
      WHERE UN.BDSESSAO = :PRSESSAO
      AND un.bdeditchave IS NOT NULL;
    END
  ELSE
    BEGIN
      /*Coloca o novo c?digo para os registros que n?o existem no banco(NOVOS REGISTROS)*/
      FOR SELECT U.BDCODUNIMED FROM TMP_TUNIDADEMEDIDA_TEMP U
          WHERE U.BDSESSAO = :PRSESSAO
          AND ((U.BDEDITCHAVE IS NULL) OR (U.BDEDITCHAVE = 0))
          INTO :wCodUniMed
      DO
        BEGIN
          UPDATE TMP_TUNIDADEMEDIDA_TEMP U SET U.BDEDITCHAVE = :PRULTCHAVE WHERE U.BDSESSAO = :PRSESSAO AND U.BDCODUNIMED = :wCodUniMed;
          PRULTCHAVE = :PRULTCHAVE - 1;
        END

      /*Atualiza o c?digo da unidade de medida nas tabelas dependentes*/
      FOR SELECT T.RDB$RELATION_NAME BDTABLE
          FROM RDB$RELATION_FIELDS T
          WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
          AND RDB$FIELD_NAME = 'BDALTCODUNIMED'
          INTO :wTable
      DO
        BEGIN
          EXECUTE STATEMENT 'UPDATE '||:wTable||' T SET T.BDALTCODUNIMED = (SELECT FIRST 1 U.BDEDITCHAVE FROM TMP_TUNIDADEMEDIDA_TEMP U WHERE U.BDSESSAO = '||:PRSESSAO||' AND UPPER(cast(U.BDAPEUNIMED AS BLOB SUB_TYPE 1)) = UPPER(CAST(T.BDAPEUNIMED AS BLOB SUB_TYPE 1))) WHERE T.BDSESSAO = '||:PRSESSAO;
    --      EXECUTE STATEMENT 'UPDATE '||:wTable||' T SET T.BDALTCODUNIMED = (SELECT FIRST 1 U.BDEDITCHAVE FROM TMP_TUNIDADEMEDIDA_TEMP U WHERE U.BDSESSAO = '||:PRSESSAO||' AND U.BDCODUNIMED = T.BDCODUNIMED) WHERE T.BDSESSAO = '||:PRSESSAO;

          EXECUTE STATEMENT 'UPDATE '||:wTable||' T SET T.BDCODUNIMED = BDALTCODUNIMED WHERE T.BDSESSAO = '||:PRSESSAO;
        END
    END


END
^

/* Alter (SP_CALC_DEPRECIACAO) */
ALTER PROCEDURE SP_CALC_DEPRECIACAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
PRCORRECAOPERIODO NUMERIC(15,2),
PRVALORCORRIGIDOATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
PRDEPRECIACAOPERIODO NUMERIC(15,2),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
PRVALORRESIDUALCONTABIL NUMERIC(15,2),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,2),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
PRVALORBAIXAREAL NUMERIC(15,2),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2))
 AS
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDTINI DATE;
DECLARE VARIABLE WDTFIM DATE;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIAMES INTEGER;
DECLARE VARIABLE WCONTINUACALCULO VARCHAR(5);
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALDEPACUMUBEM NUMERIC(15,6);
DECLARE VARIABLE WMESESDEPACUMUBEM INTEGER;
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WCODMOEDA INTEGER;
DECLARE VARIABLE WDESCMOEDA VARCHAR(20);
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,2);
DECLARE VARIABLE WVALORBAIXAAUX NUMERIC(15,2);
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WVALORAQUISICAO NUMERIC(15,6);
DECLARE VARIABLE WPOSSUIBAIXA VARCHAR(5);
DECLARE VARIABLE WREFMOEDAINI VARCHAR(10);
DECLARE VARIABLE WREFMOEDAFIM VARCHAR(10);
DECLARE VARIABLE WVALORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPDIASADEPRECIAR INTEGER;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WTOTALMESESDOPERIODO INTEGER;
DECLARE VARIABLE WDATAOFICIALINICIOLCALCULO DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WDATATOTALMESESDEPDIA DATE;
DECLARE VARIABLE WDATATOTALMESESULTIMODIA DATE;
DECLARE VARIABLE WDEPDIAFINAL VARCHAR(5);
DECLARE VARIABLE WDATAATUAL DATE;
DECLARE VARIABLE WDIFERENCAMESES INTEGER;
DECLARE VARIABLE WVALORAQUISICAOMOEDA NUMERIC(15,7);
DECLARE VARIABLE WVALORDEPRECIACAOMENSAL NUMERIC(15,7);
DECLARE VARIABLE WVALORDEPRECIACAODIARIA NUMERIC(15,6);
DECLARE VARIABLE WDATAINICIAL DATE;
DECLARE VARIABLE WDATAFINAL DATE;
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,2);
BEGIN
  /*Stored procedure para calcular a deprecia??o dos bens*/

  --#alt:6598.
  /*Esta stored procedure foi iniciada para calcular de uma forma mais r?pida, mas conseguimos melhorar a rotina anterior.
  Caso a rotina SP_CONS_CALC_DEP volte a dar problema j? tem essa meia encaminhada.
  OBS_1: Est? rotina est? no in?cio, por isso precisa implementar v?rias situa??es e testar muito bem.
  OBS_2: Tem algumas stored procedure que podem ser trocadas por rotinas do pr?prio banco para melhorar o desempenho. 
  Ex: select BDNOVADATA from diminui_meses(:wdatatotalmesesultimodia,1) into wdatatotalmesesultimodia;   --->  wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);
      select bdMESES from DIFERENCA_MESES(:wdatainicial,:wdatafinal) into :wtotalmesesdoperiodo;         --->  wtotalmesesdoperiodo = datediff(month,:wdatainicial,:wdatafinal);                 
  */

  -- Inicializa par?metros
  PRVALORCORRIGIDOANTERIOR        = 0;
  PRCORRECAOPERIODO               = 0;
  PRVALORCORRIGIDOATUAL           = 0;
  PRDEPRECIACAOACUMULADAANTERIOR  = 0;
  PRDEPRECIACAOPERIODO            = 0;
  PRDEPRECIACAOPERIODOMOEDA       = 0;
  PRDEPRECIACAOACUMULADAATUAL     = 0;
  PRDEPRECIACAOACUMULADAATUALMOED = 0;
  PRCORRECAOMONETARIADEPRECIACAO  = 0;
  PRVALORRESIDUALCONTABIL         = 0;
  PRVALORRESIDUALCONTABILMOEDA    = 0;
  PRTOTALMESESDEPRECIACAO         = 0;
  PRMESESDEPRECIADOS              = 0;
  PRMESESDEPRECIAR                = 0;
  PRTAXADEPRECIACAOANUAL          = 0;
  PRDATATAXADEPRECIACAO           = NULL;
  PRVALORBAIXA                    = 0;
  PRDEPRECIACAOBAIXAMOEDA         = 0;
  PRVALORBAIXAREAL                = 0;
  PRVALORMOEDA                    = 0;
  PRDATABAIXA                     = NULL;
  PRVALORAQUISICAOMOEDA           = 0;
  PRVALORCORRIGIDOANTERIORMOEDA   = 0;
  PRVALORAQUISICAOORIGINAL        = 0;
  PRCTADEBITODEPRE                = NULL;
  PRVALORDEPRECIACAODIARIAFIM     = 0;

  wcodbemoriginal            = 0;
  wdataorigaquisicao         = NULL;
  wdepdia                    = 'FALSE';
  wdepmensal                 = 'FALSE';
  wdepmesbaixa               = 'FALSE';
  wdatainiciocalc            = NULL;
  wdatafimcalc               = NULL;
  wdataultimoitemdep         = NULL;
  wvaldepacumubem            = 0;
  wnumdias                   = 0;
  wcodmoeda                  = 0;
  wdescmoeda                 = '';
  wvalormoeda                = 0;

  SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  INTO :wvalorbaixa;

  IF (wvalorbaixa > 0) THEN
    wpossuibaixa = 'TRUE';
  --Tipo 2 somente baixas
  IF ((prtipo = 2) AND (wvalorbaixa = 0)) THEN
    EXIT;

  SELECT tind.bddescind,tbem.bdcodind
  FROM (SELECT COALESCE(tbem.bdcodind,0) bdcodind FROM empresas_tbem tbem
        WHERE (tbem.bdcodemp = :prcodemp)
        AND   (tbem.bdcodbem = :prcodbem)) tbem
  LEFT OUTER JOIN TINDICES tind ON (tind.bdcodind = tbem.bdcodind)
  INTO :wdescmoeda,:wcodmoeda;

  SELECT tbem.bdDATORIAQUIBEM FROM empresas_tbem tbem
  WHERE (tbem.bdcodemp = :prcodemp) AND
        (tbem.bdcodbem = :prcodbem)
  INTO :wdataaquisicao;

  wmes = CAST(SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(EXTRACT(YEAR FROM wdataaquisicao) AS INTEGER);
  SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;

  --wdtini           = wmes||'-01-'||wano;
  wdtini           = wdataaquisicao;
  wdtfim           = wmes||'-'||wultdiames||'-'||wano;
  wrefatu          = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim          = CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER);
  wcontinuacalculo = 'TRUE';
  WHILE ((wrefatu <= wreffim) AND (wcontinuacalculo = 'TRUE')) DO
    BEGIN
      -- Inicializa vari?veis
      wdatainicial               = wdtini;
      wdatafinal                 = wdtfim;
      wdepdiafinal               = 'FALSE';
      wmesesdepacumubem          = 0;
      wvalorbaixa                = 0;
      wvalorbaixaaux             = 0;
      wdatabaixa                 = NULL;
      wvaloraquisicao            = 0;
      wpossuibaixa               = 'FALSE';
      wrefmoedaini               = '';
      wrefmoedafim               = '';
      wdepdiasadepreciar         = 0;
      wtotalmesesdepreciacao     = 0;
      wmesesdepreciados          = 0;
      wmesesdepreciar            = 0;
      wtotalmesesdoperiodo       = 0;
      wdataoficialiniciolcalculo = NULL;
      wdatatotalmeses            = NULL;
      wdatatotalmesesdepdia      = NULL;
      wdatatotalmesesultimodia   = NULL;
      wdataatual                 = wdatafinal;
      wdiferencameses            = NULL;
      wvaloraquisicaomoeda       = 0;
      wvalordepreciacaomensal    = 0;
      wvalordepreciacaodiaria    = 0;
      wdepreciacaoperiodo        = 0;
      wdepreciacaoperiodomoeda   = 0;

      -- Quando o valor da deprecia??o acumulada passou do valor do bem n?o precisa continuar o processo at? chegar na data informada
      IF ((wcontinuacalculo = 'TRUE') AND (prvaloraquisicaooriginal > 0) AND (prdepreciacaoacumuladaatual > COALESCE(prvaloraquisicaooriginal,0))) THEN
        wcontinuacalculo = 'FALSE';

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((prtaxadepreciacaoanual = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        SELECT tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem,
               tbem.bddepmesbaixabem, tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, tdep.bdvaldepacumubem,tdep.bdctadebitodepre, tbem.bdnumdias
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :prtaxadepreciacaoanual, :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,           :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre,       :wnumdias;

      IF ((wvaloraquisicao = 0) AND (prvaloraquisicaooriginal > 0)) THEN
        wvaloraquisicao = prvaloraquisicaooriginal;

      wvalorbaixa = 0;
      IF (wpossuibaixa = 'TRUE') THEN
        BEGIN
          FOR SELECT bddatbai,COALESCE(SUM(bdvalbai),0) AS TotalBaixa FROM empresas_tbai
              WHERE (bdcodemp = :prcodemp) AND (bdcodbem = :prcodbem)
              AND   (bddatbai BETWEEN :wdtini AND :wdtfim) GROUP BY bddatbai
              INTO :wdatabaixa,:wvalorbaixaaux DO
            BEGIN
              wvalorbaixa = wvalorbaixa + wvalorbaixaaux;
            END
        END

      IF (prvaloraquisicaooriginal IS NULL) THEN
        BEGIN
          EXCEPTION ex_date;
          SUSPEND;
          EXIT;
        END

      --if (prdatainicial > wdatafimcalc) then
      --  begin
      --    suspend;
      --    exit;
      --  end

      wvaloraquisicao = (wvaloraquisicao - wvalorbaixa);
    
      IF ((UPPER(wdepmesbaixa) = 'TRUE') AND (wvalorbaixa >= wvaloraquisicao)) THEN
        BEGIN
          wdatafinal = wdatabaixa; -- tinha prdatafinal
    
          IF (CAST((SUBSTRING(wdatabaixa FROM 1 FOR 4)) || (SUBSTRING(wdatabaixa FROM 6 FOR 2)) AS INTEGER) <=
              CAST((SUBSTRING(wdtfim FROM 1 FOR 4)) || (SUBSTRING(wdtfim FROM 6 FOR 2)) AS INTEGER)) THEN
            wdepmesbaixa = 'TRUE';
          ELSE
            wdepmesbaixa = 'FALSE';
        END
      ELSE
        wdepmesbaixa = 'FALSE';
    
      IF (UPPER(wdepmesbaixa) = 'TRUE') THEN
        wvaloraquisicao = (wvaloraquisicao + wvalorbaixa);

      IF ((((wvaloraquisicao IS NULL) OR (wvaloraquisicao <=0))) AND (UPPER(wdepmesbaixa) = 'FALSE')) THEN
        BEGIN
          SUSPEND;
          EXIT;
        END
    
      IF (prtipo = 2) THEN
        BEGIN
          prvaloraquisicaooriginal = wvalorbaixa;
          wvaloraquisicao          = wvalorbaixa;
        END

      -- C?LCULO DE DEPRECIA??O
      prvalorcorrigidoatual = wvaloraquisicao;

      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      IF ((wvalormoeda IS NULL) OR (wvalormoeda = 0) OR (POSITION('UFIR',UPPER(wdescmoeda)) = 0))  THEN
        BEGIN
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
          wrefmoedafim = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
          IF (wdataorigaquisicao IS NOT NULL) THEN
            BEGIN
              wrefmoedaini = SUBSTRING(CAST(:wdataorigaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
              wrefmoedafim = SUBSTRING(CAST(:wdataorigaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
            END
    
          SELECT MAX(tind.bdvalind) FROM tindval tind
                 WHERE (tind.bdcodind = :wcodmoeda) AND
                       (tind.bdrefind BETWEEN :wrefmoedaini AND :wrefmoedafim)
          INTO :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          IF (wvalormoeda IS NULL) THEN
            BEGIN
              SELECT FIRST 1 tind.bdvalind FROM tindval tind
                     WHERE tind.bdcodind = :wcodmoeda AND
                     tind.bdrefind <= :wrefmoedaini
                     ORDER BY tind.bdrefind
              INTO :wvalormoeda;
            END
        END

      -- Deprecia??o di?ria (In?cio)
      IF (UPPER(wdepdia) = 'TRUE' ) THEN
        IF ((SUBSTRING(wdatainiciocalc FROM 9 FOR 2)) = '01') THEN
          wdepdia = 'FALSE';
    
      IF (UPPER(wdepdia) = 'TRUE') THEN
        BEGIN
          wdepdiasadepreciar = (SUBSTRING(wdatainiciocalc FROM 9 FOR 2));
    
          wmes = CAST(SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano = CAST(SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;
    
          IF (wnumdias = 2) THEN
            wdepdiasadepreciar = wultdiames - wdepdiasadepreciar;
          ELSE
            wdepdiasadepreciar = 30 - wdepdiasadepreciar;
        END
      -- Deprecia??o di?ria (Fim)

      IF (prtaxadepreciacaoanual >= 0.1) THEN
        wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
      ELSE
        BEGIN
          prvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / wvalormoeda;
          prvalorresidualcontabil       = wvaloraquisicao;
          prvalorresidualcontabilmoeda  = (wvaloraquisicao / wvalormoeda);
          prdatataxadepreciacao         = wdataultimoitemdep;
          prvalorbaixa                  = wvalorbaixa;
          prvalorbaixareal              = wvalorbaixa;
          prvalormoeda                  = wvalormoeda;
          prdatabaixa                   = wdatabaixa;
          prvaloraquisicaomoeda         = (wvaloraquisicao / wvalormoeda);
    
          SUSPEND;
          EXIT;
        END

      IF (wdatainiciocalc IS NOT NULL) THEN
        wdataoficialiniciolcalculo = wdatainiciocalc;
      ELSE
        wdataoficialiniciolcalculo =  wdataaquisicao;

      IF (wvaloraquisicao = 0) THEN
        EXIT;
      -- Joga para uma vari?vel o numero de meses que j? foi depreciado em outro sistema
      IF (wvaldepacumubem > 0) THEN
        wmesesdepacumubem = ((wvaldepacumubem) / (wvaloraquisicao / wtotalmesesdepreciacao));

      wdatatotalmeses       = addmonth(wdataoficialiniciolcalculo, wtotalmesesdepreciacao-wmesesdepacumubem);
      wdatatotalmesesdepdia = addmonth(wdatatotalmeses, 1);
      -- Transforma no primeiro dia do m?s
      wdatatotalmeses       = SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
      wdataaquisicao        = SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
    
      SELECT bdMESES FROM DIFERENCA_MESES(:wdatatotalmeses,:wdataatual) INTO :wdiferencameses ;
      ---------------wdiferencameses = datediff(month,:wdatatotalmeses,:wdataatual); --------------------
      IF (wdiferencameses-1 > 0) THEN
        BEGIN
         IF (wdepmensal = 'FALSE') THEN
           SELECT BDNOVADATA FROM add_meses(:wdatatotalmeses,1) INTO wdataatual;
         ELSE
           wdataatual = wdatatotalmeses;
        END

      IF ((wdepmensal = 'FALSE') AND
          (CAST(EXTRACT(YEAR FROM wdatainicial) || EXTRACT(MONTH FROM wdatainicial) AS INTEGER) = --
           CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
        BEGIN
        SELECT BDNOVADATA FROM diminui_meses(:wdatafinal,1) INTO wdatafinal; -- tinha prdatafinal ---------------
        ---------------wdatafinal = addmonth(:wdatafinal,-1);
        END
    
      -- Se for relatorio de baixas, a data atual devera ser o do mes da baixa.
      IF ((prtipo = 2) OR ((wdatabaixa IS NOT NULL) AND (wvalorbaixa >= wvaloraquisicao))) THEN
        BEGIN
          wdataatual  = wdatabaixa;
          wdatafinal = wdatabaixa; -- tinha prdatafinal
        END
    
       IF ((wdatafimcalc IS NOT NULL) AND (wdatafimcalc < wdatafinal)) THEN -- tinha prdatafinal
         BEGIN
           wdataatual = wdatafimcalc;
           wdatafinal = wdatafimcalc; -- tinha prdatafinal
         END

      SELECT bdMESES FROM DIFERENCA_MESES(:wdataoficialiniciolcalculo,:wdataatual) INTO :wmesesdepreciados;
      ---------------wmesesdepreciados = datediff(month,:wdataoficialiniciolcalculo,:wdataatual); --------------------
      IF ((wdepmensal = 'FALSE') OR (wvaldepacumubem > 0)) THEN
        wmesesdepreciados = wmesesdepreciados - 1;
    
      -- Adiciona no total de meses depreciados o valor j? depreciado de outro sistema
      IF ((wvaldepacumubem > 0) AND (wmesesdepreciados >= 0)) THEN
        wmesesdepreciados = wmesesdepreciados + ((wvaldepacumubem) / (wvaloraquisicao / wtotalmesesdepreciacao));
    
      IF (wmesesdepreciados > wtotalmesesdepreciacao) THEN
        wmesesdepreciados = wtotalmesesdepreciacao;

      -- Se os meses decreciados for menor que zero, significa que foi informado uma data inferior a data de aquisicao do bem
      IF (wmesesdepreciados > 0) THEN
        BEGIN
          -- Total de meses da diferen?a do periodo de deprecia??o
          wmes = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;
          wdatatotalmesesultimodia = wmes||'-'||wultdiames||'-'||wano;
          IF (wdatafinal > wdatatotalmesesultimodia) THEN -- tinha prdatafinal
            BEGIN
              IF (wdepdia = 'TRUE') THEN
                BEGIN
                  -- Caso seja o ?ltimo m?s para depreciar
                  IF (wmesesdepreciar = 0) THEN
                    wdepdiafinal = 'TRUE';
        
                  wdatatotalmesesultimodia = addmonth(wdatatotalmesesultimodia, 1);
                  wdatatotalmesesultimodia = SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                                             SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
                END
            END
        
          IF (wdatafinal > wdatatotalmeses) THEN -- tinha prdatafinal
            wdatafinal = wdatatotalmeses; -- tinha prdatafinal
        
          IF (wdatainicial < :wdataoficialiniciolcalculo) THEN --
            wdatainicial = wdataoficialiniciolcalculo; --
        
          SELECT bdMESES FROM DIFERENCA_MESES(:wdatainicial,:wdatafinal) INTO :wtotalmesesdoperiodo; -- tinha prdatafinal
          ---------------wtotalmesesdoperiodo = datediff(month,:wdatainicial,:wdatafinal); --------------------
          IF ((wvaldepacumubem > 0) AND (wdatainicial <= wdataorigaquisicao)) THEN --
            wtotalmesesdoperiodo = wtotalmesesdoperiodo-1;
          
          -- Meses ? depreciar
          wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);
          wvaloraquisicaomoeda = (wvaloraquisicao / wvalormoeda);
          -- Deprecia??o do per?odo
          wvalordepreciacaomensal = (wvaloraquisicaomoeda / wtotalmesesdepreciacao);
    
          IF (wdepdiasadepreciar > 0) THEN
            BEGIN
              wvalordepreciacaodiaria     = (wvalordepreciacaomensal * wvalormoeda) / 30 * wdepdiasadepreciar;
              prvalordepreciacaodiariafim = (wvalordepreciacaomensal * wvalormoeda) - wvalordepreciacaodiaria;
            END
        
          IF (wdepdia = 'TRUE') THEN
            BEGIN
              -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
              wmesesdepreciar      = wmesesdepreciar + 1;
              wmesesdepreciados    = wmesesdepreciados - 1;
              wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;
            END
    
          IF (wdatainicial <= :wdataaquisicao) THEN
            BEGIN
              wdepreciacaoperiodo      = ((wvalordepreciacaodiaria) + wvalordepreciacaomensal * wtotalmesesdoperiodo * wvalormoeda);
              wdepreciacaoperiodomoeda = ((wvalordepreciacaodiaria / wvalormoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
            END
          ELSE
          IF (wdepdia = 'TRUE') THEN
            BEGIN
              wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo + 1) * wvalormoeda);
              wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo+1);
            END
          ELSE
            BEGIN
              wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo) * wvalormoeda);
              wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo);
            END
    
          -----------------------------------------------------------------------------------
          IF ((wvalordepreciacaodiaria > 0) AND (wdatainicial <= :wdataaquisicao))  THEN
            BEGIN
              wdepreciacaoacumuladaatual = wvalordepreciacaomensal * wmesesdepreciados;
              wdepreciacaoacumuladaatual = wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * wvalormoeda;
        
              wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
            END
          ELSE
            BEGIN
              wdepreciacaoacumuladaatual = wvalordepreciacaomensal * wmesesdepreciados;
              wdepreciacaoacumuladaatual = wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * wvalormoeda;
        
              IF (wvalordepreciacaodiaria > 0) THEN
                wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
              ELSE
                wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual -  ((wvalordepreciacaomensal * (wtotalmesesdoperiodo) * wvalormoeda)));
            END
    
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            wvalorcorrigidoanterior = wvaloraquisicao;
        
          IF (wdepreciacaoacumuladaanterior < 0) THEN
            wdepreciacaoacumuladaanterior = 0;
    
          wdepreciacaoacumuladaatualmoed = (wvalordepreciacaodiaria/wvalormoeda) + wvalordepreciacaomensal * wmesesdepreciados;
          wcorrecaomonetariadepreciacao  = 0;
          wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          wvalorresidualcontabilmoeda    = wvalorresidualcontabil / wvalormoeda;
          wdepreciacaobaixamoeda         = (wvalorbaixa / wtotalmesesdepreciacao);
          wdepreciacaobaixamoeda         = (wdepreciacaobaixamoeda / wvalormoeda);
    
          IF (prtipo = 2) THEN
            BEGIN
              prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
              prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior) / wvalormoeda;
            END
          ELSE
            BEGIN
              prvalorcorrigidoanterior      = wvalorcorrigidoanterior + wvalorbaixa;
              prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior + wvalorbaixa) / wvalormoeda;
            END
    
          IF ((wdepdia = 'TRUE')  AND (wdepdiafinal = 'TRUE')) THEN
            BEGIN
              IF (wdatainicial <= :wdataaquisicao) THEN
                BEGIN
                  wdepreciacaoperiodo      = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo * wvalormoeda);
                  wdepreciacaoperiodomoeda = (((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) / wvalormoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
        
                  wdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim;
                  wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual / wvalormoeda;
        
                  wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
                  wvalorresidualcontabilmoeda = 0;
        
                  wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
                END
              ELSE
                BEGIN
                  SELECT BDNOVADATA FROM diminui_meses(:wdatatotalmesesultimodia,1) INTO wdatatotalmesesultimodia;
                  ---------------wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);----------------------
        
                  wdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim;
                  wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual / wvalormoeda;
        
                  wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
                  wvalorresidualcontabilmoeda = 0;
        
                  IF (wdatainicial <> :wdatatotalmesesultimodia) THEN
                    BEGIN
                      wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
                      wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaanterior / wvalormoeda);
                    END
        
                  wdepreciacaoperiodo = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;
        
                  IF (wdepreciacaoperiodo <= 0) THEN
                    wdepreciacaoperiodomoeda = 0;
                  ELSE
                    wdepreciacaoperiodomoeda = ((wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior) / wvalormoeda);
                END
        
              wmesesdepreciados = wmesesdepreciados + 1;
              wmesesdepreciar   = 0;
            END
    
          prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;
          prdepreciacaoperiodo            = wdepreciacaoperiodo;
          prdepreciacaoperiodomoeda       = wdepreciacaoperiodomoeda;
          prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
          prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
          prcorrecaomonetariadepreciacao  = wcorrecaomonetariadepreciacao;
          prvalorresidualcontabil         = wvalorresidualcontabil;
          prvalorresidualcontabilmoeda    = wvalorresidualcontabilmoeda;
          prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
          prmesesdepreciados              = wmesesdepreciados;
          prmesesdepreciar                = wmesesdepreciar;
          prdatataxadepreciacao           = wdataultimoitemdep;
          prvalorbaixa                    = wvalorbaixa;
          prdepreciacaobaixamoeda         = wdepreciacaobaixamoeda;
          prvalorbaixareal                = wvalorbaixa;
          prvalormoeda                    = wvalormoeda;
          prdatabaixa                     = wdatabaixa;
          prvaloraquisicaomoeda           = wvaloraquisicaomoeda;
        END

      wdtini  = addmonth(wdtini, 1);
      wmes    = CAST(SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
      wano    = CAST(EXTRACT(YEAR FROM wdtini) AS INTEGER);
      wdtini  = wmes||'-01-'||wano;
      wdtfim  = addmonth(wdtini, 1)-1;
      wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  SUSPEND;
END
^

/* Alter (SP_CALC_EXP_SEFIP_COMPLEMENTAR) */
ALTER PROCEDURE SP_CALC_EXP_SEFIP_COMPLEMENTAR(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRCODAUT VARCHAR(20000),
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAGRUPAR INTEGER,
PRTIPOFC INTEGER = 1,
PRCODREC INTEGER = 0)
 RETURNS(BDMODALIDADE VARCHAR(20),
BDTERC INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDANOMESRESC INTEGER,
BDGRRFPRES INTEGER,
BDCALCFGTSMESANT VARCHAR(5),
BDBASEFGTSFOL NUMERIC(18,6),
BDBASEFGTS13 NUMERIC(18,6),
BDVALINSS NUMERIC(18,6),
BDVALINSS13 NUMERIC(18,6),
BDBASEINSS NUMERIC(18,6),
BDBASEINSSCALC13 NUMERIC(18,6),
BDBASEINSS13 NUMERIC(18,6),
BDSALFAM NUMERIC(18,6),
BDVALFGTS NUMERIC(18,6),
BDVALFGTS13 NUMERIC(18,6),
BDPERCFGTSCOL NUMERIC(18,6),
BDVALINSSFC NUMERIC(18,6),
BDVALINSS13FC NUMERIC(18,6),
BDBINSSC13 NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDINSS13DT NUMERIC(18,6),
BDVALINSSC13 NUMERIC(18,6),
BDTEMMODALIDADE0 DM_BOOLEAN,
BDMOVRESCSEFIP VARCHAR(5),
BDPISCOL VARCHAR(14),
BDPISTERC VARCHAR(14),
BDOCORRENCIACOL INTEGER,
BDCATEGORIA INTEGER,
BDDATAADMCOL DATE)
 AS
declare variable WMODALIDADE integer;
declare variable WSQL varchar(30000);
declare variable WPARFOLHANORMAL varchar(30000);
declare variable WPARCOMPANT varchar(30000);
declare variable WPARCOMPATU varchar(30000);
declare variable WTEMMODALIDADE0 smallint;
declare variable WREFFC integer;
declare variable WBFGTSIND numeric(15,6);
declare variable WDATAGRRF date;
declare variable WBFGTSSEFIP numeric(18,6);
BEGIN
--   prcodemp = 'colcon.bdcodemp = 3';
--   pranomes = 201003;
--   pragrupar = 3;
  BDINSS13DT = 0;

   IF (prcodemp IS NULL) THEN
      BEGIN
        wparfolhanormal = 'null,';
        wparcompant = 'null,';
        wparcompatu = 'null,';
      END
   ELSE
      BEGIN
        wparfolhanormal = ''''||prcodemp||''''||',';
        wparcompant = ''''||prcodemp||''''||',';
        wparcompatu = ''''||prcodemp||''''||',';
      END

   IF (prcodcol IS NULL) THEN
      BEGIN
        wparfolhanormal = wparfolhanormal||'null,';
        wparcompant = wparcompant||'null,';
        wparcompatu = wparcompatu||'null,';
      END
   ELSE
      BEGIN
        wparfolhanormal = wparfolhanormal||''''||prcodcol||''''||',';
        wparcompant = wparcompant||''''||prcodcol||''''||',';
        wparcompatu = wparcompatu||''''||prcodcol||''''||',';
      END

   /* Aut?nomos */
   IF (prcodaut IS NULL) THEN
     wparfolhanormal = wparfolhanormal||'null,';
   ELSE
     wparfolhanormal = wparfolhanormal||''''||prcodaut||''''||',';

   /*pranomes*/
   wparfolhanormal = wparfolhanormal||pranomes||',';
   wparcompant = wparcompant||pranomes||',null,';
   wparcompatu = wparcompatu||pranomes||',null,';

   /*pranomespag*/
   IF (pranomespag IS NULL) THEN
      pranomespag = pranomes;
   wparfolhanormal = wparfolhanormal||pranomespag||',';

   -- deve trazer todos os pagamentos ate o mes anterior
   IF (SUBSTRING(pranomespag FROM 5 FOR 2) = '01') THEN
     wparcompant = wparcompant||pranomes||','||(CAST(SUBSTRING(pranomespag FROM 1 FOR 4) AS INTEGER) - 1)||'12'||',';
   ELSE
     wparcompant = wparcompant||pranomes||','||(pranomespag-1)||',';

   wparcompatu = wparcompatu||pranomespag||',null,'; -- deve trazer apenas o pagamento do mes atual

   /* pragrupar */
   wparfolhanormal = wparfolhanormal||pragrupar;
   wparcompant = wparcompant||pragrupar;
   wparcompatu = wparcompatu||pragrupar;

   /* tipo folha complementar */
   wparcompant = wparcompant||','||prtipofc;
--   wparcompatu = wparcompatu||','||prtipofc;
   wparcompatu = wparcompatu||','||'0';

   BDVALINSSFC = 0;
   bdvalinss13fc = 0;

   wsql = 'select * from (';
   IF (PRTIPOFC = 1) THEN
      BEGIN
         wsql = wsql||
                'select 9 BDMODALIDADE, base.bdterc, base.bdcodemp, base.bdcodcol, base.bdcodtpcc, base.bdcodcentro, max(base.bdanomesresc) bdanomesresc, max(base.bdgrrfpres) bdgrrfpres,'||
                     'max(base.bdcalcfgtsmesant) bdcalcfgtsmesant, sum(base.bdbasefgtsfol) bdbasefgtsfol, sum(base.bdbasefgts13) bdbasefgts13, sum(base.bdvalinss) bdvalinss, sum(base.bdvalinss13) bdvalinss13,'||
                     'sum(base.bdbaseinss) bdbaseinss, sum(base.bdbaseinsscalc13) bdbaseinsscalc13, sum(base.bdbaseinss13) bdbaseinss13, sum(base.bdsalfam) bdsalfam, sum(base.bdvalfgts) bdvalfgts, sum(base.bdvalfgts13) bdvalfgts13, '||
                     'max(COLFGTS.BDPERCFGTSCOL) BDPERCFGTSCOL , 0 bdvalinssfc, 0 bdvalinss13fc, sum(base.bdbinssapfn) bdbinssapfn, sum(base.bdbinss13apfn) bdbinss13apfn, sum(base.bdinssapfn) bdinssapfn, sum(base.bdinss13apfn) bdinss13apfn, '||
                     '0 BDVALINSSC13, base.bdreffc, base.BDMOVRESCSEFIP, DOCREF.bdpiscol, '''' BDPISTERC, max(COALESCE(COLFGTS.bdocorrenciacol,0)) bdocorrenciacol, '||
                     'max(COALESCE(COLFGTS.bdcategoriacol,0)) bdcategoriacol , max(base.BDDATAGRRF) BDDATAGRRF, max(colcon_cad.BDDATAADMCOL) BDDATAADMCOL '||
                'from ('||
                     ' select x.bdterc, x.bdcodemp, x.bdcodcol, x.bdcodtpcc, x.bdcodcentro, x.bdanomesresc,'||
                            ' COALESCE(x.bdgrrfpres,0) bdgrrfpres, x.bdcalcfgtsmesant, x.bdbasefgtsfol, x.bdbasefgts13, x.bdvalinss,'||
                            ' x.bdvalinss13, x.bdbaseinss, x.bdbaseinsscalc13, x.bdbaseinss13, x.bdsalfam, x.bdvalfgts, x.bdvalfgts13, x.bdbinssapfn, x.bdbinss13apfn,'||
                            ' x.bdinssapfn, x.bdinss13apfn, '||pranomes||' BDREFFC, x.BDMOVRESCSEFIP, CAST(null as DATE) BDDATAGRRF '||
                     ' from sp_calc_exp_sefip('||wparfolhanormal||',0) x'||
                     ' union all '||
                     ' select case when GCLA.BDCODGRUPOCLA in (3,11) then 3 when GCLA.BDCODGRUPOCLA = 2 then 2 else 1 end, y.bdcodemp, y.bdcodcol, y.bdcodtpcc, y.bdcodcentro, -1, -1, ''FALSE'', coalesce(y.BDBFGTSFC,0),'||
                            ' coalesce(y.BDBFGTS13FC,0), coalesce(y.BDINSSFC,0), coalesce(y.BDINSS13FC,0), coalesce(y.BDBINSSFC,0),'||
                            ' 0, coalesce(y.BDBINSS13FC,0), coalesce(y.BDSALFAMFC,0), coalesce(y.BDFGTSFC,0), coalesce(y.BDFGTS13FC,0), '||
                            ' coalesce(y.bdbinssapfc,0), coalesce(y.bdbinss13apfc,0), coalesce(y.bdinssapfc,0), coalesce(y.bdinss13apfc,0), Y.BDREFFC, cast(null as varchar(5)), y.BDDATAGRRF '||
                     ' from vrhf_sp_tfolhacomp('||wparcompant||') y '||
                     ' left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.BDCODEMP = y.bdcodemp and COLVINC.BDCODCOL = y.bdcodcol) '||
                     ' left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) '||
                     ' left outer join TGRUPOCLASSECOL GCLA on (GCLA.BDCODGRUPOCLA = CLA.BDGRUPOCLA) '||
                ') base'||
                ' left outer join vw_vrhf_emp_tcolcon_fgtsgps COLFGTS on (BASE.BDCODEMP = COLFGTS.BDCODEMP and BASE.BDCODCOL = COLFGTS.BDCODCOL) '||
                ' left outer join vw_vrh_emp_tcolcon_docref DOCREF on (DOCREF.bdcodemp = base.bdcodemp and DOCREF.bdcodcol = base.bdcodcol) '||
                ' left outer join VRH_EMP_TCOLCON colcon_cad on (colcon_cad.BDCODEMP = base.BDCODEMP and colcon_cad.BDCODCOL = base.BDCODCOL) '||
                ' where not exists('||
                        'select z.BDCODEMP, z.BDCODCOL , z.bdcodtpcc '||
                        'from vrhf_sp_tfolhacomp('||wparcompatu||') z '||
                        'where z.BDCODEMP = base.BDCODEMP and z.BDCODCOL = base.BDCODCOL and coalesce(z.bdcodtpcc,0) = coalesce(base.bdcodtpcc,0)'||
                ')'||
                ' group by bdterc, bdcodemp, bdcodcol, bdcodtpcc, bdcodcentro, bdreffc, BDMOVRESCSEFIP, bdpiscol '||
                ' union all ';
      END

   wsql = wsql||
          ' select 0 BDMODALIDADE, case when GCLA.BDCODGRUPOCLA in (3,11) then 3 when GCLA.BDCODGRUPOCLA = 2 then 2 else 1 end bdTERC, y.bdcodemp, y.bdcodcol, y.bdcodtpcc, '||
               'y.bdcodcentro, res.bdrefrescisao bdanomesresc, COALESCE(pres.bdgrrfpres,0) bdgrrfpres, ''FALSE'' bdcalcfgtsmesant, coalesce(y.BDBFGTSFC,0) bdbasefgtsfol,'||
               ' coalesce(y.BDBFGTS13FC,0) bdbasefgts13, coalesce(y.BDINSSFC,0) ';

  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdvalinss,0) ';

   wsql = wsql||'bdvalinss, coalesce(y.BDINSS13FC,0) ';

  IF (PRCODREC <> 650) THEN
      wsql = wsql||' + coalesce(fb.bdvalinss13,0) ';

   wsql = wsql||'bdvalinss13, coalesce(y.BDBINSSFC,0) ';

  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdbaseinss,0) ';

  IF (PRCODREC <> 650) THEN
     wsql = wsql||'bdbaseinss, coalesce(fb.BDBASEINSSCALC13, 0) ';
  ELSE
     wsql = wsql||'bdbaseinss, 0 ';

  wsql = wsql||'bdbaseinsscalc13, coalesce(y.BDBINSS13FC,0) ';

  IF (PRCODREC <> 650) THEN
      wsql = wsql||' + coalesce(fb.bdbinss13,0) ';

  wsql = wsql||'bdbaseinss13, coalesce(y.BDSALFAMFC,0) bdsalfam, coalesce(y.BDFGTSFC,0) bdvalfgts, coalesce(y.BDFGTS13FC,0) bdvalfgts13, 0 BDPERCFGTSCOL, coalesce(y.BDINSSFC,0) bdvalinssfc, coalesce(y.BDINSS13FC,0) bdvalinss13fc';


  wsql = wsql||', coalesce(y.bdbinssapfc,0) ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdbinssapfn,0) ';

  wsql = wsql||'bdbinssapfn, coalesce(y.bdbinss13apfc,0) ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdbinss13apfn,0) ';

  wsql = wsql||'bdbinss13apfn, coalesce(y.bdinssapfc,0) ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdinssapfn,0) ';

  wsql = wsql||'bdinssapfn, coalesce(y.bdinss13apfc,0) ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdinss13apfn,0) ';

  wsql = wsql||'bdinss13apfn, 0 ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.BDVALINSSC13,0) ';

  wsql = wsql||'BDVALINSSC13, y.bdreffc, motsefip.BDCODSEFMFG, DOCREF.BDPISCOL, '''' BDPISTERC, COLFGTS.bdocorrenciacol, '||
               'COLFGTS.bdcategoriacol, COALESCE(y.BDDATAGRRF, y.BDDATAPAGFC) BDDATAGRRF, colcon_cad.BDDATAADMCOL ';

  wsql = wsql||' from vrhf_sp_tfolhacomp('||wparcompatu||') y '||
               ' left outer join vw_vrhf_emp_tcolcon_fgtsgps COLFGTS on (y.BDCODEMP = COLFGTS.BDCODEmP and y.BDCODCOL = COLFGTS.BDCODCOL) '||
               ' left outer join vw_vrh_emp_tcolcon_docref DOCREF on (DOCREF.bdcodemp = y.bdcodemp and DOCREF.bdcodcol = y.bdcodcol) '||
               ' left outer join vrh_emp_trescisao res on (y.bdcodemp = res.bdcodemp and y.bdcodcol = res.bdcodcol and res.bdrefrescisao <= y.bdreffn) '||
               ' left outer join vrh_base_tprepresc pres on (pres.bdcodpres = res.bdcodpres) '||
               ' left outer join VRH_BASE_TMOTFGTS motsefip on (motsefip.bdcodmfg = pres.bdcodmfg) '||
               ' left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.BDCODEMP = y.bdcodemp and COLVINC.BDCODCOL = y.bdcodcol) '||
               ' left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) '||
               ' left outer join TGRUPOCLASSECOL GCLA on (GCLA.BDCODGRUPOCLA = CLA.BDGRUPOCLA) '||
               ' left outer join VRH_EMP_TCOLCON colcon_cad on (colcon_cad.BDCODEMP = y.BDCODEMP and colcon_cad.BDCODCOL = y.BDCODCOL) ';

--               ' left outer join (select bdcodemp,bdcodcol,bdcodtpcc, bdcodcentro, sum(bdbaseinssfn) bdbaseinss,sum(bdbaseinss13) bdbinss13, sum(bdvalinss) bdvalinss, sum(bdvalinss13) bdvalinss13 from ('||

  IF (PRCODREC <> 650) THEN
     BEGIN
       wsql = wsql||
                   ' left outer join (select bdcodemp,bdcodcol,bdcodtpcc, bdcodcentro, sum(bdbaseinssfn) bdbaseinss,sum(bdbaseinss13) bdbinss13, sum(bdvalinss) bdvalinss, sum(bdvalinss13) bdvalinss13, sum(bdbinssapfn) bdbinssapfn, sum(bdbinss13apfn) bdbinss13apfn, sum(bdinssapfn) bdinssapfn, sum(bdinss13apfn) bdinss13apfn, sum(bdbaseinsscalc13) bdbaseinsscalc13, sum(bdvalinssc13) bdvalinssc13 from ('||
                   '         select k.bdcodemp,k.bdcodcol,k.bdcodtpcc, k.bdcodcentro, coalesce(k.bdbaseinss,0) bdbaseinssfn,k.bdbaseinss13, coalesce(k.bdvalinss,0) bdvalinss, coalesce(K.BDVALINSS13, 0) BDVALINSS13, '||
                                   'coalesce(k.bdbinssapfn,0) bdbinssapfn, coalesce(k.bdbinss13apfn,0) bdbinss13apfn, coalesce(k.bdinssapfn,0) bdinssapfn, coalesce(k.bdinss13apfn,0) bdinss13apfn, coalesce(k.bdbaseinsscalc13, 0) bdbaseinsscalc13, coalesce(K.BDVALINSSC13, 0) BDVALINSSC13  '||
                   '         from sp_calc_exp_sefip('||wparfolhanormal||',0) k '||
                   '         union all '||
                   '         select s.bdcodemp,s.bdcodcol, s.bdcodtpcc, s.bdcodcentro, coalesce(s.bdbinssfc,0)+coalesce(s.bdbinssfefolfc,0) bdbaseinssfn,s.bdbinss13fc, coalesce(s.bdinssfc,0)+coalesce(s.bdinssfefolfc,0),coalesce(s.BDINSS13FC,0), '||
                                   'coalesce(s.bdbinssapfc,0), coalesce(s.bdbinss13apfc,0), coalesce(s.bdinssapfc,0), coalesce(s.bdinss13apfc,0), 0 bdbaseinsscalc13, 0 BDVALINSSC13 '||
                   '         from vrhf_sp_tfolhacomp('||wparcompant||') s '||
                   '         ) group by bdcodemp,bdcodcol, bdcodtpcc, bdcodcentro) fb '||
                   '              on (y.bdcodemp = fb.bdcodemp and fb.bdcodcol = y.bdcodcol and '||
                   '               (fb.bdcodtpcc = y.bdcodtpcc or (fb.bdcodtpcc is null and y.bdcodtpcc is null) ) and '||
                   '               (fb.bdcodcentro = y.bdcodcentro or (fb.bdcodcentro is null and y.bdcodcentro is null) )) ';
    END

    IF (prtipofc > 1) THEN
       BEGIN
         wsql = wsql||' where y.BDCODTIPOFC = '||prtipofc;
       END

    wsql = wsql||') order by BDMODALIDADE, BDTERC, BDGRRFPRES, BDANOMESRESC ';


    SELECT rdb$get_context('USER_SESSION', 'W_TIPOFOLHA') FROM rdb$database INTO wparcompatu;

    SELECT rdb$set_context('USER_SESSION', 'W_TIPOFOLHA', '0') FROM rdb$database INTO wparcompant;
    wtemmodalidade0 = 0;
    FOR EXECUTE STATEMENT wsql INTO
         : wmodalidade,
         : BDTERC,
         : BDCODEMP,
         : BDCODCOL,
         : BDCODTPCC,
         : BDCODCENTRO,
         : BDANOMESRESC,
         : BDGRRFPRES,
         : BDCALCFGTSMESANT,
         : BDBASEFGTSFOL,
         : BDBASEFGTS13,
         : BDVALINSS,
         : BDVALINSS13,
         : BDBASEINSS,
         : BDBASEINSSCALC13,
         : BDBASEINSS13,
         : bdsalfam,
         : bdvalfgts,
         : bdvalfgts13,
         : BDPERCFGTSCOL,
         : bdvalinssfc,
         : bdvalinss13fc,
         : BDBINSSAPFN,
         : BDBINSS13APFN,
         : BDINSSAPFN,
         : BDINSS13APFN,
         : BDVALINSSC13,
         : wreffc,
         : BDMOVRESCSEFIP,
         : BDPISCOL,
         : BDPISTERC,
         : BDOCORRENCIACOL,
         : BDCATEGORIA,
         : wdatagrrf,
         : BDDATAADMCOL
  DO
  BEGIN
    BDBINSSC13 = 0;
    WBFGTSSEFIP = 0;
    IF (wmodalidade = 9) THEN
       bdmodalidade = '9';
    ELSE
       bdmodalidade = ' ';

    IF (prtipofc = 3) THEN
       BEGIN
         wparcompant = 'select SUM(BDVALVFC) from ('||
                          'select FC.BDVALVFC from VRHF_EMP_TVERBAFC FC '||
                          'join VRHF_EMP_TFOLHACOMP FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFFN = FC.BDREFFN and FCN.BDREFFC = FC.BDREFFC) '||
                          'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                          'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                          'where FC.BDCODEMP = '||BDCODEMP||' and FC.BDCODCOL = '||BDCODCOL||' and FC.BDREFFN <= '||pranomes||' and FC.BDREFFC = '||wreffc||
                          ' and (VER.BDCLAVER like '''||'7.060%'''||') '||
                          'and VERF.BDFGTSVER > 0 '||
                          'union all '||
                          'select FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR FC '||
                          'join VRHF_EMP_TFOLTOMCOMP FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFTOMADOR = FC.BDREFTOMADOR and FCN.BDREFFC = FC.BDREFFC and FCN.BDORDEM = FC.BDORDEM) '||
                          'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                          'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                          'where FC.BDCODEMP = '||BDCODEMP||' and FC.BDCODCOL = '||BDCODCOL||' and FC.BDREFTOMADOR <= '||pranomes||' and FC.BDREFFC = '||wreffc||
                          ' and (VER.BDCLAVER like '''||'7.060%'''||') '||
                          'and VERF.BDFGTSVER > 0) ';

         EXECUTE STATEMENT wparcompant INTO :wbfgtsind;

         IF (wbfgtsind IS NULL) THEN
            wbfgtsind = 0;

         BDBASEFGTS13 = BDBASEFGTS13 - wbfgtsind;

         --Sol. 17956 - Bruno L. R. - 07/07/2017
         IF (wdatagrrf IS NOT NULL) THEN
            BEGIN
              wparcompant = 'select BDBFGTSMESSEFIP from VRHF_EMP_VAL_GRRF_FC('||BDCODEMP||', '||BDCODCOL||', '||pranomes||', '''||wdatagrrf||''', 3)';
            END
         ELSE
            wparcompant = 'select BDBFGTSMESSEFIP from VRHF_EMP_VAL_GRRF_FC('||BDCODEMP||', '||BDCODCOL||', '||pranomes||', null, 3)';
         --Sol. 17956 - Bruno L. R. - 07/07/2017

         EXECUTE STATEMENT wparcompant INTO :wbfgtssefip;

         IF ((wbfgtssefip IS NULL) OR (wbfgtssefip < 0)) THEN
            wbfgtssefip = 0;
       END

    IF (BDBASEFGTSFOL IS NULL) THEN
       BDBASEFGTSFOL = 0;
    IF (BDBASEFGTS13 IS NULL) THEN
       BDBASEFGTS13 = 0;
    IF (BDVALINSS IS NULL) THEN
       BDVALINSS = 0;
    IF (BDVALINSS13 IS NULL) THEN
       BDVALINSS13 = 0;
    IF (BDBASEINSS IS NULL) THEN
       BDBASEINSS = 0;
    IF (BDBASEINSSCALC13 IS NULL) THEN
       BDBASEINSSCALC13 = 0;
    IF (BDBASEINSS13 IS NULL) THEN
       BDBASEINSS13 = 0;
    IF (bdvalfgts IS NULL) THEN
       bdvalfgts = 0;
    IF (bdvalfgts13 IS NULL) THEN
       bdvalfgts13 = 0;
    IF (bdpercfgtscol IS NULL) THEN
       bdpercfgtscol = 0;
    IF (bdvalinssc13 IS NULL) THEN
       bdvalinssc13 = 0;

    IF (((BDBASEFGTSFOL <> 0) OR (BDBASEFGTS13 <> 0)) AND ((BDMOVRESCSEFIP IS NULL) OR (BDMOVRESCSEFIP <> 'I1' AND BDMOVRESCSEFIP <> 'I2' AND BDMOVRESCSEFIP <> 'I3' AND BDMOVRESCSEFIP <> 'I4' AND BDMOVRESCSEFIP <> 'I5' AND BDMOVRESCSEFIP <> 'L'))) THEN
         wtemmodalidade0 = 1;
    ELSE
       BEGIN
         IF (BDMODALIDADE = ' ' AND wtemmodalidade0 < 1) THEN
            BEGIN
              IF (wbfgtssefip > 0) THEN
                 wtemmodalidade0 = 1;
              ELSE
                 BDMODALIDADE = '1';
            END

         IF (wtemmodalidade0 < 1) THEN
            wtemmodalidade0 = 0;
       END

    IF (wtemmodalidade0 = 1) THEN
       BDTEMMODALIDADE0 = 'TRUE';
    ELSE
       BDTEMMODALIDADE0 = 'FALSE';

    IF ((BDBASEFGTSFOL <> 0) OR (BDBASEFGTS13 <> 0) OR (BDBASEINSS <> 0) OR (BDBASEINSSCALC13 <> 0) OR (BDBASEINSS13 <> 0)) THEN
       SUSPEND;
  END

  SELECT rdb$set_context('USER_SESSION', 'W_TIPOFOLHA', :wparcompatu) FROM rdb$database INTO wparcompant;

END
^

/* Alter (SP_CARREGAR_TMP_TCADPRO) */
ALTER PROCEDURE SP_CARREGAR_TMP_TCADPRO(PRINICIALIZANDOSERVIDOR DM_BOOLEAN)
 AS
DECLARE VARIABLE WCODPROD INTEGER;
BEGIN
  --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
  IF (UPPER(:PRINICIALIZANDOSERVIDOR) = 'TRUE') THEN
    BEGIN
      DELETE FROM TMP_TCADPRO WHERE BDSESSAO IS NOT NULL;
      DELETE FROM TMP_TCADPRO_PART WHERE BDSESSAO IS NOT NULL;
      DELETE FROM TMP_TCADPRO_A_VALIDAR WHERE BDCODPROD IS NOT NULL;
    END
    
  /*Verifica se j? n?o existe dado na TMP_TCADPRO*/
  wCodProd = NULL;
  SELECT FIRST 1 BDCODPROD FROM TMP_TCADPRO INTO :wCodProd;

  IF ((:wCodProd IS NULL) OR (:wCodProd = 0)) THEN
    BEGIN
      /*Insert dos produtos unicos*/
      INSERT INTO TMP_TCADPRO (BDSESSAO, BDEDITCHAVE, BDCODPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA,
                               BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, BDCODCOMBANP)
      SELECT 0 BDSESSAO,
             PRO.BDCODPROD BDEDITCHAVE,
             PRO.BDCODPROD,
             PRO.bdapelidounico bdAPELIDOUNICO,
             PRO.bddescricaounica BDDESCRICAOUNICA,
             PRO.bdcodigoean BDCODIGOEAN,
             COALESCE(PRO.BDCODTIPO,0) BDCODTIPO,
             COALESCE(PRO.BDCODGEN,0) BDCODGEN,
             COALESCE(PRO.BDCODSER,0) BDCODSER,
             COALESCE(PRO.BDCODCOMBANP,0) BDCODCOMBANP
      FROM TCADPRO PRO;

      /*Insere os produtos por empresa*/
      INSERT INTO TMP_TCADPRO (BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODEMP, BDCODSAIDA, BDAPEPROD, BDDESCPROD,
                               BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER,
                               BDCODCOMBANP, BDCODUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA,
                               BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT,
                               BDCODCSTCOFENT, BDCODCSTCOFSAI)
      SELECT 0 BDSESSAO,
             PRO.BDCODPROD BDEDITCHAVE,
             PRO.BDCODPROD,
             PROV.BDCODEMP,
             COALESCE(PROV.bdcodsaida, '') BDCODsaida,
             PROV.bdapeprod bdapeprod,
             PROV.bddescprod bddescproD,
             PRO.bdapelidounico bdAPELIDOUNICO,
             PRO.bddescricaounica BDDESCRICAOUNICA,
             PRO.bdcodigoean BDCODIGOEAN,
             COALESCE(PRO.BDCODTIPO,0) BDCODTIPO,
             COALESCE(PRO.BDCODGEN,0) BDCODGEN,
             COALESCE(PRO.BDCODSER,0) BDCODSER,
             COALESCE(PRO.BDCODCOMBANP,0) BDCODCOMBANP,
             COALESCE(PROV.BDCODUNIMED,0) BDCODUNIMED,
             COALESCE(PROV.BDNCMPROD,0) BDNCMPROD,
             COALESCE(PROV.bdcodtabincid,0) BDCODTABINCID,
             COALESCE(PROV.bdgrupo,0) BDGRUPO,
             COALESCE(PROV.bdordemmarca,0) BDORDEMMARCA,
             COALESCE(PROV.BDCODCSTIPISAI,0) BDCODCSTIPISAI,
             COALESCE(PROV.BDCODCSTIPIENT,0) BDCODCSTIPIENT,
             COALESCE(PROV.BDCODCSTICMS,0) BDCODCSTICMS,
             COALESCE(PROV.BDCODCSTPISSAI,0) BDCODCSTPISSAI,
             COALESCE(PROV.BDCODCSTPISENT,0) BDCODCSTPISENT,
             COALESCE(PROV.BDCODCSTCOFENT,0) BDCODCSTCOFENT,
             COALESCE(PROV.BDCODCSTCOFSAI,0) BDCODCSTCOFSAI
      FROM TCADPRO PRO
      LEFT OUTER JOIN tcadpro_vinc PROV ON PROV.BDCODPROD = PRO.BDCODPROD
      WHERE ((PROV.BDCODEMP IS NOT NULL) AND (PROV.BDCODEMP > 0));
    END

  /*Verifica se j? n?o existe dado na TMP_TCADPRO_PART*/
  wCodProd = NULL;
  SELECT FIRST 1 BDCODPROD FROM TMP_TCADPRO_PART INTO :wCodProd;
  IF ((:wCodProd IS NULL) OR (:wCodProd = 0)) THEN
    BEGIN
      /* CARREGADO OS PRODUTOS POR PARTICIPANTE */
      INSERT INTO TMP_TCADPRO_PART (BDSESSAO,BDEDITCHAVE,BDCODPROD,BDCODTER,BDCODENTRADA,BDDESCPRODBUSCA, BDORDEM)
      SELECT 0 BDSESSAO, P.BDCODPROD BDEDITCHAVE, P.BDCODPROD, P.bdcodter, COALESCE(P.bdcodentrada, ''), COALESCE(P.bddescprodbusca, ''), P.BDORDEM FROM TCADPRO_PART P;
    END  
END
^

/* Alter (SP_COMMIT_IMP_NCM) */
ALTER PROCEDURE SP_COMMIT_IMP_NCM(PRSESSAO INTEGER,
PRREF INTEGER)
 AS
DECLARE VARIABLE WSESSAO INTEGER;
DECLARE VARIABLE WNCMPROD INTEGER;
DECLARE VARIABLE WNOMENCM VARCHAR(1100);
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(20);
DECLARE VARIABLE WTIPONCM INTEGER;
DECLARE VARIABLE WALIQIPI NUMERIC(15,6);
DECLARE VARIABLE WSECAO VARCHAR(5);
DECLARE VARIABLE WCODCSTICMS INTEGER;
DECLARE VARIABLE WCSTICMS VARCHAR(3);
DECLARE VARIABLE WALIQICMS NUMERIC(7,4);
DECLARE VARIABLE WALIQICMSST NUMERIC(7,4);
DECLARE VARIABLE WCODCSTIPIENT INTEGER;
DECLARE VARIABLE WCSTIPIENT VARCHAR(3);
DECLARE VARIABLE WCODCSTIPISAI INTEGER;
DECLARE VARIABLE WCSTIPISAI VARCHAR(3);
DECLARE VARIABLE WCODCSTPISENT INTEGER;
DECLARE VARIABLE WCSTPISENT VARCHAR(3);
DECLARE VARIABLE WCODCSTPISSAI INTEGER;
DECLARE VARIABLE WCSTPISSAI VARCHAR(3);
DECLARE VARIABLE WALIQPISLR NUMERIC(7,4);
DECLARE VARIABLE WALIQPISLP NUMERIC(7,4);
DECLARE VARIABLE WCODCSTCOFENT INTEGER;
DECLARE VARIABLE WCSTCOFENT VARCHAR(3);
DECLARE VARIABLE WCODCSTCOFSAI INTEGER;
DECLARE VARIABLE WCSTCOFSAI VARCHAR(3);
DECLARE VARIABLE WALIQCOFLR NUMERIC(7,4);
DECLARE VARIABLE WALIQCOFLP NUMERIC(7,4);
BEGIN
  /*S? os existentes*/
  FOR SELECT N.BDNCMPROD, N.BDNOMENCM, N.BDCLASSIFICACAO, N.BDTIPONCM, N.BDALIQIPI, N.BDSECAO, N.BDCODCSTICMS,
             N.BDALIQICMS, N.BDALIQICMSST, N.BDCODCSTIPIENT, N.BDCODCSTIPISAI, N.BDCODCSTPISENT, N.BDCODCSTPISSAI,
             N.BDALIQPISLR, N.BDALIQPISLP, N.BDCODCSTCOFENT, N.BDCODCSTCOFSAI, N.BDALIQCOFLR, N.BDALIQCOFLP
      FROM TMP_TNCM_TEMP N
      JOIN TNCM NCM ON(NCM.BDNCMPROD = N.BDNCMPROD)
      WHERE N.BDSESSAO = :PRSESSAO
      INTO :wNCMPROD, :wNOMENCM, :wCLASSIFICACAO, :wTIPONCM,
           :wALIQIPI, :wSECAO, :wCODCSTICMS, :wALIQICMS, :wALIQICMSST, :wCODCSTIPIENT, :wCODCSTIPISAI,
           :wCODCSTPISENT, :wCODCSTPISSAI, :wALIQPISLR, :wALIQPISLP, :wCODCSTCOFENT, :wCODCSTCOFSAI,
           :wALIQCOFLR, :wALIQCOFLP
  DO
    BEGIN
      UPDATE OR INSERT INTO TNCM(BDNCMPROD, BDNOMENCM, BDCLASSIFICACAO, BDTIPONCM,
                                 BDALIQIPI, BDSECAO, BDCODCSTICMS, BDALIQICMS, BDALIQICMSST, BDCODCSTIPIENT, BDCODCSTIPISAI,
                                 BDCODCSTPISENT, BDCODCSTPISSAI, BDALIQPISLR, BDALIQPISLP, BDCODCSTCOFENT, BDCODCSTCOFSAI,
                                 BDALIQCOFLR, BDALIQCOFLP)
      VALUES(:wNCMPROD, :wNOMENCM, :wCLASSIFICACAO, :wTIPONCM,
             :wALIQIPI, :wSECAO, :wCODCSTICMS, :wALIQICMS, :wALIQICMSST, :wCODCSTIPIENT, :wCODCSTIPISAI,
             :wCODCSTPISENT, :wCODCSTPISSAI, :wALIQPISLR, :wALIQPISLP, :wCODCSTCOFENT, :wCODCSTCOFSAI,
             :wALIQCOFLR, :wALIQCOFLP) MATCHING(BDNCMPROD);
    END

  /*NCM'S novos somente - N?o importa novos conforme solicitado pelo Fernando, s? atualiza os existentes
  INSERT INTO TNCM(BDNCMPROD, BDNOMENCM, BDCLASSIFICACAO, BDTIPONCM,
                   BDALIQIPI, BDSECAO, BDCODCSTICMS, BDALIQICMS, BDALIQICMSST, BDCODCSTIPIENT, BDCODCSTIPISAI,
                   BDCODCSTPISENT, BDCODCSTPISSAI, BDALIQPISLR, BDALIQPISLP, BDCODCSTCOFENT, BDCODCSTCOFSAI,
                   BDALIQCOFLR, BDALIQCOFLP)
  SELECT N.BDNCMPROD, N.BDNOMENCM, N.BDCLASSIFICACAO, N.BDTIPONCM, N.BDALIQIPI, N.BDSECAO, N.BDCODCSTICMS,
         N.BDALIQICMS, N.BDALIQICMSST, N.BDCODCSTIPIENT, N.BDCODCSTIPISAI, N.BDCODCSTPISENT, N.BDCODCSTPISSAI,
         N.BDALIQPISLR, N.BDALIQPISLP, N.BDCODCSTCOFENT, N.BDCODCSTCOFSAI, N.BDALIQCOFLR, N.BDALIQCOFLP
  FROM TMP_TNCM_TEMP N
  LEFT OUTER JOIN TNCM NCM ON(NCM.BDNCMPROD = N.BDNCMPROD)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDNCMPROD IS NOT NULL) AND (N.BDNCMPROD > 0))
  AND NCM.BDNCMPROD IS NULL;
  */
END
^

/* Alter (SP_COMMIT_IMP_SAIDA) */
ALTER PROCEDURE SP_COMMIT_IMP_SAIDA(PRSESSAO INTEGER,
PRSESSAOTER INTEGER)
 AS
BEGIN

  /*Commit do lan?amento de sa?da - registros n?o inconsistentes*/
  INSERT INTO VEF_EMP_TMOVSAI(BDCODEMP, BDCHAVE, BDCODTER, BDNUMDOCINI, BDDATAEMISSAO, BDESPECIE, BDSERIE, BDNUMDOCFIM, BDTIPLAN,
                              BDMODELO, BDEMITENTE, BDDATASAIDA, BDCODSITNF, BDREFLAN, BDCIFFOB, BDCODTIPO, BDCODUSU, BDDATALAN,
                              BDHORALAN, BDDATACANC, BDCHAVETALON, BDVALORNOTA, BDDESCONTONOTA, BDCHAVENFE, BDCONDPGTO, BDSUBSERIE,
                              BDCODSTATUSLAN, BDFUNDAP, BDDATAINCLUSAO, BDHORAINCLUSAO, BDCODUSUINCLU, BDTIPOLANINCLU, BDCODCID,
                              BDCODEQUIPSAT, BDCNPJDESTCFE)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE BDCHAVE, MOV.BDALTCODTER, MOV.BDNUMDOCINI, MOV.BDDATAEMISSAO, MOV.BDESPECIE,
         MOV.BDSERIE, MOV.BDNUMDOCFIM, MOV.BDTIPLAN, MOV.BDMODELO, MOV.BDEMITENTE, MOV.BDDATASAIDA, MOV.BDCODSITNF,
         MOV.BDREFLAN, MOV.BDCIFFOB, MOV.BDCODTIPO, MOV.BDCODUSU, MOV.BDDATALAN, MOV.BDHORALAN, MOV.BDDATACANC,
         MOV.BDCHAVETALON, MOV.BDVALORNOTA, MOV.BDDESCONTONOTA, MOV.BDCHAVENFE, MOV.BDCONDPGTO, MOV.BDSUBSERIE,
         MOV.BDCODSTATUSLAN, NULL BDFUNDAP, MOV.BDDATAINCLUSAO, MOV.BDHORAINCLUSAO, MOV.BDCODUSUINCLU,
         MOV.BDTIPOLANINCLU, IIF(MOV.BDCODCID = 0, NULL, MOV.BDCODCID) BDCODCID, MOV.BDCODEQUIPSAT, MOV.BDCNPJDESTCFE
  FROM (
        SELECT S.*
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE NOT EXISTS (
                          SELECT INCO.BDCODINCONSISTENCIAMOVSAI
                          FROM VEF_INCON_TMOVSAI INCO
                          WHERE INCO.BDSESSAO = S.BDSESSAO
                          AND INCO.BDCODEMP = S.BDCODEMP
                          AND INCO.BDCHAVE = S.BDCHAVE
                         )
       ) MOV
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = MOV.BDALTCODTER)
  WHERE NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER.BDCODTER
                )
  AND MOV.BDSESSAO = :PRSESSAO
  AND ((MOV.BDALTCODTER IS NOT NULL) OR (MOV.BDALTCODTER > 0));

  /*Commit dos itens do lan?amento de sa?da - registros commitados acima*/
  INSERT INTO VEF_EMP_TMOVSAIITENS(
                                   BDCODEMP, BDCHAVE, BDORDEM, BDCODOBS, BDCODCID, BDCODCSTICMS,
                                   BDCODNAT, BDALIQICMS, BDALIQST, BDBASEICMS, BDBASEIPI, BDBASEST,
                                   BDISENTASICMS, BDISENTASIPI, BDOUTRASICMS, BDOUTRASIPI, BDVLRICMS,
                                   BDVLRIPI, BDVLRST, BDIMPEXCLUIDAS, BDOUTROSIMP, BDREDBCICMS, BDVLRCONTAB,
                                   BDDESCONTO, BDICMSFRETESAI, BDACRECFINSAI, BDREGEXPSAI, BDDIGOPERNAT,
                                   BDPREFIXONAT, BDVLRPIS, BDVLRCOFINS
                                  )
  SELECT T.BDCODEMP, T.BDEDITCHAVE BDCHAVE, T.BDORDEM, T.BDCODOBS, T.BDCODCID, T.BDCODCSTICMS, T.BDCODNAT, T.BDALIQICMS,
         T.BDALIQST, T.BDBASEICMS, T.BDBASEIPI, T.BDBASEST, T.BDISENTASICMS, T.BDISENTASIPI, T.BDOUTRASICMS,
         T.BDOUTRASIPI, T.BDVLRICMS, T.BDVLRIPI, T.BDVLRST, T.BDIMPEXCLUIDAS, T.BDOUTROSIMP, T.BDREDBCICMS,
         T.BDVLRCONTAB, T.BDDESCONTO, T.BDICMSFRETESAI, T.BDACRECFINSAI, T.BDREGEXPSAI, T.BDDIGOPERNAT,
         T.BDPREFIXONAT, T.BDVLRPIS, T.BDVLRCOFINS
  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP T
  --Faz esse left pra saber se o lan?amento existe na base, se sim ent?o insere o item
  LEFT OUTER JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = T.BDCODEMP AND S.BDCHAVE = T.BDEDITCHAVE)
  WHERE T.BDSESSAO = :PRSESSAO
  AND ((S.BDCHAVE IS NOT NULL) OR (S.BDCHAVE > 0))
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = T.BDSESSAO
                 AND I.BDCODEMP = T.BDCODEMP
                 AND I.BDCHAVE = T.BDCHAVE
                );

  /*Commit do movimento de produto de sa?da*/
  INSERT INTO VEF_EMP_TMOVPROSAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODCTA, BDCODPROD, BDCODCSTCOF, BDCODCSTICMS,
                                  BDCODCSTPIS, BDCODCSTIPI, BDCODPROFATCON, BDCODFATCON, BDMOVFISICO, BDQTDITEM,
                                  BDVLRITEM, BDVLRDESC, BDVLRDESPACESSORIA, BDREDBCICMS, BDBCICMS, BDBCPIS, BDBCST,
                                  BDBCIPI, BDBCCOFINS, BDBCISSQN, BDALIQICMS, BDALIQPIS, BDALIQST, BDALIQIPI,
                                  BDALIQCOFINS, BDALIQISSQN, BDVLRICMS, BDVLRPIS, BDVLRST, BDVLRIPI, BDVLRCOFINS,
                                  BDVLRISSQN, BDCODNATREC, BDVLRFRETE)
  SELECT MOVPRO.BDCODEMP, MOVPRO.BDEDITCHAVE BDCHAVE, MOVPRO.BDORDEM, MOVPRO.BDORDEMPRO, MOVPRO.BDCODCTA, MOVPRO.BDALTCODPROD BDCODPROD, MOVPRO.BDCODCSTCOF,
         MOVPRO.BDCODCSTICMS, MOVPRO.BDCODCSTPIS, MOVPRO.BDCODCSTIPI, MOVPRO.BDCODPROFATCON, MOVPRO.BDCODFATCON, MOVPRO.BDMOVFISICO, MOVPRO.BDQTDITEM,
         MOVPRO.BDVLRITEM, MOVPRO.BDVLRDESC, MOVPRO.BDVLRDESPACESSORIA, MOVPRO.BDREDBCICMS, MOVPRO.BDBCICMS, MOVPRO.BDBCPIS, MOVPRO.BDBCST, MOVPRO.BDBCIPI,
         MOVPRO.BDBCCOFINS, MOVPRO.BDBCISSQN, MOVPRO.BDALIQICMS, MOVPRO.BDALIQPIS, MOVPRO.BDALIQST, MOVPRO.BDALIQIPI, MOVPRO.BDALIQCOFINS, MOVPRO.BDALIQISSQN,
         MOVPRO.BDVLRICMS, MOVPRO.BDVLRPIS, MOVPRO.BDVLRST, MOVPRO.BDVLRIPI, MOVPRO.BDVLRCOFINS, MOVPRO.BDVLRISSQN, MOVPRO.BDCODNATREC, MOVPRO.BDVLRFRETE
  FROM (
        SELECT P.*
        FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
        JOIN VEF_EMP_TMOVSAIITENS S ON(S.BDCODEMP = P.BDCODEMP AND S.BDCHAVE = P.BDEDITCHAVE AND S.BDORDEM = P.BDORDEM)
        WHERE P.BDSESSAO = :PRSESSAO
        AND S.BDCHAVE IS NOT NULL
       ) MOVPRO
  WHERE NOT EXISTS(
                   SELECT I.BDCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI I
                   WHERE I.BDSESSAO = MOVPRO.BDSESSAO
                   AND I.BDCODEMP = MOVPRO.BDCODEMP
                   AND I.BDCHAVE = MOVPRO.BDCHAVE
                  );
END
^

/* Alter (SP_COMMIT_UNIDADEMEDIDA) */
ALTER PROCEDURE SP_COMMIT_UNIDADEMEDIDA(PRSESSAO INTEGER,
PRCODEMP INTEGER,
PRREF INTEGER)
 AS
DECLARE VARIABLE WCODINCONSISTENCIA INTEGER;
DECLARE VARIABLE wAtuUnidMed VARCHAR(5);
DECLARE VARIABLE wEditChave  INTEGER;
DECLARE VARIABLE wDescUnimed VARCHAR(100);
DECLARE VARIABLE wApeUniMed  VARCHAR(5);
DECLARE VARIABLE wCodTipo    INTEGER;
BEGIN
  wCodInconsistencia = NULL;
  SELECT S.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) S INTO :wCodInconsistencia;

  IF ((:wCodInconsistencia IS NULL) OR (:wCodInconsistencia = 0)) THEN
    SELECT I.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS I WHERE UPPER(I.BDPLANODEFAULT) = 'TRUE' INTO :wCodInconsistencia;

  /* **********************Insere unidades de medida que n?o existem no banco********************** */
  INSERT INTO TUNIDADEMEDIDA(bdcodunimed, bddescunimed, bdapeunimed, bdcodtipo)
  SELECT un.bdeditchave bdcodunimed, un.bddescunimed, un.bdapeunimed, un.bdcodtipo
  FROM TMP_TUNIDADEMEDIDA_TEMP un
  WHERE un.bdsessao = :PRSESSAO
  AND NOT EXISTS(
                 SELECT u.bdcodunimed, u.bddescunimed,
                        u.bdapeunimed, u.bdcodtipo
                 FROM TUNIDADEMEDIDA U
                 WHERE U.BDAPEUNIMED = un.BDAPEUNIMED
                );

  /*Existe plano de inconsistencia no cadastro da empresa ou plano default*/
  IF ((:wCodInconsistencia IS NOT NULL) OR (:wCodInconsistencia > 0)) THEN
    BEGIN
      SELECT COALESCE(UPPER(I.BDATUUNIDMED), 'FALSE') BDATUUNIDMED FROM VEF_BASE_TACOESINCONS I WHERE I.BDCODPLANOINCONS = :wCodInconsistencia INTO :wAtuUnidMed;

      /*Atualiza as unidades de medida*/
      IF (:wAtuUnidMed = 'TRUE') THEN
        BEGIN
          FOR SELECT un.bdeditchave bdcodunimed, un.bddescunimed, un.bdapeunimed, un.bdcodtipo
              FROM TMP_TUNIDADEMEDIDA_TEMP un
              WHERE un.bdsessao = :PRSESSAO
              AND EXISTS(
                         SELECT u.bdcodunimed, u.bddescunimed,
                                u.bdapeunimed, u.bdcodtipo
                         FROM TUNIDADEMEDIDA U
                         WHERE U.BDAPEUNIMED = un.BDAPEUNIMED
                        )
              INTO :wEditChave, :wDescUniMed, :wApeUniMed, :wCodTipo
          DO
            UPDATE TUNIDADEMEDIDA U SET U.BDDESCUNIMED = :wDescUniMed, U.BDAPEUNIMED = :wApeUniMed, U.BDCODTIPO = :wCodTipo WHERE U.BDCODUNIMED = :wEditChave;
        END
    END


END
^

/* empty dependent procedure body */
/* Clear: SP_EXP_ATIVA_CONTABIL for: SP_CONS_CALC_DEP */
ALTER PROCEDURE SP_EXP_ATIVA_CONTABIL(PRCODEMP INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRCODPLANOPADRAO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(BDREF VARCHAR(10),
BDREFINTEIRO INTEGER,
BDCODTPLABEM INTEGER,
BDCTALONBEM VARCHAR(40),
BDNOMTPLABEM VARCHAR(100),
BDCODNOMTPLABEM VARCHAR(110),
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDCODNOMBEM VARCHAR(210),
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDDEPRECIACAOPERIODO NUMERIC(18,6),
BDVALORBAIXAPERIODO NUMERIC(18,6),
BDDEPRECIACAOACUMULADA NUMERIC(18,6),
BDTAXA NUMERIC(9,6),
BDDATATAXADEP DATE,
BDVALORRESIDUAL NUMERIC(18,6),
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCTADEBITODEPRE INTEGER,
BDCTACREDITODEPRE INTEGER,
BDHISTORICODEPRE INTEGER,
BDCTADEBITOBAIXA INTEGER,
BDCTACREDITOBAIXA INTEGER,
BDHISTORICOBAIXA INTEGER,
BDCTADEBITODEPBAI INTEGER,
BDCTACREDITODEPBAI INTEGER,
BDHISTORICODEPBAI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_CADASTRO_BEM for: SP_CONS_CALC_DEP */
ALTER PROCEDURE VSUC_SP_RETORNA_CADASTRO_BEM(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMOSTRARDEPRECIADOS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODBEM INTEGER,
BDDATATAXADEPRECIACAO DATE,
BDMESESDEPRECIADOS INTEGER,
BDDEPRECIACAOPERIODO NUMERIC(15,2),
BDDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
BDVALORRESIDUALCONTABIL NUMERIC(15,2),
BDVALORRESIDUALCONTABILMOEDA NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_CONTR_PATRIMON for: SP_CONS_CALC_DEP */
ALTER PROCEDURE VSUC_SP_RETORNA_CONTR_PATRIMON(PRCODEMP VARCHAR(2048),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRMODELO INTEGER,
PRTIPO INTEGER,
PRCODPLAPADRAO INTEGER,
PRREFEMP INTEGER,
PRMOSTRADEPRECIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRDETALHARTAXADEP INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMTPLA VARCHAR(100),
BDCODFOR INTEGER,
BDNOMFOR VARCHAR(100),
BDCODCC INTEGER,
BDCTALONCC VARCHAR(20),
BDNOMCC VARCHAR(40),
BDVALORCORRIGIDOANTERIOR NUMERIC(15,2),
BDCORRECAOPERIODO NUMERIC(15,2),
BDVALORCORRIGIDOATUAL NUMERIC(15,2),
BDDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
BDDEPRECIACAOPERIODO NUMERIC(15,2),
BDDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
BDDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
BDDEPRECIACAOACUMULADAATUALMOE NUMERIC(15,6),
BDCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
BDVALORRESIDUALCONTABIL NUMERIC(15,2),
BDVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
BDTOTALMESESDEPRECIACAO INTEGER,
BDMESESDEPRECIADOS INTEGER,
BDMESESDEPRECIAR INTEGER,
BDTAXADEPRECIACAOANUAL NUMERIC(6,6),
BDDATATAXADEPRECIACAO DATE,
BDREFERENCIA VARCHAR(7),
BDNATBEM VARCHAR(20),
BDESPECIE VARCHAR(20),
BDDATAAQUISICAO DATE,
BDVALORMOEDA NUMERIC(15,6),
BDVALORAQUISICAOMOEDA NUMERIC(15,6),
BDVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
BDVALORAQUISICAOORIGINAL NUMERIC(15,2),
BDVALORBAIXA NUMERIC(15,2),
BDSOMARDEPRECIACAO INTEGER,
BDCODORIGBEM INTEGER,
BDTIPOBEM INTEGER,
BDCLACOD VARCHAR(10),
BDULTIMOAGREGADO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_CONS_CALC_DEP) */
ALTER PROCEDURE SP_CONS_CALC_DEP(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER,
PRDETALHARTAXADEP INTEGER = 0)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,6),
PRCORRECAOPERIODO NUMERIC(15,6),
PRVALORCORRIGIDOATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6),
PRDEPRECIACAOPERIODO NUMERIC(15,6),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6),
PRVALORRESIDUALCONTABIL NUMERIC(15,6),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,6),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,6),
PRVALORBAIXAREAL NUMERIC(15,6),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,6),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,6),
BDCODEMP INTEGER,
BDCODBEM INTEGER,
PRSOMARDEPRECIACAO INTEGER,
PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDTINI DATE;
DECLARE VARIABLE WDTFIM DATE;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIAMES INTEGER;
DECLARE VARIABLE WCORRECAOPERIODO NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOATUAL NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOSAUX INTEGER;
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,6);
DECLARE VARIABLE WVALORBAIXABEM NUMERIC(15,6);
DECLARE VARIABLE WPOSSUIBAIXA VARCHAR(5);
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,6);
DECLARE VARIABLE WVALORBAIXAREAL NUMERIC(15,6);
DECLARE VARIABLE WVALORAQUISICAOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WTAXAAUX NUMERIC(6,6);
DECLARE VARIABLE WTAXAANT NUMERIC(6,6);
DECLARE VARIABLE WDEPRECIACAOPERIODOAUX NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6);
DECLARE VARIABLE WCODMOEDA INTEGER;
DECLARE VARIABLE WVALORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WREFMOEDAINI VARCHAR(10);
DECLARE VARIABLE WREFMOEDAFIM VARCHAR(10);
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALDEPACUMUBEM NUMERIC(15,6);
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WDEPDIADATA INTEGER;
DECLARE VARIABLE WFIRST VARCHAR(5);
DECLARE VARIABLE WDTBAIXAAUX DATE;
DECLARE VARIABLE WMESESDEPRECIADOSOUTRATAXA INTEGER;
DECLARE VARIABLE WDEPRECIACAOACUMULADA NUMERIC(15,6);
DECLARE VARIABLE WDATAINIMES DATE;
DECLARE VARIABLE WDATAINICIALCALCULO DATE;
DECLARE VARIABLE WDIASDEPRECIADOS INTEGER;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,6);
DECLARE VARIABLE WTIPO INTEGER;
BEGIN
  /*Stored procedure para somar os valores das deprecia??es. Principalmente
  quando houver v?rias deprecia??es cadastradas no bem. O c?lculo da deprecia??o
  ? feito na verdade na sp_cons_calc_dep_correcao*/
  prvalorcorrigidoanterior        = 0;
  prcorrecaoperiodo               = 0;
  prvalorcorrigidoatual           = 0;
  prdepreciacaoacumuladaanterior  = 0;
  prdepreciacaoperiodo            = 0;
  prdepreciacaoperiodomoeda       = 0;
  prdepreciacaoacumuladaatual     = 0;
  prdepreciacaoacumuladaatualmoed = 0;
  prcorrecaomonetariadepreciacao  = 0;
  prvalorresidualcontabil         = 0;
  prvalorresidualcontabilmoeda    = 0;
  prtotalmesesdepreciacao         = 0;
  prmesesdepreciados              = 0;
  prmesesdepreciar                = 0;
  prtaxadepreciacaoanual          = 0;
  prdatataxadepreciacao           = NULL;
  prvalorbaixa                    = 0;
  prdepreciacaobaixamoeda         = 0;
  prvalorbaixareal                = 0;
  prvalormoeda                    = 0;
  prdatabaixa                     = NULL;
  prvaloraquisicaomoeda           = 0;
  prvalorcorrigidoanteriormoeda   = 0;
  prvaloraquisicaooriginal        = 0;
  prctadebitodepre                = 0;
  prvalordepreciacaodiariafim     = 0;

  wdepreciacaoperiodo             = 0;
  wdepreciacaoperiodoaux          = 0;
  wtaxaaux                        = 0;
  wdepreciacaoperiodomoeda        = 0;
  wmesesdepreciadosaux            = 0;
  wdepreciacaoacumuladaanterior   = 0;
  wcodmoeda                       = 0;
  wvalormoeda                     = 0;
  wrefmoedaini                    = '';
  wrefmoedafim                    = '';
  wvalorbaixabem                  = 0;
  wpossuibaixa                    = 'FALSE';
  wcodbemoriginal                 = 0;
  wdataorigaquisicao              = NULL;
  wdepdia                         = 'FALSE';
  wdepmensal                      = 'FALSE';
  wdepmesbaixa                    = 'FALSE';
  wdatainiciocalc                 = NULL;
  wdatafimcalc                    = NULL;
  wdataultimoitemdep              = NULL;
  wvaldepacumubem                 = 0;
  wnumdias                        = 0;
  wdepdiadata                     = 0;
  wfirst                          = 'TRUE';
  wdtbaixaaux                     = NULL;
  wdepreciacaoacumulada           = 0;
  WDATAINIMES                     = NULL;
  WDATAINICIAlCALCULO             = NULL;
  WDEPRECIACAOACUMULADAATUAL      = 0;

  BDCODEMP = PRCODEMP;
  BDCODBEM = PRCODBEM;

  --#alt:85169. Os c?lculos para a op??o de relat?rio 2 devem ser os mesmo da deprecia??o, se n?o os valores ficam incorretos. Ana - 21/06/2018
  WTIPO = PRTIPO;
  if (WTIPO = 2) then
    WTIPO = 0;

  --alt:16006 - 03/11/2016 - Comentado aqui e implementado no SP_CONS_CALC_DEP_CORRECAO, pois deve verificar para cada per?odo se possui baixa. Pedro
  /* In?cio deprecia??o anteriores */
  --Processo para calcular os meses anteriores ao per?odo informado, pois posso ter v?rias
  --deprecia??es cadastradas
  /*SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  AND   (tbai.BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
  INTO :wvalorbaixabem;

  IF (wvalorbaixabem > 0) THEN
    wpossuibaixa = 'TRUE';
  --Tipo 2 somente baixas
  IF ((prtipo = 2) AND (wvalorbaixabem = 0)) THEN
    EXIT;*/
  --alt:16006 - Fim

  SELECT tbem.bdDATORIAQUIBEM FROM empresas_tbem tbem
  WHERE (tbem.bdcodemp = :prcodemp) AND
        (tbem.bdcodbem = :prcodbem)
  INTO :wdataaquisicao;

  --SELECT tind.bddescind,tbem.bdcodind
  SELECT tbem.bdcodind
  FROM (SELECT COALESCE(tbem.bdcodind,0) bdcodind FROM empresas_tbem tbem
        WHERE (tbem.bdcodemp = :prcodemp)
        AND   (tbem.bdcodbem = :prcodbem)) tbem
  LEFT OUTER JOIN TINDICES tind ON (tind.bdcodind = tbem.bdcodind)
  --INTO :wdescmoeda,:wcodmoeda;
  INTO :wcodmoeda;

  --#alt:21384 - Estava sempre pegando o maior valor da moeda do ano da aquisi??o do bem, quando na verdade deve pegar sempre o valor mais pr?ximo ao m?s da aquisi??o. Ana - 13/11/2017
  SELECT FIRST 1 tind.bdvalind FROM tindval tind
         WHERE tind.bdcodind = :wcodmoeda AND
         tind.bddataind <= :wdataaquisicao
         ORDER BY tind.bdrefind DESC
   INTO :wvalormoeda;

  --Converte a moeda para cruzeiros reias
  IF (wdataaquisicao <= '06/30/1994') THEN
    wvalormoeda = wvalormoeda / 1000;

  IF ((wvalormoeda = 0) OR (wvalormoeda IS NULL)) THEN
    wvalormoeda = 0.8287;

  /*wrefmoedaini = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
  wrefmoedafim = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
  SELECT MAX(tind.bdvalind) FROM tindval tind
         WHERE (tind.bdcodind = :wcodmoeda) AND
               (tind.bdrefind BETWEEN :wrefmoedaini AND :wrefmoedafim)
  INTO :wvalormoeda;
  --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
  IF (wvalormoeda IS NULL) THEN
    BEGIN
      SELECT FIRST 1 tind.bdvalind FROM tindval tind
             WHERE tind.bdcodind = :wcodmoeda AND
             tind.bdrefind <= :wrefmoedaini
             ORDER BY tind.bdrefind DESC    --#alt:17142 - Alterado para pegar da ultima referencia. Ana - 02/02/2017
      INTO :wvalormoeda;
    END*/
  --#alt:21384. fim

  wmes = CAST(SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(EXTRACT(YEAR FROM wdataaquisicao) AS INTEGER);--cast(substring(cast(wdataaquisicao as varchar(10)) from 1 for 4) as integer);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultdiames;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultdiames = EXTRACT(DAY FROM (wdataaquisicao - EXTRACT(DAY FROM wdataaquisicao) +
                       32 - EXTRACT(DAY FROM wdataaquisicao - EXTRACT(DAY FROM wdataaquisicao) + 32)));

  wdtini  = wmes||'-01-'||wano;
  wdtfim  = wmes||'-'||wultdiames||'-'||wano;
  wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim = CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER);

  --#alt:18204 - Adicionei a verifica??o da data da aquisi??o com a data final para n?o executar quando n?o pertencer ao per?odo de aquisi??o do bem. Ana - 28/04/2017
  WHILE ((wrefatu < wreffim) AND (prdatafinal >= wdataaquisicao)) DO
    BEGIN
      /* A antiga rotina da deprecia??o estava pegando sempre o valor da moeda do m?s de aquisi??o, por isso
         fiz a busca do valor fora do while das refer?ncias, mas deixei como coment?rio caso seja feito
         para busca o valor da moeda conforme o m?s em que esta calculando
      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      if ((wvalormoeda is null) or (wvalormoeda = 0) or (position('UFIR',upper(wdescmoeda)) = 0))  then
        begin
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'0101';
          wrefmoedafim = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'1231';
    
          select max(tind.bdvalind) from tindval tind
                 where (tind.bdcodind = :wcodmoeda) and
                       (tind.bdrefind between :wrefmoedaini and :wrefmoedafim)
          into :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          if (wvalormoeda is null) then
            begin
              select first 1 tind.bdvalind from tindval tind
                     where tind.bdcodind = :wcodmoeda and
                     tind.bdrefind <= :wrefmoedaini
                     order by tind.bdrefind
              into :wvalormoeda;
            end
        end*/

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((COALESCE(prtaxadepreciacaoanual,0) = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        --#alt:16415 - Alterada a verifica??o do case, pois quando n?o havia nehuma contabiliza??o ele n?o levava o valor do bem. Ana - 05/12/2016
        --Faz o select com o First, pois um bem pode ter mais de uma deprecia??o cadastrada.
        --alt:14255 - 28/06/2016 - Adicionado case para verificar o tipo da contabiliza??o e ver de onde ir? buscar valor da aquisi??o. Pedro
        --SELECT FIRST 1 tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem,
        SELECT FIRST 1 tbem.bdcodorigbem, COALESCE(CASE WHEN ((tdep.BDCONTABILIZACAO = 0) OR (tdep.BDCONTABILIZACAO IS NULL) ) THEN tbem.BDVALAQUIBEM ELSE tdep.BDVALAQUISOC END, 0),
               tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem, tbem.bddepmesbaixabem,
               tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, COALESCE(tdep.bdvaldepacumubem,0),tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        ORDER BY tdep.bddatinicalcbem DESC
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :wtaxaaux,         :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,     :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre, :wnumdias,        :wdepdiadata;

      --alt:13784 - 12/04/2016 - Se tiver trocado de taxa de deprecia??o, precisa levar os meses j? depreciados com a taxa anterior para o c?lculo da pr?xima. Pedro
      IF ((wtaxaant <> 0) AND (wtaxaant <> wtaxaaux)) THEN
        BEGIN
          wmesesdepreciadosoutrataxa = prmesesdepreciados;
          --alt:13784 - 12/04/2016 - Se estiver marcado para detalhar por taxa de deprecia??o, precisa retornar aqui a taxa. Pedro
          IF (prdetalhartaxadep = 1) THEN
            BEGIN
              prmesesdepreciar = prtotalmesesdepreciacao - prmesesdepreciados;
              prsomardepreciacao = 0; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
              SUSPEND;
            END
        END

      wdepreciacaoperiodoaux = COALESCE(wdepreciacaoperiodo,0);
      SELECT prcorrecaoperiodo, prvalorcorrigidoatual, prdepreciacaoperiodo, prmesesdepreciados, prvalorbaixa,
             prdepreciacaoperiodomoeda, prvalorresidualcontabil, prvalorresidualcontabilmoeda,
             prdepreciacaobaixamoeda, prvalorbaixareal, prvaloraquisicaomoeda,
             prdepreciacaoacumuladaanterior, prtaxadepreciacaoanual, prdepreciacaoacumuladaatualmoed,
             prtotalmesesdepreciacao, prvaloraquisicaooriginal, prdatabaixa, prdepreciacaoacumuladaatual
      FROM sp_cons_calc_dep_correcao(:prcodemp, :prcodbem, :wdtini, :wdtfim, :WTIPO /*:prtipo*/, :prcontabilizacao,:wvalormoeda,:wpossuibaixa,:wcodbemoriginal,
                                     :prvaloraquisicaooriginal,:wtaxaaux,:wdataaquisicao,:wdataorigaquisicao,:wdepdia,:wdepmensal,
                                     :wdepmesbaixa,:wdatainiciocalc,:wdatafimcalc,:wdataultimoitemdep,:wvaldepacumubem,:prctadebitodepre,:wnumdias,
                                     :wdepdiadata, :wvalorbaixabem, :wmesesdepreciadosoutrataxa, :wdepreciacaoacumulada)
      INTO :wcorrecaoperiodo, :wvalorcorrigidoatual, :wdepreciacaoperiodo, :wmesesdepreciados, :wvalorbaixa,
           :wdepreciacaoperiodomoeda, :wvalorresidualcontabil, :wvalorresidualcontabilmoeda,
           :wdepreciacaobaixamoeda, :wvalorbaixareal, :wvaloraquisicaomoeda,
           :wdepreciacaoacumuladaanterior, :prtaxadepreciacaoanual, :wdepreciacaoacumuladaatualmoed,
           :prtotalmesesdepreciacao, :prvaloraquisicaooriginal, :prdatabaixa, wdepreciacaoacumulada;

      IF (wcorrecaoperiodo > 0) THEN
        BEGIN
          wcorrecaoperiodo = ABS(wcorrecaoperiodo - prcorrecaoperiodo);
          IF (wcorrecaoperiodo > 0) THEN
            prcorrecaoperiodo = prcorrecaoperiodo + wcorrecaoperiodo;
        END

      IF (wvalorcorrigidoatual > 0) THEN
        BEGIN
          wvalorcorrigidoatual = ABS(wvalorcorrigidoatual - prvalorcorrigidoatual);
          --alt:9013 - Foi retirada a incrementa??o do valor corrigido atual daqui pois estava duplicando a corre??o baseada no valor da baixa. Pedro
          /*if (wvalorcorrigidoatual > 0) then
            prvalorcorrigidoatual = abs(prvalorcorrigidoatual - wvalorcorrigidoatual);*/
        END

      --Feito esse tratamento pois posso ter v?rias taxas cadastradas para o bem. N?o posso utilizar o
      --prdepreciacaoacumuladaanterior pois a rotina calcula como se sempre fosse a taxa do m?s em quest?o
      -- In?cio
      IF ((prdepreciacaoacumuladaanterior = 0) AND (prtaxadepreciacaoanual > 0) AND (wdepreciacaoacumuladaanterior > 0)) THEN
        BEGIN
          wdepreciacaoacumuladaanterior = ABS(wdepreciacaoacumuladaanterior - prdepreciacaoacumuladaanterior);
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoacumuladaanterior;
        END
      ELSE
      IF (wdepreciacaoperiodoaux > 0) THEN
        prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoperiodoaux;

      IF ((prdepreciacaoacumuladaatualmoed = 0) AND (prtaxadepreciacaoanual > 0) AND (wdepreciacaoacumuladaatualmoed > 0)) THEN
        BEGIN
          wdepreciacaoacumuladaatualmoed = ABS(wdepreciacaoacumuladaatualmoed - prdepreciacaoacumuladaatualmoed);
          IF (wdepreciacaoacumuladaatualmoed > 0) THEN
            prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoacumuladaatualmoed;
        END
      ELSE
      IF (wdepreciacaoperiodomoeda > 0) THEN
        prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoperiodomoeda;
      -- Fim

      IF (wvalorresidualcontabil > 0) THEN
        BEGIN
          wvalorresidualcontabil = ABS(wvalorresidualcontabil - prvalorresidualcontabil);
          IF ((prvalorresidualcontabil > 0) AND (wdepreciacaoperiodo > 0) AND (wvalorresidualcontabil <> wdepreciacaoperiodo)) THEN
            wvalorresidualcontabil = wdepreciacaoperiodo;

          IF (wvalorresidualcontabil > 0) THEN
            prvalorresidualcontabil = ABS(prvalorresidualcontabil - wvalorresidualcontabil);
        END

      IF (wvalorresidualcontabilmoeda > 0) THEN
        BEGIN
          wvalorresidualcontabilmoeda = ABS(wvalorresidualcontabilmoeda - prvalorresidualcontabilmoeda);
          IF ((prvalorresidualcontabilmoeda > 0) AND (wdepreciacaoperiodomoeda > 0) AND (wvalorresidualcontabilmoeda <> wdepreciacaoperiodomoeda)) THEN
            wvalorresidualcontabilmoeda = wdepreciacaoperiodomoeda;

          IF (wvalorresidualcontabilmoeda > 0) THEN
            prvalorresidualcontabilmoeda = ABS(prvalorresidualcontabilmoeda - wvalorresidualcontabilmoeda);
        END

      --alt:14761 - 16/06/2016 - Se tiver valor de deprecia??o acumulada (informado no cadastro da deprecia??o)
      --? feito um c?lculo da quantidade de meses j? depreciados e assim precisa retornar eles tamb?m. Pedro
      IF ((wdepreciacaoperiodo > 0) OR (wvaldepacumubem > 0)) THEN
        BEGIN
          IF ((wtaxaaux > 0) AND (wtaxaaux <> prtaxadepreciacaoanual)) THEN
            wmesesdepreciadosaux = wmesesdepreciadosaux + ABS(wmesesdepreciadosaux - prmesesdepreciados);

          IF ((wmesesdepreciados > 0) AND ((prmesesdepreciados = 0) OR (wmesesdepreciados > prmesesdepreciados))) THEN --alt:13784 - 12/04/2016 - Quando trocada a taxa de deprecia??o n?o estava levando os meses depreciados corretamente. Pedro
            prmesesdepreciados = wmesesdepreciados;
          --alt:9013 - Colocada essa valida??o para n?o continuar depreciando depois do total de meses da deprecia??o, isso acontecia quando tinha deprecia??o di?ria. Pedro
          ELSE IF (prmesesdepreciados <> prtotalmesesdepreciacao) THEN
            prmesesdepreciados = prmesesdepreciados + 1;
        END
      --#Alt:5105
      /*if (wvalorbaixa > 0) then
        begin
          wvalorbaixa = ABS(wvalorbaixa - prvalorbaixa);
          if (wvalorbaixa > 0) then
            prvalorbaixa = prvalorbaixa + wvalorbaixa;
        end*/

      IF (wdepreciacaobaixamoeda > 0) THEN
        BEGIN
          wdepreciacaobaixamoeda = ABS(wdepreciacaobaixamoeda - prdepreciacaobaixamoeda);
          IF (wdepreciacaobaixamoeda > 0) THEN
            prdepreciacaobaixamoeda = prdepreciacaobaixamoeda + wdepreciacaobaixamoeda;
        END

      IF (wvalorbaixareal > 0) THEN
        BEGIN
          wvalorbaixareal = ABS(wvalorbaixareal - prvalorbaixareal);
          IF (wvalorbaixareal > 0) THEN
            prvalorbaixareal = prvalorbaixareal + wvalorbaixareal;
        END

      IF (wvaloraquisicaomoeda > 0) THEN
        BEGIN
          wvaloraquisicaomoeda = ABS(wvaloraquisicaomoeda - prvaloraquisicaomoeda);
          IF (wvaloraquisicaomoeda > 0) THEN
            prvaloraquisicaomoeda = ABS(prvaloraquisicaomoeda - wvaloraquisicaomoeda);
        END

      IF (prdatabaixa IS NOT NULL) THEN
        wdtbaixaaux = prdatabaixa;

      wtaxaant = wtaxaaux;
      wtaxaaux = prtaxadepreciacaoanual;
      wdtini   = addmonth(wdtini, 1);
      wdtfim   = addmonth(wdtini, 1)-1;
      wrefatu  = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  --alt:15196 - 09/11/2016 - Alterado para carregar a deprecia??o acumulada da vari?vel que est? somando o valor para cada per?odo. Pedro
  /*IF (wdepreciacaoperiodo > 0) THEN
    prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoperiodo;*/

  prdepreciacaoacumuladaanterior = wdepreciacaoacumulada;

  wtaxaaux = COALESCE(wtaxaaux,0);
  /* Final deprecia??o anteriores */

  wdtini  = prdatainicial;
  wmes    = CAST(SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano    = CAST(EXTRACT(YEAR FROM wdtini) AS INTEGER);--cast(substring(cast(wdtini as varchar(10)) from 1 for 4) as integer);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultdiames;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultdiames = EXTRACT(DAY FROM (wdtini - EXTRACT(DAY FROM wdtini) +
               32 - EXTRACT(DAY FROM wdtini - EXTRACT(DAY FROM wdtini) + 32)));
  wdtfim  = wmes||'-'||wultdiames||'-'||wano;
  IF (wdtfim > prdatafinal) THEN
    wdtfim = prdatafinal;
  wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim = CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER);

  prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior;

  --#alt:18204 - Adicionei a verifica??o da data da aquisi??o com a data final para n?o executar quando n?o pertencer ao per?odo de aquisi??o do bem. Ana - 28/04/2017
  WHILE ((wrefatu <= wreffim) AND (prdatafinal >= wdataaquisicao)) DO
    BEGIN
      /* A antiga rotina da deprecia??o estava pegando sempre o valor da moeda do m?s de aquisi??o, por isso
         fiz a busca do valor fora do while das refer?ncias, mas deixei como coment?rio caso seja feito
         para busca o valor da moeda conforme o m?s em que esta calculando
      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      if ((wvalormoeda is null) or (wvalormoeda = 0) or (position('UFIR',upper(wdescmoeda)) = 0))  then
        begin
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'0101';
          wrefmoedafim = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'1231';
    
          select max(tind.bdvalind) from tindval tind
                 where (tind.bdcodind = :wcodmoeda) and
                       (tind.bdrefind between :wrefmoedaini and :wrefmoedafim)
          into :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          if (wvalormoeda is null) then
            begin
              select first 1 tind.bdvalind from tindval tind
                     where tind.bdcodind = :wcodmoeda and
                     tind.bdrefind <= :wrefmoedaini
                     order by tind.bdrefind
              into :wvalormoeda;
            end
        end*/

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((COALESCE(prtaxadepreciacaoanual,0) = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        --#alt:16415 - Alterada a verifica??o do case, pois quando n?o havia nehuma contabiliza??o ele n?o levava o valor do bem. Ana - 05/12/2016
        --Faz o select com o First, pois um bem pode ter mais de uma deprecia??o cadastrada.
        --alt:14255 - 28/06/2016 - Adicionado case para verificar o tipo da contabiliza??o e ver de onde ir? buscar valor da aquisi??o. Pedro
        --SELECT FIRST 1 tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem,
        SELECT FIRST 1 tbem.bdcodorigbem, COALESCE(CASE WHEN ((tdep.BDCONTABILIZACAO = 0) OR (tdep.BDCONTABILIZACAO IS NULL) ) THEN tbem.BDVALAQUIBEM ELSE tdep.BDVALAQUISOC END, 0),
               tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem, tbem.bddepmesbaixabem,
               tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, COALESCE(tdep.bdvaldepacumubem,0),tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :wtaxaaux,         :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,     :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre, :wnumdias,        :wdepdiadata;

      --alt:13784 - 12/04/2016 - Se tiver trocado de taxa de deprecia??o, precisa levar os meses j? depreciados com a taxa anterior para o c?lculo da pr?xima. Pedro
      IF ((wtaxaant <> 0) AND (wtaxaant <> wtaxaaux)) THEN
        BEGIN
          wmesesdepreciadosoutrataxa = prmesesdepreciados;
          --alt:13784 - 12/04/2016 - Se estiver marcado para detalhar por taxa de deprecia??o, precisa retornar aqui a taxa. Pedro
          IF (prdetalhartaxadep = 1) THEN
            BEGIN
              prmesesdepreciar = prtotalmesesdepreciacao - prmesesdepreciados;
              prsomardepreciacao = 0; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
              SUSPEND;
            END
        END

      --alt:15793 - 22/09/2016 - Se tiver informa??o de deprecia??o em outra taxa ou valor acumulado, n?o ? o primeiro m?s a depreciar,
      --ent?o precisa mudar o valor desta vari?vel, pois estava calculando incorretamente a deprecia??o acumulada atual nestes casos. Pedro
      wFirst = IIF((wvaldepacumubem = 0) AND (wmesesdepreciadosoutrataxa = 0) AND (wFirst = 'TRUE'), 'TRUE', 'FALSE');

      --#alt:16929 - Quando h? um valor de deprecia??o acumulada cadastrado deve ser substituido pelo valor da deprecia??o acumulada anterior ao per?odo. Ana - 01/02/2017
      wdatainimes = SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                    SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
      wdatainicialcalculo = SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                            SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

      wdiasdepreciados = DATEDIFF(DAY,:wdatainicialcalculo,:wdatainimes);

      IF ((wdiasdepreciados < 30) AND (wdepreciacaoacumuladaanterior > 0) AND ((wdiasdepreciados > -1) OR (prdepreciacaoacumuladaanterior <> wdepreciacaoacumuladaanterior)) )THEN
        prdepreciacaoacumuladaanterior = wvaldepacumubem;
      --#alt:16929. fim

      SELECT prdepreciacaoperiodo, prdepreciacaoperiodomoeda, prcorrecaomonetariadepreciacao,
             prvalorresidualcontabil, prvalorresidualcontabilmoeda, prtotalmesesdepreciacao,
             prmesesdepreciados, prmesesdepreciar, prtaxadepreciacaoanual, prdatataxadepreciacao, prvalorbaixa,
             prdepreciacaobaixamoeda, prvalorbaixareal, prvalormoeda, prdatabaixa, prvaloraquisicaomoeda, prvalorcorrigidoanteriormoeda,
             prvaloraquisicaooriginal, prctadebitodepre, prvalordepreciacaodiariafim, prvalorcorrigidoanterior,
             prvalorcorrigidoatual, prdepreciacaoacumuladaanterior, prdepreciacaoacumuladaatualmoed, prdepreciacaoacumuladaatual, prcompensacaobaixaperanterior
      FROM sp_cons_calc_dep_correcao(:prcodemp, :prcodbem, :wdtini, :wdtfim, :prtipo, :prcontabilizacao,:wvalormoeda,:wpossuibaixa,:wcodbemoriginal,
                                     :prvaloraquisicaooriginal,:wtaxaaux,:wdataaquisicao,:wdataorigaquisicao,:wdepdia,:wdepmensal,
                                     :wdepmesbaixa,:wdatainiciocalc,:wdatafimcalc,:wdataultimoitemdep,:wvaldepacumubem,:prctadebitodepre,:wnumdias,
                                     :wdepdiadata, :wvalorbaixabem, :wmesesdepreciadosoutrataxa, :prdepreciacaoacumuladaatual)
      INTO   :wdepreciacaoperiodo, :wdepreciacaoperiodomoeda, :wcorrecaomonetariadepreciacao,
             :wvalorresidualcontabil, :wvalorresidualcontabilmoeda, :prtotalmesesdepreciacao,
             :wmesesdepreciados, :prmesesdepreciar, :prtaxadepreciacaoanual, :prdatataxadepreciacao, :wvalorbaixa, 
             :wdepreciacaobaixamoeda, :wvalorbaixareal, :prvalormoeda, :prdatabaixa, :wvaloraquisicaomoeda, :wvalorcorrigidoanteriormoeda, 
             :prvaloraquisicaooriginal, :prctadebitodepre, :prvalordepreciacaodiariafim, :wvalorcorrigidoanterior,
             :wvalorcorrigidoatual, :wdepreciacaoacumuladaanterior, :wdepreciacaoacumuladaatualmoed, :wdepreciacaoacumuladaatual, :prcompensacaobaixaperanterior;

      --#alt:16929 - Alterada verifica??o para substituir o valor da deprecia??o acumuludada anterior.
      -- Quando h? uma deprecia??o acumulada anterior cadastrada na taxa de deprecia??o, ent?o esta deve ser substituida. Ana - 31/01/2017
      --#Alt:5105 -> Acrescentado a vari?vel wfirst
      IF ((prdepreciacaoacumuladaanterior = 0)  AND (wdepreciacaoacumuladaanterior > 0) AND (wvaldepacumubem <> 0) /*AND (wfirst = 'TRUE')*/) THEN
        BEGIN
          wdepreciacaoacumuladaanterior = ABS(wdepreciacaoacumuladaanterior - prdepreciacaoacumuladaanterior);
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoacumuladaanterior;

          IF (wfirst = 'TRUE') THEN
          prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior;
        END
      wfirst = 'FALSE';

      IF (((wtaxaaux = prtaxadepreciacaoanual) OR (wtaxaaux = 0)) AND (prdepreciacaoacumuladaatualmoed = 0)) THEN
        BEGIN
          wdepreciacaoacumuladaatualmoed = ABS(wdepreciacaoacumuladaatualmoed - wdepreciacaoperiodomoeda);
          IF (wdepreciacaoacumuladaatualmoed > 0) THEN
            prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoacumuladaatualmoed;
        END

      IF ((wvalorcorrigidoanterior > 0) AND (prvalorcorrigidoanterior = 0)) THEN
        prvalorcorrigidoanterior = wvalorcorrigidoanterior;

      IF ((wvalorcorrigidoanteriormoeda > 0) AND (prvalorcorrigidoanteriormoeda = 0)) THEN
        prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;

      prdepreciacaoperiodo            = prdepreciacaoperiodo + COALESCE(wdepreciacaoperiodo,0);
      prdepreciacaoperiodomoeda       = prdepreciacaoperiodomoeda + COALESCE(wdepreciacaoperiodomoeda,0);
      prcorrecaomonetariadepreciacao  = prcorrecaomonetariadepreciacao + COALESCE(wcorrecaomonetariadepreciacao,0);

      --alt:14761 - 20/06/2016 - Quando h? baixa, pode n?o haver deprecia??o no per?odo, ent?o estava sendo calculado incorretamente. Pedro
      --alt:14624 - 14/06/2016 - Aparentemente estava somando novamente a deprecia??o do per?odo porque vinha
      --errado do sp_cons_calc_dep_correcao, por?m agora vem certo e estava somando valor de um m?s a mais. Pedro
      --prdepreciacaoacumuladaatual     = prdepreciacaoacumuladaatual + COALESCE(wdepreciacaoperiodo,0);
      --prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + COALESCE(wdepreciacaoperiodomoeda,0);
      --prdepreciacaoacumuladaatual     = prdepreciacaoacumuladaanterior + COALESCE(wdepreciacaoperiodo,0);
      --prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatual / COALESCE(wvalormoeda,0);

      --#alt:18200 - Comentado pois foram feitas altera??es na sp_cons_calc_dep_correcao que n?o h? mais necessidade de fazer esta verifica??o. Ana - 04/05/2017
      --alt:16006 - 03/11/2016 - S? deve carregar o saldo anterior no caso de ter baixa e n?o depreciar neste m?s, caso contrario, se estiver calculando mais de um m?s de uma vez, o saldo anterior vem incorreto. Pedro
      /*if ((wdepmesbaixa <> 'TRUE') and (wvalorbaixa > 0)) then
        prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;  */
      --alt:14624 - Fim

      --#alt:16852 - Quando n?o tiver uma taxa cadastrada ent?o deve levar o valor correto do valo residual que ? o valor original do bem - o total de baixas. Ana - 01/02/2017
      IF (prtotalmesesdepreciacao = 0) THEN
        prvalorresidualcontabil = wvalorresidualcontabil;
      ELSE
      IF (wvalorresidualcontabil > 0) THEN
        BEGIN
          wvalorresidualcontabil = ABS(wvalorresidualcontabil - prvalorresidualcontabil);
          --alt:16006 - 23/11/2016 - Corrigido para trazer o valor residual considerando quando houver baixa. Pedro
          --IF ((prvalorresidualcontabil > 0) AND (wdepreciacaoperiodo > 0) AND (wvalorresidualcontabil <> wdepreciacaoperiodo)) THEN
          --  wvalorresidualcontabil = wdepreciacaoperiodo;

          IF (wvalorresidualcontabil > 0) THEN
            prvalorresidualcontabil = ABS(prvalorresidualcontabil - wvalorresidualcontabil);
        END

      --#alt:16852 - Quando o valor da aquisi??o for o mesmo do valor residual o valor residual moeda ja vem correto da sp. Ana - 10/02/2017
      IF (prvaloraquisicaooriginal = prvalorresidualcontabil) THEN
        prvalorresidualcontabilmoeda = wvalorresidualcontabilmoeda;
      ELSE
      IF (wvalorresidualcontabilmoeda > 0) THEN
        BEGIN
          wvalorresidualcontabilmoeda = ABS(wvalorresidualcontabilmoeda - prvalorresidualcontabilmoeda);
          --alt:16006 - 23/11/2016 - Corrigido para trazer o valor residual considerando quando houver baixa. Pedro
          --IF ((prvalorresidualcontabilmoeda > 0) AND (wdepreciacaoperiodomoeda > 0) AND (wvalorresidualcontabilmoeda <> wdepreciacaoperiodomoeda)) THEN
          --  wvalorresidualcontabilmoeda = wdepreciacaoperiodomoeda;

          IF (wvalorresidualcontabilmoeda > 0) THEN
            prvalorresidualcontabilmoeda = ABS(prvalorresidualcontabilmoeda - wvalorresidualcontabilmoeda);
        END

      --alt:14761 - 20/06/2016 - Se tiver baixa no per?odo tamb?m precisa retornar os meses depreciados. Pedro
      --alt:14761 - 16/06/2016 - Se tiver valor de deprecia??o acumulada (informado no cadastro da deprecia??o)
      --? feito um c?lculo da quantidade de meses j? depreciados e assim precisa retornar eles tamb?m. Pedro
      IF ((wdepreciacaoperiodo > 0) OR (wvaldepacumubem > 0) OR (wvalorbaixa > 0)) THEN
        BEGIN
          IF ((wtaxaaux > 0) AND (wtaxaaux <> prtaxadepreciacaoanual)) THEN
            wmesesdepreciadosaux = wmesesdepreciadosaux + ABS(wmesesdepreciadosaux - prmesesdepreciados);

          IF ((wmesesdepreciados > 0) AND ((prmesesdepreciados = 0) OR (wmesesdepreciados > prmesesdepreciados))) THEN --alt:13784 - 12/04/2016 - Quando trocada a taxa de deprecia??o n?o estava levando os meses depreciados corretamente. Pedro
            prmesesdepreciados = wmesesdepreciados;
          --alt:9013 - Comentado pois essa valida??o n?o faz sentido quando ? deprecia??o di?ria. Pedro
          /*else
            if (not prmesesdepreciados = prtotalmesesdepreciacao) then
               prmesesdepreciados = prmesesdepreciados + 1; */
        END

      IF (wvalorbaixa > 0) THEN
        BEGIN
          --#alt:18200 - Comentado pois desta forma estava calculando o valor da baixa incorretamente. Ana - 04/05/2017
          --wvalorbaixa = ABS(wvalorbaixa - prvalorbaixa);
          IF (wvalorbaixa > 0) THEN
            prvalorbaixa = prvalorbaixa + wvalorbaixa;
        END

      IF (wdepreciacaobaixamoeda > 0) THEN
        BEGIN
          wdepreciacaobaixamoeda = ABS(wdepreciacaobaixamoeda - prdepreciacaobaixamoeda);
          IF (wdepreciacaobaixamoeda > 0) THEN
            prdepreciacaobaixamoeda = prdepreciacaobaixamoeda + wdepreciacaobaixamoeda;
        END

      IF (wvalorbaixareal > 0) THEN
        BEGIN
          wvalorbaixareal = ABS(wvalorbaixareal - prvalorbaixareal);
          IF (wvalorbaixareal > 0) THEN
            prvalorbaixareal = prvalorbaixareal + wvalorbaixareal;
        END

      IF (wvaloraquisicaomoeda > 0) THEN
        BEGIN
          wvaloraquisicaomoeda = ABS(wvaloraquisicaomoeda - prvaloraquisicaomoeda);
          IF (wvaloraquisicaomoeda > 0) THEN
            prvaloraquisicaomoeda = ABS(prvaloraquisicaomoeda - wvaloraquisicaomoeda);
        END

      IF (wvalorcorrigidoatual > 0) THEN
        BEGIN
          --#alt:18200 - O valor ja vem correto da sp_cons_calc_dep_correcao com as novas altera??es. Ana - 02/05/2017
          prvalorcorrigidoatual = wvalorcorrigidoatual;
          /*wvalorcorrigidoatual = ABS(wvalorcorrigidoatual - prvalorcorrigidoatual);
          IF (wvalorcorrigidoatual > 0) THEN
            prvalorcorrigidoatual = ABS(prvalorcorrigidoatual - wvalorcorrigidoatual);*/
          --#alt:18200. fim
        END

      --#alt:19501 - Foi feito o tratamento na sp de corre??o para quando o bem estiver totalmente baixado e n?o for o m?s da baixa total, ent?o todos os saldos devem ser zerados. Ana - 22/09/2017
      IF ((wdepreciacaoperiodo = 0) AND (wdepreciacaoacumuladaatual = 0) AND (prdepreciacaoacumuladaanterior <> 0) AND (prvalorbaixa = 0) ) THEN
        BEGIN
          prdepreciacaoacumuladaanterior = 0;
          prdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * wvalormoeda);
          --se n?o tiver baixa no per?odo da consulta, ent?o o bem ja foi totalmente baixado. Com isso o saldo anterior, valor residual e valor residual moeda devem ir zerados
          IF (wpossuibaixa = 'FALSE') THEN
            BEGIN
              prdepreciacaoacumuladaatual  = 0;
              prvalorresidualcontabil      = 0;
              prvalorresidualcontabilmoeda = 0;
            END
        END
      ELSE
        IF ((prdepreciacaoacumuladaatual = 0) OR (wdepreciacaoacumuladaatual <> 0)) THEN
        BEGIN
          --antes o valor de retorno da sp era setado direto na vari?vel de retorno, mas n?o deve substituir sempre
          prdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual;
        END
      --#alt:19501. fim

      IF (prdatabaixa IS NOT NULL) THEN
        BEGIN
          wdtbaixaaux = prdatabaixa;
          --#alt:19501 - Atribui ? vari?vel o valor true quando possuir alguma baixa no per?odo. Colocando como true n?o interfere na sp da corre??o, pois la dentro ? refeita esta verifica??o. Ana - 22/09/2017'
          wpossuibaixa = 'TRUE';
        END

      wtaxaant = wtaxaaux;
      wtaxaaux = COALESCE(prtaxadepreciacaoanual,0);
      wdtini   = addmonth(wdtini, 1);
      wdtfim   = addmonth(wdtini, 1)-1;
      IF (wdtfim > prdatafinal) THEN
        wdtfim = prdatafinal;
      wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  --#alt:18200 - Alterada forma de c?lculo do valor corrigido atual (valor corrigido anterior + corre??o do per?odo - valor de baixas do per?odo). Ana - 02/05/2017
  prvalorcorrigidoatual = (prvalorcorrigidoanterior + prcorrecaoperiodo - prvalorbaixa);

  --#alt:19501 - Se o valor corrigido atual for zero, ent?o o bem ja foi totalmente depreciado/baixado. Ana - 22/09/2017
  IF (prvalorcorrigidoatual = 0) THEN
    BEGIN
      prcorrecaomonetariadepreciacao = 0;
      prvalorresidualcontabil        = 0;
      prvalorresidualcontabilmoeda   = 0;
    END

  prtotalmesesdepreciacao = prtotalmesesdepreciacao + wmesesdepreciadosaux;
  --alt:11609 - 21/10/2015 - Corrigido, estava retornando o valor incorreto para o meses a depreciar. H? um outro c?lculo 
  --que ? feito na vari?vel wmesesdepreciados que n?o estava sendo propagado por pegar o valor do prmesesdepreciados. Pedro
  prmesesdepreciar        = prtotalmesesdepreciacao - prmesesdepreciados; --alt:13978 - 06/04/2016 - Voltado como era antes, corrigido o tratamento dos campos. Pedro
  --prmesesdepreciar        = prtotalmesesdepreciacao - wmesesdepreciados;

  --#alt:16929 - Estava trazendo a quantidade de meses depreciados maior que o total de meses de deprecia??o e os meses a depreciar negativo. Ana - 01/02/2017
  IF (prmesesdepreciados > prtotalmesesdepreciacao) THEN
    BEGIN
      prmesesdepreciados = prtotalmesesdepreciacao;
      prmesesdepreciar   = 0;
    END

  --#alt:16852 - Quando n?o tiver uma taxa cadastrada ent?o deve levar o valor correto do valor residual. Quando o valor residual for 0 o residual moeda tamb?m deve ser. Ana - 08/02/2017
  IF (((prtotalmesesdepreciacao = prmesesdepreciados) AND (prtotalmesesdepreciacao > 0)) OR (prvalorresidualcontabil = 0)) THEN
    BEGIN
      prcorrecaomonetariadepreciacao = 0;
      prvalorresidualcontabil        = 0;
      prvalorresidualcontabilmoeda   = 0;
    END

  --#alt:17098 - Com um per?odo maior do que a data da baixa estava retornando null, ent?o se teve alguma baixa durante o per?odo selecionado deve retornar essa data. Ana - 19/05/2017
  IF ((prdatabaixa IS NULL) AND (wdtbaixaaux IS NOT NULL))THEN
    prdatabaixa = wdtbaixaaux;

  --alt:9581 - Joga o valor para a vari?vel de retorno, antes no ?ltimo m?s em alguns casos n?o retornava nada. Pedro
  --prmesesdepreciados = wmesesdepreciados; --alt:13978 - 06/04/2016 - Agora o retorno est? correto acima, e se jogar o valor aqui, mata outro tratamento acima. Pedro

  --#Alt:5105
  IF (prvaloraquisicaooriginal = wvalorbaixabem) THEN
    BEGIN
      prvalorresidualcontabil      = 0;
      prvalorresidualcontabilmoeda = 0;

      IF ((wdepmesbaixa = 'TRUE') AND
          (wreffim > CAST((SUBSTRING(wdtbaixaaux FROM 1 FOR 4)) || (SUBSTRING(wdtbaixaaux FROM 6 FOR 2)) AS INTEGER))) THEN
        BEGIN
          prvalorcorrigidoanterior        = 0;
          prcorrecaoperiodo               = 0;
          prvalorcorrigidoatual           = 0;
          prvalorbaixa                    = 0;
          prdepreciacaoacumuladaanterior  = 0;
          prdepreciacaoperiodo            = 0;
          prdepreciacaoperiodomoeda       = 0;
          prdepreciacaoacumuladaatual     = 0;
          prdepreciacaoacumuladaatualmoed = 0;
          prcorrecaomonetariadepreciacao  = 0;
          prtotalmesesdepreciacao         = 0;
          prmesesdepreciados              = 0;
          prmesesdepreciar                = 0;
        END
    END

  prsomardepreciacao = 1; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
  SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: SP_CONS_CALC_DEP for: SP_CONS_CALC_DEP_CORRECAO */
ALTER PROCEDURE SP_CONS_CALC_DEP(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER,
PRDETALHARTAXADEP INTEGER = 0)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,6),
PRCORRECAOPERIODO NUMERIC(15,6),
PRVALORCORRIGIDOATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6),
PRDEPRECIACAOPERIODO NUMERIC(15,6),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6),
PRVALORRESIDUALCONTABIL NUMERIC(15,6),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,6),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,6),
PRVALORBAIXAREAL NUMERIC(15,6),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,6),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,6),
BDCODEMP INTEGER,
BDCODBEM INTEGER,
PRSOMARDEPRECIACAO INTEGER,
PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_CONS_CALC_DEP_CORRECAO) */
ALTER PROCEDURE SP_CONS_CALC_DEP_CORRECAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER,
PRVLRMOEDA NUMERIC(15,6),
PRPOSSUIBAIXA VARCHAR(5),
PRCODBEMORIGINAL INTEGER,
PRVALORAQUISICAO NUMERIC(15,6),
PRTAXADEPANUAL NUMERIC(6,6),
PRDATAAQUISICAO DATE,
PRDATAORIGAQUISICAO DATE,
PRDEPDIA VARCHAR(5),
PRDEPMENSAL VARCHAR(5),
PRDEPMESBAIXA VARCHAR(5),
PRDATAINICIOCALC DATE,
PRDATAFIMCALC DATE,
PRDATAULTIMOITEMDEP DATE,
PRVALDEPACUMUBEM NUMERIC(15,6),
PRCTADEBDEPRE INTEGER,
PRNUMDIAS INTEGER,
PRDEPDIADATA INTEGER,
PRVALORBAIXABEM NUMERIC(15,6),
PRMESESDEPRECIADOSOUTRATAXA INTEGER,
PRVALORACUMULADOANTERIOR NUMERIC(15,6))
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,6),
PRCORRECAOPERIODO NUMERIC(15,6),
PRVALORCORRIGIDOATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6),
PRDEPRECIACAOPERIODO NUMERIC(15,6),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6),
PRVALORRESIDUALCONTABIL NUMERIC(15,6),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,6),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,6),
PRVALORBAIXAREAL NUMERIC(15,6),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,6),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,6),
PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOPERIODO DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED DOUBLE PRECISION;
DECLARE VARIABLE WVALORRESIDUALCONTABIL DOUBLE PRECISION;
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WDIASDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WVALORAQUISICAO DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOAUX DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOORIGINAL DOUBLE PRECISION;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAATUAL DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALORBAIXA DOUBLE PRECISION;
DECLARE VARIABLE WVALORBAIXAAUX DOUBLE PRECISION;
DECLARE VARIABLE WVALORBAIXAPER DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPDIASADEPRECIAR INTEGER;
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WTOTALMESESDOPERIODO INTEGER;
DECLARE VARIABLE WVALORDEPRECIACAOMENSAL DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPRECIACAODIARIA DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPRECIACAODIARIABAIXA DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDIFERENCAMESES INTEGER;
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WVALDEPACUMUBEM DOUBLE PRECISION;
DECLARE VARIABLE WMESESDEPACUMUBEM INTEGER;
DECLARE VARIABLE WDATAOFICIALINICIOLCALCULO DATE;
DECLARE VARIABLE WDATAINICIALINICIOCALCULO DATE;
DECLARE VARIABLE WULTIMODIADOMES SMALLINT;
DECLARE VARIABLE WDIA SMALLINT;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WDEPDIADATA INTEGER;
DECLARE VARIABLE WDATAINICIALOFICIAL DATE;
DECLARE VARIABLE WDEPDIAFINAL VARCHAR(5);
DECLARE VARIABLE WDATATOTALMESESULTIMODIA DATE;
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATATOTALMESESDEPDIA DATE;
DECLARE VARIABLE WVALORCORRIGIDOANTERIORMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WVERIFICAMESINTEIRO INTEGER;
DECLARE VARIABLE WDIASDEPDIARIA DOUBLE PRECISION;
DECLARE VARIABLE WMESESDEPDIARIA DOUBLE PRECISION;
DECLARE VARIABLE WDATAINICIOCALCAUX DATE;
BEGIN
  /*Stored procedure para calcular a deprecia??o dos bens*/
  -- Inicializa par?metros
  PRVALORCORRIGIDOANTERIOR        = 0;
  PRCORRECAOPERIODO               = 0;
  PRVALORCORRIGIDOATUAL           = 0;
  PRDEPRECIACAOACUMULADAANTERIOR  = 0;
  PRDEPRECIACAOPERIODO            = 0;
  PRDEPRECIACAOPERIODOMOEDA       = 0;
  PRDEPRECIACAOACUMULADAATUAL     = 0;
  PRDEPRECIACAOACUMULADAATUALMOED = 0;
  PRCORRECAOMONETARIADEPRECIACAO  = 0;
  PRVALORRESIDUALCONTABIL         = 0;
  PRVALORRESIDUALCONTABILMOEDA    = 0;
  PRTOTALMESESDEPRECIACAO         = 0;
  PRMESESDEPRECIADOS              = 0;
  PRMESESDEPRECIAR                = 0;
  PRTAXADEPRECIACAOANUAL          = 0;
  PRDATATAXADEPRECIACAO           = NULL;
  PRVALORBAIXA                    = 0;
  PRDEPRECIACAOBAIXAMOEDA         = 0;
  PRVALORBAIXAREAL                = 0;
  PRVALORMOEDA                    = 0;
  PRDATABAIXA                     = NULL;
  PRVALORAQUISICAOMOEDA           = 0;
  PRVALORCORRIGIDOANTERIORMOEDA   = 0;
  PRVALORAQUISICAOORIGINAL        = 0;
  PRCTADEBITODEPRE                = NULL;
  PRVALORDEPRECIACAODIARIAFIM     = 0;

  -- Inicializa vari?veis
  wdatainicialoficial            = prdatainicial;
  wdepdiafinal                   = 'FALSE';
  wnumdias                       = 0;
  wdepdiadata                    = 0;
  wultimodiadomes                = 0;
  wdepdiasadepreciar             = 0;
  wvalordepreciacaodiaria        = 0;
  wvalordepreciacaodiariabaixa   = 0;
  wvaloraquisicaomoeda           = 0;
  wvalorcorrigidoanterior        = 0;
  wdepreciacaoacumuladaanterior  = 0;
  wdepreciacaoperiodo            = 0;
  wdepreciacaoperiodomoeda       = 0;
  wdepreciacaoacumuladaatual     = 0;
  wdepreciacaoacumuladaatualmoed = 0;
  wvalorresidualcontabil         = 0;
  wvalorresidualcontabilmoeda    = 0;
  wtotalmesesdepreciacao         = 0;
  wmesesdepreciados              = 0;
  wdiasdepreciados               = 0;
  wmesesdepreciar                = 0;
  wvaloraquisicao                = 0;
  wvaloraquisicaoaux             = 0;
  wvaloraquisicaooriginal       = 0;
  wdataaquisicao                 = NULL;
  wdatainiciocalc                = NULL;
  wdatafimcalc                   = NULL;
  wdataatual                     = :prdatafinal;
  wdatatotalmeses                = NULL;
  wdatatotalmesesdepdia          = NULL;
  wdatatotalmesesultimodia       = NULL;
  wdataultimoitemdep             = NULL;
  wvalorbaixa                    = 0;
  wvalorbaixaaux                 = 0;
  wvalorbaixaper                 = 0;
  wvaldepacumubem                = 0;
  wmesesdepacumubem              = 0;
  wdataoficialiniciolcalculo     = NULL;
  wdatainicialiniciocalculo      = NULL;
  --alt:16494 - 25/11/2016 - Inicializar a vari?vel, ficava null quando calculava um per?odo antes do in?cio
  --da deprecia??o, assim os meses que deveriam depreciar concatenava com null e ficava sempre null. Pedro
  prvaloracumuladoanterior       = COALESCE(prvaloracumuladoanterior, 0);

  -- Para melhorar o desempenho da rotina esse select foi jogado na Stored Procedure SP_CONS_CALC_DEP para ser chamada apenas quando
  -- for necess?ria. As informa??es do select est?o sendo passadas por par?metro
  /*select tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem,
         tbem.bddepmesbaixabem, tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, tdep.bdvaldepacumubem,tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
  from empresas_tbem tbem
  left outer join empresas_tdepreciacao tdep on ((tbem.bdcodemp = tdep.bdcodemp) and (tbem.bdcodbem = tdep.bdcodbem) and
                                                 (tdep.bdcontabilizacao = :prcontabilizacao) and
                                                 (Cast((substring(tdep.bddatinicalcbem from 1 for 4)) || (substring(tdep.bddatinicalcbem from 6 for 2)) as integer) <=
                                                  Cast((substring(:prdatainicial from 1 for 4)) || (substring(:prdatainicial from 6 for 2)) as integer)) and
                                                 ((Cast((substring(tdep.bddatfimcalcbem from 1 for 4)) || (substring(tdep.bddatfimcalcbem from 6 for 2)) as integer) >=
                                                   Cast((substring(:prdatafinal from 1 for 4)) || (substring(:prdatafinal from 6 for 2)) as integer)) or (tdep.bddatfimcalcbem is null)))
  where (tbem.bdcodemp = :prcodemp) and
        (tbem.bdcodbem = :prcodbem)
  into :wcodbemoriginal, :wvaloraquisicao,    :prtaxadepreciacaoanual,
       :wdataaquisicao,  :wdataorigaquisicao, :wdepdia,            :wdepmensal, : wdepmesbaixa,
       :wdatainiciocalc, :wdatafimcalc,       :wdataultimoitemdep, :wvaldepacumubem, :prctadebitodepre, :wnumdias, :wdepdiadata;*/
  --wcodbemoriginal        = prcodbemoriginal;
  wvaloraquisicao        = prvaloraquisicao;
  wvaloraquisicaooriginal= wvaloraquisicao;
  prtaxadepreciacaoanual = prtaxadepanual;
  wdataaquisicao         = prdataaquisicao;
  wdataorigaquisicao     = prdataorigaquisicao;
  wdepdia                = prdepdia;
  wdepmensal             = prdepmensal;
  wdepmesbaixa           = prdepmesbaixa;
  wdatainiciocalc        = prdatainiciocalc;
  wdatafimcalc           = prdatafimcalc;
  wdataultimoitemdep     = prdataultimoitemdep;
  wvaldepacumubem        = prvaldepacumubem;
  prctadebitodepre       = prctadebdepre;
  wnumdias               = prnumdias;
  wdepdiadata            = prdepdiadata;
  wdepreciacaoacumuladaatual = prvaloracumuladoanterior;

  IF (wvaloraquisicao IS NULL) THEN
     BEGIN
       EXCEPTION ex_date;
       SUSPEND;
       EXIT;
     END

   IF (prdatainicial > wdatafimcalc) THEN
     EXIT;

  --alt:16006 - 03/11/2016 - Implementado aqui o c?lculo da baixa de todos os per?odos. Pedro
  --Processo para calcular os meses anteriores ao per?odo informado, pois posso ter v?rias deprecia??es cadastradas
  SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  AND   (tbai.BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
  INTO :wvalorbaixa;
  IF (wvalorbaixa > 0) THEN
    prpossuibaixa = 'TRUE';

  --#alt:85169. Deve fazer os outros c?lculos. Ana - 20/06/2018
  --Tipo 2 somente baixas
  /*IF ((prtipo = 2) AND (wvalorbaixa = 0)) THEN
    EXIT;*/
  --alt:16006 - Fim

  prvaloraquisicaooriginal = wvaloraquisicao;
  /*#Alt:5105. Conforme visto com o Celso quando o bem tem alguma baixa parcial o sistema calcula a depreci??o desde o in?cio levando em conta
  a baixa, e n?o apenas no m?s da baixa pra frente.*/
  --wvalorbaixa = 0;
  --wvalorbaixa = prvalorbaixabem; --alt:16006 - Calcula aqui o valor da baixa. Pedro
  IF (prpossuibaixa = 'TRUE') THEN
    BEGIN
      FOR SELECT bddatbai,COALESCE(SUM(bdvalbai),0) AS TotalBaixa FROM empresas_tbai
          WHERE (bdcodemp = :prcodemp) AND (bdcodbem = :prcodbem) AND (BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
          AND   (bddatbai BETWEEN :prdatainicial AND :prdatafinal) GROUP BY bddatbai
          INTO :wdatabaixa,:wvalorbaixaaux DO
        BEGIN
          --#Alt:5105
          --wvalorbaixa = wvalorbaixa + wvalorbaixaaux;
          wvalorbaixaper = wvalorbaixaper + wvalorbaixaaux;
        END
    END
  wvaloraquisicao = (wvaloraquisicao - wvalorbaixa);

  --alt:8005 - Foi removida esta valida??o porque n?o faz sentido e fazia com que n?o funcionasse corretamente em alguns casos. Pedro
  IF ((UPPER(wdepmesbaixa) = 'TRUE') /*and (wvalorbaixa >= wvaloraquisicao)*/) THEN
    BEGIN
      --alt:8005 - Foi removido porque n?o faz sentido setar um ano igual ao outro sendo que vai comparar os dois depois, isso fazia com que n?o funcionasse corretamente em alguns casos. Pedro
      --prdatafinal = wdatabaixa;

      --alt:8005 - Estava ocorrendo um erro no m?s da baixa, por isso foi adicionada a valida??o do "wdatabaixa is null".
      --Mas isso gerou outro problema agora e aparentemente o problema que acontecia antes n?o ocorreu mais, ent?o retirei. Pedro
      IF ((CAST((SUBSTRING(wdatabaixa FROM 1 FOR 4)) || (SUBSTRING(wdatabaixa FROM 6 FOR 2)) AS INTEGER) <=
          CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER))) THEN
        wdepmesbaixa = 'TRUE';
      ELSE
        wdepmesbaixa = 'FALSE';
    END
  ELSE
    wdepmesbaixa = 'FALSE';

  --alt:9013 - Foi colocado aqui o c?lculo do valor corrigido atual, pois precisava ser antes de juntar novamente o valor da baixa ao valor da aquisi??o. Pedro
  -- C?LCULO DE DEPRECIA??O
  prcorrecaoperiodo     = 0;

  --#alt:18200. Desta forma que estava retornando o valor n?o estava correta. Ana - 02/05/2017
  --#alt:16852 - Adicionada verifica??o para retornar o valor da baixa do per?odo quando tiver taxa cadastrada, pois estava calculando errado o valor residual. Ana - 01/02/2017
  /*if (prtaxadepanual <> 0) then
    prvalorcorrigidoatual = wvalorbaixaper;
  else
    prvalorcorrigidoatual = wvalorbaixa;*/

  --alt:9581 - Foi alterado para jogar devolta apenas a baixa do per?odo, n?o a baixa de todos os per?odos,
  --pois quando tinha mais de uma baixa e estava marcada a op??o calcular deprecia??o do m?s da baixa ele trazia o valor original para a deprecia??o do m?s,
  --sendo que deveria ser o valor original menos baixas que tenham ocorrido em per?odo anterior. Pedro
  IF ((UPPER(wdepmesbaixa) = 'TRUE') /*and (wdatabaixa is null)*/) THEN
    --wvaloraquisicao = (wvaloraquisicao + wvalorbaixa);
    wvaloraquisicao = (wvaloraquisicao + wvalorbaixaper);

  --alt:9581 - Implementado aqui, pois se cair no exit precisa retornar a quantidade de meses depreciados. Pedro
  IF (wdatainiciocalc IS NOT NULL) THEN
    wdataoficialiniciolcalculo = wdatainiciocalc;
  ELSE
    wdataoficialiniciolcalculo =  wdataaquisicao;

  -- Meses j? depreciados
  wmesesdepreciados = DATEDIFF(MONTH,:wdataoficialiniciolcalculo,:wdataatual);
  IF (wmesesdepreciados < 0) THEN
    wmesesdepreciados = 0;

  --#alt:16929 - Adicionada verifica??o para atribuir o valor do campo cadastrado na depreci??o acumulada, pois estava ignorando este campo e fazendo os calculos errados. Ana - 31/01/2017
  wdatainicialoficial = SUBSTRING(CAST(prdatainicial AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                        SUBSTRING(CAST(prdatainicial AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
  wdatainicialiniciocalculo = SUBSTRING(CAST(wdataoficialiniciolcalculo AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdataoficialiniciolcalculo AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

  wdiasdepreciados = DATEDIFF(DAY,:wdatainicialiniciocalculo,:wdatainicialoficial);
  IF ((wvaldepacumubem <> 0) AND ((wdiasdepreciados < 30) AND ((wvaldepacumubem <> prdepreciacaoacumuladaanterior) OR (wdiasdepreciados > -1)))) THEN
    wdepreciacaoacumuladaatual = wVALDEPACUMUBEM;
  wdatainicialoficial = prdatainicial;
  --#alt:16929. fim

  --alt:13784 - 12/04/2016 - Implementado para contar corretamente no caso de ter duas taxas de deprecia??o distintas. Pedro
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) /*>*/=
      CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER)) THEN
    wmesesdepreciados = wmesesdepreciados + 1;

  IF (prmesesdepreciadosoutrataxa > 0) THEN --alt:13784 - 12/04/2016 - Se j? tiver depreciado algum m?s com a taxa anterior, precisa somar esses meses tamb?m. Pedro
    wmesesdepreciados = wmesesdepreciados + prmesesdepreciadosoutrataxa;
  --alt:13784 - Fim

  prmesesdepreciados = wmesesdepreciados;
  --alt:9581 - Fim

  IF ((((wvaloraquisicao IS NULL) OR (wvaloraquisicao <= 0))) AND (UPPER(wdepmesbaixa) = 'FALSE')) THEN
     BEGIN
       --alt:14624 - 27/05/2016 - Se tiver baixa no per?odo, precisa calcular o valor depreciado at? ent?o. Pedro
       --alt:14761 - 20/06/2016 - Adicionados par?metros remanescentes. Pedro
       --alt:15375 - 12/08/2016 - Adicionada verifica??o do valor da aquisi??o, este processo ? executado no cadastro de deprecia??o
       --para verificar se h? valor depreciado anterior a ele, e como n?o possui valor da aquisi??o ainda, ocorre erro. Pedro
       ------- if ((wvaloraquisicao is not null) and (wvaloraquisicao > 0)) then  **** Essa regra estava dando problema. Foi comentado porque n?o conseguiram explicar a raz?o dela (Solicita??o.: 15605)
       --#alt:15259 - Quando o valor vinha zerado gerava um erro. Ana - 16/09/2016
       IF ( prtaxadepreciacaoanual <> 0) THEN
         BEGIN
           wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
           wvalordepreciacaomensal = (prvaloraquisicao / wtotalmesesdepreciacao);
         END

       --#alt:19501 - Se o bem ja foi totalmente baixado ent?o n?o deve possuir deprecia??o acumulada anterior e nem deprecia??o no per?odo, quando consultado em um per?odo ap?s a baixa total. Ana - 21/09/2017
       IF ((wvalorbaixa >= wvaloraquisicaooriginal) AND (wvalorbaixa <> wvalorbaixaper) AND (wvalorbaixaper = 0)) THEN
         BEGIN
           prdepreciacaoacumuladaanterior = 0;
           wdepreciacaoacumuladaatual = wvaloraquisicao;
           wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual;
         END
       ELSE
         BEGIN
           IF ((wvalordepreciacaodiaria > 0) AND (wdatainicialoficial <= :wdataaquisicao))  THEN
             BEGIN
               --alt:16006 - 03/11/2016 - Alterado para carregar o valor acumulado depreciado de uma vari?vel que calcula m?s a m?s, pois quando na aquisi??o utilizava a deprecia??o di?ria, nos meses seguintes desconsiderava este valor. Pedro
               --wdepreciacaoacumuladaatual     = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wmesesdepreciados);
               wdepreciacaoacumuladaatual     = (wvalordepreciacaodiaria + wvalordepreciacaomensal + wdepreciacaoacumuladaatual);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
             END
           ELSE
             BEGIN
               --alt:16006 - 03/11/2016 - Alterado para carregar o valor acumulado depreciado de uma vari?vel que calcula m?s a m?s, pois quando na aquisi??o utilizava a deprecia??o di?ria, nos meses seguintes desconsiderava este valor. Pedro
               --wdepreciacaoacumuladaatual     = (wvalordepreciacaomensal * wmesesdepreciados);
               wdepreciacaoacumuladaatual     = (wvalordepreciacaomensal + wdepreciacaoacumuladaatual);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
             END
    
           --#Alt:5105
           IF (wvalorbaixaper > 0) THEN
             BEGIN
               prdatabaixa  = wdatabaixa;
               prvalorbaixa = wvalorbaixaper;
               wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual - wvalordepreciacaomensal);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
               prdepreciacaoacumuladaanterior = wdepreciacaoacumuladaatual;
    
               --#Alt:16327 (In?cio) - Precisa ser setado o valor corrigido anterior mesmo que o valor do bem j? tenha baixado totalmente. E o
               --valor ? jogado para uma vari?vel local do tipo Double Precision e depois para a de sa?da,
               --pois pode gerar um erro de "Aritmethic Overflow" por calcular um valor grande demais.
               wvalorcorrigidoanterior  = (wvaloraquisicao + wvalorbaixaper);
               prvalorcorrigidoanterior = wvalorcorrigidoanterior;
    
               wvalorcorrigidoanteriormoeda  = (wvaloraquisicao + wvalorbaixaper) / prvlrmoeda;
               prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;
               --#Alt:16327 (Fim)
             END
           ELSE
             prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaatual - wvalordepreciacaomensal;
         END

       prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
       prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
       prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
       --alt:14624 - Fim
       --alt:14761 - Fim
       prcompensacaobaixaperanterior = wdepreciacaoacumuladaatual; --alt:16006 - 24/11/2016 - Tratado para retornar o valor da deprecia??o acumulada para quando tem baixa total. Pedro

       --alt:15196 - 24/11/2016 - Adapta??o para zerar o valor residual da deprecia??o. Pedro
       IF ((prdepreciacaoacumuladaanterior + wtotalmesesdepreciacao) > wvaloraquisicao) THEN
         BEGIN
           IF (prdepreciacaoacumuladaanterior < wvaloraquisicao) THEN
             BEGIN
               wtotalmesesdepreciacao = wvaloraquisicao - prdepreciacaoacumuladaanterior;
               prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior + wtotalmesesdepreciacao;
             END
           ELSE
             BEGIN
               wtotalmesesdepreciacao = 0;
               --#alt:19501 - N?o deve assumir o valor da aquisi??o, pois mesmo que o bem ja tenha sido totalmente baixado ainda h? como depreciar o valor acumulado anterior. Ana - 21/09/2017
               --prdepreciacaoacumuladaatual = wvaloraquisicao;
             END
    
           prdepreciacaoperiodomoeda = wtotalmesesdepreciacao * prvlrmoeda;
           prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatual * prvlrmoeda;
           prdepreciacaoperiodo = wtotalmesesdepreciacao;
         END

       SUSPEND;
       EXIT;
     END

  IF (prtipo = 2) THEN
    BEGIN
      --#alt:85169. Ana - 20/06/2018
      wvaloraquisicaoaux       = wvaloraquisicao;
      if ((wvalorbaixaper > 0) and (wvalorbaixa > 0)) then
        begin
          wvaloraquisicao          = wvalorbaixa;
          --prvaloraquisicaooriginal = wvalorbaixa;
        end
      --#alt:85169. fim
    END

  --alt:9013 - Foi retirado daqui e colocado mais acima, pois quando chegava aqui o valor estava incorreto, baseado no valor original da aquisi??o, desconsiderando a baixa. Pedro
  -- C?LCULO DE DEPRECIA??O
  /*prcorrecaoperiodo     = 0;
  prvalorcorrigidoatual = wvaloraquisicao;*/

  -- Deprecia??o di?ria (In?cio)
  --#alt:19501 - Alterada verifica??o da vari?vel "wNumDias". Ana - 24/10/2017
  --#alt:18200 - N?o estava fazendo a deprecia??o di?ria quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
  --alt:15196 - 24/11/2016 - Adicionada valida??o do "wNumDias", caso esteja selecionado para iniciar a deprecia??o no
  --dia seguinte ? aquisi??o, ter? um dia a menos para depreciar, e n?o ser? mais deprecia??o mensal nesta regra. Pedro
  --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
  --IF ((UPPER(wdepdia) = 'TRUE' ) AND ((SUBSTRING(wdatainiciocalc FROM 9 FOR 2)) = '01')) THEN
  IF ((UPPER(wdepdia) = 'TRUE') AND (wnumdias <= 2) AND
      (((EXTRACT(DAY FROM wdatainiciocalc) = 1) AND (wdatainiciocalc BETWEEN prdatainicial AND prdatafinal)) OR
       ((wdatabaixa BETWEEN prdatainicial AND prdatafinal) AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0)))) THEN
    wdepdia = 'FALSE';

  IF (UPPER(wdepdia) = 'TRUE') THEN
    BEGIN
      --#alt:18200 - Adicionei a verifica??o da diferen?a de meses da baixa para a aquisi??o do bem, pois n?o estava fazendo a deprecia??o di?ria corretamente
      --             quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
      --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
      IF ((wdatabaixa BETWEEN prdatainicial AND prdatafinal) AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0)) THEN
        BEGIN
          --alt:16006 - 03/11/2016 - Se n?o for uma baixa total, ent?o deve dividir o m?s em duas partes para calcular a deprecia??o sobre o valor do bem antes e depois da baixa. Pedro
          IF (wvaloraquisicao <= 0) THEN
            wdepdiasadepreciar = EXTRACT(DAY FROM wdatabaixa);
          ELSE
            wdepdiasadepreciar = EXTRACT(DAY FROM wdatabaixa) -1;
        END
      ELSE
        BEGIN
          -- Total de meses para a deprecia??o
          IF (prtaxadepreciacaoanual >= 0.1) THEN
            wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);

          --#alt:19501 - N?o estava considerando os dias a depreciar quando tem deprecia??o acumulada informada. Ana - 24/10/2017
          IF ((wvaldepacumubem <> 0) AND (wtotalmesesdepreciacao <> 0)) THEN
            BEGIN
              wmesesdepdiaria = (wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
              wverificamesinteiro = (TRUNC(wmesesdepdiaria));
              wdiasdepdiaria = (wmesesdepdiaria - wverificamesinteiro);
              IF (wdiasdepdiaria > 0) THEN
                BEGIN
                  --#alt:21342 - Quando a quantidade de dias depreciados for igual a 0.01 significa que h? um valor de depreci??o di?ria mas n?o fecha em um dia completo.
                  --             para isso truncamos o valor em 0.04 que j? equivale a um dia para conseguir fazer os calculos. Ana - 09/11/2017
                  IF (wdiasdepdiaria < 0.04) THEN
                    wdiasdepdiaria = 0.04;

                  wmes = (ABS((TRUNC((((wmesesdepdiaria)/12) - TRUNC((wmesesdepdiaria)/12)) * 12)-12)+1));
                  wano = (EXTRACT(YEAR FROM wdatainiciocalc));
                  wano = (wano - TRUNC(wverificamesinteiro/12));

                  --#alt:21342 - Tenho que considerar a quantidade de dia de cada m?s e n?o deixar fixo 30 dias. Ana - 13/11/2017
                  SELECT ULTDIA FROM ULTIMO_DIA_MES(:wmes, :wano)
                  INTO :wUltimoDiaDoMes;
                  IF (wUltimoDiaDoMes > 0) THEN
                    wdepdiasadepreciar = (TRUNC(wdiasdepdiaria * wUltimoDiaDoMes));

                  --#alt:21342 - Adicionei a verifica??o dos dias para n?o ocorrer erro na conver??o. Ana - 09/11/2017
                  IF ((wdepdiasadepreciar > 0) AND (wano > 0) AND (wmes > 0) )THEN
                    wdatainiciocalcaux = (CAST(wano AS VARCHAR(4)) ||'-'|| CAST(wmes AS VARCHAR(2)) ||'-'|| CAST(wdepdiasadepreciar AS VARCHAR(2)));
                END
            END
          ELSE
            BEGIN
          wdepdiasadepreciar = EXTRACT(DAY FROM wdatainiciocalc);
              wdatainiciocalcaux = wdatainiciocalc;
            END

          -- C?lculo que retorna o ?ltimo dia do m?s
          --alt:18200 - 22/05/2017 - Corrigido, j? reduz um dia a mais quando ? pra depreciar apenas no dia seguinte. Pedro
          --#alt:18200 - Quando for dia 31 deve considerar como 30 dias e depreciar apenas um dia. Ana - 19/05/2017
          IF (wnumdias = 2) THEN
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatainiciocalcaux - EXTRACT(DAY FROM wdatainiciocalcaux) +
                                                32 - EXTRACT(DAY FROM wdatainiciocalcaux - EXTRACT(DAY FROM wdatainiciocalcaux) + 32)));
          ELSE
            wUltimoDiaDoMes = 30;

          --alt:8005 - Adicionado um dia a mais, pois sempre faltava um dia no c?lculo di?rio. Pedro
          --IF (wnumdias = 2) THEN
          IF (wvaldepacumubem = 0) THEN
            wdepdiasadepreciar = (wultimodiadomes + 1) - wdepdiasadepreciar;
          ELSE
            BEGIN
              --#alt:18204 - Quando o mes tinha 31 dias estava desconciderando o ultimo dia para depreciar. Ana - 28/04/2017
              /*IF (wultimodiadomes = 31) THEN
                wdepdiasadepreciar = (32) - wdepdiasadepreciar;
              ELSE*/
                wdepdiasadepreciar = (30 + 1) - wdepdiasadepreciar;
            END
          --alt:8005 - Fim
          -- Caso a op??o Dia seguinte a aquisi??o esteja selecionada preciso diminuir um dia no
          -- n?mero de dias a depreciar, pois a wdepdiasadepreciar veio calculada conforme
          -- a data de aquisi??o
          IF (wdepdiadata = 2) THEN
            wdepdiasadepreciar = wdepdiasadepreciar - 1;
          IF (wdepdiasadepreciar < 0) THEN
            wdepdiasadepreciar = 0;
        END
      --alt:13156 - Fim
    END
  -- Deprecia??o di?ria (Fim)

  -- Total de meses para a deprecia??o
  IF (prtaxadepreciacaoanual >= 0.1) THEN
    wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
  ELSE
    BEGIN
      --#Alt:16327 - Tamb?m precisamos setar o valor corrigido anterior quando o bem n?o possui taxa de deprecia??o
      wvalorcorrigidoanterior  = (wvaloraquisicao + wvalorbaixaper);
      prvalorcorrigidoanterior = wvalorcorrigidoanterior;

      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / prvlrmoeda;
      --wvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / prvlrmoeda; #Alt:16327 - Alterado a vari?vel "wvalorbaixa" para a "wvalorbaixaper"
      wvalorcorrigidoanteriormoeda  = (wvaloraquisicao + wvalorbaixaper) / prvlrmoeda;
      prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;

      prvalorresidualcontabil       = wvaloraquisicao;

      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvalorresidualcontabilmoeda  = wvaloraquisicao / prvlrmoeda;
      wvalorresidualcontabilmoeda = wvaloraquisicao / prvlrmoeda;
      prvalorresidualcontabilmoeda = wvalorresidualcontabilmoeda;
      
      prdatataxadepreciacao         = wdataultimoitemdep;
      --#Alt:5105
      --prvalorbaixa                  = wvalorbaixa;
      prvalorbaixa                  = wvalorbaixaper;
      prvalorbaixareal              = wvalorbaixa;
      prvalormoeda                  = prvlrmoeda;
      prdatabaixa                   = wdatabaixa;
      
      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvaloraquisicaomoeda         = (wvaloraquisicao / prvlrmoeda);
      wvaloraquisicaomoeda = (wvaloraquisicao / prvlrmoeda);
      prvaloraquisicaomoeda = wvaloraquisicaomoeda;
    
      SUSPEND;
      EXIT;
    END

  IF (wdatainiciocalc IS NOT NULL) THEN
    wdataoficialiniciolcalculo = wdatainiciocalc;
  ELSE
    wdataoficialiniciolcalculo =  wdataaquisicao;

  IF (wvaloraquisicao = 0) THEN
     EXIT;

  -- Joga para vari?vel o n?mero de meses que j? foi depreciado em outro sistema
  IF (prmesesdepreciadosoutrataxa > 0) THEN --alt:13784 - 12/04/2016 - Se j? tiver meses depreciados anteriormente com outras taxas, precisa buscar esses meses. Pedro
    wmesesdepacumubem = prmesesdepreciadosoutrataxa;
  ELSE IF (wvaldepacumubem > 0) THEN
    --#alt:16911 - Alterada formula para o calculo dos meses de deprecia??o acumulada. Ana - 26/01/2016
    --wmesesdepacumubem = (wvaldepacumubem / ( wvaloraquisicao / wtotalmesesdepreciacao ));
    wmesesdepacumubem = (wvaldepacumubem / ( wvaloraquisicaooriginal / wtotalmesesdepreciacao ));

  --wmesesdepacumubem= 24311;
  wdatatotalmeses       = addmonth(wdataoficialiniciolcalculo, wtotalmesesdepreciacao-wmesesdepacumubem);
  wdatatotalmesesdepdia = addmonth(wdatatotalmeses, 1);
  wdatatotalmeses       = SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                          SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
  -- Transforma no primeiro dia do m?s
  wdataaquisicao = SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                   SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

  wdiferencameses = DATEDIFF(MONTH,:wdatatotalmeses,:wdataatual);
  IF (wdiferencameses < 0) THEN
    wdiferencameses = 0;
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >=
      CAST((SUBSTRING(wdataaquisicao FROM 1 FOR 4)) || (SUBSTRING(wdataaquisicao FROM 6 FOR 2)) AS INTEGER)) THEN
    wdiferencameses = wdiferencameses + 1;

  IF (wdiferencameses-1 > 0) THEN
    BEGIN
     IF (wdepmensal = 'FALSE') THEN
       BEGIN
         wdataatual = addmonth(:wdatatotalmeses,1);
         wmes       = CAST(SUBSTRING(CAST(wdataatual AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
         wano       = CAST(SUBSTRING(CAST(wdataatual AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
         wdataatual = wmes||'-01-'||wano;
       END
     ELSE
       wdataatual = wdatatotalmeses;
    END

  IF ((wdepmensal = 'FALSE') AND
      (CAST(EXTRACT(YEAR FROM :prdatainicial) || EXTRACT(MONTH FROM :prdatainicial) AS INTEGER) = CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
    BEGIN
      prdatafinal = addmonth(:prdatafinal,-1);
      wmes       = CAST(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
      wano       = CAST(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
      prdatafinal = wmes||'-01-'||wano;
    END

  -- Se for relatorio de baixas, a data atual devera ser o do mes da baixa.
  --if ((prtipo = 2) or (wdatabaixa is not null)) then
  IF ((prtipo = 2) AND (wdatabaixa IS NOT NULL)) THEN
    BEGIN
      wdataatual  = wdatabaixa;
      prdatafinal = wdatabaixa;
    END

   IF ((wdatafimcalc IS NOT NULL) AND (wdatafimcalc < prdatafinal)) THEN
     BEGIN
       wdataatual  = wdatafimcalc;
       prdatafinal = wdatafimcalc;
     END

  -- Meses j? depreciados
  wmesesdepreciados = DATEDIFF(MONTH,:wdataoficialiniciolcalculo,:wdataatual);
  IF (wmesesdepreciados < 0) THEN
    wmesesdepreciados = 0;


  --#alt:19501 - Devo considerar a deprecia??o di?ria no m?s da aquisi??o, que n?o s?o considerados como m?s cheio e por isso est?o informados nas casas ap?s
  --             a v?rgula. Esta deprecia??o di?ria era desconsiderada para os c?lculos. Ana - 18/10/2017
  IF (wdepdia = 'TRUE') THEN
    BEGIN
  wverificamesinteiro = TRUNC(wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
      wdiasdepdiaria = ((wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao)) - wverificamesinteiro);
    END
  ELSE
    BEGIN
      wverificamesinteiro = TRUNC(wdepreciacaoacumuladaatual/(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
      wdiasdepdiaria = ((wdepreciacaoacumuladaatual /(wvaloraquisicaooriginal / wtotalmesesdepreciacao)) - wverificamesinteiro);
    END

  --#alt:19501 - N?o deve considerar um m?s a mais na deprecia??o di?ria. E verifico o par?metro, pois a vari?vel sofre altera??o. Ana - 23/10/2017
  IF (prdepdia = 'FALSE') THEN
    BEGIN
      IF ((wdepmensal = 'TRUE') AND (wvaldepacumubem <> 0) AND (wdiasdepdiaria > 0)) THEN
    wmesesdepreciados = wmesesdepreciados + 1;
  ELSE
  --#alt:19501. Apenas somando este m?s altera bastante os c?culos da deprecia??o. Para somar este m?s s? em situa??es bem espec?ficas. Ana - 18/10/2017
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (((CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >
           CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER))) OR
     ((CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) =
       CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER)) AND
          ((wvaldepacumubem <> 0) OR (wdepmensal = 'TRUE'))) ) THEN
    wmesesdepreciados = wmesesdepreciados + 1;
    END

  --alt:14761 - 16/06/2016 - Retirada valida??o do wvaldepacumubem, sen?o no m?s inicial sem deprecia??o nele e com valor depreciado anteriormente cadastrado, estava retornando um m?s a mais como depreciado. Pedro
  --alt:14624 - 06/06/2016 - Precisa verificar tamb?m se o campo "wvaldepacumubem" est? nulo; estava incorreta a condi??o da data > ou = (o m?s retorna sem o zero, ex: 20158, assim n?o atendia a condi??o). Pedro
  --alt:13784 - 12/04/2016 - S? deve descontar um m?s se a data inicial for de m?s igual ou posterior a data de aquisi??o, n?o levando em considera??o apenas se h? valor j? depreciado. Pedro
  --IF ((wdepmensal = 'FALSE') OR (wvaldepacumubem > 0)) THEN
  --if ((wdepmensal = 'FALSE') AND (wvaldepacumubem = 0) and
  --   (CAST(EXTRACT(YEAR FROM :prdatainicial) || EXTRACT(MONTH FROM :prdatainicial) AS INTEGER) >= CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
  --if ((wdepmensal = 'FALSE') and (coalesce(wvaldepacumubem, 0) = 0) and
  IF ((wdepmensal = 'FALSE') AND
     ((EXTRACT(YEAR FROM :prdatainicial) > EXTRACT(YEAR FROM wdataorigaquisicao)) OR
      ((EXTRACT(YEAR FROM :prdatainicial) = EXTRACT(YEAR FROM wdataorigaquisicao)) AND (EXTRACT(MONTH FROM :prdatainicial) >= EXTRACT(MONTH FROM wdataorigaquisicao))))) THEN
    wmesesdepreciados = wmesesdepreciados - 1;

  --alt:13784 - 12/04/2016 - Se j? tiver depreciado meses com outra taxa, deve somar esse per?odo. Pedro
  IF (prmesesdepreciadosoutrataxa > 0) THEN
    wmesesdepreciados = wmesesdepreciados + prmesesdepreciadosoutrataxa;

  -- Adiciona no total de meses depreciados o valor j? depreciado de outro sistema
  IF ((wvaldepacumubem > 0) AND (wmesesdepreciados >=0)) THEN
     --#alt:18200 - Alterado para pegar o valor original da aquisi??o e n?o o valor ja corrigido. Ana - 03/05/2017
     --wmesesdepreciados = wmesesdepreciados + (wvaldepacumubem / (wvaloraquisicao / wtotalmesesdepreciacao));
     wmesesdepreciados = wmesesdepreciados + (wvaldepacumubem / (wvaloraquisicaooriginal / wtotalmesesdepreciacao));

  --#alt:19501 - Antes os c?lculos da deprecia??o do per?odo estavam incorretos quando o bem possuia baixa parcial, ent?o o total de meses depreciados sempre foi suficiente. Por?m, com
  --             estas altera??es, a quantidade de meses depreciados pode ser com um m?s a mais para fazer o c?lculo de compensa??o de baixa do per?odo anterior corretamente. Ana - 19/10/2017
  IF (((wmesesdepreciados > (wtotalmesesdepreciacao + 1)) AND (wdepmesbaixa = 'FALSE')) OR
      ((wmesesdepreciados > (wtotalmesesdepreciacao))     AND (wdepmesbaixa = 'TRUE')) ) THEN
     wmesesdepreciados = wtotalmesesdepreciacao;

  --#alt:19501 - Quando o bem possui deprecia??o no m?s da aquisi??o e deprecia??o di?ria, e for no m?s da aquisi??o, n?o vai considerar a deprecia??o deste m?s da aquisi??o.
  --             Essa deprecia??o ocorrer? no final do per?odo. Ana - 23/10/2017
  -- Se os meses decreciados for menor que zero, significa que foi informado uma data inferior a data de aquisicao do bem
  /*IF (wmesesdepreciados <= 0) THEN
    BEGIN
      SUSPEND;
      EXIT;
    END*/

  --#alt:19501 - Adicionada a atribui??o aqui, pois preciso dela para controle da vari?vel wdepdiafinal. Ana - 17/10/2017
  -- Meses ? depreciar
  wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);

  -- Total de meses da diferen?a do periodo de deprecia??o
  wmes = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultimodiadomes;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultimodiadomes = EXTRACT(DAY FROM (wdatatotalmesesdepdia - EXTRACT(DAY FROM wdatatotalmesesdepdia) +
                                      32 - EXTRACT(DAY FROM wdatatotalmesesdepdia - EXTRACT(DAY FROM wdatatotalmesesdepdia) + 32)));
  wdatatotalmesesultimodia = wmes||'-'||wultimodiadomes||'-'||wano;
  IF ((:prdatafinal > wdatatotalmesesultimodia) AND (wdepdia = 'TRUE')) THEN
    BEGIN
      -- Caso seja o ?ltimo m?s para depreciar
      IF (wmesesdepreciar = 0) THEN
        wdepdiafinal = 'TRUE';

      wdatatotalmesesultimodia = addmonth(wdatatotalmesesultimodia, 1);
      wdatatotalmesesultimodia = SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                                 SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
    END
  ELSE
    BEGIN
      --alt:8005 - Foi adicionada excess?o "else" e esta valida??o porque se tiver terminado a quantidade de dias a depreciar deve calcular o final da deprecia??o (os restos). Pedro
      IF (wmesesdepreciar = 0) THEN
        wdepdiafinal = 'TRUE';
    END

  IF (:prdatafinal > wdatatotalmeses) THEN
     prdatafinal = wdatatotalmeses;

  IF (:prdatainicial < :wdataoficialiniciolcalculo) THEN
      prdatainicial = wdataoficialiniciolcalculo;

  wtotalmesesdoperiodo = DATEDIFF(MONTH,:prdatainicial,:prdatafinal);
  IF (wtotalmesesdoperiodo < 0) THEN
    wtotalmesesdoperiodo = 0;
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
      CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER)) THEN
    wtotalmesesdoperiodo = wtotalmesesdoperiodo + 1;

  --#alt:18204 - Quando a data for igual a data origem de aquisi??o ent?o n?o deve ser calculado. Ana - 28/04/2017
  IF ((wvaldepacumubem > 0) AND (prdatainicial </*=*/ wdataorigaquisicao)) THEN
    wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;

  --#alt:6151. - Carlos Mello(08/11/2013)
  IF (((wtotalmesesdoperiodo > 0) AND
       ((CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) >
         CAST((SUBSTRING(wdatatotalmeses FROM 1 FOR 4)) || (SUBSTRING(wdatatotalmeses FROM 6 FOR 2)) AS INTEGER)) OR
        ((wdepmensal = 'TRUE') AND
         (CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
          CAST((SUBSTRING(wdatatotalmeses FROM 1 FOR 4)) || (SUBSTRING(wdatatotalmeses FROM 6 FOR 2)) AS INTEGER))))) OR
      (wtotalmesesdoperiodo < 0) ) THEN
    wtotalmesesdoperiodo = 0;

  --#alt:19501 - Movi essa atribui??o para cima, pois h? verifica??es com esta vari?vel. Ana - 17/10/2017
  -- Meses ? depreciar
  --wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);
  wvaloraquisicaomoeda = wvaloraquisicao / prvlrmoeda;
  -- Deprecia??o do per?odo
  --wvalordepreciacaomensal = (wvaloraquisicaomoeda / wtotalmesesdepreciacao); --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro

  --#alt:85169. O valor da aquisi??o deve ser o original para calcular a deprecia??o correta e n?o influenciar nos outro valores. Ana- 20/06/2018
  --wvalordepreciacaomensal = (wvaloraquisicao / wtotalmesesdepreciacao);
  IF (prtipo = 2) THEN
    wvalordepreciacaomensal = (wvaloraquisicaoaux / wtotalmesesdepreciacao);
  ELSE
    wvalordepreciacaomensal = (wvaloraquisicao / wtotalmesesdepreciacao);

  --#alt:19501 - Quando tenho deprecia??o acumulada anterior cadastrada devo considerar os meses pertinentes a essa deprecia??o, independente da deprecia??o di?ria. Ana - 17/10/2017
  IF ((wdepdia = 'TRUE') /*AND ((wvaldepacumubem = 0) AND (wvaldepacumubem = wdepreciacaoacumuladaatual))*/) THEN
    BEGIN
      -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
      wmesesdepreciar      = wmesesdepreciar + 1;
      wmesesdepreciados    = wmesesdepreciados - 1;
      wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;
    END

  --alt:15196 - 09/11/2016 - Se depreciou no m?s da aquisi??o, ir? terminar a deprecia??o um m?s antes. Pedro
  IF (wdepmensal = 'TRUE') THEN
    wdatatotalmeses = AddMonth(wdatatotalmeses, -1);

  IF (wdepdiasadepreciar > 0) THEN
    BEGIN
      --#alt:5105. - Carlos Mello(27/11/2013)
      IF (wnumdias = 2) THEN
        BEGIN
          -- C?lculo que retorna o ?ltimo dia do m?s
          --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
          IF (wdatabaixa BETWEEN prdatainicial AND prdatafinal) THEN
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) +
                                                32 - EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32)));
          ELSE
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatainiciocalc - EXTRACT(DAY FROM wdatainiciocalc) +
                                                32 - EXTRACT(DAY FROM wdatainiciocalc - EXTRACT(DAY FROM wdatainiciocalc) + 32)));

          --alt:13156 - Fim
          --alt:16006 - 03/11/2016 - Alterado para dividir o valor da daprecia??o antes e depois da baixa, no caso da baixa parcial. Pedro
          --wvalordepreciacaodiaria  = (wvalordepreciacaomensal * prvlrmoeda) / wultimodiadomes * wdepdiasadepreciar;
          wvalordepreciacaodiaria = (prvaloraquisicaooriginal / wtotalmesesdepreciacao) / wultimodiadomes * wdepdiasadepreciar;
          wvalordepreciacaodiariabaixa = (wvalordepreciacaomensal / wultimodiadomes) * (wultimodiadomes - wdepdiasadepreciar);
          wDia = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32 -
                                   EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32))) - EXTRACT(DAY FROM wdatainiciocalc);
          prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados -1 + (CAST(wdepdiasadepreciar + wDia AS FLOAT) / wUltimoDiaDoMes));
        END
      ELSE
        BEGIN
          --alt:16006 - 03/11/2016 - Alterado para dividir o valor da daprecia??o antes e depois da baixa, no caso da baixa parcial. Pedro
          --wvalordepreciacaodiaria  = (wvalordepreciacaomensal * prvlrmoeda) / 30 * wdepdiasadepreciar;
          wvalordepreciacaodiaria = (prvaloraquisicaooriginal / wtotalmesesdepreciacao) / 30 * wdepdiasadepreciar;
          wvalordepreciacaodiariabaixa = (wvalordepreciacaomensal / 30) * (30 - wdepdiasadepreciar);
          wDia = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32 -
                                   EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32))) - EXTRACT(DAY FROM wdatainiciocalc);
          prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados -1 + (CAST(wdepdiasadepreciar + wDia AS FLOAT) / 30));
        END
      --alt:16006 - Fim

      --alt:15196 - 09/11/2016 - Esta nova vari?vel calcula corretamente o valor a ser compensado no final da deprecia??o. Pedro
      --prvalordepreciacaodiariafim = (wvalordepreciacaomensal * prvlrmoeda) - wvalordepreciacaodiaria;
      prvalordepreciacaodiariafim = wvalordepreciacaodiariabaixa;
    END
  ELSE
    --#alt:19501 - Adicionei o valor pertinente a deprecia??o di?ria no m?s da aquisi??o. Ana - 24/10/2017
    --alt:15196 - 09/11/2016 - Calcula o valor a ser compensado ap?s a baixa para bens SEM deprecia??o di?ria. Pedro
    prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * ((wmesesdepreciados + wdiasdepdiaria) - IIF(wdepmesbaixa = 'TRUE', 0, 1));

  --#alt:18200 - Adicionei a verifica??o da diferen?a de meses da baixa para a aquisi??o do bem, pois n?o estava fazendo a deprecia??o di?ria corretamente
  --             quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
  --alt:16006 - 03/11/2016 - Separado o c?lculo para per?odo com baixa do per?odo depreciado em outro sistema,
  --pois precisa utilizar o valor da deprecia??o acumulada do c?lculo m?s a m?s, caso contr?rio, caso o primeiro
  --m?s tenha sido depreciado diariamente, estava desconsiderando este valor para os meses seguintes. Pedro
  --alt:13156 - 17/02/2016 - Na baixa tamb?m deve descontar o valor proporcional ao n?mero de dias, se o par?metro estiver marcado. Pedro
  IF ((wdatabaixa BETWEEN prdatainicial AND prdatafinal)  AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0))THEN
    BEGIN
      wdepreciacaoperiodo = (wvalordepreciacaodiaria + wvalordepreciacaodiariabaixa) + (wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  --#alt:19501 - Quando for deprecia??o di?ria e tiver valor de deprecia??o acumulada anterior informada, deve ignorar qualquer c?lculo feito anteriormente. Ana - 17/10/2017
  ELSE IF ((wdatainicialoficial <= :wdataaquisicao) AND
          (((wdepdia = 'TRUE') AND (wvaldepacumubem = 0) OR ((wdepdia = 'FALSE') AND (wvaldepacumubem <> 0))) AND
          (wvaldepacumubem = wdepreciacaoacumuladaatual))) THEN
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo) / prvlrmoeda;
      wdepreciacaoperiodo      = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  ELSE
  IF (wdepdia = 'TRUE') THEN
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo +1) * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * (wtotalmesesdoperiodo+1));
      wdepreciacaoperiodo      = wvalordepreciacaomensal * (wtotalmesesdoperiodo +1);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  ELSE
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodo      = wvalordepreciacaomensal * wtotalmesesdoperiodo;
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END

  --#alt:19501 - Quando ? informado um valor de deprecia??o acumulada anterior, deve ignorar o qualquer calculo feito anteriormente(deprecia??o diaria) e permanecer com o valor informado. Ana - 17/10/2017
  IF ((prvaloracumuladoanterior = 0) AND (wvaldepacumubem <> 0) AND (wvaldepacumubem = wdepreciacaoacumuladaatual)) THEN
    BEGIN
      wdepreciacaoacumuladaatual    = (wdepreciacaoperiodo + wdepreciacaoacumuladaatual);
      wdepreciacaoacumuladaanterior = (wvaldepacumubem);
    END
  ELSE
   IF ((wvalordepreciacaodiaria > 0) AND (wdatainicialoficial <= :wdataaquisicao))  THEN
     BEGIN
       --alt:16006 - 03/11/2016 - Utiliza o valor da deprecia??o acumulado na vari?vel. Pedro
       --wdepreciacaoacumuladaatual    = (wvalordepreciacaomensal * wmesesdepreciados);
       wdepreciacaoacumuladaatual    = (wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * prvlrmoeda);
       wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
     END
   ELSE
     BEGIN
       --alt:16006 - 03/11/2016 - Utiliza o valor da deprecia??o acumulado na vari?vel. Pedro
       --wdepreciacaoacumuladaatual = (wvalordepreciacaomensal * wmesesdepreciados);
       --wdepreciacaoacumuladaatual = (wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * prvlrmoeda);
       wdepreciacaoacumuladaatual = wdepreciacaoperiodo + wdepreciacaoacumuladaatual;
      
       IF (wvalordepreciacaodiaria > 0) THEN
         wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
       ELSE
         BEGIN
          --#alt:19501 - Na deprecia??o di?ria devo considerar um m?s a mais no total de meses do per?odo. Ana - 25/10/2017 
           --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
           --alt:9013 - Dividido em duas partes porque calculando tudo de uma s? vez estava ocorrendo um over flow. Pedro
           --wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda;
          IF (wdepdia = 'TRUE') THEN
            wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * (wtotalmesesdoperiodo +1);
          ELSE
           wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * wtotalmesesdoperiodo;
           wdepreciacaoacumuladaanterior = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;
           --wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual -  (wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda));
           --alt:9013 - Fim
         END
     END

  --#alt:18200 - N?o precisa fazer esta verifica??o, pois o valor corrigido anterior sempre deve ser em rela??o ao valor da aquisi??o. Ana - 02/05/2017
  --IF (wdepreciacaoacumuladaanterior > 0) THEN
  wvalorcorrigidoanterior = wvaloraquisicao;

  IF (wdepreciacaoacumuladaanterior < 0) THEN
    wdepreciacaoacumuladaanterior = 0;

  --#alt:18200 - S? vai considerar a compensa??o da baixa do per?odo anterior se tiver deprecia??o acumulada anterior ou se o m?s da baixa n?o for o mesmo da aquisi??o.
  --             Deve ser o valor da aquisi??o original pois o valor da aquisi??o ? diminuido conforme os valores das baixas. Ana - 04/05/2017
  --alt:16006 - 03/11/2016 - Caso esteja deprecia??o diariamente e seja um m?s com baixa, deduz o valor dos meses anteriores que foram depreciados calculando valor inteiro do bem (sem baixa). Pedro
  --IF ((wvalorbaixaper > 0) AND (wvalorbaixa < wvaloraquisicao)) THEN
  IF ((wvalorbaixaper > 0) AND (wvalorbaixa < wvaloraquisicaooriginal) AND ((wdepreciacaoacumuladaanterior <> 0) OR (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0))) THEN
    wdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual - prcompensacaobaixaperanterior;
  ELSE IF (wvalorbaixa = wvaloraquisicao) THEN
    prcompensacaobaixaperanterior = wdepreciacaoacumuladaatual;

  --alt:15196 - 09/11/2016 - Agora o valor da deprecia??o mensal vem sem a moeda, ent?o precisa converter. Pedro
  --wdepreciacaoacumuladaatualmoed = ((wvalordepreciacaodiaria / prvlrmoeda) + wvalordepreciacaomensal * wmesesdepreciados);
  wdepreciacaoacumuladaatualmoed = (wvalordepreciacaodiaria + (wvalordepreciacaomensal * wmesesdepreciados)) / prvlrmoeda;
  wdepreciacaobaixamoeda         = (wvalorbaixa / wtotalmesesdepreciacao);
  wdepreciacaobaixamoeda         = (wdepreciacaobaixamoeda / prvlrmoeda);

  IF (prtipo = 2) THEN
    BEGIN
      prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
      prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior / prvlrmoeda);
    END
  ELSE
    BEGIN
      --#alt:18200 - N?o estava calculando certo. Atribuia o valor da aquisi??o menos todas as baixas e somava todas as baixas aqui novamente, mas s? deve somar as baixas que ja foram efetuadas. Ana - 02/05/2017
      /*prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + wvalorbaixa);
      prvalorcorrigidoanteriormoeda = ((wvalorcorrigidoanterior + wvalorbaixa) / prvlrmoeda);  */
      prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + (wvalorbaixaper));
      prvalorcorrigidoanteriormoeda = ((wvalorcorrigidoanterior + (wvalorbaixaper)) / prvlrmoeda);

      --#alt:19501 - Quando ? deprecia??o no mes da baixa, n?o deve considerar os valores de baixa no per?odo para c?lculo do valor corrigido anterior(Estes valores ja est?o inclusos). Ana - 16/10/2017
      --#alt:18200 - Apenas se o valor for maior deve substituir. Ana - 02/05/2017
      IF ((prvalorcorrigidoanterior >/*=*/ prvaloraquisicaooriginal) OR (UPPER(wdepmesbaixa) = 'TRUE') ) THEN
        BEGIN
          prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
          prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior / prvlrmoeda);
        END
    END

  --#alt:19501 - O calculo deve ser em cima do valor corrigido atual e n?o do valor da aquisi??o, quando possuir valor. Ana - 16/10/2017
  IF (prvalorcorrigidoanterior > 0) THEN
    wvalorresidualcontabil         = (((prvalorcorrigidoanterior + prcorrecaoperiodo) - wvalorbaixaper) - wdepreciacaoacumuladaatual);
  ELSE
    wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
  wvalorresidualcontabilmoeda    = (wvalorresidualcontabil / prvlrmoeda);
  --#alt:19501. fim

  IF ((wdepdia = 'TRUE') AND (wdepdiafinal = 'TRUE')) THEN
    BEGIN
      --alt:8005 - Alterado para n?o entrar aqui caso as datas sejam iguais, pois se entrar aqui ele mata a deprecia??o di?ria. Pedro
      --if (wdatainicialoficial <= :wdataaquisicao) then
      IF (wdatainicialoficial < :wdataaquisicao) THEN
        BEGIN
          --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
          --wdepreciacaoperiodo            = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
          --wdepreciacaoperiodomoeda       = (((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) / prvlrmoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
          wdepreciacaoperiodo            = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
          wdepreciacaoperiodomoeda       = wdepreciacaoperiodo / prvlrmoeda;
          wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim);
          wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual / prvlrmoeda);
          wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          wvalorresidualcontabilmoeda    = 0;
          wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
        END
      ELSE
        --#alt:19501 - Se o bem ja foi totalmente depreciado, n?o deve mais executar esta parte. Estava retornando a deprecia??o errada. Ana - 25/10/2017
       IF ((CAST(wvalorcorrigidoanterior AS NUMERIC(15,0)) <> CAST(wdepreciacaoacumuladaatual AS NUMERIC(15,0))) AND
            (CAST(wvalorcorrigidoanterior AS NUMERIC(15,1)) <> CAST(wdepreciacaoacumuladaatual AS NUMERIC(15,1))) OR
           ((wmesesdepreciados + 1) < wtotalmesesdepreciacao)) THEN
        BEGIN
          wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);
          wmes                     = CAST(SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano                     = CAST(SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          wdatatotalmesesultimodia = wmes||'-01-'||wano;

          --alt:14256 - 14/07/2016 - Alterada valida??o, n?o estava trazendo o valor da deprecia??o di?ria nos meses subsequentes ao t?rmino da deprecia??o. Pedro
          --alt:9013 - Retirado pois estava trazendo depreciacao anterior a mais do que devia quando usava deprecia??o di?ria. Pedro
          --IF (wdatatotalmesesultimodia BETWEEN PRDATAINICIAL AND PRDATAFINAL) THEN
          IF (wdatatotalmesesultimodia <= prdatainicial) THEN
             wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim);

          wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual / prvlrmoeda);

          wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          --#alt:16852 - Comentado pois n?o h? necessidade de zerar e estava fazendo com que o valor fosse errado. Ana - 10/02/2017
          --wvalorresidualcontabilmoeda = 0;

          IF (wdatainicialoficial <> :wdatatotalmesesultimodia) THEN
            BEGIN
              wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
              wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaanterior / prvlrmoeda);
            END

          wdepreciacaoperiodo = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;

          IF (wdepreciacaoperiodo <= 0) THEN
            wdepreciacaoperiodomoeda = 0;
          ELSE
            wdepreciacaoperiodomoeda = ((wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior) / prvlrmoeda);
        END

      --alt:9013 - Retirado pois sempre trazia um m?s a mais de deprecia??o quando ? di?ria. Pedro
      /*wmesesdepreciados = wmesesdepreciados + 1;
      wmesesdepreciar   = 0;*/
    END

  --#alt:18200 - Alterada forma de c?lculo do valor corrigido atual (valor corrigido anterior + corre??o do per?odo - valor de baixas do per?odo). Ana - 02/05/2017
  --prvalorcorrigidoatual = (prvalorcorrigidoanterior + prcorrecaoperiodo - wvalorbaixaper);

  --alt:15196 - 24/11/2016 - Adapta??o para zerar o valor residual da deprecia??o. Pedro
  IF ((wdepreciacaoacumuladaanterior + wdepreciacaoperiodo) > wvaloraquisicao) THEN
    BEGIN
      IF (wdepreciacaoacumuladaanterior < wvaloraquisicao) THEN
        BEGIN
          wdepreciacaoperiodo = wvaloraquisicao - wdepreciacaoacumuladaanterior;
          wdepreciacaoacumuladaatual = wdepreciacaoacumuladaanterior + wdepreciacaoperiodo;
        END

      wdepreciacaoperiodomoeda = wdepreciacaoperiodo * prvlrmoeda;
      wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual * prvlrmoeda;
    END

  IF ((wdepdia = 'TRUE')) THEN
    BEGIN
      -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
      wmesesdepreciar      = wmesesdepreciar - 1;
      wmesesdepreciados    = wmesesdepreciados + 1;
      wtotalmesesdoperiodo = wtotalmesesdoperiodo +1;
    END

  prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;
  prdepreciacaoperiodo            = wdepreciacaoperiodo;
  prdepreciacaoperiodomoeda       = wdepreciacaoperiodomoeda;
  prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
  prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
  prcorrecaomonetariadepreciacao  = 0;
  prvalorresidualcontabil         = wvalorresidualcontabil;
  prvalorresidualcontabilmoeda    = wvalorresidualcontabilmoeda;
  prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
  prmesesdepreciados              = wmesesdepreciados;
  prmesesdepreciar                = wmesesdepreciar;
  prdatataxadepreciacao           = wdataultimoitemdep;
  --#Alt:5105
  --prvalorbaixa                    = wvalorbaixa;
  prvalorbaixa                    = wvalorbaixaper;
  prdepreciacaobaixamoeda         = wdepreciacaobaixamoeda;
  prvalorbaixareal                = wvalorbaixa;
  prvalormoeda                    = prvlrmoeda;
  prdatabaixa                     = wdatabaixa;
  prvaloraquisicaomoeda           = wvaloraquisicaomoeda;

  SUSPEND;
END
^

/* Alter (SP_CONS_CALC_INTERMITENTE) */
ALTER PROCEDURE SP_CONS_CALC_INTERMITENTE(PRCODEMP INTEGER = null,
PRCODCOL INTEGER = null,
PRCODCONTRATO INTEGER = null,
PRDATAINICIAL DATE = null,
PRDATAFINAL DATE = null)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRGCOL VARCHAR(13),
BDCODCONTTI INTEGER,
BDDESCCONTRATOTI VARCHAR(2000),
BDDATACONVTI DATE,
BDHORACONVTI TIME,
BDDATAINISERVTI DATE,
BDDATAFIMSERVTI DATE,
BDDATAPAGTI DATE,
BDLIQUIDO NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDDATAPGTOFN DATE,
BDFGTSFN NUMERIC(18,6),
BDFGTS13FN NUMERIC(18,6),
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(18,6),
BDREFAUXVFN NUMERIC(18,6),
BDVALVFN NUMERIC(18,6),
BDVALIFN NUMERIC(18,6),
BDDESCVER VARCHAR(40),
BDTIPOCODVER INTEGER,
BDORDEMVER INTEGER)
 AS
declare variable WSQL varchar(10000);
declare variable WWHERE varchar(500);
declare variable WSQL2 varchar(5000);
declare variable WWHERE2 varchar(500);
begin
    --<Local aonde deve ser zerado as vari?veis>--
    wSQL   = ' ';
    wWhere = ' ';

    /**************************************************************************/
    /*                      In?cio da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL = wSQL ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL = wSQL ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    --<Contrato>--
    wSQL = wSQL ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAPAGTI,'           || ASCII_CHAR(13);
    --<C?lculo>--
    wSQL = wSQL ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDATAPGTOFN,'                  || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFVFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALIFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDTIPOCODVER,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDORDEMVER'                    || ASCII_CHAR(13);
    wSQL = wSQL ||' FROM (SELECT'                             || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDCODCONTTI,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDLIQUIDO,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDBINSSFN,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDDATAPGTOFN,'       || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTSFN,'           || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTS13FN,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODEMP,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODCOL,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODVER,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDDESCVER,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDORDEMVER,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_DESCVERB.BDTIPOCODVER,'     || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFFN,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFVFN,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFAUXVFN,'    || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALVFN,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALIFN'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       FROM VRHF_EMP_TFOLHAINT XF_CALCULO' || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VRHF_EMP_TVERBAINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP    = XLF_VERBASCALC.BDCODEMP AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCOL    = XLF_VERBASCALC.BDCODCOL AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCONTTI = XLF_VERBASCALC.BDCODCONTTI AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDREFFN     = XLF_VERBASCALC.BDREFFN)'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB      ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'         || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB  ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'        || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    if (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere = wWhere || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

            wWhere = wWhere || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END

    IF (wWhere <> '') THEN
        BEGIN
            wWhere = ' WHERE ' || ASCII_CHAR(13) || wWhere;
        END

    wSQL = wSQL || wWhere || ASCII_CHAR(13);

    wSQL = wSQL || ') F_CALC ' || ASCII_CHAR(13);
    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL = wSQL ||'           JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP)'           || ASCII_CHAR(13);
    wSQL = wSQL ||'           JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP)'               || ASCII_CHAR(13);
    wSQL = wSQL ||'           JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP     AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL     AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI)'    || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          J_CONTRATO_INT.BDCODCOL = LF_REFCOL.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLCAD.BDREFCOL)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLDOC2.BDREFCOL)'           || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wWhere = ' ';
    if ((prDataInicial is not null) AND ( prDataFinal is not null)) THEN
        BEGIN
            wWhere = wWhere || 'J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN' || prDataInicial || ' AND ' || prDataFinal;
        END



    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/

    --<Local aonde deve ser zerado as vari?veis>--
    wSQL2   = ' ';
    wWhere2 = ' ';

    /**************************************************************************/
    /*                      In?cio da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL2 = wSQL2 ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL2 = wSQL2 ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    --<Contrato>--
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAPAGTI,'           || ASCII_CHAR(13);
    --<C?lculo>--
    wSQL2 = wSQL2 ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDATAPGTOFN,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFVFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALIFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDTIPOCODVER,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDORDEMVER'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||' FROM (SELECT'                                             || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'        XF_CALCULO.BDCODCONTTI,'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'SUM(XF_CALCULO.BDLIQUIDO) AS BDLIQUIDO,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDBINSSFT) AS BDBINSSFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPGTOFT AS BDDATAPGTOFN,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTSFT) AS BDFGTSFN,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTS13FT) AS BDFGTS13FN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'                         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'                        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR AS BDREFFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDREFVFT) AS BDREFVFN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFAUXVFT AS BDREFAUXVFN,'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALVFT) AS BDVALVFN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALIFT) AS BDVALIFN'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       FROM VRHF_EMP_TFOLHATOMINT XF_CALCULO'              || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VRHF_EMP_TVERBATOMINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP     = XLF_VERBASCALC.BDCODEMP AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCOL     = XLF_VERBASCALC.BDCODCOL AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCONTTI  = XLF_VERBASCALC.BDCODCONTTI AND'  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDREFTOMADOR = XLF_VERBASCALC.BDREFTOMADOR AND' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDORDEM      = XLF_VERBASCALC.BDORDEM)'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB         ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB     ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'          || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    if (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

             wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END

    IF (wWhere2 <> '') THEN
        BEGIN
            wWhere2 = ' WHERE ' || ASCII_CHAR(13) || wWhere2;
        END

    wSQL2 = wSQL2 || wWhere2 || ASCII_CHAR(13);

    wSQL2 = wSQL2 ||'       GROUP BY'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDCODCONTTI,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPGTOFT,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR,'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFAUXVFT'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||') F_CALC'                                   || ASCII_CHAR(13);

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL2 = wSQL2 ||'           JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP)'               || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI)'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          J_CONTRATO_INT.BDCODCOL = LF_REFCOL.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLCAD.BDREFCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLDOC2.BDREFCOL)'           || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wWhere2 = ' ';
    if ((prDataInicial is not null) AND ( prDataFinal is not null)) THEN
        BEGIN
            wWhere2 = wWhere2 || 'J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN' || prDataInicial || ' AND ' || prDataFinal;
        END



    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/
    
    wSQL = wSQL    || ASCII_CHAR(13) ||
           'UNION' || ASCII_CHAR(13) ||
           wSQL2;

    /*Seta a compet?ncia para o banco*/
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(201806);

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDNOMEMP,
        :BDCNPJEMP,
        :BDLOGREMP,
        :BDENDEMP,
        :BDNUMEMP,
        :BDCODCID,
        :BDNOMCID,
        :BDNOMCOL,
        :BDCPFCOL,
        :BDPISCOL,
        :BDRGCOL,
        :BDCODCONTTI,
        :BDDESCCONTRATOTI,
        :BDDATACONVTI,
        :BDHORACONVTI,
        :BDDATAINISERVTI,
        :BDDATAFIMSERVTI,
        :BDDATAPAGTI,
        :BDLIQUIDO,
        :BDBINSSFN,
        :BDDATAPGTOFN,
        :BDFGTSFN,
        :BDFGTS13FN,
        :BDCODCOL,
        :BDCODVER,
        :BDREFFN,
        :BDREFVFN,
        :BDREFAUXVFN,
        :BDVALVFN,
        :BDVALIFN,
        :BDDESCVER,
        :BDTIPOCODVER,
        :BDORDEMVER
    DO
        SUSPEND;
end
^

/* Alter (SP_CONSULTA_DARF_RETENCAO) */
ALTER PROCEDURE SP_CONSULTA_DARF_RETENCAO(PRCODEMP INTEGER,
PRDATAINI VARCHAR(12),
PRDATAFIN VARCHAR(12),
PRTIPOAPURACAORET INTEGER,
PRTIPOAPURACAORETIR INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDTIPLAN INTEGER,
BDNUMDOCINI VARCHAR(15),
BDDATAEMISSAO DATE,
BDVALORNOTA NUMERIC(15,2),
BDVALORPAGO NUMERIC(15,2),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDVLRINSS NUMERIC(15,2),
BDVLRIR NUMERIC(15,2),
BDISSRET NUMERIC(15,2),
BDCODTER INTEGER,
BDNOMETER VARCHAR(100),
BDCGCTER VARCHAR(18))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WTIPLAN INTEGER;
DECLARE VARIABLE WNUMDOCINI VARCHAR(15);
DECLARE VARIABLE WDATAEMISSAO DATE;
DECLARE VARIABLE WVALORNOTA NUMERIC(15,2);
DECLARE VARIABLE WVALORPAGO NUMERIC(15,2);
DECLARE VARIABLE WVLRPIS NUMERIC(15,2);
DECLARE VARIABLE WVLRCOFINS NUMERIC(15,2);
DECLARE VARIABLE WVLRCSOCIAL NUMERIC(15,2);
DECLARE VARIABLE WVLRINSS NUMERIC(15,2);
DECLARE VARIABLE WVLRIR NUMERIC(15,2);
DECLARE VARIABLE WISSRET NUMERIC(15,2);
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WNOMETER VARCHAR(100);
DECLARE VARIABLE WCGCTER VARCHAR(18);
BEGIN
    wSQL =         'SELECT mov.BDCODEMP, mov.BDCHAVE, mov.BDTIPLAN, mov.BDNUMDOCINI, mov.BDDATAEMISSAO, mov.BDVALORNOTA, mov.BDVALORPAGO, ';
    wSQL = wSQL || '       mov.BDVLRPIS, mov.BDVLRCOFINS, mov.BDVLRCSOCIAL, mov.BDVLRINSS, mov.BDVLRIR, mov.BDISSRET, ';
    wSQL = wSQL || '       ter.BDCODTER, ter.BDNOMETER, ter.BDCGCTER ';
    wSQL = wSQL || 'from ( ';
    /* Servi?os */
    /* Tipo de apura??o das reten??es (PIS/Cofins/CSLL) */
    wSQL = wSQL || '            select ser.BDCODEMP, ser.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ';
    wSQL = wSQL || '                   ser.BDVALORNOTA, ser.BDVALORNOTA as BDVALORPAGO, ';
    wSQL = wSQL || '                   ser.BDCODTER, ';
    wSQL = wSQL || '                   ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ret.BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
    wSQL = wSQL || '            from VEF_EMP_TMOVSER ser ';
    wSQL = wSQL || '            left outer join VEF_EMP_TMOVSERRET ret on (ret.BDCODEMP = ser.BDCODEMP and ret.BDCHAVE = ser.BDCHAVE) ';
    wSQL = wSQL || '            where ser.BDCODEMP = '||prCODEMP||' ';
    wSQL = wSQL || '              and ser.BDDATAEMISSAO between '''||prDATAINI||''' and '''||prDATAFIN||'''';
    wSQL = wSQL || '              and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRINSS > 0) or (ret.BDISSRET > 0)) ';
    IF (prTIPOAPURACAORET = 1) THEN
      BEGIN
        wSQL = wSQL || '              and ser.BDCONDPGTO <> 1 ';
        wSQL = wSQL || '            union all ';
        wSQL = wSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ser.BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO,  ser.BDCODTER, ';
        wSQL = wSQL || '                   pgto.BDVALORRETPIS as BDVLRPIS, pgto.BDVALORRETCOFINS as BDVLRCOFINS, pgto.BDVALORRETCSLL as BDVLRCSOCIAL, pgto.BDVALORRETINSS as BDVLRINSS, 0 as BDVLRIR, pgto.BDVALORRETISSQN as BDISSRET ';
        wSQL = wSQL || '            from (select * from VEF_EMP_TMOVSERPARPGTO pgto ';
        wSQL = wSQL || '                  where pgto.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and (pgto.BDDATAPGTOPAR between '''||prDATAINI||''' and '''||prDATAFIN||''') ';
        wSQL = wSQL || '                    and (pgto.BDCODTIPOBAIXA <> 2)) pgto '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
        wSQL = wSQL || '            join (select ser.BDCODEMP, ser.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ser.BDVALORNOTA, ser.BDCODTER, ';
        wSQL = wSQL || '                         ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ret.BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
        wSQL = wSQL || '                  from VEF_EMP_TMOVSER ser ';
        wSQL = wSQL || '                  left outer join VEF_EMP_TMOVSERRET ret on (ret.BDCODEMP = ser.BDCODEMP and ret.BDCHAVE = ser.BDCHAVE) ';
        wSQL = wSQL || '                  where ser.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRINSS > 0) or (ret.BDISSRET > 0)) ';
        wSQL = wSQL || '                    and ser.BDCONDPGTO = 1 ) ser on (ser.BDCODEMP = pgto.BDCODEMP and ser.BDCHAVE = pgto.BDCHAVE) ';
      END
    wSQL = wSQL || '            union all ';
    /* Tipo de apura??o das reten??es IR */
    wSQL = wSQL || '            select ser.BDCODEMP, ser.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ';
    wSQL = wSQL || '                   ser.BDVALORNOTA as BDVALORNOTA, ';
    wSQL = wSQL || '                   ser.BDVALORNOTA as BDVALORPAGO, ';
    wSQL = wSQL || '                   ser.BDCODTER, ';
    wSQL = wSQL || '                   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, ret.BDVLRIR, 0 as BDISSRET ';
    wSQL = wSQL || '            from VEF_EMP_TMOVSER ser ';
    wSQL = wSQL || '            left outer join VEF_EMP_TMOVSERRET ret on (ret.BDCODEMP = ser.BDCODEMP and ret.BDCHAVE = ser.BDCHAVE) ';
    wSQL = wSQL || '            where ser.BDCODEMP = '||prCODEMP||' ';
    wSQL = wSQL || '              and ser.BDDATAEMISSAO between '''||prDATAINI||''' and '''||prDATAFIN||'''';
    wSQL = wSQL || '              and (ret.BDVLRIR > 0) ';
    IF (prTIPOAPURACAORETIR = 1) THEN
      BEGIN
        wSQL = wSQL || '              and ser.BDCONDPGTO <> 1 ';
        wSQL = wSQL || '            union all ';
        wSQL = wSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ';
        wSQL = wSQL || '            ser.BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO, ';
        wSQL = wSQL || '                   ser.BDCODTER, ';
        wSQL = wSQL || '                   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, pgto.BDVALORRETIRRF as BDVLRIR, 0 as BDISSRET ';
        wSQL = wSQL || '            from (select * from VEF_EMP_TMOVSERPARPGTO pgto ';
        wSQL = wSQL || '                  where pgto.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and (pgto.BDDATAPGTOPAR between '''||prDATAINI||''' and '''||prDATAFIN||''') ';
        wSQL = wSQL || '                    and (pgto.BDCODTIPOBAIXA <> 2)) pgto '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
        wSQL = wSQL || '            join (select ser.BDCODEMP, ser.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ';
        wSQL = wSQL || '                         ser.BDVALORNOTA, ';
        wSQL = wSQL || '                         ser.BDCODTER, ';
        wSQL = wSQL || '                         ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ret.BDVLRINSS, ret.BDVLRIR, ret.BDISSRET ';
        wSQL = wSQL || '                  from VEF_EMP_TMOVSER ser ';
        wSQL = wSQL || '                  left outer join VEF_EMP_TMOVSERRET ret on (ret.BDCODEMP = ser.BDCODEMP and ret.BDCHAVE = ser.BDCHAVE) ';
        wSQL = wSQL || '                  where ser.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and (ret.BDVLRIR > 0) ';
        wSQL = wSQL || '                    and ser.BDCONDPGTO = 1 ) ser on (ser.BDCODEMP = pgto.BDCODEMP and ser.BDCHAVE = pgto.BDCHAVE) ';
      END
    wSQL = wSQL || '      union all ';
    /* Demais Documentos */
    /* Tipo de apura??o das reten??es (PIS/Cofins/CSLL) */
    wSQL = wSQL || '            select dem.BDCODEMP, dem.BDCHAVE, dem.BDIND_OPER + 1 as BDTIPLAN, dem.BDNUMDOC as BDNUMDOCINI, ';
    wSQL = wSQL || '                   dem.BDDT_OPER as BDDATAEMISSAO, ';
    wSQL = wSQL || '                   dem.BDVL_OPER as BDVALORNOTA, dem.BDVL_OPER as BDVALORPAGO, ';
    wSQL = wSQL || '                   dem.BDCODTER, ret.BDVLRPIS, ret.BDVLRCOFINS, ';
    wSQL = wSQL || '                   ret.BDVLRCSOCIAL, 0 as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
    wSQL = wSQL || '            from VEF_EMP_TMOVDEMAISDOC_F100 dem ';
    wSQL = wSQL || '            left outer join VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
    wSQL = wSQL || '            where dem.BDCODEMP = '||prCODEMP||' ';
    wSQL = wSQL || '              and dem.BDDT_OPER between '''||prDATAINI||''' and '''||prDATAFIN||'''';
    wSQL = wSQL || '              and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRIR > 0) or (ret.BDISSRET > 0)) ';
    IF (prTIPOAPURACAORET = 1) THEN
      BEGIN
        wSQL = wSQL || '              and dem.BDCONDPGTO <> 1 ';
        wSQL = wSQL || '            union all ';
        wSQL = wSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, dem.BDTIPLAN, dem.BDNUMDOCINI, dem.BDDATAEMISSAO, dem.BDVL_OPER as BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO, dem.BDCODTER, ';
        wSQL = wSQL || '                   pgto.BDVALORRETPIS as BDVLRPIS, pgto.BDVALORRETCOFINS as BDVLRCOFINS, pgto.BDVALORRETCSLL as BDVLRCSOCIAL, pgto.BDVALORRETINSS as BDVLRINSS, 0 as BDVLRIR, pgto.BDVALORRETISSQN as BDISSRET ';
        wSQL = wSQL || '            from (select * from VEF_EMP_TMOVF100PARPGTO pgto ';
        wSQL = wSQL || '                  where pgto.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and (pgto.BDDATAPGTOPAR between '''||prDATAINI||''' and '''||prDATAFIN||''') ';
        wSQL = wSQL || '                    and (pgto.BDCODTIPOBAIXA <> 2)) pgto '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
        wSQL = wSQL || '            join (select dem.BDCODEMP, dem.BDCHAVE, dem.BDIND_OPER + 1 as BDTIPLAN, dem.BDNUMDOC as BDNUMDOCINI, ';
        wSQL = wSQL || '                         dem.BDDT_OPER as BDDATAEMISSAO, dem.BDVL_OPER, dem.BDCODTER, ret.BDVLRPIS, ret.BDVLRCOFINS, ';
        wSQL = wSQL || '                         ret.BDVLRCSOCIAL, 0 as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
        wSQL = wSQL || '                  from VEF_EMP_TMOVDEMAISDOC_F100 dem ';
        wSQL = wSQL || '                  left outer join VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
        wSQL = wSQL || '                  where dem.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRIR > 0) or (ret.BDISSRET > 0)) ';
        wSQL = wSQL || '                    and dem.BDCONDPGTO = 1 ) dem on (dem.BDCODEMP = pgto.BDCODEMP and dem.BDCHAVE = pgto.BDCHAVE) ';
      END
    wSQL = wSQL || '            union all ';
    /* Tipo de apura??o das reten??es IR */
    wSQL = wSQL || '            select dem.BDCODEMP, dem.BDCHAVE, dem.BDIND_OPER + 1 as BDTIPLAN, dem.BDNUMDOC as BDNUMDOCINI, ';
    wSQL = wSQL || '                   dem.BDDT_OPER as BDDATAEMISSAO, ';
    wSQL = wSQL || '                   dem.BDVL_OPER as BDVALORNOTA, dem.BDVL_OPER as BDVALORPAGO, ';
    wSQL = wSQL || '                   dem.BDCODTER, 0 as BDVLRPIS, 0 as BDVLRCOFINS, ';
    wSQL = wSQL || '                   0 as BDVLRCSOCIAL, 0 as BDVLRINSS, ret.BDVLRIR, 0 as BDISSRET ';
    wSQL = wSQL || '            from VEF_EMP_TMOVDEMAISDOC_F100 dem ';
    wSQL = wSQL || '            left outer join VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
    wSQL = wSQL || '            where dem.BDCODEMP = '||prCODEMP||' ';
    wSQL = wSQL || '              and dem.BDDT_OPER between '''||prDATAINI||''' and '''||prDATAFIN||'''';
    wSQL = wSQL || '              and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRIR > 0) or (ret.BDISSRET > 0)) ';
    IF (prTIPOAPURACAORETIR = 1) THEN
      BEGIN
        wSQL = wSQL || '              and dem.BDCONDPGTO <> 1 ';
        wSQL = wSQL || '            union all ';
        wSQL = wSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, dem.BDTIPLAN, dem.BDNUMDOCINI, dem.BDDATAEMISSAO, ';
        wSQL = wSQL || '                   dem.BDVL_OPER as BDVALORNOTA, ';
        wSQL = wSQL || '                   pgto.BDVALORPGTOPAR as BDVALORPAGO, ';
        wSQL = wSQL || '                   dem.BDCODTER, ';
        wSQL = wSQL || '                   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, pgto.BDVALORRETIRRF as BDVLRIR, 0 as BDISSRET ';
        wSQL = wSQL || '            from (select * from VEF_EMP_TMOVF100PARPGTO pgto ';
        wSQL = wSQL || '                  where pgto.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and (pgto.BDDATAPGTOPAR between '''||prDATAINI||''' and '''||prDATAFIN||''') ';
        wSQL = wSQL || '                    and (pgto.BDCODTIPOBAIXA <> 2)) pgto '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
        wSQL = wSQL || '            join (select dem.BDCODEMP, dem.BDCHAVE, dem.BDIND_OPER + 1 as BDTIPLAN, dem.BDNUMDOC as BDNUMDOCINI, ';
        wSQL = wSQL || '                         dem.BDDT_OPER as BDDATAEMISSAO, dem.BDVL_OPER, dem.BDCODTER, ret.BDVLRPIS, ret.BDVLRCOFINS, ';
        wSQL = wSQL || '                         ret.BDVLRCSOCIAL, 0 as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
        wSQL = wSQL || '                  from VEF_EMP_TMOVDEMAISDOC_F100 dem ';
        wSQL = wSQL || '                  left outer join VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
        wSQL = wSQL || '                  where dem.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRIR > 0) or (ret.BDISSRET > 0)) ';
        wSQL = wSQL || '                    and dem.BDCONDPGTO = 1 ) dem on (dem.BDCODEMP = pgto.BDCODEMP and dem.BDCHAVE = pgto.BDCHAVE) ';
      END
    wSQL = wSQL || '      union all ';
    /* Entradas */
    /* Tipo de apura??o das reten??es (PIS/Cofins/CSLL) */
    wSQL = wSQL || '            select ent.BDCODEMP, ent.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ';
    wSQL = wSQL || '                   ent.BDVALORNOTA, ent.BDVALORNOTA as BDVALORPAGO, ent.BDCODTER, ';
    wSQL = wSQL || '                   ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ret.BDINSSRET as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
    wSQL = wSQL || '            from VEF_EMP_TMOVENT ent ';
    wSQL = wSQL || '            left outer join VEF_EMP_TMOVENTRET ret on (ret.BDCODEMP = ent.BDCODEMP and ret.BDCHAVE = ent.BDCHAVE) ';
    wSQL = wSQL || '            where ent.BDCODEMP = '||prCODEMP||' ';
    wSQL = wSQL || '              and ent.BDDATAEMISSAO between '''||prDATAINI||''' and '''||prDATAFIN||''' ';
--  wSQL = wSQL || '              and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRIR > 0) or (ret.BDISSRET > 0)) ';
    wSQL = wSQL || '              and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDISSRET > 0)) ';
    IF (prTIPOAPURACAORET = 1) THEN
      BEGIN
        wSQL = wSQL || '              and ent.BDCONDPGTO <> 1 ';
        wSQL = wSQL || '            union all ';
        wSQL = wSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ent.BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO, ent.BDCODTER, ';
        wSQL = wSQL || '                   pgto.BDVALORRETPIS as BDVLRPIS, pgto.BDVALORRETCOFINS as BDVLRCOFINS, pgto.BDVALORRETCSLL as BDVLRCSOCIAL, pgto.BDVALORRETINSS as BDVLRINSS, 0 as BDVLRIR, pgto.BDVALORRETISSQN as BDISSRET ';
        wSQL = wSQL || '            from (select * from VEF_EMP_TMOVENTPARPGTO pgto ';
        wSQL = wSQL || '                  where pgto.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and (pgto.BDDATAPGTOPAR between '''||prDATAINI||''' and '''||prDATAFIN||''') ';
        wSQL = wSQL || '                    and (pgto.BDCODTIPOBAIXA <> 2)) pgto '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
        wSQL = wSQL || '            join (select ent.BDCODEMP, ent.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ent.BDVALORNOTA, ent.BDCODTER, ';
        wSQL = wSQL || '                         ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ret.BDINSSRET as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
        wSQL = wSQL || '                  from VEF_EMP_TMOVENT ent ';
        wSQL = wSQL || '                  left outer join VEF_EMP_TMOVENTRET ret on (ret.BDCODEMP = ent.BDCODEMP and ret.BDCHAVE = ent.BDCHAVE) ';
        wSQL = wSQL || '                  where ent.BDCODEMP = '||prCODEMP||' ';
--      wSQL = wSQL || '                    and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRIR > 0) or (ret.BDISSRET > 0)) ';
        wSQL = wSQL || '                    and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDISSRET > 0)) ';
        wSQL = wSQL || '                    and ent.BDCONDPGTO = 1 ) ent on (ent.BDCODEMP = pgto.BDCODEMP and ent.BDCHAVE = pgto.BDCHAVE) ';
      END
    wSQL = wSQL || '            union all ';
    /* Tipo de apura??o das reten??es IR */
    wSQL = wSQL || '            select ent.BDCODEMP, ent.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ';
    wSQL = wSQL || '                   ent.BDVALORNOTA, ent.BDVALORNOTA as BDVALORPAGO, ent.BDCODTER, ';
    wSQL = wSQL || '                   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, ret.BDVLRIR, 0 as BDISSRET ';
    wSQL = wSQL || '            from VEF_EMP_TMOVENT ent ';
    wSQL = wSQL || '            left outer join VEF_EMP_TMOVENTRET ret on (ret.BDCODEMP = ent.BDCODEMP and ret.BDCHAVE = ent.BDCHAVE) ';
    wSQL = wSQL || '            where ent.BDCODEMP = '||prCODEMP||' ';
    wSQL = wSQL || '              and ent.BDDATAEMISSAO between '''||prDATAINI||''' and '''||prDATAFIN||''' ';
--  wSQL = wSQL || '              and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRIR > 0) or (ret.BDISSRET > 0)) ';
    wSQL = wSQL || '              and (ret.BDVLRIR > 0) ';
    IF (prTIPOAPURACAORETIR = 1) THEN
      BEGIN
        wSQL = wSQL || '              and ent.BDCONDPGTO <> 1 ';
        wSQL = wSQL || '            union all ';
        wSQL = wSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ';
        wSQL = wSQL || '                   ent.BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO, ent.BDCODTER, ';
        wSQL = wSQL || '                   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, pgto.BDVALORRETIRRF as BDVLRIR, 0 as BDISSRET ';
        wSQL = wSQL || '            from (select * from VEF_EMP_TMOVENTPARPGTO pgto ';
        wSQL = wSQL || '                  where pgto.BDCODEMP = '||prCODEMP||' ';
        wSQL = wSQL || '                    and (pgto.BDDATAPGTOPAR between '''||prDATAINI||''' and '''||prDATAFIN||''') ';
        wSQL = wSQL || '                    and (pgto.BDCODTIPOBAIXA <> 2)) pgto '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
        wSQL = wSQL || '            join (select ent.BDCODEMP, ent.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ent.BDVALORNOTA, ent.BDCODTER, ';
        wSQL = wSQL || '                         ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ret.BDINSSRET as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
        wSQL = wSQL || '                  from VEF_EMP_TMOVENT ent ';
        wSQL = wSQL || '                  left outer join VEF_EMP_TMOVENTRET ret on (ret.BDCODEMP = ent.BDCODEMP and ret.BDCHAVE = ent.BDCHAVE) ';
        wSQL = wSQL || '                  where ent.BDCODEMP = '||prCODEMP||' ';
--      wSQL = wSQL || '                    and ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRIR > 0) or (ret.BDISSRET > 0)) ';
        wSQL = wSQL || '                    and (ret.BDVLRIR > 0) ';
        wSQL = wSQL || '                    and ent.BDCONDPGTO = 1 ) ent on (ent.BDCODEMP = pgto.BDCODEMP and ent.BDCHAVE = pgto.BDCHAVE) ';
      END      
    wSQL = wSQL || '      ) mov ';
    wSQL = wSQL || 'left outer join VW_TTERCEIRO ter on (ter.BDCODTER = mov.BDCODTER) ';
    wSQL = wSQL || 'order by mov.BDCODEMP, mov.BDTIPLAN, mov.BDCHAVE ';

  FOR EXECUTE STATEMENT wSQL INTO
       wCODEMP     ,
       wCHAVE      ,
       wTIPLAN     ,
       wNUMDOCINI  ,
       wDATAEMISSAO,
       wVALORNOTA  ,
       wVALORPAGO  ,
       wVLRPIS     ,
       wVLRCOFINS  ,
       wVLRCSOCIAL ,
       wVLRINSS    ,
       wVLRIR      ,
       wISSRET     ,
       wCODTER     ,
       wNOMETER    ,
       wCGCTER     DO
  BEGIN
    IF ((BDCODEMP <> wCODEMP) OR (BDCHAVE <> wCHAVE) OR (BDTIPLAN <> wTIPLAN)) THEN
      BEGIN
        SUSPEND;

        BDVLRPIS      = 0;
        BDVLRCOFINS   = 0;
        BDVLRCSOCIAL  = 0;
        BDVLRINSS     = 0;
        BDVLRIR       = 0;
        BDISSRET      = 0;
      END

    BDCODEMP      = wCODEMP;
    BDCHAVE       = wCHAVE;
    BDTIPLAN      = wTIPLAN;
    BDNUMDOCINI   = wNUMDOCINI;
    BDDATAEMISSAO = wDATAEMISSAO;
    BDVALORNOTA   = wVALORNOTA;
    BDVALORPAGO   = wVALORPAGO;

    BDVLRPIS      = COALESCE(wVLRPIS,0)     + COALESCE(BDVLRPIS,0);
    BDVLRCOFINS   = COALESCE(wVLRCOFINS,0)  + COALESCE(BDVLRCOFINS,0);
    BDVLRCSOCIAL  = COALESCE(wVLRCSOCIAL,0) + COALESCE(BDVLRCSOCIAL,0);
    BDVLRINSS     = COALESCE(wVLRINSS,0)    + COALESCE(BDVLRINSS,0);
    BDVLRIR       = COALESCE(wVLRIR,0)      + COALESCE(BDVLRIR,0);
    BDISSRET      = COALESCE(wISSRET,0)     + COALESCE(BDISSRET,0);

    BDCODTER      = wCODTER;
    BDNOMETER     = wNOMETER;
    BDCGCTER      = wCGCTER;
  END
  
  IF ((wCODEMP IS NOT NULL) AND (wCHAVE IS NOT NULL) AND (wTIPLAN IS NOT NULL)) THEN
    SUSPEND;
  
END
^

/* Alter (SP_CONSULTA_PLANO_CONTAS) */
ALTER PROCEDURE SP_CONSULTA_PLANO_CONTAS(PRCODPLADARAO INTEGER,
PRTODASCONTAS INTEGER,
PRCONSOLIDADA VARCHAR(3072),
PRFILTRO VARCHAR(1024))
 RETURNS(BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDGRUPOCTA INTEGER,
BDRELCTA INTEGER,
BDFILTROGER VARCHAR(20),
BDFORMULA VARCHAR(200),
BDCONDICAO VARCHAR(100),
BDPARTICIPANTE INTEGER,
BDPERTENCECONTA INTEGER,
BDCLANOM VARCHAR(140),
BDCODSUBCONTA INTEGER,
BDGRUPOSUBCONTA VARCHAR(10),
BDCODNATSUBCONTA INTEGER,
BDCTAEMPREENDIMENTOSIMOB DM_BOOLEAN,
BDCTAUNIDADEIMOB DM_BOOLEAN)
 AS
DECLARE VARIABLE WTIPCTA INTEGER;
DECLARE VARIABLE WSQL VARCHAR(4096);
DECLARE VARIABLE WPRIM INTEGER;
DECLARE VARIABLE WTAM INTEGER;
DECLARE VARIABLE WSQLAUX VARCHAR(1024);
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WTOTALCHAR INTEGER;
DECLARE VARIABLE WTOTALCHAR_ANT INTEGER;
DECLARE VARIABLE WCONSOLIDADA VARCHAR(20);
BEGIN
  wsql = 'select bdCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDNOMCTA, BDAPECTA, ';
  wsql = wsql||' BDGRUPOCTA, BDRELCTA, BDFILTROGER, BDFORMULA, BDCONDICAO, BDPARTICIPANTE, ';
  wsql = wsql||' BDPERTENCECONTA, BDCLANOM, BDCODSUBCONTA, BDGRUPOSUBCONTA, BDCODNATSUBCONTA, BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB, ';

  --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
  IF ((TRIM(PRCONSOLIDADA) = '') OR (prconsolidada IS NULL)) THEN
    wsql = wsql||' null as BDCONSOLIDADA ';
  ELSE
    wsql = wsql||' case when (BDCODTPLA in ('||prconsolidada||')) and (BDTIPCTA = 2) then BDCTALON end as BDCONSOLIDADA ';
  --alt:10645 - Fim

  wsql = wsql||'from PLANOS_TPLA ';
  wsql = wsql||'where bdcodplapadrao = '||prcodpladarao||' ';
  IF (prfiltro <> '') THEN
     wsql = wsql||prfiltro;
  wsql = wsql||' Order By bdCTALON ASC ';

  wprim = 0;

  FOR EXECUTE STATEMENT wsql
      INTO :bdcodplapadrao, :bdcodtpla, :bdctalon, :bdtipcta, :bdnomcta, :bdapecta, :bdgrupocta, :bdrelcta, 
           :bdfiltroger, :bdformula, :bdcondicao, :bdparticipante, :bdpertenceconta, :bdclanom, :bdcodsubconta, :bdgruposubconta,
           :bdcodnatsubconta, :bdctaempreendimentosimob, :bdctaunidadeimob, :WSQLAUX DO
      BEGIN
        --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
        IF (wsqlaux IS NOT NULL) THEN
          wconsolidada = wsqlaux;

        IF (bdtipcta IN (0,2)) THEN
           BEGIN
             wtipcta = bdtipcta;
             IF (bdtipcta = 2) THEN
                SELECT CONTAR_CHAR FROM contar_char(:bdctalon, '.') INTO :wTotalChar;
           END
        ELSE
          IF ((wtipcta = 2) AND (bdtipcta = 1)) THEN
             BEGIN
               SELECT CONTAR_CHAR FROM contar_char(:bdctalon, '.') INTO :WTOTALCHAR_ANT;

               IF (WTOTALCHAR_ANT <= wTotalChar) THEN
                  wtipcta = 0;
             END

        IF (prtodascontas = 1) THEN
           SUSPEND;
        ELSE
        BEGIN
        --alt:7608 - Retirada esse filtro para retornar as contas consolidadas da classifica??o filtrada que n?o estava retornando antes. Pedro
        IF ((prfiltro <> '') /*and (prconsolidada <> '')*/) THEN
           BEGIN
             --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
             --IF (TRIM(prconsolidada) <> '') THEN
             IF (TRIM(wconsolidada) <> '') THEN
                BEGIN
                  --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
                  --wtam = strlen(TRIM(prconsolidada));
                  wtam = strlen(TRIM(wconsolidada));
                  IF ((bdtipcta = 0) OR ((bdtipcta = 1) AND (wtipcta = 0))) THEN
                     SUSPEND;
                  ELSE
                  IF (bdtipcta = 2) THEN
                     BEGIN
                       wsqlaux = 'select bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdnomcta, bdapecta, ';
                       wsqlaux = wsqlaux||'bdgrupocta, bdrelcta, bdfiltroger, bdformula, bdcondicao, BDPARTICIPANTE, ';
                       wsqlaux = wsqlaux||'BDPERTENCECONTA, BDCLANOM, BDCODSUBCONTA, BDGRUPOSUBCONTA, BDCODNATSUBCONTA, BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB ';
                       wsqlaux = wsqlaux||'from planos_tpla ';
                       wsqlaux = wsqlaux||'where bdcodplapadrao = '||prcodpladarao;
                       wsqlaux = wsqlaux||' and substring(bdctalon from 1 for '||strlen(bdctalon)||') = '''||bdctalon||'''';
                       wsqlaux = wsqlaux||' order by bdctalon';

                       FOR EXECUTE STATEMENT wsqlaux
                           INTO :bdcodplapadrao, :bdcodtpla, :bdctalon, :bdtipcta, :bdnomcta, :bdapecta,
                                :bdgrupocta, :bdrelcta, :bdfiltroger, :bdformula, :bdcondicao, :bdparticipante,
                                :bdpertenceconta, :bdclanom, :bdcodsubconta, :bdgruposubconta, :bdcodnatsubconta, :bdctaempreendimentosimob, :bdctaunidadeimob DO
                           BEGIN
                             IF (bdtipcta = 2) THEN
                                SUSPEND;
                             ELSE
                             --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
                             --IF ((SUBSTRING(bdctalon FROM 1 FOR wtam) = TRIM(prconsolidada)) AND (bdtipcta = 1)) THEN
                             IF ((SUBSTRING(bdctalon FROM 1 FOR wtam) = TRIM(wconsolidada)) AND (bdtipcta = 1)) THEN
                                SUSPEND;
                           END
                     END
                END
             ELSE
                --alt:7608 - Retirada essa op??o pois agora retorna contas anal?ticas que n?o deve. Pedro
                IF ((bdtipcta IN (0,2)) OR
                   (bdtipcta = 1 AND wtipcta = 0) /*or
                   ((bdtipcta = 1) and (prfiltro <> ''))*/) THEN
                   SUSPEND;
           END
        ELSE
        IF ((bdtipcta = 2) AND (prfiltro <> '')) THEN
           BEGIN
             IF (wprim = 0) THEN
                BEGIN
                  wprim = 1;
                  --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
                  --IF (prconsolidada = '') THEN
                  IF (wconsolidada = '') THEN
                     BEGIN
                       wsqlaux = 'select bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdnomcta, bdapecta, ';
                       wsqlaux = wsqlaux||'bdgrupocta, bdrelcta, bdfiltroger, bdformula, bdcondicao, BDPARTICIPANTE, ';
                       wsqlaux = wsqlaux||'BDPERTENCECONTA, BDCLANOM, BDCODSUBCONTA, BDGRUPOSUBCONTA, BDCODNATSUBCONTA, BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB ';
                       wsqlaux = wsqlaux||'from planos_tpla ';
                       wsqlaux = wsqlaux||'where bdcodplapadrao = '||prcodpladarao;
                       wsqlaux = wsqlaux||' and substring(bdctalon from 1 for '||strlen(bdctalon)||') = '''||bdctalon||'''';
          
                       FOR EXECUTE STATEMENT wsqlaux
                           INTO :bdcodplapadrao, :bdcodtpla, :bdctalon, :bdtipcta, :bdnomcta, :bdapecta,
                                :bdgrupocta, :bdrelcta, :bdfiltroger, :bdformula, :bdcondicao, :bdparticipante,
                                :bdpertenceconta, :bdclanom, :bdcodsubconta, :bdgruposubconta, :bdcodnatsubconta, :bdctaempreendimentosimob, :bdctaunidadeimob DO
                           SUSPEND;
                     END
                  ELSE
                     SUSPEND;
                END
           END
        ELSE
           --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
           --IF (TRIM(prconsolidada) <> '') THEN
           IF (TRIM(wconsolidada) <> '') THEN
              BEGIN
                --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
                --wtam = strlen(TRIM(prconsolidada));
                wtam = strlen(TRIM(wconsolidada));
                IF (bdtipcta IN (0,2)) THEN
                   SUSPEND;
                ELSE
                   --alt:10645 - 26/03/2015 - Alterado para poder abrir mais de um grupo de contas consolidadas ao mesmo tempo. Pedro
                   --IF (((SUBSTRING(bdctalon FROM 1 FOR wtam) = TRIM(prconsolidada)) AND (wtipcta IN (1,2))) OR (wtipcta = 0)) THEN
                   IF (((SUBSTRING(bdctalon FROM 1 FOR wtam) = TRIM(wconsolidada)) AND (wtipcta IN (1,2))) OR (wtipcta = 0)) THEN
                      SUSPEND;
              END
           ELSE
              --alt:7608 - Retirada essa op??o pois retornava contas anal?ticas que n?o deveria. Pedro
              IF ((bdtipcta IN (0,2)) OR
                 (bdtipcta = 1 AND wtipcta = 0) /*or
                 ((bdtipcta = 1) and (prfiltro <> ''))*/) THEN
                 SUSPEND;

        END /* todas as contas */

      END
END
^

/* Alter (SP_CONSULTACLIENTES) */
ALTER PROCEDURE SP_CONSULTACLIENTES(PRREFMICRO INTEGER,
PRCODCLI VARCHAR(10240),
PRCODSITCLI INTEGER)
 RETURNS(BDCODCLI INTEGER,
BDCODESC INTEGER,
BDCODPRESER INTEGER,
BDCODCLIMATRIZ INTEGER,
BDCNPJCLI VARCHAR(18),
BDDATAINIATIVCLI DATE,
BDDATAFIMATIVCLI DATE,
BDORGAOCLI VARCHAR(20),
BDNUMREGCLI VARCHAR(40),
BDNOMECARTORIO VARCHAR(100),
BDDATAREGCLI DATE,
BDLIVROREG VARCHAR(15),
BDFOLHAREG VARCHAR(15),
BDDOCAUXREG VARCHAR(18),
BDCODTIPOCLI INTEGER,
BDDATACADCLI DATE,
BDCODCID INTEGER,
BDCODCNAE INTEGER,
BDCODNATJUR INTEGER,
BDDESCPLASITFIN VARCHAR(50),
BDCODPLASITFIN INTEGER,
BDAPECLI DM_BDAPEMP,
BDNOMCLI DM_BDNOMEMP,
BDNOMREDUZCLI DM_BDNOMREDUZEMP,
BDCEPCLI VARCHAR(9),
BDLOGRCLI VARCHAR(15),
BDENDCLI DM_BDENDERECO,
BDNUMCLI INTEGER,
BDCOMPLCLI DM_BDCOMPENDERECO,
BDBAICLI DM_BDBAIRRO,
BDDDDCLI INTEGER,
BDFONECLI DM_BDTELEFONE,
BDDDDFAXCLI INTEGER,
BDFONEFAXCLI DM_BDTELEFONE,
BDDDDCELCLI INTEGER,
BDCELCLI DM_BDTELEFONE,
BDCXPCLI DM_CXPOSTAL,
BDIECLI VARCHAR(20),
BDIMCLI VARCHAR(20),
BDEMAILCLI DM_BDEMAIL,
BDCAPITALSOC DM_NUMERIC_15_2,
BDORGAOPUBLICO DM_BOOLEAN,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCCNAE VARCHAR(200),
BDDESCNAT VARCHAR(100),
BDNUMFUN INTEGER,
BDCODPLATRIB INTEGER,
BDINATIVO DM_BOOLEAN,
BDDESCPLATRIB VARCHAR(50),
BDCODIBGECID INTEGER,
BDCODFEDCID INTEGER,
BDCODSPEDPAIS INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'cli.BDCODCLI, cli.BDCODESC, cli.BDCODPRESER, cli.BDCODCLIMATRIZ, ';
  wSql = wSql||'cli.BDCNPJCLI, cli.BDDATAINIATIVCLI, cli.BDDATAFIMATIVCLI, ';
  wSql = wSql||'cli.BDORGAOCLI, cli.BDNUMREGCLI, cli.BDNOMECARTORIO, cli.BDDATAREGCLI, ';
  wSql = wSql||'cli.BDLIVROREG, cli.BDFOLHAREG, cli.BDDOCAUXREG, cli.BDCODTIPOCLI, cli.BDDATACADCLI, ';
  wSql = wSql||'refcli.BDCODCID, refcli.BDCODCNAE, refcli.BDCODNATJUR, ';
  wSql = wSql||'/*refcli.BDCODSITCLI,*/ refcli.BDAPECLI, refcli.BDNOMCLI, ';
  wSql = wSql||'refcli.BDNOMREDUZCLI, refcli.BDCEPCLI, refcli.BDLOGRCLI, ';
  wSql = wSql||'refcli.BDENDCLI, refcli.BDNUMCLI, refcli.BDCOMPLCLI, ';
  wSql = wSql||'refcli.BDBAICLI, refcli.BDDDDCLI, refcli.BDFONECLI, ';
  wSql = wSql||'refcli.BDDDDFAXCLI, refcli.BDFONEFAXCLI, refcli.BDDDDCELCLI, ';
  wSql = wSql||'refcli.BDCELCLI, refcli.BDCXPCLI,refcli.BDIECLI, refcli.BDIMCLI, ';
  wSql = wSql||'refcli.BDEMAILCLI, refcli.BDCAPITALSOC, refcli.BDORGAOPUBLICO, ';
  wSql = wSql||'/*refcli.BDDATAENTRADA, refcli.BDDATASAIDA,*/ refcli.bdnumfun, refcli.bdinativo, refcli.bdcodplatrib, ';
  wSql = wSql||'refcli.BDCODPLANOONLINE, refcli.BDCODPLAPADRAO, refcli.BDCODHIST, ';
  wSql = wsql||'cid.bdnomcid, uf.bdsiglauf, ';
  wSql = wSql||'/*sitcli.bddescsitcli,*/ cnae.BDDESCCNAE, natjur.bddescnat, tplatrib.bddescplatrib, ';
  wSql = wSql||'cid.bdcodibge bdcodibgecid, cid.bdcodfed bdcodfedcid, pais.bdcodsped bdcodspedpais, ';
  wSql = wSql||'refcli.BDCODPLASITFIN, plasit.BDDESCPLASITFIN ';
  wSql = wSql||' from VFIN_BASE_TCLIENTE cli ';
  wSql = wSql||' join vw_vfin_clientes_ref refcli on (refcli.bdcodcli = cli.bdcodcli) ';
  wSql = wSql||' left outer join tcidade cid on (cid.bdcodcid = refcli.bdcodcid)  ';
  wSql = wSql||' left outer join tpais pais on pais.bdcodpais = cid.bdcodpais ';
  wSql = wSql||' left outer join tuf uf on (uf.bdcoduf = cid.bdcoduf) ';
  /*wSql = wSql||' left outer join vfin_base_ttabsitcli sitcli on (sitcli.bdcodsitcli = refcli.bdcodsitcli) ';*/
  wSql = wSql||' left outer join VFIN_BASE_TPLANOSITFIN plasit on (plasit.bdcodplasitfin = refcli.bdcodplasitfin) ';
  wSql = wSql||' left outer join tcnae cnae on (cnae.bdcodcnae = refcli.bdcodcnae) ';
  wSql = wSql||' left outer join tnatjur natjur on (natjur.bdcodnatjur = refcli.bdcodnatjur) ';
  wSql = wSql||' left outer join VCT_PLANO_TRIBUTARIO tplatrib on (tplatrib.bdcodplatrib = refcli.bdcodplatrib) ';

  wwhere = '';

  IF ((prcodcli IS NOT NULL) AND (prcodcli <> '0') AND (prcodcli <> '')) THEN
     BEGIN
       SELECT POSITION('=', :prcodcli) FROM RDB$DATABASE INTO wpos;

       IF (wPos = 0) THEN
          SELECT POSITION(' in (', :prcodcli) FROM RDB$DATABASE INTO :wpos;

       IF (wPos = 0) THEN
          SELECT POSITION(' between ', :prcodcli) FROM RDB$DATABASE INTO :wpos;

       IF (wpos > 0) THEN
          wwhere = wwhere||' ('||prcodcli||') ';
       ELSE
          wwhere = wwhere||' cli.bdcodcli = '||prcodcli;
     END

  /*Comentado pois n?o existe mais o campo BDCODSITCLI na tabela de clientes*/
  /* filra situa??o do cliente*/
  /*if (PRCODSITCLI is not null and PRCODSITCLI <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wWhere = 'ref.bdCODSITCLI = '||prCODSITCLI;
     end*/

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By cli.BDCODCLI';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    /*BDCODSITCLI,*/
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    /*BDDATAENTRADA,
    BDDATASAIDA,*/
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDNOMCID,
    BDSIGLAUF,
    /*BDDESCSITCLI,*/
    BDDESCCNAE,
    BDDESCNAT,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODPLASITFIN,
    BDDESCPLASITFIN
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONSULTACLIENTES_SIS) */
ALTER PROCEDURE SP_CONSULTACLIENTES_SIS(PRREFMICRO INTEGER,
PRCODCLI INTEGER,
PRCODSITCLI INTEGER)
 RETURNS(BDCODCLI INTEGER,
BDCODESC INTEGER,
BDCODPRESER INTEGER,
BDCODCLIMATRIZ INTEGER,
BDCNPJCLI VARCHAR(18),
BDDATAINIATIVCLI DATE,
BDDATAFIMATIVCLI DATE,
BDORGAOCLI VARCHAR(20),
BDNUMREGCLI VARCHAR(40),
BDNOMECARTORIO VARCHAR(100),
BDDATAREGCLI DATE,
BDLIVROREG VARCHAR(15),
BDFOLHAREG VARCHAR(15),
BDDOCAUXREG VARCHAR(18),
BDCODTIPOCLI INTEGER,
BDDATACADCLI DATE,
BDCODCID INTEGER,
BDCODCNAE INTEGER,
BDCODNATJUR INTEGER,
BDAPECLI DM_BDAPEMP,
BDNOMCLI DM_BDNOMEMP,
BDNOMREDUZCLI DM_BDNOMREDUZEMP,
BDCEPCLI VARCHAR(9),
BDLOGRCLI VARCHAR(15),
BDENDCLI DM_BDENDERECO,
BDNUMCLI INTEGER,
BDCOMPLCLI DM_BDCOMPENDERECO,
BDBAICLI DM_BDBAIRRO,
BDDDDCLI INTEGER,
BDFONECLI DM_BDTELEFONE,
BDDDDFAXCLI INTEGER,
BDFONEFAXCLI DM_BDTELEFONE,
BDDDDCELCLI INTEGER,
BDCELCLI DM_BDTELEFONE,
BDCXPCLI DM_CXPOSTAL,
BDIECLI VARCHAR(20),
BDIMCLI VARCHAR(20),
BDEMAILCLI DM_BDEMAIL,
BDCAPITALSOC DM_NUMERIC_15_2,
BDORGAOPUBLICO DM_BOOLEAN,
BDDATAENTRADA DATE,
BDDATASAIDA DATE,
BDCODCONT INTEGER,
BDCONTATO VARCHAR(60),
BDPROFISCONTATO VARCHAR(60),
BDDATANASCCON DATE,
BDCPFCON VARCHAR(18),
BDCODCIDETI INTEGER,
BDNOMENDETI DM_BDNOMEMP,
BDLOGRETI VARCHAR(15),
BDENDERECOETI DM_BDENDERECO,
BDNUMEROETI INTEGER,
BDCOMPLETI DM_BDCOMPENDERECO,
BDBAIRROETI DM_BDBAIRRO,
BDCEPETI VARCHAR(9),
BDCXPETI DM_CXPOSTAL,
BDNOMCIDETI VARCHAR(40),
BDSIGLAUFETI VARCHAR(2),
BDCODENQFED INTEGER,
BDCOMERCIO DM_BOOLEAN,
BDINDUSTRIA DM_BOOLEAN,
BDSERVICO DM_BOOLEAN,
BDANEXOIII DM_BOOLEAN,
BDANEXOIV DM_BOOLEAN,
BDANEXOV DM_BOOLEAN,
BDANEXOVI DM_BOOLEAN,
BDPERINSS DM_NUMERIC_7_4_ALIQ,
BDDEDINSSNF DM_BOOLEAN,
BDUSARPERISS INTEGER,
BDRETIR DM_BOOLEAN,
BDRETCSLL DM_BOOLEAN,
BDRETCOF DM_BOOLEAN,
BDRETPIS DM_BOOLEAN,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCSITCLI VARCHAR(100),
BDDESCCNAE VARCHAR(200),
BDDESCNAT VARCHAR(100),
BDNUMFUN INTEGER,
BDINATIVO DM_BOOLEAN,
BDCODPLATRIB INTEGER,
BDDESCPLATRIB VARCHAR(50),
BDCODIBGECID INTEGER,
BDCODFEDCID INTEGER,
BDCODSPEDPAIS INTEGER,
BDINCENTCULT DM_BOOLEAN,
BDCODIBGECIDETI INTEGER,
BDCODFEDCIDETI INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODSITESP INTEGER,
BDCODPLASITFIN INTEGER,
BDDESCPLASITFIN VARCHAR(50),
BDCODHIST INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'ref.BDCODCLI, ';
  wSql = wSql||'ref.BDCODESC, ';
  wSql = wSql||'ref.BDCODPRESER, ';
  wSql = wSql||'ref.BDCODCLIMATRIZ, ';
  wSql = wSql||'ref.BDCNPJCLI, ';
  wSql = wSql||'ref.BDDATAINIATIVCLI, ';
  wSql = wSql||'ref.BDDATAFIMATIVCLI, ';
  wSql = wSql||'ref.BDORGAOCLI, ';
  wSql = wSql||'ref.BDNUMREGCLI, ';
  wSql = wSql||'ref.BDNOMECARTORIO, ';
  wSql = wSql||'ref.BDDATAREGCLI, ';
  wSql = wSql||'ref.BDLIVROREG, ';
  wSql = wSql||'ref.BDFOLHAREG, ';
  wSql = wSql||'ref.BDDOCAUXREG, ';
  wSql = wSql||'ref.BDCODTIPOCLI, ';
  wSql = wSql||'ref.BDDATACADCLI, ';
  wSql = wSql||'ref.BDCODCID, ';
  wSql = wSql||'ref.BDCODCNAE, ';
  wSql = wSql||'ref.BDCODNATJUR, ';
  /*wSql = wSql||'ref.BDCODSITCLI, ';*/
  wSql = wSql||'ref.BDAPECLI, ';
  wSql = wSql||'ref.BDNOMCLI, ';
  wSql = wSql||'ref.BDNOMREDUZCLI, ';
  wSql = wSql||'ref.BDCEPCLI, ';
  wSql = wSql||'ref.BDLOGRCLI, ';
  wSql = wSql||'ref.BDENDCLI, ';
  wSql = wSql||'ref.BDNUMCLI, ';
  wSql = wSql||'ref.BDCOMPLCLI, ';
  wSql = wSql||'ref.BDBAICLI, ';
  wSql = wSql||'ref.BDDDDCLI, ';
  wSql = wSql||'ref.BDFONECLI, ';
  wSql = wSql||'ref.BDDDDFAXCLI, ';
  wSql = wSql||'ref.BDFONEFAXCLI, ';
  wSql = wSql||'ref.BDDDDCELCLI, ';
  wSql = wSql||'ref.BDCELCLI, ';
  wSql = wSql||'ref.BDCXPCLI, ';
  wSql = wSql||'ref.BDIECLI, ';
  wSql = wSql||'ref.BDIMCLI, ';
  wSql = wSql||'ref.BDEMAILCLI, ';
  wSql = wSql||'ref.BDCAPITALSOC, ';
  wSql = wSql||'ref.BDORGAOPUBLICO, ';
  /*wSql = wSql||'ref.BDDATAENTRADA, ';
  wSql = wSql||'ref.BDDATASAIDA, ';*/
  wSql = wSql||'ref.bdnomcid, ';
  wSql = wSql||'ref.bdsiglauf, ';
  /*wSql = wSql||'ref.bddescsitcli, ';*/
  wSql = wSql||'ref.bddesccnae, ';
  wSql = wSql||'ref.bddescnat, ';
  wSql = wSql||'ref.bdnumfun, ';
  wSql = wSql||'ref.bdinativo, ';
  wSql = wSql||'ref.bdcodplatrib, ';
  wSql = wSql||'ref.bddescplatrib, ';
  wSql = wSql||'ref.bdcodibgecid, ';
  wSql = wSql||'ref.bdcodfedcid, ';
  wSql = wSql||'ref.bdcodspedpais, ';
  wSql = wSql||'ref.BDCODPLANOONLINE, ';
  wSql = wSql||'ref.BDCODPLAPADRAO, ';
  wSql = wSql||'ref.BDCODHIST, ';
  wSql = wSql||'reftot.BDCODCONT, ';
  wSql = wSql||'reftot.BDCONTATO, ';
  wSql = wSql||'reftot.BDPROFISCONTATO, ';
  wSql = wSql||'reftot.BDDATANASCCON, ';
  wSql = wSql||'reftot.BDCPFCON, ';
  wSql = wSql||'reftot.BDCODCIDETI, ';
  wSql = wSql||'reftot.BDNOMENDETI, ';
  wSql = wSql||'reftot.BDLOGRETI, ';
  wSql = wSql||'reftot.BDENDERECOETI, ';
  wSql = wSql||'reftot.BDNUMEROETI, ';
  wSql = wSql||'reftot.BDCOMPLETI, ';
  wSql = wSql||'reftot.BDBAIRROETI, ';
  wSql = wSql||'reftot.BDCEPETI, ';
  wSql = wSql||'reftot.BDCXPETI, ';
  wSql = wSql||'reftot.BDNOMCIDETI, ';
  wSql = wSql||'reftot.BDSIGLAUFETI, ';
  wSql = wSql||'reftot.BDCODENQFED, ';
  wSql = wSql||'reftot.BDCOMERCIO, ';
  wSql = wSql||'reftot.BDINDUSTRIA, ';
  wSql = wSql||'reftot.BDSERVICO, ';
  wSql = wSql||'reftot.BDANEXOIII, ';
  wSql = wSql||'reftot.BDANEXOIV, ';
  wSql = wSql||'reftot.BDANEXOV, ';
  wSql = wSql||'reftot.BDANEXOVI, ';
  wSql = wSql||'reftot.BDPERINSS, ';
  wSql = wSql||'reftot.BDDEDINSSNF, ';
  wSql = wSql||'reftot.BDUSARPERISS, ';
  wSql = wSql||'reftot.BDRETIR, ';
  wSql = wSql||'reftot.BDRETCSLL, ';
  wSql = wSql||'reftot.BDRETCOF, ';
  wSql = wSql||'reftot.BDRETPIS, ';
  wSql = wSql||'reftot.BDINCENTCULT, ';
  wSql = wSql||'reftot.BDCODIBGECIDETI, ';
  wSql = wSql||'reftot.BDCODFEDCIDETI, ';
  wSql = wSql||'reftot.BDCODSITESP, ';
  wSql = wSql||'ref.BDCODPLASITFIN, ';
  wSql = wSql||'ref.BDDESCPLASITFIN ';


  WPAR = 'from sp_consultaclientes('||prrefmicro;
  IF (prcodcli IS NOT NULL AND prcodcli <> 0) THEN
    wpar = wpar||','||prcodcli||',';
  ELSE
    wpar = wpar||',null,';

  IF (PRCODSITCLI IS NULL) THEN
    wpar = wpar||'0) ref';
  ELSE
    wpar = wpar||PRCODSITCLI||') ref';

  wSql = wsql || wpar;

  wSql = wsql || ' left outer join VW_VFIN_BASE_TCLIENTE_REF_TOTAL reftot on (reftot.bdcodcli = ref.bdcodcli) ';

  wwhere = '';

  IF (prcodcli IS NOT NULL AND prcodcli <> 0) THEN
     wwhere = wwhere || ' ref.bdcodcli = '||prcodcli;

  /*Comentado pois n?o existe mais o campo BDCODSITCLI na tabela de clientes*/
  /* filra empresas inativas */
  /*IF (prcodsitcli IS NOT NULL AND prcodsitcli <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'ref.BDCODSITCLI) = '||prcodsitcli;
     END*/

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By ref.BDCODCLI';


  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    /*BDCODSITCLI,*/
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    /*BDDATAENTRADA,
    BDDATASAIDA,*/
    BDNOMCID,
    BDSIGLAUF,
    /*BDDESCSITCLI,*/
    BDDESCCNAE,
    BDDESCNAT,
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCONT,
    BDCONTATO,
    BDPROFISCONTATO,
    BDDATANASCCON,
    BDCPFCON,
    BDCODCIDETI,
    BDNOMENDETI,
    BDLOGRETI,
    BDENDERECOETI,
    BDNUMEROETI,
    BDCOMPLETI,
    BDBAIRROETI,
    BDCEPETI,
    BDCXPETI,
    BDNOMCIDETI,
    BDSIGLAUFETI,
    BDCODENQFED,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDPERINSS,
    BDDEDINSSNF,
    BDUSARPERISS,
    BDRETIR,
    BDRETCSLL,
    BDRETCOF,
    BDRETPIS,
    BDINCENTCULT,
    BDCODIBGECIDETI,
    BDCODFEDCIDETI,
    BDCODSITESP,
    BDCODPLASITFIN,
    BDDESCPLASITFIN
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONSULTAEMPRESAS) */
ALTER PROCEDURE SP_CONSULTAEMPRESAS(PRREFMICRO INTEGER,
PRCODEMP VARCHAR(10240),
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDDATAINIATIVEMP DATE,
BDORGAOEMP VARCHAR(8),
BDDATAREGEMP DATE,
BDDATACONSTEMP DATE,
BDOMIE DM_BOOLEAN,
BDDESCCARTEMP VARCHAR(40),
BDDATAFIMATIVEMP DATE,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCODCENTROS INTEGER,
BDCODCID INTEGER,
BDCODCONT INTEGER,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDNOMFANEMP VARCHAR(200),
BDNOMREDUZEMP DM_BDNOMREDUZEMP,
BDAPEEMP DM_BDAPEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDLOGREMP VARCHAR(15),
BDIEEMP VARCHAR(20),
BDIMEMP VARCHAR(20),
BDSITEMP VARCHAR(5),
BDDDDFAXEMP INTEGER,
BDNOMCID VARCHAR(40),
BDCODUF INTEGER,
BDNOMECONT VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCUF VARCHAR(40),
BDCODPLANOONLINE INTEGER,
BDCODENQFED INTEGER,
BDPERSONALIZACAO VARCHAR(120),
BDCODCONTEF INTEGER,
BDLIVRO VARCHAR(15),
BDFOLHA VARCHAR(15),
BDNOMECARTORIO VARCHAR(100),
BDDATACADEMP DATE,
BDTIPOAPURACAORET INTEGER,
BDCODPLATRIB INTEGER,
BDTRANMANUAL VARCHAR(5),
BDTIPOAPURACAORETIR INTEGER,
BDCODESC INTEGER,
BDCODPLAPADRAOREF INTEGER,
BDCODIBGE INTEGER,
BDFORMATRIBUTACAO INTEGER,
BDSTATUS_ES INTEGER,
BDABRIRRATEIO DM_BOOLEAN,
BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
BDINTEGRANET DM_BOOLEAN,
BDIGNORAREDISS DM_BOOLEAN,
BDDATAINIESOCIAL DATE,
BDOPCAOESOCIAL INTEGER,
BDDDDCELULAREMP INTEGER,
BDCELULAREMP DM_BDTELEFONE,
BDCODCLI INTEGER,
BDDATAOBRIGREINF DATE,
BDNRTCE VARCHAR(20),
BDSTATUSEMP INTEGER,
BDQTDBACKUPEMP INTEGER,
BDMATRIZNAOCADSIS VARCHAR(5),
BDSITUACAOESOCIAL INTEGER,
BDCODGIARS INTEGER,
BDINCORPORADORAS DM_BOOLEAN)
 AS
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WPOS integer;
declare variable WTUDO integer;
BEGIN
  SELECT x.bdcodusu FROM SP_GET_USUARIO x INTO :wTudo;
  IF ((wtudo IS NULL) OR (wtudo = 0)) THEN
     wTudo = 1;
  ELSE
     BEGIN
       SELECT COUNT(tgrp.bdcodgrupo) FROM tgrupousuario tgrp
       INNER JOIN tgrupousuario_usuario tusu ON (tusu.bdcodgrupo = tgrp.bdcodgrupo AND tusu.bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x))
       WHERE tgrp.bdcodesc IS NULL
       -- 0 - Mostrar empresas que n?o pertencem ao grupo
       -- 1 - Esconder empresas que n?o pertencem ao grupo
       OR ((tgrp.bdimpemp IS NULL) OR (tgrp.bdimpemp = 0))
       INTO :wtudo;
     END

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  IF (wtudo = 0) THEN
     wsql = wsql||' distinct ';
  wSql = wSql||'TEMP.BDCODEMP, TEMP.BDCODMATRIZ, TEMP.BDCNPJEMP, TEMP.BDDATAINIATIVEMP, ';
  wSql = wSql||'TEMP.BDORGAOEMP, TEMP.BDDATAREGEMP,  TEMP.BDDATACONSTEMP, TEMP.BDDESCCARTEMP, ';
  wSql = wSql||'TEMP.BDDATAFIMATIVEMP, TEMP.BDFORMATRIBUTACAOEMP, TEMP.BDNRTCE, TEMP.BDOMIE, ';
  wSql = wSql||'tref.BDCODPLAPADRAO, tref.BDCODHIST, tref.BDCODCENTROS,  ';
  wSql = wSql||'tref.BDCODCID, tref.BDCODCONT,  ';
  wSql = wSql||'tref.BDCODNATJUR, tref.BDCODCNAE, tref.BDNOMEMP, tref.BDNOMREDUZEMP, tref.BDAPEEMP, tref.BDENDEMP,  ';
  wSql = wSql||'tref.BDNUMEMP, tref.BDBAIEMP, tref.BDCEPEMP, tref.BDDDDEMP, tref.BDFONEEMP,  ';
  wSql = wSql||'tref.BDFAXEMP, tref.BDEMAILEMP, tref.BDCOMPLEMP, tref.BDLOGREMP, tref.BDIEEMP, tref.BDIMEMP,  ';
  wSql = wSql||'tref.BDSITEMP, tref.BDDDDFAXEMP,  ';
  wSql = wSql||'TCID.BDNOMCID, TCID.BDCODUF,  ';
  wSql = wSql||'TCON.BDNOMECONT, test.BDSIGLAUF, test.BDDESCUF, ';
--                 'tref.bdcnaeprep,'||
  wSql = wSql||'tref.bdcodplanoonline, enq.bdcodenqfed, ';

  wSql = wSql||'case when (tesc.bdprintesc = 1) then tesc.bdnomesc ';
  wSql = wSql||'     when (tesc.bdprintesc = 2) then tesc.bdnomesc||'||''' - '''||'||(select first 1 BDPERSONALIZACAO from TPERSONALIZACAO) ';
  wSql = wSql||'     else (select first 1 BDPERSONALIZACAO from TPERSONALIZACAO) end bdpersonalizacao, ';

  wsql = wsql||' tref.BDCODCONTEF, TEMP.BDLIVRO, TEMP.BDFOLHA, TEMP.BDNOMECARTORIO, TEMP.BDDATACADEMP, ger.BDTIPOAPURACAORET, tref.bdcodplatrib, ';
  wsql = wsql||' TEMP.BDTRANMANUAL, ger.BDTIPOAPURACAORETIR, TEMP.bdcodesc, tref.BDCODPLAPADRAOREF, TCID.BDCODIBGE, TEMP.BDSTATUS_ES, ';
  wSQL = wSQL||' tref.BDABRIRRATEIO, BDNAOPERMITERATEIOGRUPO, '; --alt:13677 - 15/03/2016 - Adicionados par?metros. Pedro
  wSql = wSql||' TEMP.BDINTEGRANET, ger.BDIGNORAREDISS, ';
  wSql = wSql||' TEMP.BDDATAINIESOCIAL, FAS.BDOPCAOESOCIAL, ';
  wSql = wSql||' TREF.BDDDDCELULAREMP, tref.BDCELULAREMP, temp.bdcodcli, temp.BDDATAOBRIGREINF, tref.BDNOMFANEMP, ';
  wSql = wSql||' TEMP.BDSTATUSEMP, TEMP.BDQTDBACKUPEMP, TEMP.BDMATRIZNAOCADSIS, TEMP.BDSITUACAOESOCIAL, TCID.BDCODGIARS, temp.BDINCORPORADORAS ';
  wSql = wSql||' from TEMPRESAS TEMP ';
  wSql = wSql||' join vw_tempresas_ref tref  on (tref.bdcodemp = temp.bdcodemp) ';
  wSql = wSql||' join VW_TENQFED Enq  on (Enq.bdcodemp = temp.bdcodemp) ';
  wSql = wSql||' left outer join TCIDADE TCID on (TCID.BDCODCID = Tref.BDCODCID) ';
  wSql = wSql||' left outer join TCONTADOR_PADRAO TCON  on (Tcon.BDCODCONT = tref.BDCODCONT)';
  wSql = wSql||' left outer join TUF test  on (test.BDCODUF = TCID.BDCODUF) ';

  wSql = wSql||' left outer join tescritorio tesc on (tesc.bdcodesc = temp.bdcodesc) ';
  wSql = wSql||' left outer join VW_VEF_BASE_TEMPPARGER ger on ger.bdcodemp = temp.bdcodemp ';
  wSql = wSql||' left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.bdcodemp = temp.bdcodemp ';

  IF (wtudo = 0) THEN
     BEGIN
       wSql = wSql||'inner join tgrupousuario tgrp on (tgrp.bdcodesc = temp.bdcodesc) ';
       wSql = wSql||'inner join tgrupousuario_usuario tusu on (tusu.bdcodusu = (select x.bdcodusu from SP_GET_USUARIO x) and tusu.bdcodgrupo = tgrp.bdcodgrupo) ';
     END

  wwhere = '';

/*  if (prcodemp is not null and prcodemp <> 0) then
     wwhere = wwhere || ' TEMP.bdcodemp = '||prcodemp;*/
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '0') AND (prcodemp <> '')) THEN
     BEGIN
       SELECT pos FROM pos('=', :prcodemp) INTO :wpos;

       IF (wPos = 0) THEN
          SELECT pos FROM pos(' in (', :prcodemp) INTO :wpos;

       IF (wPos = 0) THEN
          SELECT pos FROM pos(' between ', :prcodemp) INTO :wpos;

       IF (wPos = 0) THEN
          SELECT pos FROM pos(' is ', LOWER(:prcodemp)) INTO :wpos;

       IF (wpos > 0) THEN
          wwhere = wwhere||' ('||prcodemp||') ';
       ELSE
          wwhere = wwhere||' TEMP.bdcodemp = '||prcodemp;
     END

  /* filra empresas inativas */
  IF (prinativas IS NOT NULL AND prinativas <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'UPPER(tref.BDSITEMP) = '''||'FALSE''';
     END


  /*
  for select BDCODUSU from sp_get_usuario
  into
    :wcodusu
  do

   filtra as empresas por usuario
  if (wcodusu is not null and wcodusu <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TEMP.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     end   */

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TEMP.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODMATRIZ,
    :BDCNPJEMP,
    :BDDATAINIATIVEMP,
    :BDORGAOEMP,
    :BDDATAREGEMP,
    :BDDATACONSTEMP,
    :BDDESCCARTEMP,
    :BDDATAFIMATIVEMP,
    :BDFORMATRIBUTACAO,
    :BDNRTCE,
    :BDOMIE,
    :BDCODPLAPADRAO,
    :BDCODHIST,
    :BDCODCENTROS,
    :BDCODCID,
    :BDCODCONT,
    :BDCODNATJUR,
    :BDCODCNAE,
    :BDNOMEMP,
    :BDNOMREDUZEMP,
    :BDAPEEMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDFAXEMP,
    :BDEMAILEMP,
    :BDCOMPLEMP,
    :BDLOGREMP,
    :BDIEEMP,
    :BDIMEMP,
    :BDSITEMP,
    :BDDDDFAXEMP,
    :BDNOMCID,
    :BDCODUF,
    :BDNOMECONT,
    :BDSIGLAUF,
    :BDDESCUF,
    --:bdcnaeprep,
    :bdcodplanoonline,
    :bdcodenqfed,
    :bdpersonalizacao,
    :bdcodcontef,
    :BDLIVRO,
    :BDFOLHA,
    :BDNOMECARTORIO,
    :BDDATACADEMP,
    :BDTIPOAPURACAORET,
    :BDCODPLATRIB,
    :BDTRANMANUAL,
    :BDTIPOAPURACAORETIR,
    :bdcodesc,
    :BDCODPLAPADRAOREF,
    :BDCODIBGE,
    :BDSTATUS_ES,
    :BDABRIRRATEIO,
    :BDNAOPERMITERATEIOGRUPO,
    :BDINTEGRANET,
    :BDIGNORAREDISS,
    :BDDATAINIESOCIAL,
    :BDOPCAOESOCIAL,
    :BDDDDCELULAREMP,
    :BDCELULAREMP,
    :BDCODCLI,
    :BDDATAOBRIGREINF,
    :BDNOMFANEMP,
    :BDSTATUSEMP, 
    :BDQTDBACKUPEMP,
    :BDMATRIZNAOCADSIS,
    :BDSITUACAOESOCIAL,
    :BDCODGIARS,
    :BDINCORPORADORAS
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* empty dependent procedure body */
/* Clear: SP_COMMIT_UNIDADEMEDIDA for: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_COMMIT_UNIDADEMEDIDA(PRSESSAO INTEGER,
PRCODEMP INTEGER,
PRREF INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOC for: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_EXPORTA_BLOCOC(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRVALIDAREXPORTACAO /* DM_BOOLEAN */ VARCHAR(5),
PRARQUIVO VARCHAR(100))
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOD for: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_EXPORTA_BLOCOD(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRVALIDAREXPORTACAO /* DM_BOOLEAN */ VARCHAR(5),
PRARQUIVO VARCHAR(100))
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOE for: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_EXPORTA_BLOCOE(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRPERIODOAPUR INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_GERAR_INCON_TERCEIRO for: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_GERAR_INCON_TERCEIRO(PRSESSAO INTEGER,
PRREF INTEGER,
PRCODEMP INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_GERAR_PARCELAS_AUT for: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_GERAR_PARCELAS_AUT(PRSESSAO INTEGER,
PRTIPOMOV VARCHAR(3),
PRCODEMP INTEGER,
PRREF INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_GET_ACOES_INCONSISTENCIA for: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_GET_ACOES_INCONSISTENCIA(PRCODEMP INTEGER,
PRREF INTEGER)
 RETURNS(BDCODPLANOINCONS INTEGER,
BDNCMPROD INTEGER,
BDSAICFOPNCAD INTEGER,
BDENTCFOPCANC INTEGER,
BDCODUNIMED INTEGER,
BDENTCFOPNCAD INTEGER,
BDSAICFOPCANC INTEGER,
BDDESCRICAO VARCHAR(100),
BDPLANODEFAULT /* DM_BOOLEAN */ VARCHAR(5),
BDATUPROD /* DM_BOOLEAN */ VARCHAR(5),
BDATUPART /* DM_BOOLEAN */ VARCHAR(5),
BDATUUNIDMED /* DM_BOOLEAN */ VARCHAR(5),
BDATUINFCOM /* DM_BOOLEAN */ VARCHAR(5),
BDATUOBS /* DM_BOOLEAN */ VARCHAR(5),
BDATUMAQREDZ /* DM_BOOLEAN */ VARCHAR(5),
BDATUBICO /* DM_BOOLEAN */ VARCHAR(5),
BDATUBOMBA /* DM_BOOLEAN */ VARCHAR(5),
BDATUTANQUE /* DM_BOOLEAN */ VARCHAR(5),
BDATUFATCONV /* DM_BOOLEAN */ VARCHAR(5),
BDPARTIEISE /* DM_BOOLEAN */ VARCHAR(5),
BDCADPROAUTO /* DM_BOOLEAN */ VARCHAR(5),
BDENTAJUCFOP /* DM_BOOLEAN */ VARCHAR(5),
BDENTIMPIPIDIF /* DM_BOOLEAN */ VARCHAR(5),
BDENTIMPICMSDIF /* DM_BOOLEAN */ VARCHAR(5),
BDSAIAJUCFOP /* DM_BOOLEAN */ VARCHAR(5),
BDSAIIMPIPIDIF /* DM_BOOLEAN */ VARCHAR(5),
BDSAIIMPICMSDIF /* DM_BOOLEAN */ VARCHAR(5),
BDSERAJUCFOP /* DM_BOOLEAN */ VARCHAR(5),
BDSERIMPISSDIF /* DM_BOOLEAN */ VARCHAR(5),
BDPARTBUSCASITE /* DM_BOOLEAN */ VARCHAR(5),
BDPRODNCMVAZIO /* DM_BOOLEAN */ VARCHAR(5),
BDREDZCODTER INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_INSERT_OR_UPDATE_TTERCEIRO for: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_INSERT_OR_UPDATE_TTERCEIRO(PRSESSAO INTEGER,
PRREFEMP INTEGER,
PRCODEMP INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_CONSULTAEMPRESAS_SIS) */
ALTER PROCEDURE SP_CONSULTAEMPRESAS_SIS(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDDATAINIATIVEMP DATE,
BDORGAOEMP VARCHAR(8),
BDDATAREGEMP DATE,
BDDATACONSTEMP DATE,
BDDESCCARTEMP VARCHAR(40),
BDDATAFIMATIVEMP DATE,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCODCENTROS INTEGER,
BDCODCID INTEGER,
BDCODCONT INTEGER,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDNOMREDUZEMP DM_BDNOMREDUZEMP,
BDAPEEMP DM_BDAPEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDFAXEMP DM_BDTELEFONE,
BDDDDCELULAREMP INTEGER,
BDCELULAREMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDLOGREMP VARCHAR(15),
BDIEEMP VARCHAR(20),
BDIMEMP VARCHAR(20),
BDSITEMP VARCHAR(5),
BDDDDFAXEMP INTEGER,
BDNOMCID VARCHAR(40),
BDCODUF INTEGER,
BDNOMECONT VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCUF VARCHAR(40),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODCONFATIVO INTEGER,
BDSUFRAMA VARCHAR(9),
BDCODACESSOSN VARCHAR(12),
BDPERFILSPED INTEGER,
BDATIVIDADESPED INTEGER,
BDCODCONFIPI INTEGER,
BDCODCONFIRLP INTEGER,
BDCODCONFDIMESC INTEGER,
BDCODPORTEEMP INTEGER,
BDCODAPUCON INTEGER,
BDCODESCCONT INTEGER,
BDCODREGAPU INTEGER,
BDCONTPRODEC VARCHAR(5),
BDNRPARPRODEC INTEGER,
BDLANBCICMSVALCONT VARCHAR(5),
BDLANBCICMSISEOUT INTEGER,
BDLANCLISAISER VARCHAR(5),
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDMOVSER VARCHAR(5),
BDPERCISS NUMERIC(15,6),
BDREDPERCISS NUMERIC(15,6),
BDMOVIRRF VARCHAR(5),
BDALIQIRRF NUMERIC(15,6),
BDISENTOIRRF NUMERIC(15,6),
BDEMPINATIVA VARCHAR(5),
BDEMPDIFPAPEL VARCHAR(5),
BDEMPBARREST VARCHAR(5),
BDVERIFICARNOTASJALAN INTEGER,
BDCODPLANOONLINE INTEGER,
BDLRISSSN NUMERIC(15,6),
BDCOMERCIO VARCHAR(5),
BDINDUSTRIA VARCHAR(5),
BDSERVICO VARCHAR(5),
BDANEXOIII VARCHAR(5),
BDANEXOIV VARCHAR(5),
BDANEXOV VARCHAR(5),
BDCODENQFED INTEGER,
BDSUBSTRIB INTEGER,
BDCODCONFDACON INTEGER,
BDCODCONFICMSSPED INTEGER,
BDCODCONFCIAP INTEGER,
BDREDBCICMSENT NUMERIC(15,6),
BDREDBCICMSSAI NUMERIC(15,6),
BDCODCONFDASN INTEGER,
BDRETPARPIS VARCHAR(5),
BDRETPARCOFINS VARCHAR(5),
BDRETPARCSLL VARCHAR(5),
BDRETPARIRRF VARCHAR(5),
BDRETPARISSQN VARCHAR(5),
BDRETPARINSS VARCHAR(5),
BDRETPARFUNRURAL VARCHAR(5),
BDTIPOAPURACAO INTEGER,
BDSOMFREBASEICMS VARCHAR(5),
BDSOMFREVLRCONTAB VARCHAR(5),
BDCODPLATROCA INTEGER,
BDCODPLACFOP INTEGER,
BDCODCONFBLOCOP INTEGER,
BDCREDPRESUMIDO VARCHAR(5),
BDTERMOACEITE VARCHAR(5),
BDANTECIPAIMPOSTO VARCHAR(5),
BDTIPODECLARANTEDMED INTEGER,
BDREGISTROANSDMED INTEGER,
BDNUMEROCNESDMED INTEGER,
BDDTOBRIGSPEDCONT DATE,
BDTIPOAPURACAORET INTEGER,
BDTIPOAPURACAORETIR INTEGER,
BDDTOBRIGSPEDICMS DATE,
BDCODCONTEF INTEGER,
BDLIVRO VARCHAR(15),
BDFOLHA VARCHAR(15),
BDNOMECARTORIO VARCHAR(100),
BDLANCAPARCELAAUTO VARCHAR(5),
BDCODIGOPLA INTEGER,
BDINDATIV INTEGER,
BDTRANMANUAL VARCHAR(5),
BDIMPORTARVALORESICMSSN DM_BOOLEAN,
BDDIFALIQ VARCHAR(5),
BDDIFALIQBASEEM INTEGER,
BDANEXOVI DM_BOOLEAN,
BDCODPLATRIB INTEGER,
BDCODPLAPADRAOREF INTEGER,
BDINDNATPJ INTEGER,
BDCODIBGE INTEGER,
BDFORMATRIBUTACAO INTEGER,
BDSOMAPISCOFVLRCONT DM_BOOLEAN,
BDSOMAIIVLRCONT DM_BOOLEAN,
BDMANTERPARCELAS DM_BOOLEAN,
BDCODPLANOINCONS INTEGER,
BDABRIRRATEIO DM_BOOLEAN,
BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
BDINTEGRANET DM_BOOLEAN,
BDSOMAIPIPROD DM_BOOLEAN,
BDSOMAICMSVLRCONT DM_BOOLEAN,
BDCODPLAE115 INTEGER,
BDDATACADEMP DATE,
BDCODCLATRI INTEGER,
BDDATAOBRIGREINF DATE,
BDSOMASTPROD DM_BOOLEAN,
BDCALCANTICMS VARCHAR(5),
BDCONSIPIBC VARCHAR(5),
BDIMPICMSST VARCHAR(5),
BDANEXOIII_2018 VARCHAR(5),
BDANEXOIV_2018 VARCHAR(5),
BDANEXOV_2018 VARCHAR(5),
BDSTATUSEMP INTEGER,
BDQTDBACKUPEMP INTEGER,
BDIMPORTARISS VARCHAR(5),
BDINCORPORADORAS DM_BOOLEAN)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);
    wSql = ' select ';
    wSql = wsql || 'Tref.BDCODEMP, ';
    wSql = wsql || 'tref.BDCODMATRIZ, ';
    wSql = wsql || 'tref.BDCNPJEMP, ';
    wSql = wsql || 'tref.BDDATAINIATIVEMP, ';
    wSql = wsql || 'tref.BDORGAOEMP, ';
    wSql = wsql || 'tref.BDDATAREGEMP, ';
    wSql = wsql || 'tref.BDDATACONSTEMP, ';  --alt:14844 - Adicionado campo BDDATACONSTEMP na consulta. Ana - 05/08/2016
    wSql = wsql || 'tref.BDDESCCARTEMP, ';
    wSql = wsql || 'tref.BDDATAFIMATIVEMP, ';
    wSql = wsql || 'tref.BDCODPLAPADRAO, ';
    wSql = wsql || 'tref.BDCODHIST, ';
    wSql = wsql || 'tref.BDCODCENTROS, ';
    wSql = wsql || 'tref.BDCODCID, ';
    wSql = wsql || 'tref.BDCODCONT, ';
    wSql = wsql || 'tref.BDCODNATJUR, ';
    wSql = wsql || 'tref.BDCODCNAE, ';
    wSql = wsql || 'tref.BDNOMEMP, ';
    wSql = wsql || 'tref.BDNOMREDUZEMP, ';
    wSql = wsql || 'tref.BDAPEEMP, ';
    wSql = wsql || 'tref.BDENDEMP, ';
    wSql = wsql || 'tref.BDNUMEMP, ';
    wSql = wsql || 'tref.BDBAIEMP, ';
    wSql = wsql || 'tref.BDCEPEMP, ';
    wSql = wsql || 'tref.BDDDDEMP, ';
    wSql = wsql || 'tref.BDFONEEMP, ';
    wSql = wsql || 'tref.BDFAXEMP, ';
    wSql = wsql || 'tref.BDDDDCELULAREMP, ';
    wSql = wsql || 'tref.BDCELULAREMP, ';
    wSql = wsql || 'tref.BDEMAILEMP, ';
    wSql = wsql || 'tref.BDCOMPLEMP, ';
    wSql = wsql || 'tref.BDLOGREMP, ';
    wSql = wsql || 'tref.BDIEEMP, ';
    wSql = wsql || 'tref.BDIMEMP, ';
    wSql = wsql || 'tref.BDSITEMP, ';
    wSql = wsql || 'tref.BDDDDFAXEMP, ';
    wSql = wsql || 'Tref.BDNOMCID, ';
    wSql = wsql || 'Tref.BDCODUF, ';
    wSql = wsql || 'Tref.BDNOMECONT, ';
    wSql = wsql || 'tref.BDSIGLAUF, ';
    wSql = wsql || 'tref.BDDESCUF, ';
    wSql = wsql || 'tref.BDTRANMANUAL, ';
    wSQL = wsql || 'tref.BDDATACADEMP, ';

    wSql = wsql || 'trefsis.bdretinss, ';
    wSql = wsql || 'trefsis.bdvlrmininss, ';
    wSql = wsql || 'trefsis.bdSUFRAMA, ';
    wSql = wsql || 'trefsis.bdcodacessosn, ';
    wSql = wsql || 'trefsis.bdperfilsped, ';
    wSql = wsql || 'trefsis.bdatividadesped, ';
    wSql = wsql || 'trefsis.BDCODCONFIPI, ';
    wSql = wsql || 'trefsis.BDCODCONFIRLP, ';
    wSql = wsql || 'trefsis.BDCODCONFDIMESC, ';
    wSql = wsql || 'trefsis.BDCODPORTEEMP, ';
    wSql = wsql || 'trefsis.BDCODAPUCON, ';
    wSql = wsql || 'trefsis.BDCODESCCONT, ';
    wSql = wsql || 'trefsis.BDCODREGAPU, ';
    wSql = wsql || 'trefsis.BDCONTPRODEC, ';
    wSql = wsql || 'trefsis.BDNRPARPRODEC, ';
    --wSql = wsql || 'trefsis.BDDIAVCTOEMPSC, ';
    wSql = wsql || 'trefsis.BDCODCONFATIVO, ';
    --harry 17-02-2011
    wSql = wsql || 'trefsis.BDLANBCICMSVALCONT, ';
    wSql = wsql || 'trefsis.BDLANBCICMSISEOUT, ';
    wSql = wsql || 'trefsis.BDLANCLISAISER, ';
    wSql = wsql || 'trefsis.BDLANPROENT, ';
    wSql = wsql || 'trefsis.BDLANPROSAI, ';
    wSql = wsql || 'trefsis.BDMOVSER, ';
    wSql = wsql || 'trefsis.BDPERCISS, ';
    wSql = wsql || 'trefsis.BDREDPERCISS, ';
    wSql = wsql || 'trefsis.BDMOVIRRF, ';
    wSql = wsql || 'trefsis.BDALIQIRRF, ';
    wSql = wsql || 'trefsis.BDISENTOIRRF, ';
    wSql = wsql || 'trefsis.BDEMPINATIVA, ';
    wSql = wsql || 'trefsis.BDEMPDIFPAPEL, ';
    wSql = wsql || 'trefsis.BDEMPBARREST, ';
    wSql = wsql || 'trefsis.BDVERIFICARNOTASJALAN, ';

    wSql = wsql || 'tref.bdcodplanoonline, ';

    wSql = wsql || 'trefsis.bdlrisssn, ';
    wSql = wsql || 'trefsis.bdcomercio, ';
    wSql = wsql || 'trefsis.bdindustria, ';
    wSql = wsql || 'trefsis.bdservico, ';
    wSql = wsql || 'trefsis.bdanexoiii, ';
    wSql = wsql || 'trefsis.bdanexoiv, ';
    wSql = wsql || 'trefsis.bdanexov, ';
    wSql = wsql || 'enq.BDCODENQFED, ';
    wSql = wsql || 'case when (not (enq.BDFORMATRIBUTACAO is null)) then enq.BDFORMATRIBUTACAO else tref.BDFORMATRIBUTACAO end, ';
    wSql = wsql || 'TREFSIS.BDSUBSTRIB, ';
    wSql = wsql || 'TREFSIS.bdcodconfdacon, ';
    wSql = wsql || 'TREFSIS.bdcodconficmssped, ';
    wSql = wsql || 'TREFSIS.BDCODCONFCIAP, ';
    wSql = wsql || 'TREFSIS.BDREDBCICMSENT, ';
    wSql = wsql || 'TREFSIS.BDREDBCICMSSAI, ';
    wSql = wsql || 'TREFSIS.BDCODCONFDASN, ';

    wSql = wsql || 'TREFSIS.BDRETPARPIS, ';
    wSql = wsql || 'TREFSIS.BDRETPARCOFINS, ';
    wSql = wsql || 'TREFSIS.BDRETPARCSLL, ';
    wSql = wsql || 'TREFSIS.BDRETPARIRRF, ';
    wSql = wsql || 'TREFSIS.BDRETPARISSQN, ';
    wSql = wsql || 'TREFSIS.BDRETPARINSS, ';
    wSql = wsql || 'TREFSIS.BDRETPARFUNRURAL, ';
    wSql = wsql || 'TREFSIS.bdtipoapuracao, ';
    wSql = wsql || 'TREFSIS.BDSOMFREVLRCONTAB, ';
    wSql = wsql || 'TREFSIS.BDSOMFREBASEICMS, ';
    wSql = wsql || 'TREFSIS.BDCODPLATROCA, ';
    wSql = wsql || 'TREFSIS.bdcodplacfop, ';
    wSql = wsql || 'TREFSIS.bdcodconfblocop, ';
    wSql = wSql || 'TREFSIS.bdcredpresumido, ';
    wSql = wSql || 'TREFSIS.bdTERMOACEITE, '; --#Alt:84445 (04/06/2018) Patr?cio H. Lehn
    wSql = wSql || 'TREFSIS.bdantecipaimposto, ';
    wSql = wsql || 'TREFSIS.BDTIPODECLARANTEDMED, ';
    wSql = wsql || 'TREFSIS.BDREGISTROANSDMED, ';
    wSql = wsql || 'TREFSIS.BDNUMEROCNESDMED, ';
    wSql = wsql || 'TREFSIS.BDDTOBRIGSPEDCONT, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORET, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORETIR, ';
    wSql = wSql || 'TREFSIS.BDDTOBRIGSPEDICMS, ';
    wsql = wsql || 'TREF.BDCODCONTEF, ';
    wsql = wsql || 'TREF.BDLIVRO, ';
    wsql = wsql || 'TREF.BDFOLHA, ';
    wsql = wsql || 'TREF.BDNOMECARTORIO, ';
    wsql = wsql || 'TREFSIS.BDLANCAPARCELAAUTO, ';
    wsql = wsql || 'TREFSIS.BDCODIGOPLA, ';
    wSql = wsql || 'TREFSIS.BDINDATIV, ';
    wSql = wSql || 'parinteg.BDIMPORTARVALORESICMSSN, ';
    wSql = wSql || 'parinteg.BDDIFALIQ, ';
    wSql = wSql || 'parinteg.BDDIFALIQBASEEM, ';
    wSql = wSql || 'TREFSIS.BDANEXOVI, ';
    wsql = wsql || 'tref.bdcodplatrib, ';
    wSQL = wSQL || 'TREF.BDCODPLAPADRAOREF, '; --alt:11108 - Adicionado novo campo na tabela e na SP. Pedro
    wSql = wsql || 'TREFSIS.BDINDNATPJ, ';
    wSql = wsql || 'TREF.BDCODIBGE, '; --Sol: 11334 Patrick T. S? 03/07/2015. Traz o c?digo do IBGE para verificar o tipo de ISS da empresa
     /*
      Sol: 11439 Patrick T. S? 03/07/2015. Retorna campos para verificar
      se ? para somar ou n?o o imposto de importa??o(II). Parametros incluidos no cadastro de empresas.
    */
    wSql = wSql || 'parinteg.BDSOMAPISCOFVLRCONT, ';
    wSql = wSql || 'parinteg.BDSOMAIIVLRCONT, ';
    wsql = wsql || 'TREFSIS.BDMANTERPARCELAS, ';
    wsql = wsql || 'TREFSIS.BDCODPLANOINCONS, ';
    wSQL = wSQL || 'tref.BDABRIRRATEIO, '; --alt:13677 - 15/03/2016 - Adicionados par?metros. Pedro
    wSQL = wSQL || 'tref.BDNAOPERMITERATEIOGRUPO, '; --alt:13677 - 15/03/2016 - Adicionados par?metros. Pedro
    wSQL = wSQL || 'tref.BDINTEGRANET, '; --alt:14035 - Adicionado par?metro para o IntegraNet. Everton
    wSQL = wSQL || 'parinteg.BDSOMAIPIPROD, ';
    wSql = wSql || 'parinteg.BDSOMAICMSVLRCONT, ';
    wSql = wSql || 'parinteg.BDCODPLAE115, ';
    wSql = wSql || 'tesocial.BDCODCLATRI, ';
    wSql = wSql || 'tref.BDDATAOBRIGREINF, ';
    wSQL = wSQL || 'parinteg.BDSOMASTPROD, ';
    wSql = wSql || 'parinteg.BDCALCANTICMS, ';
    wSql = wSql || 'parinteg.BDCONSIPIBC, ';
    WSQL = WSQL || 'parinteg.BDIMPICMSST, ';
    wSql = wsql || 'trefsis.bdanexoiii_2018, ';
    wSql = wsql || 'trefsis.bdanexoiv_2018, ';
    wSql = wsql || 'trefsis.bdanexov_2018, ';
    wSQL = wsql || 'tref.BDSTATUSEMP, ';   --#Alt:16965 - Carlos Mello (06/10/2017)
    wSQL = wsql || 'tref.BDQTDBACKUPEMP, '; --#Alt:16965 - Carlos Mello (06/10/2017)
    wSql = wSql || 'parinteg.BDIMPORTARISS, ';
    wSql = wsql || 'tref.BDINCORPORADORAS ';
/*
       parger.BDLANBCICMSVALCONT,
       parger.BDLANBCICMSISEOUT,
       parger.BDLANCLISAISER,
       parger.BDLANPROENT,
       parger.BDLANPROSAI,
       parger.BDMOVSER,
       parger.BDPERCISS,
       parger.BDREDPERCISS,
       parger.BDMOVIRRF,
       parger.BDALIQIRRF,
       parger.BDISENTOIRRF,
       parger.BDEMPINATIVA,
       parger.BDEMPDIFPAPEL,
       parger.BDEMPBARREST,
       parger.BDVERIFICARNOTASJALAN
*/

  WPAR = 'from sp_consultaempresas('||prrefmicro;
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wpar = wpar||','||prcodemp||',';
  ELSE
    wpar = wpar||',null,';

  IF (prinativas IS NULL) THEN
    wpar = wpar||'0) tref';
  ELSE
    wpar = wpar||prinativas||') tref';

--  if (prinativas is null) then
--     wSql = wsql || ' from sp_consultaempresas('||prrefmicro||','||PRCODEMP||',0) tref';
--  else
--     wSql = wsql || ' from sp_consultaempresas('||prrefmicro||','||PRCODEMP||','||PRINATIVAS||') tref';

    wSql = wsql || wpar;

    wSql = wsql || ' left outer join vw_emp_ref_TOTAL TREFSIS on (TREFSIS.bdcodemp = tref.bdcodemp) ';
    wSql = wsql || ' left outer join VW_TENQFED Enq  on (Enq.bdcodemp = tref.bdcodemp) ';
    wSql = wSql || ' left outer join VW_VEF_BASE_TEMPPARINTEG parinteg on ( parinteg.bdCodEmp = tref.bdCodEmp ) and ( parinteg.bdRefEmp = trefsis.bdRefEmp ) ';
    wSql = wSql || ' left outer join VW_VRHF_BASE_TEMPESOCIAL tesocial on ( tesocial.bdcodemp = tref.bdcodemp) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' tref.bdcodemp = '||prcodemp;

  /* filra empresas inativas */
  IF (prinativas IS NOT NULL AND prinativas <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'UPPER(tref.BDSITEMP) = '''||'FALSE''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By tref.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODMATRIZ,
    :BDCNPJEMP,
    :BDDATAINIATIVEMP,
    :BDORGAOEMP,
    :BDDATAREGEMP,
    :BDDATACONSTEMP, --alt:14844 - Novo campo no cadastro de empresa. Ana - 05/08/2016
    :BDDESCCARTEMP,
    :BDDATAFIMATIVEMP,
    :BDCODPLAPADRAO,
    :BDCODHIST,
    :BDCODCENTROS,
    :BDCODCID,
    :BDCODCONT,
    :BDCODNATJUR,
    :BDCODCNAE,
    :BDNOMEMP,
    :BDNOMREDUZEMP,
    :BDAPEEMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDFAXEMP,
    :bddddcelularemp,
    :bdcelularemp,
    :BDEMAILEMP,
    :BDCOMPLEMP,
    :BDLOGREMP,
    :BDIEEMP,
    :BDIMEMP,
    :BDSITEMP,
    :BDDDDFAXEMP,
    :BDNOMCID,
    :BDCODUF,
    :BDNOMECONT,
    :BDSIGLAUF,
    :BDDESCUF,
    :BDTRANMANUAL,
    :BDDATACADEMP, 

    :bdretinss,
    :bdvlrmininss,
    :BDSUFRAMA,
    :bdcodacessosn,
    :bdperfilsped,
    :bdatividadesped,

    :BDCODCONFIPI,
    :BDCODCONFIRLP,
    :BDCODCONFDIMESC,
    :BDCODPORTEEMP,
    :BDCODAPUCON,
    :BDCODESCCONT ,
    :BDCODREGAPU ,
    :BDCONTPRODEC ,
    :BDNRPARPRODEC ,
    --:BDDIAVCTOEMPSC,
    :BDCODCONFATIVO,

    --harry 17-02-2011
    :bdlanbcicmsvalcont,
    :bdlanbcicmsiseout,
    :bdlanclisaiser,
    :bdlanproent,
    :bdlanprosai,
    :bdmovser,
    :bdperciss,
    :bdredperciss,
    :bdmovirrf,
    :bdaliqirrf ,
    :bdisentoirrf,
    :bdempinativa ,
    :bdempdifpapel,
    :bdempbarrest,
    :bdverificarnotasjalan,
    :bdcodplanoonline,
    :bdlrisssn,
    :bdcomercio,
    :bdindustria,
    :bdservico,
    :bdanexoiii,
    :bdanexoiv,
    :bdanexov,
    :BDCODENQFED,
    :BDFORMATRIBUTACAO,
    :BDSUBSTRIB,
    :bdcodconfdacon,
    :bdcodconficmssped,
    :BDCODCONFCIAP,
    :BDREDBCICMSENT,
    :BDREDBCICMSSAI,
    :BDCODCONFDASN,

    :BDRETPARPIS,
    :BDRETPARCOFINS,
    :BDRETPARCSLL,
    :BDRETPARIRRF,
    :BDRETPARISSQN,
    :BDRETPARINSS,
    :BDRETPARFUNRURAL,
    :bdtipoapuracao,
    :bdsomfrevlrcontab,
    :bdsomfrebaseicms,
    :bdcodplatroca,
    :bdcodplacfop,
    :bdcodconfblocop,
    :bdcredpresumido,
    :bdtermoaceite,
    :bdantecipaimposto,
    :BDTIPODECLARANTEDMED,
    :BDREGISTROANSDMED,
    :BDNUMEROCNESDMED,
    :BDDTOBRIGSPEDCONT,
    :BDTIPOAPURACAORET,
    :BDTIPOAPURACAORETIR,
    :BDDTOBRIGSPEDICMS,
    :BDCODCONTEF,
    :BDLIVRO,
    :BDFOLHA,
    :BDNOMECARTORIO,
    :BDLANCAPARCELAAUTO,
    :BDCODIGOPLA,
    :BDINDATIV,
    :BDIMPORTARVALORESICMSSN,
    :BDDIFALIQ,
    :BDDIFALIQBASEEM,
    :BDANEXOVI,
    :BDCODPLATRIB,
    :BDCODPLAPADRAOREF,
    :BDINDNATPJ,
    :BDCODIBGE,
    :BDSOMAPISCOFVLRCONT,
    :BDSOMAIIVLRCONT,
    :BDMANTERPARCELAS,
    :bdcodplanoincons,
    :BDABRIRRATEIO,
    :BDNAOPERMITERATEIOGRUPO,
    :BDINTEGRANET,
    :BDSOMAIPIPROD,
    :BDSOMAICMSVLRCONT,
    :BDCODPLAE115,
    :BDCODCLATRI,
    :BDDATAOBRIGREINF,
    :BDSOMASTPROD,
    :BDCALCANTICMS,
    :BDCONSIPIBC,
    :BDIMPICMSST,
    :BDANEXOIII_2018,
    :BDANEXOIV_2018,
    :BDANEXOV_2018,
    :BDSTATUSEMP,
    :BDQTDBACKUPEMP,
    :BDIMPORTARISS,
    :BDINCORPORADORAS
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONTABILIZAR_LANCAMENTO) */
ALTER PROCEDURE SP_CONTABILIZAR_LANCAMENTO(PRSESSAO INTEGER,
PRULTCHAVE INTEGER,
PRUSUARIO INTEGER,
PRTIPLAN VARCHAR(4),
PRTRANSACAO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(250);
BEGIN
  /*Sol : 14207 Patrick T. S? 09/06/2016. Criada contabiliza??o no banco.*/

  /*Insere os registros no cont?bil*/
  IF (TRIM(:PRTIPLAN) = 'SAI') THEN
    BEGIN
      /*Cria o gerador para o sequencial. Por Exemplo: Chave 1 tem valor cont?bil e icms, ent?o h? 2 registros com chave 1 na tabela TMP_TLANC_CONTABILIZACAO_TEMP, por?m s?o 2 chaves para o
      cont?bil, se fizer bdchave(1) - bdchave_vsuc(8) = 8(faz na trigger da tabela), chaves duplicadas, com o gerador isso n?o acontece, ? criado e destruido um gerador para cada sess?o(terminal)*/

      wSql = 'CREATE SEQUENCE GEN_ICMS115_'||:PRSESSAO;
      EXECUTE STATEMENT wSql;

      wSql =         'UPDATE TMP_TLANC_CONTABILIZACAO_TEMP I SET I.BDCHAVE_VSUC = '||:PRULTCHAVE||', ';
      wSql = wSql || 'I.BDTRANSACAO = '||:PRTRANSACAO||', ';
      wSql = wSql || 'I.BDSEQ = GEN_ID(GEN_ICMS115_'||:PRSESSAO||', 1) ';
      wSql = wSql || 'WHERE BDSESSAO = '||:PRSESSAO;
      wSql = wSql || 'ORDER BY BDSESSAO, BDCODEMP, BDCHAVE, BDORD DESC';

      EXECUTE STATEMENT wSql;

      wSql = 'DROP SEQUENCE GEN_ICMS115_'||:PRSESSAO;
      EXECUTE STATEMENT wSql;

      /*Reten??o de pis, cofins, contribui??o social, ir e inss */
      INSERT INTO VSUC_EMPRESAS_TLAN(BDCODEMP, BDCHAVE, BDCODPLAPADRAO, BDCODUSU, BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO, BDTRANSACAO, BDTRANFECHADA, BDCODTPHI)
      SELECT C.BDCODEMP, C.BDCHAVE_VSUC, C.BDCODPLAPADRAO, :PRUSUARIO, C.BDDEBITO, C.BDCREDITO, C.BDCOMPL, C.BDDATA, C.BDVALOR, C.BDTIPOLAN, C.BDDCTO, C.BDTRANSACAO, C.BDTRANFECHADA, C.BDCODTPHI
      FROM TMP_TLANC_CONTABILIZACAO_TEMP C
      JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDCHAVE)
      WHERE C.BDSESSAO = :PRSESSAO
      --AND ((S.BDCHAVE IS NOT NULL) or (S.BDCHAVE > 0))
      ORDER BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORD;

      /*Insert na tol */
      INSERT INTO TOL_VEF_EMP_TMOVSAI(BDCHAVE, BDCODEMP, BDCHAVESAI, BDORDEM, BDFORMULA)
      SELECT C.BDCHAVE_VSUC, C.BDCODEMP, C.BDCHAVE, C.BDORDEM, C.BDFORMULA
      FROM TMP_TLANC_CONTABILIZACAO_TEMP C
      JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDCHAVE)
      WHERE C.BDSESSAO = :PRSESSAO
      --AND ((S.BDCHAVE IS NOT NULL) or (S.BDCHAVE > 0))
      ORDER BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORD;

      /*Insert na TOL_UPDATE_CONTA */
      INSERT INTO TOL_UPDATE_CONTA(bdcodplanoonline, bdchave, bdcodemp, bdchavelan, bdchavetitulo, bdtipolan, bdclassifbusca, bdclassiftitulo)
      SELECT C.BDCODPLANOONLINE, C.BDCHAVECONTA, C.BDCODEMP, C.BDCHAVE_VSUC, C.BDCHAVETITULO, C.BDTIPOLAN, C.BDCLASSIFBUSCA, C.BDCLASSIFTITULO
      FROM TMP_TLANC_CONTABILIZACAO_TEMP C
      JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDCHAVE)
      WHERE C.BDSESSAO = :PRSESSAO
      --AND ((S.BDCHAVE IS NOT NULL) or (S.BDCHAVE > 0))
      ORDER BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORD;

      /*Apaga as contabiliza??es que j? foram gravadas da tabela tempor?ria */
      DELETE FROM TMP_TLANC_CONTABILIZACAO_TEMP C
      WHERE C.BDSESSAO = :PRSESSAO
      AND EXISTS(
                 SELECT TOL.BDCHAVE
                 FROM TOL_VEF_EMP_TMOVSAI TOL
                 WHERE TOL.BDCODEMP = C.BDCODEMP
                 AND TOL.BDCHAVE = C.BDCHAVE_VSUC
                 AND TOL.BDCHAVESAI = C.BDCHAVE
                 AND TOL.BDORDEM = C.BDORDEM
                );

    END

END
^

/* Alter (SP_COPIA_ACOES_PLANOTROCA) */
ALTER PROCEDURE SP_COPIA_ACOES_PLANOTROCA(PRCODPLANOTROCA INTEGER,
PRTIPOLANDE INTEGER,
PRTIPOLANPARA INTEGER)
 AS
DECLARE VARIABLE WCODTPIMP INTEGER;
DECLARE VARIABLE WDESC VARCHAR(5);
DECLARE VARIABLE WBASEISS VARCHAR(5);
DECLARE VARIABLE WREDBC VARCHAR(5);
DECLARE VARIABLE WST VARCHAR(5);
DECLARE VARIABLE WIPI VARCHAR(5);
DECLARE VARIABLE WFRETE VARCHAR(5);
DECLARE VARIABLE WDESPACE VARCHAR(5);
DECLARE VARIABLE WNFPROD VARCHAR(5);
DECLARE VARIABLE WCHAVETPIMP INTEGER;
DECLARE VARIABLE WCHAVEANT INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WSQL VARCHAR(10000);
BEGIN

  WSQL = ' INSERT INTO VEF_BASE_TPLANOACOESTROCA ';
  WSQL = WSQL||' (BDCODPLATROCA, BDCHAVE,  BDCODCSTPISENTFIL, BDNCMPROD, BDCODCSTICMSENTFIL, BDCODCSTCOFENTFIL, ';
  WSQL = WSQL||' BDCODCSTIPIENTFIL, BDCODCSTPISSAIFIL, BDCODCSTIPISAIFIL, BDCODCSTCOFSAIFIL, BDCODTER, BDCODCSTCOFENTACAO, ';
  WSQL = WSQL||' BDCODCSTICMSSAIFIL, BDCODCSTICMSENTACAO, BDCODNATBCCOFACAO, BDCODNATRECCOFACAO, BDCODCSTCOFSAIACAO, ';
  WSQL = WSQL||' BDCODCSTIPIENTACAO, BDCODCSTPISENTACAO, BDCODCSTPISSAIACAO, BDCODCSTIPISAIACAO, BDCODNATBCPISACAO, ';
  WSQL = WSQL||' BDCODNATRECPISACAO, BDCODPROD, BDCODNAT, BDCODCSTICMSSAIACAO, BDTIPOLAN, BDMODELO, BDESPECIE, ';
  WSQL = WSQL||' BDSERIE, BDQTDFILTRO, BDAPLICAACOES, BDZERARVLR, BDCSTICMSACAO, BDCSTIPIACAO, BDCSTPISACAO, BDCSTCOFINSACAO, ';
  WSQL = WSQL||' BDALIQICMSACAO, BDALIQICMSSTACAO, BDALIQIPIACAO, BDALIQPISACAO, BDALIQCOFINSACAO, BDALIQICMS, BDALIQICMSST, ';
  WSQL = WSQL||' BDALIQPIS, BDALIQIPI, BDALIQCOFINS, BDVALORICMSACAO, BDVALORICMSSTACAO, BDVALORPISACAO, BDVALORIPIACAO, ';
  WSQL = WSQL||' BDVALORCOFINSACAO, BDLANCAREMICMSACAO, BDNATCREPISACAO, BDNATCRECOFINSACAO, BDNATRECPISACAO, BDNATRECCOFINSACAO, ';
  WSQL = WSQL||' BDBCICMSACAO, BDBCICMSSTACAO, BDBCIPIACAO, BDBCPISACAO, BDBCCOFINSACAO, BDCODNATLANCACAO, BDSERIELANCACAO, ';
  WSQL = WSQL||' BDORDEMFRETELANCACAO, BDALIQICMSFIL, BDBCICMSC197ACAO, BDALIQICMSC197ACAO, BDVALORICMSC197ACAO, BDALIQICMSC197, ';
  WSQL = WSQL||' BDCODOBSC195, BDCODAJUC197, BDBCRETPISACAO, BDBCRETCOFINSACAO, BDBCRETCSLLACAO, BDBCRETIRRFACAO, BDBCRETINSSACAO, ';
  WSQL = WSQL||' BDALIQRETPISACAO, BDALIQRETCOFINSACAO, BDALIQRETCSLLACAO, BDALIQRETIRRFACAO, BDALIQRETINSSACAO, BDALIQRETPIS, ';
  WSQL = WSQL||' BDALIQRETCOFINS, BDALIQRETCSLL, BDALIQRETIRRF, BDALIQRETINSS, BDVALORRETPISACAO, BDVALORRETCOFINSACAO, ';
  WSQL = WSQL||' BDVALORRETCSLLACAO, BDVALORRETIRRFACAO, BDVALORRETINSSACAO, BDCODRECRETPISACAO, BDCODRECRETPIS, ';
  WSQL = WSQL||' BDCODRECRETCOFINSACAO, BDCODRECRETCOFINS, BDCODRECRETCSLLACAO, BDCODRECRETCSLL, BDCODRECRETIRRFACAO, ';
  WSQL = WSQL||' BDCODRECRETIRRF, BDCODRECRETINSSACAO, BDCODRECRETINSS, BDVLRIGUALA, BDVLRMENORQUE, BDVLRMAIORQUE,BDCODNATFLANCACAO) ';

  WSQL = WSQL||' SELECT BDCODPLATROCA, (SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = '||prcodplanotroca||') AS BDCHAVE, ';
  WSQL = wSQL||'        BDCODCSTPISENTFIL, BDNCMPROD, BDCODCSTICMSENTFIL, BDCODCSTCOFENTFIL, BDCODCSTIPIENTFIL, BDCODCSTPISSAIFIL, BDCODCSTIPISAIFIL, ';
  WSQL = WSQL||'        BDCODCSTCOFSAIFIL, BDCODTER, BDCODCSTCOFENTACAO, BDCODCSTICMSSAIFIL, BDCODCSTICMSENTACAO, BDCODNATBCCOFACAO, BDCODNATRECCOFACAO, BDCODCSTCOFSAIACAO, ';
  WSQL = WSQL||'        BDCODCSTIPIENTACAO, BDCODCSTPISENTACAO, BDCODCSTPISSAIACAO, BDCODCSTIPISAIACAO, BDCODNATBCPISACAO, BDCODNATRECPISACAO, BDCODPROD, BDCODNAT, ';
  WSQL = WSQL||'        BDCODCSTICMSSAIACAO,'||prtipolanpara||' AS BDTIPOLAN, ';

  IF (prtipolanpara = 3) THEN --Redu??o Z n?o tem modelo
    BEGIN
      WSQL = WSQL||'      NULL AS BDMODELO, ';
    END
  ELSE
    BEGIN
      WSQL = WSQL||'      BDMODELO, ';
    END

  WSQL = WSQL||'        BDESPECIE, BDSERIE, BDQTDFILTRO, BDAPLICAACOES, BDZERARVLR, BDCSTICMSACAO, BDCSTIPIACAO, BDCSTPISACAO, ';
  WSQL = WSQL||'        BDCSTCOFINSACAO, BDALIQICMSACAO, BDALIQICMSSTACAO, BDALIQIPIACAO, BDALIQPISACAO, BDALIQCOFINSACAO, BDALIQICMS, BDALIQICMSST, BDALIQPIS, BDALIQIPI, ';
  WSQL = WSQL||'        BDALIQCOFINS, BDVALORICMSACAO, BDVALORICMSSTACAO, BDVALORPISACAO, BDVALORIPIACAO, BDVALORCOFINSACAO, BDLANCAREMICMSACAO, BDNATCREPISACAO, BDNATCRECOFINSACAO, ';
  WSQL = WSQL||'        BDNATRECPISACAO, BDNATRECCOFINSACAO, BDBCICMSACAO, BDBCICMSSTACAO, BDBCIPIACAO, BDBCPISACAO, BDBCCOFINSACAO, BDCODNATLANCACAO, BDSERIELANCACAO, ';
  WSQL = WSQL||'        BDORDEMFRETELANCACAO, BDALIQICMSFIL, BDBCICMSC197ACAO, BDALIQICMSC197ACAO, BDVALORICMSC197ACAO, BDALIQICMSC197, BDCODOBSC195, BDCODAJUC197, BDBCRETPISACAO, ';
  WSQL = WSQL||'        BDBCRETCOFINSACAO, BDBCRETCSLLACAO, BDBCRETIRRFACAO, BDBCRETINSSACAO, BDALIQRETPISACAO, BDALIQRETCOFINSACAO, BDALIQRETCSLLACAO, BDALIQRETIRRFACAO, ';
  WSQL = WSQL||'        BDALIQRETINSSACAO, BDALIQRETPIS, BDALIQRETCOFINS, BDALIQRETCSLL, BDALIQRETIRRF, BDALIQRETINSS, BDVALORRETPISACAO, BDVALORRETCOFINSACAO, BDVALORRETCSLLACAO, ';
  WSQL = WSQL||'        BDVALORRETIRRFACAO, BDVALORRETINSSACAO, BDCODRECRETPISACAO, BDCODRECRETPIS, BDCODRECRETCOFINSACAO, BDCODRECRETCOFINS, BDCODRECRETCSLLACAO, BDCODRECRETCSLL, ';
  WSQL = WSQL||'        BDCODRECRETIRRFACAO, BDCODRECRETIRRF, BDCODRECRETINSSACAO, BDCODRECRETINSS, BDVLRIGUALA, BDVLRMENORQUE, BDVLRMAIORQUE,BDCODNATFLANCACAO ';
  WSQL = WSQL||' FROM VEF_BASE_TPLANOACOESTROCA ';
  WSQL = WSQL||' WHERE bdcodplatroca = '||prcodplanotroca;
  WSQL = WSQL||' AND bdtipolan = '||prtipolande;
  EXECUTE STATEMENT WSQL;

  SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = :prcodplanotroca AND BDTIPOLAN = :prtipolanpara INTO :wchavetpimp;

  wChaveAnt = 0;
  FOR SELECT TT.bdchave, TT.bdcodtpimp FROM VEF_BASE_TTIPOTROCA TT
      JOIN VEF_BASE_TPLANOACOESTROCA TP ON(TP.bdcodplatroca = TT.bdcodplatroca AND TP.bdchave = TT.bdchave AND TP.bdtipolan = :prtipolande)
      WHERE TT.bdcodplatroca = :prcodplanotroca ORDER BY TT.bdchave DESC, TT.bdcodtpimp DESC INTO :wchave, :wcodtpimp DO
    BEGIN
      IF (:wChaveant <> :wChave) THEN
        BEGIN
          wChaveAnt = :wChave;
          wchavetpimp = :wchavetpimp - 1;
        END
      INSERT INTO VEF_BASE_TTIPOTROCA(BDCODPLATROCA, BDCHAVE, bdcodtpimp) VALUES(:prcodplanotroca, :wchavetpimp, :wcodtpimp);
    END

  SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = :prcodplanotroca AND BDTIPOLAN = :prtipolanpara INTO :wchavetpimp;

  wChaveAnt = 0;
  FOR SELECT SM.bdchave, SM.bdcodtpimp, SM.bdsomanfprod, SM.bdsomadespace, sm.bdsomafrete, sm.bdsomaipi, sm.bdsomast, sm.bdsomaredbc, sm.bdsomabaseiss FROM VEF_BASE_TSOMABC SM
      JOIN VEF_BASE_TPLANOACOESTROCA PA ON(PA.bdcodplatroca = SM.bdcodplatroca AND PA.bdchave = SM.bdchave AND PA.bdtipolan = :prtipolande)
      WHERE SM.bdcodplatroca = :prcodplanotroca ORDER BY SM.bdchave DESC, SM.bdcodtpimp DESC INTO :wchave, :wcodtpimp, :wnfprod, :wdespace, :wfrete, :wipi, :wst, :wredbc, :wbaseiss DO
  BEGIN
    IF (:wChaveAnt <> :wChave) THEN
      BEGIN
        wChaveAnt = :wChave;
        wchavetpimp = :wchavetpimp - 1;
      END

      INSERT INTO VEF_BASE_TSOMABC(BDCODTPIMP, BDCODPLATROCA, BDCHAVE, BDSOMANFPROD, BDSOMADESPACE, BDSOMAFRETE, BDSOMAIPI, BDSOMAST, BDSOMAREDBC, BDSOMABASEISS)
      VALUES(:wcodtpimp, :prcodplanotroca, :wchavetpimp, :wnfprod, :wdespace, :wfrete, :wipi, :wst, :wredbc, :wbaseiss);
  END

  SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = :prcodplanotroca AND BDTIPOLAN = :prtipolanpara INTO :wchavetpimp;

  wChaveAnt = 0;
  FOR SELECT SUB.bdchave, SUB.bdcodtpimp, SUB.bdsubnfprod, SUB.bdsubdespace, SUB.bdsubfrete, SUB.bdsubipi, SUB.bdsubst, SUB.bdsubredbc, SUB.bdsubbaseiss, SUB.bdsubdesc FROM VEF_BASE_TSUBTRACAOBC SUB
      JOIN VEF_BASE_TPLANOACOESTROCA PA ON(PA.bdcodplatroca = SUB.bdcodplatroca AND PA.bdchave = SUB.bdchave AND PA.bdtipolan = :prtipolande)
      WHERE SUB.bdcodplatroca = :prcodplanotroca ORDER BY SUB.bdchave DESC, SUB.bdcodtpimp DESC INTO :wchave, :wcodtpimp, :wnfprod, :wdespace, :wfrete, :wipi, :wst, :wredbc, :wbaseiss, :wdesc DO
  BEGIN
    IF (:wChaveAnt <> :wChave) THEN
      BEGIN
        wChaveAnt = :wChave;
        wchavetpimp = :wchavetpimp - 1;
      END

      INSERT INTO VEF_BASE_TSUBTRACAOBC(BDCODTPIMP, BDCODPLATROCA, BDCHAVE, BDSUBNFPROD, BDSUBDESPACE, BDSUBFRETE, BDSUBIPI, BDSUBST, BDSUBREDBC, BDSUBBASEISS, BDSUBDESC)
      VALUES(:wcodtpimp, :prcodplanotroca, :wchavetpimp, :wnfprod, :wdespace, :wfrete, :wipi, :wst, :wredbc, :wbaseiss, :wDesc);
  END

END
^

/* Alter (SP_COPIA_ATIVIDADES_MUNICIPAIS) */
ALTER PROCEDURE SP_COPIA_ATIVIDADES_MUNICIPAIS(CODCIDNOVA INTEGER,
CODCIDCOPIAR INTEGER = 4445,
REFERENCIA INTEGER = 201201)
 AS
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WSQL VARCHAR(2000);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(1000);
DECLARE VARIABLE WCAMPO VARCHAR(32);
BEGIN
  /* VERIFICA SE A CIDADE DESTINIO EXISTE */
  WSQL = 'SELECT BDCODCID FROM TCIDADE WHERE BDCODCID = '||:CODCIDNOVA;
  EXECUTE STATEMENT WSQL INTO :WCODCID;

  /* CASO A CIDADE PARA INSERIR AS ATIVIDADES N?O EXISTA, N?O EXECUTA O INSERT */
  IF ((WCODCID IS NULL) OR (WCODCID = 0)) THEN
    EXIT;

  /* LIMPA A TABELA DE ATIVIDADES DA CIDADE QUE VAI COPIAR 
  WSQL = 'DELETE FROM TATVMUNICIPAL WHERE BDCODCID = '||:CODCIDNOVA;
  EXECUTE STATEMENT WSQL; */

  /* OBT?M OS CAMPOS DA TABELA DE ATIVIDADES */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''TATVMUNICIPAL''';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODCID') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA DE ATIVIDADES DA CIDADE A COPIAR PARA A CIDADE NOVA */
  WSQL = 'INSERT INTO TATVMUNICIPAL (BDCODCID'||WCAMPOSINSERT||') '||
         ' SELECT '||CODCIDNOVA||WCAMPOSINSERT||' FROM TATVMUNICIPAL WHERE BDCODCID = (SELECT BDCODCID FROM TCIDADE WHERE BDCODCID = '||CODCIDCOPIAR||' and BDREFATVM = '||REFERENCIA||')';
  WSQL = WSQL || ' AND NOT EXISTS (SELECT X.BDCODATVM FROM tatvmunicipal X WHERE X.bdcodcid = '||CODCIDNOVA||' and BDREFATVM = '||REFERENCIA||')';

  EXECUTE STATEMENT wSQL;
END
^

/* empty dependent procedure body */
/* Clear: SP_COPIA_DADOS_EMPRESA for: SP_COPIA_DADOS_EMPRESA */
ALTER PROCEDURE SP_COPIA_DADOS_EMPRESA(PRTABELA VARCHAR(50),
PRCODEMP INTEGER,
PRCODEMPBACKUP VARCHAR(10),
PRREFEMP INTEGER)
 RETURNS(BDINSERIU /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CRIA_BACKUP_EMPRESA for: SP_COPIA_DADOS_EMPRESA */
ALTER PROCEDURE SP_CRIA_BACKUP_EMPRESA(PRCODEMP INTEGER,
PRREFEMP INTEGER,
PRCODPLANOONLINEDE INTEGER,
PRCODPLANOONLINEPARA INTEGER,
PRCODUSU INTEGER,
PRCODUSUINTRANET INTEGER,
PRNOMUSUINTRANET VARCHAR(80),
PRCODCONTABLALUR INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_COPIA_DADOS_EMPRESA) */
ALTER PROCEDURE SP_COPIA_DADOS_EMPRESA(PRTABELA VARCHAR(50),
PRCODEMP INTEGER,
PRCODEMPBACKUP VARCHAR(10),
PRREFEMP INTEGER)
 RETURNS(BDINSERIU DM_BOOLEAN)
 AS
declare variable WSQLINSERT varchar(30000);
declare variable WSQLINSERTCAMPOS varchar(30000);
declare variable WSQLJOIN varchar(10000);
declare variable WSQLUNIONJOIN varchar(30000);
declare variable WSQLREF varchar(100);
declare variable WSQLDATA varchar(30000);
declare variable WSQLWHEREJOINS varchar(30000);
declare variable WSQLWHERE varchar(30000);
declare variable WPOSSUICAMPOEMP varchar(5);
declare variable WPOSSUICAMPOREF varchar(5);
declare variable WPOSSUICAMPODATA varchar(5);
declare variable WPOSSUICAMPOOBRIGATORIO varchar(5);
declare variable WEXISTEREG varchar(5);
declare variable WTABELAAUX varchar(50);
declare variable WCODEMPAUX varchar(10);
declare variable WCAMPOTABELA varchar(300);
declare variable WCAMPOTABELADESTINO varchar(300);
declare variable WFKANTERIOR varchar(300);
declare variable WFKATUAL varchar(300);
declare variable WCAMPODATA varchar(20);
declare variable WULTIMODIA integer;
declare variable WINSERIU varchar(5);
declare variable WAPELIDOORIGEM varchar(10);
declare variable WAPELIDODESTINO varchar(10);
declare variable WAPELIDODESTINOAUX varchar(10);
declare variable WNOTNULL integer;
declare variable WCOUNT integer;
declare variable WDATA date;
begin
  WPOSSUICAMPOOBRIGATORIO = 'FALSE';
  WPOSSUICAMPOEMP  = 'FALSE';
  WPOSSUICAMPOREF  = 'FALSE';
  WPOSSUICAMPODATA = 'FALSE';
  WSQLDATA         = '';
  WSQLREF          = '';
  WSQLJOIN         = '';
  WSQLUNIONJOIN    = '';
  WSQLWHEREJOINS   = '';
  WSQLWHERE        = '';
  WEXISTEREG       = 'FALSE';
  WINSERIU         = 'FALSE';
  WAPELIDOORIGEM   = 'ORG';
  WAPELIDODESTINO  = 'DEST';
  WAPELIDODESTINOAUX  = WAPELIDODESTINO;
  WCOUNT              = 1;
  WCAMPOTABELA        = '';
  WCAMPOTABELADESTINO = '';
  WFKANTERIOR         = '';
  WFKATUAL            = '';

  BDINSERIU = 'FALSE';

  --Faz a verifica??o se ? alguma das tabelas da online ou suas agregadas, pois ai n?o deve inserir nada
  select TABELA
  from (select distinct(CD.RDB$RELATION_NAME) as TABELA
        from RDB$RELATION_CONSTRAINTS CO
        inner join RDB$INDEX_SEGMENTS ID on (CO.RDB$INDEX_NAME = ID.RDB$INDEX_NAME)
        inner join RDB$REF_CONSTRAINTS RE on (CO.RDB$CONSTRAINT_NAME = RE.RDB$CONSTRAINT_NAME)
        inner join RDB$RELATION_CONSTRAINTS CD on (RE.RDB$CONST_NAME_UQ = CD.RDB$CONSTRAINT_NAME)
        inner join(select distinct trim(CONSTRAINTSORIGEM.RDB$RELATION_NAME) as CAMPO
                   from RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM
                   where CONSTRAINTSORIGEM.RDB$RELATION_NAME like('TOL_%')) TE on (TE.CAMPO = CO.RDB$RELATION_NAME)
        where CD.RDB$RELATION_NAME <> 'VSUC_EMPRESAS_TLAN')
  where TABELA = :PRTABELA into :WTABELAAUX;

  if ((trim(WTABELAAUX) <> '') or not (WTABELAAUX is null)) then
    exit;

  select ULTDIA from ULTIMO_DIA_MES(cast(substring(cast(:PRREFEMP as varchar(8)) from 5 for 2) as integer), cast(substring(cast(:PRREFEMP as varchar(8)) from 1 for 4) as integer))
  into :WULTIMODIA;
  WDATA = substring(cast(PRREFEMP as varchar(8)) from 5 for 2)||'-'||WULTIMODIA||'-'||substring(cast(PRREFEMP as varchar(8)) from 1 for 4);

  if (trim(PRTABELA) <> 'TLIVRO' and
      trim(PRTABELA) <> 'TEMPRESAS' and
      trim(PRTABELA) <> 'PLANOS_TPLA' and
      trim(PRTABELA) <> 'TEMPRESAS_REF' and
      trim(PRTABELA) <> 'TBLOQLAN_EMPRESA' and
      trim(PRTABELA) <> 'TBLOQLAN_USUARIO' and
      trim(PRTABELA) <> 'TEMPRESAS_BACKUP_ONLINE') then
  begin
    --Verifica se os dados das dependencias da tabela ja foram setadas
    for select distinct(CD.RDB$RELATION_NAME)
        from RDB$RELATION_CONSTRAINTS CO
        inner join RDB$INDEX_SEGMENTS ID on (CO.RDB$INDEX_NAME = ID.RDB$INDEX_NAME)
        inner join RDB$REF_CONSTRAINTS RE on (CO.RDB$CONSTRAINT_NAME = RE.RDB$CONSTRAINT_NAME)
        inner join RDB$RELATION_CONSTRAINTS CD on (RE.RDB$CONST_NAME_UQ = CD.RDB$CONSTRAINT_NAME)
        where CO.RDB$RELATION_NAME = :PRTABELA and
              RDB$FIELD_NAME = 'BDCODEMP'
        into :WTABELAAUX
    do
    begin
      WTABELAAUX = trim(WTABELAAUX);

      if (WTABELAAUX <> PRTABELA) then
        select BDINSERIU from SP_COPIA_DADOS_EMPRESA(trim(:WTABELAAUX),:PRCODEMP,:PRCODEMPBACKUP,:PRREFEMP) into :WINSERIU;

      WAPELIDODESTINO = WAPELIDODESTINOAUX || WCOUNT;

      WSQLDATA     = '';
      WSQLREF      = '';
      WCAMPOTABELA = '';
      WSQLWHEREJOINS = '';

      --Verifica se a empresa dependente possui os campos de data ou referencia, para adicionar no join
      select first 1 trim(A.RDB$FIELD_NAME) as BDCAMPO
      from RDB$RELATION_FIELDS A
      where (A.RDB$RELATION_NAME = :WTABELAAUX) and
            (((trim(A.RDB$FIELD_NAME) like 'BDDATA%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATANASC%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATAINI%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATABASE%')) or
             ((trim(A.RDB$FIELD_NAME) like 'BDDT%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDTINI%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDTNASC%')) or
             ((trim(A.RDB$FIELD_NAME) like 'BDDAT%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATINI%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATNASC%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATANASC%')))
      order by RDB$FIELD_POSITION
      into :WCAMPOTABELA;

      if ((WCAMPOTABELA <> '') and not(WCAMPOTABELA is null)) then
        WSQLWHEREJOINS = WSQLWHEREJOINS || ' and '||WAPELIDODESTINO||'.'||WCAMPOTABELA||' <= '''||WDATA||'''' ;

      WCAMPOTABELA = '';
      select first 1 trim(A.RDB$FIELD_NAME) as BDCAMPO
      from RDB$RELATION_FIELDS A
      where (A.RDB$RELATION_NAME = :WTABELAAUX) and
            (trim(A.RDB$FIELD_NAME) like 'BDREFEMP')
      order by RDB$FIELD_POSITION
      into :WCAMPOTABELA;

      if ((WCAMPOTABELA <> '') and not(WCAMPOTABELA is null)) then
        WSQLWHEREJOINS = WSQLWHEREJOINS || ' and '||WAPELIDODESTINO||'.'||WCAMPOTABELA||' <= ' || PRREFEMP;

      --Monta os Joins
      WSQLJOIN = ' join ' || WTABELAAUX || ' ' || WAPELIDODESTINO || ' on(' || WAPELIDODESTINO || '.BDCODEMP = ' || PRCODEMPBACKUP;
      for select IO.RDB$INDEX_NAME, IO.RDB$FIELD_NAME AS CAMPOORIGEM, FO.RDB$NULL_FLAG , ID.RDB$FIELD_NAME as CAMPODESTINO
          from RDB$RELATION_CONSTRAINTS CO
          inner join RDB$INDEX_SEGMENTS IO on (CO.RDB$INDEX_NAME = IO.RDB$INDEX_NAME)
          inner join RDB$REF_CONSTRAINTS RE on (CO.RDB$CONSTRAINT_NAME = RE.RDB$CONSTRAINT_NAME)
          inner join RDB$RELATION_FIELDS FO on (CO.RDB$RELATION_NAME = FO.RDB$RELATION_NAME and IO.RDB$FIELD_NAME = FO.RDB$FIELD_NAME)
          inner join RDB$RELATION_CONSTRAINTS CD on (RE.RDB$CONST_NAME_UQ = CD.RDB$CONSTRAINT_NAME)
          inner join RDB$INDEX_SEGMENTS ID on (CD.RDB$INDEX_NAME = ID.RDB$INDEX_NAME)
          where CO.RDB$RELATION_NAME = :PRTABELA and
                CD.RDB$RELATION_NAME = :WTABELAAUX and
                IO.RDB$FIELD_POSITION = ID.RDB$FIELD_POSITION
      into :WFKATUAL, :WCAMPOTABELA, :WNOTNULL, :WCAMPOTABELADESTINO
      do
      begin
        WCAMPOTABELA = trim(WCAMPOTABELA);
        WCAMPOTABELADESTINO = trim(WCAMPOTABELADESTINO);

        --Verifica se as FKs s?o diferentes, pois se forem significa que existe mais de uma fk pra mesma tabela e precisamos de dois joins diferentes
        if ((WFKATUAL <> WFKANTERIOR) and (WFKANTERIOR <> ''))then
        begin
          WCOUNT = WCOUNT + 1;

          WSQLJOIN = WSQLJOIN || ') ';

          WAPELIDODESTINO = WAPELIDODESTINOAUX || WCOUNT;

          if (WPOSSUICAMPOOBRIGATORIO = 'TRUE') then
            WSQLUNIONJOIN = WSQLUNIONJOIN || ' left ' || WSQLJOIN;
          else
            WSQLUNIONJOIN = WSQLUNIONJOIN || ' inner ' || WSQLJOIN;

          WSQLJOIN = ' join ' || WTABELAAUX || ' ' || WAPELIDODESTINO || ' on(' || WAPELIDODESTINO || '.BDCODEMP = ' || PRCODEMPBACKUP;
        end

        if ((WCAMPOTABELA <> 'BDCODEMP') and (WCAMPOTABELA <> 'BDFILIAL')) then
        begin
          --Verifica se possui algum campo dependente que n?o pode ficar vazio na tabela
          if (not (WNOTNULL is null))  then
            WPOSSUICAMPOOBRIGATORIO = 'TRUE';

          WSQLJOIN = WSQLJOIN || ' and ' || WAPELIDODESTINO || '.' || WCAMPOTABELADESTINO|| ' = ' || WAPELIDOORIGEM || '.' || WCAMPOTABELA;

          --Adiciona o campo de FK que n?o ? obrigat?rio no where pois n?o estava funcionando corretamente com o inner/left join
          if (WPOSSUICAMPOOBRIGATORIO = 'FALSE') then
            WSQLWHERE= WSQLWHERE||' and (('||WAPELIDOORIGEM||'.'||WCAMPOTABELA||' in (select '||WAPELIDODESTINO||'.'||WCAMPOTABELADESTINO||' from '||WTABELAAUX||' '||WAPELIDODESTINO||
                                          ' where '||WAPELIDODESTINO||'.'||'BDCODEMP = '||PRCODEMPBACKUP||WSQLWHEREJOINS||')) or ('||WAPELIDOORIGEM||'.'||WCAMPOTABELA||' is null))';
        end

        WFKANTERIOR = WFKATUAL;
      end
      WSQLJOIN = WSQLJOIN||WSQLDATA||WSQLREF||') ';

      if (WPOSSUICAMPOOBRIGATORIO = 'FALSE') then
      begin
        if (WINSERIU = 'FALSE') then
          WINSERIU = 'TRUE';

        WSQLJOIN = '';
      end
      else
        WSQLUNIONJOIN = WSQLUNIONJOIN || ' inner ' || WSQLJOIN;

      WCOUNT = WCOUNT + 1;
      WFKANTERIOR = '';

      if (WINSERIU = 'FALSE') then
        exit;
    end

    WSQLDATA = '';
    WSQLREF  = '';

    --Monta o insert
    WSQLINSERT = 'insert into ' || PRTABELA || ' (BDCODEMP';
    WSQLINSERTCAMPOS = 'select ' || PRCODEMPBACKUP;
    for select trim(A.RDB$FIELD_NAME)
        from RDB$RELATION_FIELDS A
        where (A.RDB$RELATION_NAME = :PRTABELA)
        order by RDB$FIELD_POSITION
    into :WCAMPOTABELA
    do
    begin
      if (WCAMPOTABELA = 'BDREFEMP') then
        WPOSSUICAMPOREF = 'TRUE';

      --Tratamento para filtro pela data
      if (WPOSSUICAMPODATA = 'FALSE') then
      begin
        if (((position('BDDATA', :WCAMPOTABELA) > 0) and
             (position('BDDATAINI', :WCAMPOTABELA) = 0) and
             (position('BDDATABASE', :WCAMPOTABELA) = 0) and
             (position('BDDATANASC', :WCAMPOTABELA) = 0)) or
            ((position('BDDT', :WCAMPOTABELA) > 0) and
             (position('BDDTINI', :WCAMPOTABELA) = 0) and
             (position('BDDTNASC', :WCAMPOTABELA) = 0)) or
            ((position('BDDAT', :WCAMPOTABELA) > 0) and
             (position('BDDATINI', :WCAMPOTABELA) = 0) and
             (position('BDDATABASE', :WCAMPOTABELA) = 0) and
             (position('BDDATNASC', :WCAMPOTABELA) = 0) and
             (position('BDDATANASC', :WCAMPOTABELA) = 0))) then
        begin
          WPOSSUICAMPODATA = 'TRUE';
          WCAMPODATA = WCAMPOTABELA;
        end
      end

      if (WCAMPOTABELA <> 'BDCODEMP') then
      begin
        WSQLINSERT = WSQLINSERT || ',' || WCAMPOTABELA;
        WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ',' || WAPELIDOORIGEM ||'.'|| WCAMPOTABELA;
      end
      else
        WPOSSUICAMPOEMP = 'TRUE';
    end
    WSQLINSERT = WSQLINSERT || ') ';

    --Cria filtro pela data
    if (WPOSSUICAMPODATA = 'TRUE') then
      WSQLDATA = ' and ' || WAPELIDOORIGEM ||'.'|| WCAMPODATA || ' <= ''' ||WDATA||'''' ;

    --Cria filtro pela refer?ncia
    if (WPOSSUICAMPOREF = 'TRUE') then
      WSQLREF = ' and '|| WAPELIDOORIGEM ||'.BDREFEMP <= ' || PRREFEMP;

    WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ' from ' || PRTABELA || ' ' || WAPELIDOORIGEM ||' '|| WSQLUNIONJOIN || ' where '||WAPELIDOORIGEM || '.BDCODEMP = ' || PRCODEMP ||
                       WSQLREF || WSQLDATA || WSQLWHERE;

    if (WPOSSUICAMPOEMP = 'TRUE') then
    begin
      --Verifica se ja possui algo cadastrado para a empresa nova na tabela, pois h? alguns registros que s?o setados pelas triggers das tabelas TEMPRESAS e TEMPRESAS_REF
      execute statement 'select first 1 BDCODEMP from ' || PRTABELA || ' where BDCODEMP = ' || PRCODEMPBACKUP into :WCODEMPAUX;
      if ((WCODEMPAUX = '') or (WCODEMPAUX is null) or (WCODEMPAUX = '0')) then
        WEXISTEREG = 'FALSE';
      else
        WEXISTEREG = 'TRUE';

      --Insere os registros
      if (WEXISTEREG = 'FALSE') then
        execute statement WSQLINSERT || WSQLINSERTCAMPOS;

      --Precisa verificar se foi inserido algum registro, pois no caso da recursividade, preciso que as tabelas dependentes tenham esse registro
      execute statement 'select first 1 BDCODEMP from ' || PRTABELA || ' where BDCODEMP = ' || PRCODEMPBACKUP into :WCODEMPAUX;
      if ((WCODEMPAUX = '') or (WCODEMPAUX is null) or (WCODEMPAUX = '0')) then
        BDINSERIU = 'FALSE';
      else
        BDINSERIU = 'TRUE';
    end
  end
  else
    BDINSERIU = 'TRUE';

  suspend;
end
^

/* Alter (SP_COPIA_PLANOTROCA) */
ALTER PROCEDURE SP_COPIA_PLANOTROCA(PRCODPLANO INTEGER,
PRCODPLANOCOPIADO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(5000);
DECLARE VARIABLE WCAMPO VARCHAR(32);
BEGIN

  /*PRCODPLANO        | C?digo do plano que foi cadastrado
    PRCODPLANOCOPIADO | C?digo do plano que ser? copiado para o plano cadastrado.

    VEF_BASE_TPLANOACOESTROCA - Tabela principal 1?
    VEF_BASE_TTIPOTROCA - Tabela Secundaria      2?
    VEF_BASE_TSOMABC - Tabela dependente         3?
    VEF_BASE_TSUBTRACAOBC - Tabela depedente     3?
  */

  /* Alt.: 15144 - A partir de agora vai carregar os campo da tabela e gerar o sql com base nesses campos,
                   Feito assim para n?o ter mais problemas de quando forem inclu?dos campos novos nos planos. */

  /* OBT?M OS CAMPOS DA TABELA DE PLANO DE A??ES */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA DE PLANO DE A??ES A COPIAR PARA O NOVO PLANO */
  WSQL = 'INSERT INTO VEF_BASE_TPLANOACOESTROCA (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

  /* OBT?M OS CAMPOS DA TABELA "VEF_BASE_TTIPOTROCA" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TTIPOTROCA'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TTIPOTROCA" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TTIPOTROCA (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TTIPOTROCA WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

  /* OBT?M OS CAMPOS DA TABELA "VEF_BASE_TSOMABC" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TSOMABC'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TSOMABC" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TSOMABC (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TSOMABC WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

  /* OBT?M OS CAMPOS DA TABELA "VEF_BASE_TSUBTRACAOBC" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TSUBTRACAOBC'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TSUBTRACAOBC" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TSUBTRACAOBC (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TSUBTRACAOBC WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;
END
^

/* Alter (SP_CRIA_BACKUP_EMPRESA) */
ALTER PROCEDURE SP_CRIA_BACKUP_EMPRESA(PRCODEMP INTEGER,
PRREFEMP INTEGER,
PRCODPLANOONLINEDE INTEGER,
PRCODPLANOONLINEPARA INTEGER,
PRCODUSU INTEGER,
PRCODUSUINTRANET INTEGER,
PRNOMUSUINTRANET VARCHAR(80),
PRCODCONTABLALUR INTEGER)
 AS
declare variable WSQL varchar(30000);
declare variable WSQLINSERT varchar(30000);
declare variable WSQLINSERTCAMPOS varchar(30000);
declare variable WTABELA varchar(50);
declare variable WCAMPOTABELA varchar(300);
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
declare variable WQTDBACKUPEMP integer;
declare variable WCODEMPBACKUP char(10);
declare variable WCODEMPBACKUPMATRIZ char(10);
declare variable WCODEMPAUX char(6);
declare variable WINSERIU varchar(50);
declare variable WCHAVE integer;
declare variable WTIPOLAN integer;
declare variable WULTIMODIA integer;
declare variable WDATA date;
declare variable WTEMPOINI time;
begin
  /*
    Foram utilizadas v?rias System Tables para efetuar o backup da empresa. Para facilitar a manuten??o destes SQLs ? interessante utilizar documenta??o do firebird:
    https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-appx04-systables.html
  */

  WSQL            = '';
  WCODEMPBACKUP   = '';

  --La?o das empresas
  WSQL = WSQL || 'select BDCODMATRIZ, BDCODEMP, BDQTDBACKUPEMP ';
  WSQL = WSQL || 'from TEMPRESAS ';
  WSQL = WSQL || 'where BDCODEMP = ' || PRCODEMP || ' or (BDCODMATRIZ = ' || PRCODEMP || ') ';

  for execute statement WSQL
          into :WCODMATRIZ, :WCODEMP, :WQTDBACKUPEMP
  do
  begin
    --Incrementa a quantidade de backup da empresa
    WQTDBACKUPEMP = WQTDBACKUPEMP + 1;
    WTEMPOINI = current_time;

    --Cria a chave da empresa backup
    WCODEMPAUX = LPAD(cast(:WCODEMP as varchar(6)), 6, '0');

    if (WQTDBACKUPEMP <= 9) then
      WCODEMPBACKUP = '10' || WQTDBACKUPEMP || WCODEMPAUX;
    else
      WCODEMPBACKUP = '1' || WQTDBACKUPEMP || WCODEMPAUX;

    --Cadastra a empresa backup com o status 1(backup) e quantidade de backup
    WTABELA = 'TEMPRESAS';

    if ((WCODMATRIZ is null) or (WCODMATRIZ = 0)) then
    begin
      WCODEMPBACKUPMATRIZ = WCODEMPBACKUP;
      WSQLINSERT = 'insert into ' || WTABELA || ' (BDCODEMP,BDSTATUSEMP,BDQTDBACKUPEMP';
      WSQLINSERTCAMPOS = 'select ' || WCODEMPBACKUP || ',1,0';
    end
    else
    begin
      WSQLINSERT = 'insert into ' || WTABELA || ' (BDCODEMP,BDSTATUSEMP,BDQTDBACKUPEMP,BDCODMATRIZ';
      WSQLINSERTCAMPOS = 'select ' || WCODEMPBACKUP || ',1,0,' || WCODEMPBACKUPMATRIZ ;
    end

    for execute statement 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE (A.RDB$RELATION_NAME = ''' || WTABELA || ''') AND ' || ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = ''' || 'RDB$FIELD_TYPE' || ''') ORDER BY RDB$FIELD_POSITION'
            into :WCAMPOTABELA
    do
    begin
      if (((WCAMPOTABELA = 'BDCODMATRIZ') and ((WCODMATRIZ is null) or (WCODMATRIZ = 0))) or
          (WCAMPOTABELA <> 'BDCODMATRIZ') and (WCAMPOTABELA <> 'BDCODEMP') and
          (WCAMPOTABELA <> 'BDSTATUSEMP') and (WCAMPOTABELA <> 'BDQTDBACKUPEMP')) then
      begin
        WSQLINSERT = WSQLINSERT || ',' || WCAMPOTABELA;
        WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ',' || WCAMPOTABELA;
      end
    end
    WSQLINSERT = WSQLINSERT || ') ';
    WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ' from ' || WTABELA || ' where BDCODEMP = ' || WCODEMP;
    execute statement WSQLINSERT || WSQLINSERTCAMPOS;

    --Copia as referencias da empresa
    WTABELA = 'TEMPRESAS_REF';

    WSQLINSERT = 'insert into ' || WTABELA || ' (BDCODEMP,BDAPEEMP';
    WSQLINSERTCAMPOS = 'select ' || WCODEMPBACKUP ||',''Backup - '||WCODEMPBACKUP||'''';
    for execute statement 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE (A.RDB$RELATION_NAME = ''' || WTABELA || ''') AND ' || ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = ''' || 'RDB$FIELD_TYPE' || ''') ORDER BY RDB$FIELD_POSITION'
        into :WCAMPOTABELA
    do
    begin
      if ((WCAMPOTABELA <> 'BDCODEMP') and (WCAMPOTABELA <> 'BDAPEEMP')) then
      begin
        WSQLINSERT = WSQLINSERT || ',' || WCAMPOTABELA;
        WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ',' || WCAMPOTABELA;
      end
    end
    WSQLINSERT = WSQLINSERT || ') ';
    WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ' from ' || WTABELA || ' where BDCODEMP = ' || WCODEMP || ' and BDREFEMP <= ' || PRREFEMP;
    execute statement WSQLINSERT || WSQLINSERTCAMPOS;

    --Gera a data com o ultimo dia da refer?ncia selecionada
    select ULTDIA from ULTIMO_DIA_MES(cast(substring(cast(:PRREFEMP as varchar(8)) from 5 for 2) as integer), cast(substring(cast(:PRREFEMP as varchar(8)) from 1 for 4) as integer))
    into :WULTIMODIA;
    WDATA = substring(cast(PRREFEMP as varchar(8)) from 5 for 2)||'-'||WULTIMODIA||'-'||substring(cast(PRREFEMP as varchar(8)) from 1 for 4);

    --#alt:24127. Tive que adicionar tratamento para pegar s? as tabelas que o BDCODEMP seja PK. Ana - 03/05/2018
    --La?o com as tabelas que s?o dependentes da tabela TEMPRESAS para inser??o dos valores
    for select BDCAMPO
        from (select distinct trim(CONSTRAINTSORIGEM.RDB$RELATION_NAME) as BDCAMPO
              from RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM
              inner join RDB$INDEX_SEGMENTS INDICES on (CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME)
              inner join RDB$REF_CONSTRAINTS RELACIONAMENTOS on (CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME = RELACIONAMENTOS.RDB$CONSTRAINT_NAME)
              inner join RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO on (RELACIONAMENTOS.RDB$CONST_NAME_UQ = CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME)
              where (RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_TEMPRESAS' or RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_TEMPRESAS_REF' or INDICES.RDB$FIELD_NAME = 'BDCODEMP')) ALLTABLES
        inner join(select CONSTRAINTS.RDB$RELATION_NAME
                   from RDB$RELATION_CONSTRAINTS CONSTRAINTS
                   inner join RDB$INDEX_SEGMENTS IND on (CONSTRAINTS.RDB$INDEX_NAME = IND.RDB$INDEX_NAME)
                   where IND.RDB$FIELD_NAME = 'BDCODEMP' and
                         CONSTRAINTS.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY') PKTABLES on (PKTABLES.RDB$RELATION_NAME = ALLTABLES.BDCAMPO) 
        into :WTABELA
    do
    begin
      select BDINSERIU from SP_COPIA_DADOS_EMPRESA(trim(:WTABELA), :WCODEMP, :WCODEMPBACKUP, :PRREFEMP) into :WINSERIU;

      --Altero os campos bdfilial das tabelas na empresa backup
      if ((WCODMATRIZ is not null) and (WCODMATRIZ > 0) and (:WINSERIU = 'TRUE') and (trim(:WTABELA) = 'VSUC_EMPRESAS_TLAN')) then
        execute statement 'update VSUC_EMPRESAS_TLAN set BDFILIAL = '||:WCODEMPBACKUP||' where BDCODEMP = '||:WCODEMPBACKUPMATRIZ||' and BDFILIAL = '||:WCODEMP||' and BDDATA <= '''||:WDATA||'''';
    end

    --Altera tipo dos lan?amentos da on-line
    for select BDCHAVE, BDTIPOLAN
        from VSUC_EMPRESAS_TLAN
        where BDCODEMP = :WCODEMPBACKUP and
              BDTIPOLAN in (100, 200, 3000)
        into :WCHAVE, :WTIPOLAN
    do
    begin
      --"Lan?amento on-line ?NICO fiscal" para "Copia lan?amento on-line ?NICO fiscal"
      if (WTIPOLAN = 100) then
      begin
        update VSUC_EMPRESAS_TLAN set BDTIPOLAN = 31
        where BDCODEMP = :WCODEMPBACKUP and
              BDCHAVE = :WCHAVE;
      end
      --"Lan?amento on-line ?NICO folha" para "Copia lan?amento on-line ?NICO folha"
      else if (WTIPOLAN = 200) then
        begin
          update VSUC_EMPRESAS_TLAN set BDTIPOLAN = 33
          where BDCODEMP = :WCODEMPBACKUP and
                BDCHAVE = :WCHAVE;
        end
     --"Lan?amento on-line ?NICO financeiro" para "Copia lan?amento on-line ?NICO financeiro"
        else if (WTIPOLAN = 3000) then
          begin
            update VSUC_EMPRESAS_TLAN set BDTIPOLAN = 35
            where BDCODEMP = :WCODEMPBACKUP and
                  BDCHAVE = :WCHAVE;
          end
    end

    --Leva os zeramentos da empresa original para a backup, pois na original n?o faz sentido ter mais
    execute statement 'update VSUC_EMPRESAS_TENCEXE set BDCODEMP = '||:WCODEMPBACKUP||' where BDCODEMP = '||:WCODEMP||' and BDDATAFIMZER <= '''||:WDATA||'''';
        
    --Incrementa a quantidade de backups na empresa original
    execute statement 'update TEMPRESAS set BDQTDBACKUPEMP = (BDQTDBACKUPEMP + 1) where BDCODEMP = ' || :WCODEMP;

    --Se a empresa usar o lalur, o c?digo do lalur deve ser alterado na empresa original a partir do per?odo da recontabiliza??o em diante
    if ((PRCODCONTABLALUR <> 0) and not(PRCODCONTABLALUR is null)) then
      execute statement 'update TEMPRESAS_REF set BDCODCONTABLALUR = '||:PRCODCONTABLALUR||' where BDCODEMP = '||:WCODEMP||' and BDREFEMP > '||:PRREFEMP;

    --Adiciona na tabela os processos de backup efetuados
    execute statement 'update or insert into TEMPRESAS_BACKUP_ONLINE (BDCODEMP, BDCODPLANOONLINEDE, BDCODEMPBKP, BDCODPLANOONLINEPARA, '||
                                             'BDCODUSU, BDREFPROCESSO, BDDATA, BDHORA, BDCODUSUINTRANET, BDNOMUSUINTRANET) '||
                      'values('||:WCODEMP||','||:PRCODPLANOONLINEDE||','||:WCODEMPBACKUP||','||:PRCODPLANOONLINEPARA||','||:PRCODUSU||','
                               ||:PRREFEMP||','''||current_date||''','''||current_time||''','||:PRCODUSUINTRANET||','''||PRNOMUSUINTRANET||''')'||
                      'matching (BDCODEMP)';

    --Adiciona no log a c?pia efetuada
    WSQLINSERT = 'Efetuada c?pia da empresa: '||:WCODEMP||'.
'              ||'Empresa gerada: '||:WCODEMPBACKUP||'.
'              ||'Lan?amentos at? o per?odo: '||:PRREFEMP;

    execute procedure SP_INSERIR_LOG(WCODEMP, NULL, PRCODUSU, NULL, 4, NULL, cast(addday(:wdata, 1) as date), WTEMPOINI, WSQLINSERT, 0, 0,
                                     CURRENT_USER, 'SERVIDOR', 'TfrProcessoTrocaPlanoContabilizacao', 'Processo de troca de contabiliza??o',
                                     NULL, 'TEMPRESAS', NULL, 'FALSE', cast(addday(:wdata, 1) as date));
  end
end
^

/* Alter (SP_CRIA_DADOSCALC_BAIXA) */
ALTER PROCEDURE SP_CRIA_DADOSCALC_BAIXA AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WLIQUIDO NUMERIC(18,6);
DECLARE VARIABLE WREFCOMP INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WDATAAUX DATE;
BEGIN
  /* Procedure Text */
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdcodemp IS NOT NULL;

  /* 1 - Terceiros */
  FOR SELECT bdcodemp,bdcodter,bdcodserv,bdliquido FROM vrhf_base_calc_terc
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp, wcodcol, wreferencia,NULL,1,NULL,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 2 - 13? salario */
  FOR SELECT bdcodemp,bdcodcol,bdref13,bdliquido FROM vrhf_emp_t13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,2,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 3 -  ad 13? */
  FOR SELECT bdcodemp,bdcodcol,bdrefa13,bdliquido FROM vrhf_emp_ta13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,3,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 4 -  ad sal */
  FOR SELECT bdcodemp,bdcodcol,BDDATAAD,bdliquido FROM vrhf_emp_tadsal
   INTO
     :wcodemp,
     :wcodcol,
     :wdata,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,4,NULL,wdata,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 5 -  c 13? */
  FOR SELECT bdcodemp,bdcodcol,bdrefc13,bdref13,bdliquido FROM vrhf_emp_tc13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wrefcomp,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,5,wreferencia,NULL,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 6 - folha normal*/
  FOR SELECT bdcodemp,bdcodcol,bdreffn,bdliquido FROM vrhf_emp_tfolhanormal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,6,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 7 - folha normal tomador */
  FOR SELECT bdcodemp,bdcodcol,bdreftomador,bdliquido FROM vrhf_emp_tfolhatomador
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,7,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 8 -  fc */
  FOR SELECT bdcodemp,bdcodcol,bdreffn,bdrefcomp,bdliquido,bddatapagfc FROM vrhf_emp_tfolhacomp
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wrefcomp,
     :wliquido,
     :wdata
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,8,wreferencia,wdata,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 9 -  fct */
  FOR SELECT x.bdcodemp,x.bdcodcol,x.bdreftomador,x.bdliquido,x.bdrefcomp,x.bddatapagfc FROM vrhf_emp_tfoltomcomp x
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido,
     :wrefcomp,
     :wdata
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,9,wreferencia,wdata,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 10 -  f?rias */
  FOR SELECT x.bdcodemp,x.bdcodcol,x.bdliquido,x.bdiniperaquisfe,x.bdcodfe,x.bdiniperaquisfe,x.bdrefpagabofe FROM VRH_EMP_TFERIAS x
   INTO
     :wcodemp,
     :wcodcol,
     :wliquido,
     :wdata,
     :wreferencia,
     :wdataaux,
     :wrefcomp
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,10,NULL,NULL,NULL,wdata,wreferencia,wliquido,wdataaux,wrefcomp);
  END
END
^

/* Alter (SP_CRIA_PRE_CONTABILIZACAO) */
ALTER PROCEDURE SP_CRIA_PRE_CONTABILIZACAO(PRSESSAO INTEGER,
PRCODPLANOONLINE INTEGER,
PRENQFED INTEGER,
PRCODCONFIRLP INTEGER)
 AS
DECLARE VARIABLE WTIPOINTCOF INTEGER;
DECLARE VARIABLE WTIPOINTPIS INTEGER;
DECLARE VARIABLE WTIPOINTICMS INTEGER;
DECLARE VARIABLE WTIPOINTIPI INTEGER;
DECLARE VARIABLE wEF INTEGER;
BEGIN
  /*
    BDORD - Campo para ordernar a contabiliza??o
    ******************Legenda*******************
    1 - Valor cont?bil com desconto
    2 - desconto
    3 - Impostos
    4 - Reten??es
    5 - Diferen?a
    6 - Outras CFOPS
  */
  DELETE FROM TMP_TLANC_CONTABILIZACAO_TEMP WHERE BDSESSAO = :PRSESSAO;

  SELECT o.bdtipointcofins, o.bdtipointpis,
         o.bdtipointicms, o.bdtipointipi
  FROM TPLANO_CONF_ONLINE O
  WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :wTipoIntCof, :wTipoIntPis, :wTipoIntIcms, :wTipoIntIpi;

  wEF = 3;

  /*Monta a contabiliza??o na tabela TMP_TLANC_CONTABILIZACAO_TEMP faltando preencher apenas a chave do cont?bil e a transa??o*/

  /*----------------------------------------------------Valor cont?bil------------------------------------------------------------*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEM, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU,
         IIF((MOV.BDTOTALRET = 0), MOV.BDCONTADEBPROV, NULL) BDCONTADEBPROV, /*Quanto tem reten??o s? contabiliza com a conta cr?dito*/
         MOV.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAEMISSAO, MOV.BDVLRCONTAB,
         MOV.BDTIPOLAN, MOV.BDNUMDOCINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE, MOV.BDCHAVECONF,
         MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVE, MOV.BDCODTPHI, 1 BDORD /*Campo para ordena??o da contabiliza??o*/
  FROM (
        SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
               I.BDCOMPHIST_VLRCONTAB, S.BDDATAEMISSAO, I.BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO,
               'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
               C.BDCHAVE, C.BDCODTPHI, (COALESCE(R.BDVLRPIS, 0) + COALESCE(R.BDVLRCOFINS, 0) +
                                        COALESCE(R.BDVLRCSOCIAL, 0) + COALESCE(R.BDVLRIR, 0) +
                                        COALESCE(R.BDINSSRET, 0) + COALESCE(R.BDISSRET, 0)) BDTOTALRET, S.BDDESCONTONOTA
        FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
        JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
        --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (111, 117, 170))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
        JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111 /*Valor cont?bil - A vista*/
                                                                                            WHEN s.BDCONDPGTO = 1 THEN 117 /*Valor cont?bil - Prazo*/
                                                                                            WHEN s.BDCONDPGTO = 2 THEN 170 /*Valor cont?bil - Outras*/
                                                                                       END))
        LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDCODITEMONLINE = 88 AND CD.BDCONTADEBPROV IS NOT NULL)
        LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE AND R.BDSESSAO = I.BDSESSAO)
        /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
        LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
        WHERE I.BDSESSAO = :PRSESSAO
        AND (((S.BDDESCONTONOTA = 0) OR (S.BDDESCONTONOTA IS NULL)) OR (CD.BDCHAVE IS NULL))
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
        AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
        AND NOT EXISTS(
                       SELECT INCO.BDCODINCONSISTENCIA
                       FROM VEF_INCON_TMOVSAI INCO
                       WHERE INCO.BDCODEMP = I.BDCODEMP
                       AND   INCO.BDCHAVE  = I.BDCHAVE
                       AND   INCO.BDSESSAO = I.BDSESSAO
                      )
       ) MOV
  WHERE MOV.BDORDEM = 1; /*Contabiliza??o das reten??es fica na primeira ordem*/

  /*Valor cont?bil de quanto o lan?amento tem desconto*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEM, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU,
         MOV.BDCONTADEBPROV, NULL BDCONTACREDPROV/*MOV.BDCONTACREDPROV*/, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAEMISSAO, MOV.BDVLRCONTAB,
         MOV.BDTIPOLAN, MOV.BDNUMDOCINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE, MOV.BDCHAVECONF,
         MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVE, MOV.BDCODTPHI, 1 BDORD
  FROM (
        SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
               I.BDCOMPHIST_VLRCONTAB, S.BDDATAEMISSAO, I.BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO,
               'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
               C.BDCHAVE, C.BDCODTPHI, (COALESCE(R.BDVLRPIS, 0) + COALESCE(R.BDVLRCOFINS, 0) +
                                        COALESCE(R.BDVLRCSOCIAL, 0) + COALESCE(R.BDVLRIR, 0) +
                                        COALESCE(R.BDINSSRET, 0) + COALESCE(R.BDISSRET, 0)) BDTOTALRET, S.BDDESCONTONOTA
        FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
        JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
        --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (111, 117, 170))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
        JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111 /*Valor cont?bil - A vista*/
                                                                                            WHEN s.BDCONDPGTO = 1 THEN 117 /*Valor cont?bil - Prazo*/
                                                                                            WHEN s.BDCONDPGTO = 2 THEN 170 /*Valor cont?bil - Outras*/
                                                                                       END))
        LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDCODITEMONLINE = 88 AND CD.BDCONTADEBPROV IS NOT NULL)
        LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE AND R.BDSESSAO = I.BDSESSAO)
        /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
        LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
        WHERE I.BDSESSAO = :PRSESSAO
        AND S.BDDESCONTONOTA > 0 /*Somente lan?amentos que tem desconto*/
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
        AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
        AND CD.BDCHAVE IS NOT NULL /*Verifica sem tem conta de desconto*/
        AND NOT EXISTS(
                       SELECT INCO.BDCODINCONSISTENCIA
                       FROM VEF_INCON_TMOVSAI INCO
                       WHERE INCO.BDCODEMP = I.BDCODEMP
                       AND   INCO.BDCHAVE  = I.BDCHAVE
                       AND   INCO.BDSESSAO = I.BDSESSAO
                      )
       )  MOV
  WHERE MOV.BDORDEM = 1
  AND MOV.BDTOTALRET = 0;

  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEM, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU,
         MOV.BDCONTADEBPROV,MOV.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAEMISSAO, MOV.BDVLRCONTAB,
         MOV.BDTIPOLAN, MOV.BDNUMDOCINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE, MOV.BDCHAVECONF,
         MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVE, MOV.BDCODTPHI, 5 BDORD
  FROM (
        SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
               I.BDCOMPHIST_VLRCONTAB, S.BDDATAEMISSAO, I.BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO,
               'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
               C.BDCHAVE, C.BDCODTPHI
        FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
        JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
        --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (111, 117, 170))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
        JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111 /*Valor cont?bil - A vista*/
                                                                                            WHEN s.BDCONDPGTO = 1 THEN 117 /*Valor cont?bil - Prazo*/
                                                                                            WHEN s.BDCONDPGTO = 2 THEN 170 /*Valor cont?bil - Outras*/
                                                                                       END))
        /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
        LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
        WHERE I.BDSESSAO = :PRSESSAO
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
        AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
        AND NOT EXISTS(
                       SELECT INCO.BDCODINCONSISTENCIA
                       FROM VEF_INCON_TMOVSAI INCO
                       WHERE INCO.BDCODEMP = I.BDCODEMP
                       AND   INCO.BDCHAVE  = I.BDCHAVE
                       AND   INCO.BDSESSAO = I.BDSESSAO
                      )
       ) MOV
  WHERE MOV.BDORDEM > 1;

  /*------------------------------------------------------------------------------------------------------------------------------*/
  /*--------------------------------------------------------Impostos--------------------------------------------------------------*/
  /********************************************************************************************************************************/
  IF (:wTipoIntIcms = 0) THEN /*Icms e Icms ST nota a nota*/
    BEGIN
      IF (:PRENQFED NOT IN(1, 2)) THEN /*Empresas do simples nacional n?o contabilizam ICMS, PIS, Cofins e IPI. Somente ICMS ST*/
        BEGIN
          /*------------------------------------------------------ICMS----------------------------------------------------------------*/
          INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                    bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                    bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
          SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
                 I.BDCOMPHIST_VLRICMS, S.BDDATAEMISSAO, I.BDVLRICMS, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE,
                 C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 3 BDORD
          FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
          JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
          --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (112, 118, 171))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
          JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 112 /*ICMS - A vista*/
                                                                                              WHEN s.BDCONDPGTO = 1 THEN 118 /*ICMS - Prazo*/
                                                                                              WHEN s.BDCONDPGTO = 2 THEN 171 /*ICMS - Outras*/
                                                                                         END))
          /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
          LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
          WHERE I.BDSESSAO = :PRSESSAO
          AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
          AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
          AND I.BDVLRICMS > 0
          AND NOT EXISTS(
                         SELECT INCO.BDCODINCONSISTENCIA
                         FROM VEF_INCON_TMOVSAI INCO
                         WHERE INCO.BDCODEMP = I.BDCODEMP
                         AND   INCO.BDCHAVE  = I.BDCHAVE
                         AND   INCO.BDSESSAO = I.BDSESSAO
                        );
          /*--------------------------------------------------------------------------------------------------------------------------*/
        END

      /*------------------------------------------------------ICMS ST-------------------------------------------------------------*/
      INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
      SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
             I.BDCOMPHIST_VLRICMSST, S.BDDATAEMISSAO, I.BDVLRST, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE,
             C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 3 BDORD
      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
      --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (113, 119, 172))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
      JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 113 /*ICMS ST - A vista*/
                                                                                          WHEN s.BDCONDPGTO = 1 THEN 119 /*ICMS ST - Prazo*/
                                                                                          WHEN s.BDCONDPGTO = 2 THEN 172 /*ICMS ST - Outras*/
                                                                                     END))   
      /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
      WHERE I.BDSESSAO = :PRSESSAO
      AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
      AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
      AND I.BDVLRST > 0
      AND NOT EXISTS(
                     SELECT INCO.BDCODINCONSISTENCIA
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND   INCO.BDCHAVE  = I.BDCHAVE
                     AND   INCO.BDSESSAO = I.BDSESSAO
                    );
      /*--------------------------------------------------------------------------------------------------------------------------*/
    END

  IF ((:wTipoIntIpi = 0) AND (:PRENQFED NOT IN(1, 2))) THEN /*Ipi nota a nota*/ /*Empresas do simples nacional n?o contabilizam ICMS, PIS, Cofins e IPI. Somente ICMS ST*/
    BEGIN
      /*--------------------------------------------------------IPI---------------------------------------------------------------*/
      INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
      SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
             I.BDCOMPHIST_VLRIPI, S.BDDATAEMISSAO, I.BDVLRIPI, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE,
             C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 3 BDORD
      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
      --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (114, 120, 173))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
      JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 114 /*IPI - A vista*/
                                                                                          WHEN s.BDCONDPGTO = 1 THEN 120 /*IPI - Prazo*/
                                                                                          WHEN s.BDCONDPGTO = 2 THEN 173 /*IPI - Outras*/
                                                                                     END))
      /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
      WHERE I.BDSESSAO = :PRSESSAO
      AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
      AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
      AND I.BDVLRIPI > 0
      AND NOT EXISTS(
                     SELECT INCO.BDCODINCONSISTENCIA
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND   INCO.BDCHAVE  = I.BDCHAVE
                     AND   INCO.BDSESSAO = I.BDSESSAO
                    );
      /*--------------------------------------------------------------------------------------------------------------------------*/
    END

  IF ((:wTipoIntPis = 0) AND (:PRENQFED NOT IN(1, 2)) AND ((:PRCODCONFIRLP IS NULL) OR (:PRCODCONFIRLP = 0))) THEN /*Pis nota a nota*/ /*Empresas do simples nacional n?o contabilizam ICMS, PIS, Cofins e IPI. Somente ICMS ST*/
    BEGIN
      /*--------------------------------------------------------PIS---------------------------------------------------------------*/
      INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
      SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
             I.BDCOMPHIST_VLRPIS, S.BDDATAEMISSAO, I.BDVLRPIS, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE,
             C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 3 BDORD
      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
      --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (115, 121, 174))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
      JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 115 /*PIS - A vista*/
                                                                                          WHEN s.BDCONDPGTO = 1 THEN 121 /*PIS - Prazo*/
                                                                                          WHEN s.BDCONDPGTO = 2 THEN 174 /*PIS - Outras*/
                                                                                     END))
      /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
      WHERE I.BDSESSAO = :PRSESSAO
      AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
      AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
      AND I.BDVLRPIS > 0
      AND NOT EXISTS(
                     SELECT INCO.BDCODINCONSISTENCIA
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND   INCO.BDCHAVE  = I.BDCHAVE
                     AND   INCO.BDSESSAO = I.BDSESSAO
                    );
      /*--------------------------------------------------------------------------------------------------------------------------*/
    END

  IF ((:wTipoIntCof = 0) AND (:PRENQFED NOT IN(1, 2)) AND ((:PRCODCONFIRLP IS NULL) OR (:PRCODCONFIRLP = 0))) THEN /*Cofins nota a nota*/ /*Empresas do simples nacional n?o contabilizam ICMS, PIS, Cofins e IPI. Somente ICMS ST*/
    BEGIN
      /*-------------------------------------------------------Cofins-------------------------------------------------------------*/
      INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
      SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
             I.BDCOMPHIST_VLRCOFINS, S.BDDATAEMISSAO, I.BDVLRCOFINS, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE,
             C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 3 BDORD
      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
      --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (116, 122, 175))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
      JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 116 /*Cofins - A vista*/
                                                                                          WHEN s.BDCONDPGTO = 1 THEN 122 /*Cofins - Prazo*/
                                                                                          WHEN s.BDCONDPGTO = 2 THEN 175 /*Cofins - Outras*/
                                                                                     END))
      /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
      WHERE I.BDSESSAO = :PRSESSAO
      AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
      AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
      AND I.BDVLRCOFINS > 0
      AND NOT EXISTS(
                     SELECT INCO.BDCODINCONSISTENCIA
                     FROM VEF_INCON_TMOVSAI INCO
                     WHERE INCO.BDCODEMP = I.BDCODEMP
                     AND   INCO.BDCHAVE  = I.BDCHAVE
                     AND   INCO.BDSESSAO = I.BDSESSAO
                    );
    END
  /*--------------------------------------------------------------------------------------------------------------------------*/
  /****************************************************************************************************************************/
  /*------------------------------------------------------Reten??es-----------------------------------------------------------*/

  /*Reten??o de pis*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, NULL BDCONTACREDPROV,
         I.BDCOMPHIST_VLRPISRET, S.BDDATAEMISSAO, R.BDVLRPIS, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA,
         :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 4 BDORD
  FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
  LEFT OUTER JOIN (
                   SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRPISRET
                   FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                   WHERE I.BDSESSAO = :PRSESSAO
                   AND I.BDORDEM = 1
                   ORDER BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM
                  ) I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = I.BDSESSAO)
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO)
  JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODREC = R.BDCODRECPIS AND C.BDCODITEMONLINE = 89)
  /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
  LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
  WHERE R.BDSESSAO = :PRSESSAO
  AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
  AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
  AND NOT EXISTS(
                 SELECT INCO.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI INCO
                 WHERE INCO.BDCODEMP = I.BDCODEMP
                 AND INCO.BDCHAVE = I.BDCHAVE
                 AND INCO.BDSESSAO = I.BDSESSAO
                );

  /*Reten??o de cofins*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, NULL BDCONTACREDPROV,
         I.BDCOMPHIST_VLRCOFRET, S.BDDATAEMISSAO, R.BDVLRCOFINS, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA,
         :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 4 BDORD
  FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
  LEFT OUTER JOIN (
                   SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRCOFRET
                   FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                   WHERE I.BDSESSAO = :PRSESSAO
                   AND I.BDORDEM = 1
                   ORDER BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM
                  ) I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = I.BDSESSAO)
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO)
  JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODREC = R.BDCODRECCOFINS AND C.BDCODITEMONLINE = 90)
  /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
  LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
  WHERE R.BDSESSAO = :PRSESSAO
  AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
  AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
  AND NOT EXISTS(
                 SELECT INCO.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI INCO
                 WHERE INCO.BDCODEMP = I.BDCODEMP
                 AND INCO.BDCHAVE = I.BDCHAVE
                 AND INCO.BDSESSAO = I.BDSESSAO
                );

  /*Reten??o de contribui??o social*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, NULL BDCONTACREDPROV,
         I.BDCOMPHIST_VLRCSRET, S.BDDATAEMISSAO, R.BDVLRCSOCIAL, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA,
         :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 4 BDORD
  FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
  LEFT OUTER JOIN (
                   SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRCSRET
                   FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                   WHERE I.BDSESSAO = :PRSESSAO
                   AND I.BDORDEM = 1
                   ORDER BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM
                  ) I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = I.BDSESSAO)
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO)
  JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODREC = R.BDCODRECCSOCIAL AND C.BDCODITEMONLINE = 91)
  /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
  LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
  WHERE R.BDSESSAO = :PRSESSAO
  AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
  AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
  AND NOT EXISTS(
                 SELECT INCO.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI INCO
                 WHERE INCO.BDCODEMP = I.BDCODEMP
                 AND INCO.BDCHAVE = I.BDCHAVE
                 AND INCO.BDSESSAO = I.BDSESSAO
                );

  /*Reten??o de imposto de renda*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, NULL BDCONTACREDPROV,
         I.BDCOMPHIST_VLRIRRET, S.BDDATAEMISSAO, R.BDVLRIR, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA,
         :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 4 BDORD
  FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
  LEFT OUTER JOIN (
                   SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRIRRET
                   FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                   WHERE I.BDSESSAO = :PRSESSAO
                   AND I.BDORDEM = 1
                   ORDER BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM
                  ) I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = I.BDSESSAO)
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO)
  JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODREC = R.BDCODRECIR AND C.BDCODITEMONLINE = 92)
  /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
  LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
  WHERE R.BDSESSAO = :PRSESSAO
  AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
  AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
  AND NOT EXISTS(
                 SELECT INCO.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI INCO
                 WHERE INCO.BDCODEMP = I.BDCODEMP
                 AND INCO.BDCHAVE = I.BDCHAVE
                 AND INCO.BDSESSAO = I.BDSESSAO
                );

  /*Reten??o de inss*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, NULL BDCONTACREDPROV,
         I.BDCOMPHIST_VLRINSSRET, S.BDDATAEMISSAO, R.BDINSSRET, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA,
         :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 4 BDORD
  FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
  LEFT OUTER JOIN (
                   SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRINSSRET
                   FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                   WHERE I.BDSESSAO = :PRSESSAO
                   AND I.BDORDEM = 1
                   ORDER BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM
                  ) I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = I.BDSESSAO)
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO)
  JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODREC = R.BDCODRECINSS AND C.BDCODITEMONLINE = 93)
  /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
  LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
  WHERE R.BDSESSAO = :PRSESSAO
  AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
  AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
  AND NOT EXISTS(
                 SELECT INCO.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI INCO
                 WHERE INCO.BDCODEMP = I.BDCODEMP
                 AND INCO.BDCHAVE = I.BDCHAVE
                 AND INCO.BDSESSAO = I.BDSESSAO
                );
  /*------------------------------------------------------------Diferen?a do valor cont?bil---------------------------------------------------*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEM, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU,
         MOV.BDCONTADEBPROV, NULL BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAEMISSAO, (COALESCE(MOV.BDVLRCONTAB, 0) - COALESCE(MOV.BDTOTALRET, 0)) BDVLRCON,
         MOV.BDTIPOLAN, MOV.BDNUMDOCINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE, MOV.BDCHAVECONF,
         MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVE, MOV.BDCODTPHI, 4 BDORD
  FROM (
        SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
               I.BDCOMPHIST_VLRCONTAB, S.BDDATAEMISSAO, I.BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO,
               'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
               C.BDCHAVE, C.BDCODTPHI, (COALESCE(R.BDVLRPIS, 0) + COALESCE(R.BDVLRCOFINS, 0) +
                                        COALESCE(R.BDVLRCSOCIAL, 0) + COALESCE(R.BDVLRIR, 0) +
                                        COALESCE(R.BDINSSRET, 0) + COALESCE(R.BDISSRET, 0)) BDTOTALRET
        FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
        JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
        --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (111, 117, 170))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
        JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111 /*Valor cont?bil - A vista*/
                                                                                            WHEN s.BDCONDPGTO = 1 THEN 117 /*Valor cont?bil - Prazo*/
                                                                                            WHEN s.BDCONDPGTO = 2 THEN 170 /*Valor cont?bil - Outras*/
                                                                                       END))
        LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE AND R.BDSESSAO = I.BDSESSAO)
        /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
        LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = :wEF)
        WHERE I.BDSESSAO = :PRSESSAO
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
        AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
        AND NOT EXISTS(
                       SELECT INCO.BDCODINCONSISTENCIA
                       FROM VEF_INCON_TMOVSAI INCO
                       WHERE INCO.BDCODEMP = I.BDCODEMP
                       AND   INCO.BDCHAVE  = I.BDCHAVE
                       AND   INCO.BDSESSAO = I.BDSESSAO
                      )
       ) MOV
      WHERE MOV.BDTOTALRET > 0
      AND MOV.BDORDEM = 1;
  /*------------------------------------------------------------------------------------------------------------------------------------------*/

  /*----------------------------------------------------------------Desconto------------------------------------------------------------------*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV,
         I.BDCOMPHIST_VLRDESCONTO, S.BDDATAEMISSAO, S.BDDESCONTONOTA, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO,
         'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
         C.BDCHAVE, C.BDCODTPHI, 2 BDORD
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE AND I.BDSESSAO = S.BDSESSAO AND I.BDORDEM = 1)
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = S.BDSESSAO)
  JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODITEMONLINE = 88 AND C.BDCONTADEBPROV IS NOT NULL)
  /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
  LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = :wEF)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
        AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
  AND S.BDDESCONTONOTA > 0;

  /*Contabiliza vlrcontab + desconto*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                            bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                            bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord)
  SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, NULL BDCONTADEBPROV, C.BDCONTACREDPROV,
         I.BDCOMPHIST_VLRCONTAB, S.BDDATAEMISSAO, (COALESCE(I.BDVLRCONTAB, 0) + COALESCE(S.BDDESCONTONOTA, 0)) BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO,
         'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
         C.BDCHAVE, C.BDCODTPHI, 1 BDORD
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE AND I.BDSESSAO = S.BDSESSAO AND I.BDORDEM = 1)
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = S.BDSESSAO)
  --JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE IN (111, 117, 170))) -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
  JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111 /*Valor cont?bil - A vista*/
                                                                                      WHEN s.BDCONDPGTO = 1 THEN 117 /*Valor cont?bil - Prazo*/
                                                                                      WHEN s.BDCONDPGTO = 2 THEN 170 /*Valor cont?bil - Outras*/
                                                                                 END))
  LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDCODITEMONLINE = 88 AND CD.BDCONTADEBPROV IS NOT NULL)
  /*Sa?da olha data de emiss?o, ao fazer a contabiliza??o de entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
  LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = :wEF)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDCODSITNF NOT IN (2, 3, 4, 5)
  AND ((IC.BDCODEMP IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO)))
  AND S.BDDESCONTONOTA > 0
  AND CD.BDCHAVE IS NOT NULL; /*Verifica se tem conta desconto*/

END
^

/* Alter (SP_CRIA_REFERENCIA_COLCON_REF) */
ALTER PROCEDURE SP_CRIA_REFERENCIA_COLCON_REF(PRAAAAMM INTEGER,
PRWHERE VARCHAR(32000) = '')
 AS
DECLARE VARIABLE WTAB VARCHAR(300);
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WCOL INTEGER;
DECLARE VARIABLE WREFCOL INTEGER;
DECLARE VARIABLE WCRIARREF SMALLINT;
DECLARE VARIABLE WSQLNOMECAMPOS1 VARCHAR(120);
DECLARE VARIABLE WSQLNOMECAMPOS2 VARCHAR(150);
DECLARE VARIABLE WNCAMPO VARCHAR(300);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLI VARCHAR(30000);
BEGIN
  /* SQL que retorna o nome dos campos da tabela */
  wsqlnomecampos1 = 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE ';
  wsqlnomecampos2 = ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = '''||'RDB$FIELD_TYPE'||''') ORDER BY RDB$FIELD_POSITION';


  /* La?o das empresas */
  FOR EXECUTE STATEMENT 'select bdcodemp, bdcodcol from VRH_EMP_TCOLCON '||TRIM(prwhere) INTO :wemp, :wcol DO
  BEGIN
    wrefcol = NULL;
    SELECT MAX(BDREFCOL) FROM VRH_EMP_TCOLCON_REF WHERE BDCODEMP = :wemp AND BDCODCOL = :wcol AND BDREFCOL <= :praaaamm INTO :wrefcol;
    /* Verifica se a tabela VRH_EMP_TCOLCON_REF tem refer?ncia informada. Sen?o tiver cria a refer?ncia */
    IF (wrefcol < praaaamm) THEN
      wcriarref = 1;
    ELSE
      wcriarref = 0;

    wsql = '';
    IF (wcriarref = 1) THEN
      BEGIN
        wsql  = 'insert into VRH_EMP_TCOLCON_REF (BDCODEMP,BDCODCOL,BDREFCOL';
        wsqli = 'select BDCODEMP,BDCODCOL,'||praaaamm;
        FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||'VRH_EMP_TCOLCON_REF'||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
        BEGIN
          IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDCODCOL' AND wncampo <> 'BDREFCOL') THEN
            BEGIN
              wsql  = wsql||','||wncampo;
              wsqli = wsqli||','||wncampo;
            END
        END
        wsql  = wsql||') ';
        wsqli = wsqli||' from VRH_EMP_TCOLCON_REF where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDREFCOL = '||wrefcol;
        EXECUTE STATEMENT wsql||wsqli;
      END

    /* La?o com as tabelas que s?o dependentes da tabela VRH_EMP_TCOLCON_REF */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VRH_EMP_TCOLCON_REF'
    INTO :wtab DO
      BEGIN
        wrefcol = NULL;
        EXECUTE STATEMENT 'select MAX(BDREFCOL) from '||wtab||' where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDREFCOL <= '||praaaamm INTO :wrefcol;
        /* Verifica se a tabela tem refer?ncia informada. Sen?o tiver cria a refer?ncia */
        IF (wrefcol < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDCODCOL,BDREFCOL';
            wsqli = 'select BDCODEMP,BDCODCOL,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDCODCOL' AND wncampo <> 'BDREFCOL') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDREFCOL = '||wrefcol;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END
  END
END
^

/* Alter (SP_CRIA_REFERENCIA_EMPRESAS_REF) */
ALTER PROCEDURE SP_CRIA_REFERENCIA_EMPRESAS_REF(PRAAAAMM INTEGER,
PRWHERE VARCHAR(32000) = '')
 AS
DECLARE VARIABLE WTAB VARCHAR(300);
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WREFEMP INTEGER;
DECLARE VARIABLE WCRIARREF SMALLINT;
DECLARE VARIABLE WSQLNOMECAMPOS1 VARCHAR(120);
DECLARE VARIABLE WSQLNOMECAMPOS2 VARCHAR(150);
DECLARE VARIABLE WNCAMPO VARCHAR(300);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLI VARCHAR(30000);
BEGIN
  /* SQL que retorna o nome dos campos da tabela */
  wsqlnomecampos1 = 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE ';
  wsqlnomecampos2 = ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = '''||'RDB$FIELD_TYPE'||''') ORDER BY RDB$FIELD_POSITION';


  /* La?o das empresas */
  FOR EXECUTE STATEMENT 'select bdcodemp from TEMPRESAS '||TRIM(prwhere) INTO :wemp DO
  BEGIN
    wrefemp = NULL;
    SELECT MAX(BDREFEMP) FROM TEMPRESAS_REF WHERE BDCODEMP = :wemp AND BDREFEMP <= :praaaamm INTO :wrefemp;
    /* Verifica se a tabela TEMPRESAS_REF tem refer?ncia informada. Sen?o tiver cria a refer?ncia */
    IF (wrefemp < praaaamm) THEN
      wcriarref = 1;
    ELSE
      wcriarref = 0;

    wsql = '';
    IF (wcriarref = 1) THEN
      BEGIN
        wsql  = 'insert into tempresas_ref (BDCODEMP,BDREFEMP';
        wsqli = 'select BDCODEMP,'||praaaamm;
        FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||'TEMPRESAS_REF'||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
        BEGIN
          IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
            BEGIN
              wsql  = wsql||','||wncampo;
              wsqli = wsqli||','||wncampo;
            END
        END
        wsql  = wsql||') ';
        wsqli = wsqli||' from TEMPRESAS_REF where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
        EXECUTE STATEMENT wsql||wsqli;
      END

    /* La?o com as tabelas que s?o dependentes da tabela TEMPRESAS_REF */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_TEMPRESAS_REF'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MAX(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP <= '||praaaamm INTO :wrefemp;
        /* Verifica se a tabela tem refer?ncia informada. Sen?o tiver cria a refer?ncia */
        IF (wrefemp < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END


    /* La?o com as tabelas que s?o dependentes da tabela VEF_BASE_TEMPCADATV */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VEF_BASE_TEMPCADATV'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MAX(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP <= '||praaaamm INTO :wrefemp;
        /* Verifica se a tabela tem refer?ncia informada. Sen?o tiver cria a refer?ncia */
        IF (wrefemp < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END



    /* La?o com as tabelas que s?o dependentes da tabela VEF_BASE_TEMPPAREST */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VEF_BASE_TEMPPAREST'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MAX(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP <= '||praaaamm INTO :wrefemp;
        /* Verifica se a tabela tem refer?ncia informada. Sen?o tiver cria a refer?ncia */
        IF (wrefemp < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END
  END
END
^

/* Alter (SP_ELIMINA_DUPLICIDADE_IMP) */
ALTER PROCEDURE SP_ELIMINA_DUPLICIDADE_IMP(PRSESSAO INTEGER,
PRORIGEM VARCHAR(3))
 AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WSQL VARCHAR(500);
DECLARE VARIABLE WC INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCHAVES VARCHAR(200);
DECLARE VARIABLE WTABLE VARCHAR(200);
DECLARE VARIABLE WLISTACHAVE VARCHAR(200);
BEGIN
  PRORIGEM = UPPER(:PRORIGEM);

  IF (:PRORIGEM = 'SAI') THEN
    BEGIN
      wI = 1;
      WHILE (:wI <= 2) DO
        BEGIN
          wSQL =         ' SELECT S.BDCODEMP, LIST(S.BDCHAVE) FROM TMP_VEF_EMP_TMOVSAI_TEMP S ';
          wSQL = wSQL || ' WHERE S.BDSESSAO = '||:PRSESSAO;
          wSQL = wSQL || '   AND ((s.BDCHAVENFECANC IS NOT NULL) AND (s.BDDATACANC IS NOT NULL) AND (s.BDNUMDOCINI IS NOT NULL) AND (s.BDNUMDOCFIM IS NOT NULL)) '; -- Alt.: 18626 - N?o considerar eventos de cancelamento...
          wSQL = wSQL || ' GROUP BY S.BDCODEMP, S.BDDATAEMISSAO, S.BDNUMDOCINI, S.BDNUMDOCFIM, ';

          IF (:wI = 1) THEN
            wSQL = wSQL || '          S.BDSERIEORIGINAL, S.BDESPECIE, S.BDMODELO, S.BDNOMETER ';
          ELSE
            wSQL = wSQL || '          S.BDSERIEORIGINAL, S.BDESPECIE, S.BDMODELO, S.BDCNPJ ';

          wSQL = wSQL || ' HAVING COUNT(BDCHAVE) > 1 ';

          FOR EXECUTE STATEMENT :wSQL INTO :wCodEmp, :wListaChave DO
            BEGIN
              wChaves = '';
              wSQL =         ' SELECT SKIP 1 s.bdchave ';
              wSQL = wSQL || ' FROM TMP_VEF_EMP_TMOVSAI_TEMP S ';
              wSQL = wSQL || '               WHERE s.bdsessao = '||:PRSESSAO;
              wSQL = wSQL || '               AND s.bdcodemp = '||:wCodEmp;
              wSQL = wSQL || '               AND s.bdchave IN ('||:wListaChave||')';
              wSQL = wSQL || '               ORDER BY s.bdsessao, s.bdcodemp, s.bdchave';
    
              FOR EXECUTE STATEMENT :wSQL INTO :wC
              DO
                BEGIN
                  IF (:wChaves = '') THEN
                    wChaves = wChaves || :wC;
                  ELSE
                    wChaves = wChaves || ', '|| :wC;
                END
    
              FOR SELECT TRIM(RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME) AS BDTABLE
                  FROM RDB$RELATION_CONSTRAINTS, RDB$INDICES, RDB$RELATION_FIELDS
                  WHERE RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME LIKE '%TMP_%_TEMP%'
                  AND RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND RDB$RELATION_CONSTRAINTS.RDB$INDEX_NAME = RDB$INDICES.RDB$INDEX_NAME
                  AND RDB$RELATION_FIELDS.RDB$RELATION_NAME = RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_TCADPRO_INSUMOS_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_VEF_BASE_TNATOP_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_TTERCEIRO_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_TUNIDADEMEDIDA_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_TCADPRO_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME CONTAINING('SAI')
                  AND RDB$RELATION_FIELDS.RDB$FIELD_NAME = 'BDCHAVE'
                  GROUP BY RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME, RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME
                  ORDER BY RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME
                  INTO :wTable
              DO
                EXECUTE STATEMENT 'DELETE FROM '||:wTable||' T WHERE T.BDSESSAO = '||:PRSESSAO||' AND T.BDCODEMP = '||:wCodEmp||' AND T.BDCHAVE IN('||:wChaves||')';
            END
          wI = wI + 1;
        END
    END
END
^

/* Alter (SP_EXCLUI_VERBA_DE_TUDO) */
ALTER PROCEDURE SP_EXCLUI_VERBA_DE_TUDO(PRCODVER INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODVER INTEGER;
BEGIN
  wsql = 'select first 1 BDCODVER from ('||
         'select BDCODVER from VRHF_BASE_ITEMS_CALCTERC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TFICHAHE where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TFICHAHN where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TFICHAOUTRAS where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TFICHARV where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_THIST_FOLHACOMP where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TPLANLANC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TPLANLANC_ADSAL where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TPLANLANC_FA where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TRATEIO_VERBAS where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBA13 where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAA13 where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAAD where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAC13 where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFA where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFCTOMADOR where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFE where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFN where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFN_PREV_RESC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFT_PREV_RESC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAPREPFN where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBATOMADOR where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRH_EMP_TDEP_PENSAO where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRH_EMP_TPARCELAMENTOS where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVSCOL where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVNCOL where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVSEMP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVNEMP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVSEMP_ESP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_FUNCOES_TVNFUC where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_FUNCOES_TVSFUC where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_FUNCOES_TVSFUC_ESP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_BASE_TVERBASEMP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from TCONF_CONTAS_ONLINE where BDCODVER = '||prCODVER||' '||
     'union all '||
     'select BDCODVER from VRHF_EMP_TVERBAINT where BDCODVER = '||prCODVER||' '||
     'union all '||
     'select BDCODVER from VRHF_EMP_TVERBATOMINT where BDCODVER = '||prCODVER||' '||
     ')';

  EXECUTE STATEMENT wsql INTO :wcodver;

  IF (wcodver <> 0) THEN
     UPDATE VRH_BASE_TVERBAS SET BDDESCVER = '*** N?O UTILIZAR ***', BDDESCREDVER = '*** N?O UTILIZAR ***' WHERE BDCODVER = :prcodver;
  ELSE
     BEGIN
       -- 17901 | Marcelo B. M. | 08/06/2017 | Trocada ordem das tabelas
       DELETE FROM VRHF_BASE_TRUBRICAS_DOM_VER_PD WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TVERBAS WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TVERBAS_PADRAO WHERE BDCODVERPD = :prcodver;
       DELETE FROM VRHF_BASE_ITEMS_CALCTERC WHERE BDCODVER = :prcodver;       
       DELETE FROM VRHF_BASE_TVNPRES WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVNSIND WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVNTER WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSPRES WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSPRES_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSSIND WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSSIND_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSTER WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_CUSTOS_TVNCUSTO WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_CUSTOS_TVSCUSTO WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_CUSTOS_TVSCUSTO_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TFICHAHE WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TFICHAHN WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TFICHAOUTRAS WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TFICHARV WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_THIST_FOLHACOMP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TPLANLANC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TPLANLANC_ADSAL WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TPLANLANC_FA WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TRATEIO_VERBAS WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBA13 WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAA13 WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAA13_RAT WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAAD WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAC13 WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFA WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFCTOMADOR WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFE WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFN WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFN_PREV_RESC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFT_PREV_RESC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAPREPFN WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBARFE WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBATOMADOR WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBA_13_RAT WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVNCOL WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVNEMP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVSCOL WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVSEMP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVSEMP_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_VERBAS_GRCS WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_FUNCOES_TVNFUC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_FUNCOES_TVSFUC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_FUNCOES_TVSFUC_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_MTE_TVERBASCONF WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCALCVESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCALCVESP WHERE BDCODVERCVE = :prcodver;
       DELETE FROM VRH_BASE_TCONF_FICHA_HE WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCONF_FICHA_HN WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCONF_FICHA_RV WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TITENSBLUESOFT WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TNATUREZA_VERBAS_GRUPO WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPLACONFVERBAPONTOITEM WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPLANO_LPL_ITEM WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPLA_TSERV WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPREPESTAB WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPREPSIT WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPREPSIT WHERE BDCODVER15DIAS = :prcodver;
       DELETE FROM VRH_BASE_TPREPSIT_DIA WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPREPSIT_DIA WHERE BDCODVER15DIAS = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAESOCIAL_VER WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAES_VER_PD WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAS_DOM_VER WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAS_VERBA WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAS_VERBA_TP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TSALHORESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TSINDTREF WHERE BDVERFERIST = :prcodver;
       DELETE FROM VRH_BASE_TSINDTREF WHERE BDVERMULRESST = :prcodver;
       DELETE FROM VRH_BASE_TVERBASEMP_PADRAO WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVERBASEMP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TVERBASESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TVERBASESP WHERE BDCODVERESP = :prcodver;
       DELETE FROM VRH_EMP_CONF_VCON_VERBAS WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_EMP_TDEP_PENSAO WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_EMP_TPARCELAMENTOS WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_EMP_TPROCESSOS_VERBAS WHERE BDCODVERBA = :prcodver;
       DELETE FROM VRH_EMP_VERBA_RHNET WHERE BDCODVER = :prcodver;
       DELETE FROM TCONF_CONTAS_ONLINE WHERE BDCODVER = :prcodver;       
       DELETE FROM VRHF_EMP_TVERBAINT WHERE BDCODVER = :prcodver;       
       DELETE FROM VRHF_EMP_TVERBATOMINT WHERE BDCODVER = :prcodver;       
     END

END
^

/* Alter (SP_EXP_ATIVA_CONTABIL) */
ALTER PROCEDURE SP_EXP_ATIVA_CONTABIL(PRCODEMP INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRCODPLANOPADRAO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(BDREF VARCHAR(10),
BDREFINTEIRO INTEGER,
BDCODTPLABEM INTEGER,
BDCTALONBEM VARCHAR(40),
BDNOMTPLABEM VARCHAR(100),
BDCODNOMTPLABEM VARCHAR(110),
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDCODNOMBEM VARCHAR(210),
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDDEPRECIACAOPERIODO NUMERIC(18,6),
BDVALORBAIXAPERIODO NUMERIC(18,6),
BDDEPRECIACAOACUMULADA NUMERIC(18,6),
BDTAXA NUMERIC(9,6),
BDDATATAXADEP DATE,
BDVALORRESIDUAL NUMERIC(18,6),
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCTADEBITODEPRE INTEGER,
BDCTACREDITODEPRE INTEGER,
BDHISTORICODEPRE INTEGER,
BDCTADEBITOBAIXA INTEGER,
BDCTACREDITOBAIXA INTEGER,
BDHISTORICOBAIXA INTEGER,
BDCTADEBITODEPBAI INTEGER,
BDCTACREDITODEPBAI INTEGER,
BDHISTORICODEPBAI INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WDATINI DATE;
DECLARE VARIABLE WDATFIN DATE;
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WDEPMESBAIXABEM VARCHAR(5);
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,6);
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WVALORMENSAL NUMERIC(15,6);
DECLARE VARIABLE WDEPMESAQUIBEM VARCHAR(15);
DECLARE VARIABLE WDEPDIARIA VARCHAR(10);
DECLARE VARIABLE WDATORIAQUIBEM DATE;
DECLARE VARIABLE WNUMDIAS SMALLINT;
DECLARE VARIABLE WDIASNOMES SMALLINT;
DECLARE VARIABLE WDATAFIMDEP DATE;
DECLARE VARIABLE WVALORCORRIGIDOATUAL NUMERIC(15,6);
BEGIN
 --alt:8005 - Adicionado par?metros tbem.BDDEPMESAQUIBEM, tbem.BDDEPDIARIA, tbem.BDDATORIAQUIBEM, tbem.BDNUMDIAS. Pedro
 --alt:9598 - Adicionados par?metros tpcc.BDCODTPCC, tpcc.BDNOMCTA. Pedro
 wsql = 'select tbem.bdcodbem, tbem.BDNOMBEM, tpla.BDCODTPLA, tpla.bdctalon, tpla.bdnomcta, tpcc.BDCODTPCC, tpcc.BDNOMCTA, ';
 wsql = wsql||' tbem.BDDEPMESBAIXABEM, tbem.BDDEPMESAQUIBEM, tbem.BDDEPDIARIA, tbem.BDDATORIAQUIBEM, tbem.BDNUMDIAS ';
 wsql = wsql||' from empresas_tbem tbem ';
 wsql = wsql||' left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = ' || :prcodplanopadrao || ')' || ' and (tpla.bdcodplapadrao = tbem.bdcodplapadrao and tpla.bdcodtpla = tbem.bdcodtpla)) ';
 --alt:9598 - Adicionado left outer join para trazer a descri??o do centro de custos. Pedro
 wsql = wsql||' left outer join CENTROS_TPCC tpcc on (tpcc.BDCODCENTRO = tbem.BDCODCENTRO and tpcc.BDCODTPCC = tbem.BDCODTPCC) ';
 wsql = wsql||' where (tbem.bdcodemp = ' || :prcodemp || ') ';
 wsql = wsql||' and (tpla.bdctalon between '''|| prctalonini ||''' and '''|| prctalonfim ||''') ';
 wsql = wsql||' Order By tpla.bdctalon, tbem.bdcodbem asc ';

 --alt:14256 - 06/07/2016 - Alterados nomes dos campos para melhor distin??o, pois agora retorna v?rias contas. Pedro
 FOR EXECUTE STATEMENT wsql INTO :bdcodbem , :bdnombem,  :bdcodtplabem, :bdctalonbem, :bdnomtplabem, :bdcodtpcc, :bdnomtpcc, :wdepmesbaixabem, :wdepmesaquibem, :wdepdiaria, :wdatoriaquibem, :wnumdias DO
   BEGIN
     bddepreciacaoperiodo = 0;
     bdvalorbaixaperiodo = 0;
     bddepreciacaoacumulada = 0;

     wdatini = prdatainicial;
     wdatfin = addmonth(wdatini, 1)-1;

      WHILE (wdatfin <= prdatafinal) DO
       BEGIN
         bddepreciacaoperiodo = 0;
         bdvalorbaixaperiodo = 0;
         bddepreciacaoacumulada = 0;
         bdcodnombem = bdcodbem || ' -  ' || bdnombem;
         bdcodnomtplabem = bdcodtplabem || ' -  ' || bdnomtplabem; --alt:14256 - 06/07/2016 - Alterados nomes dos campos para melhor distin??o, pois agora retorna v?rias contas. Pedro
         bdrefinteiro = SUBSTRING(CAST(wdatfin AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wdatfin AS VARCHAR(10)) FROM 6 FOR 2);

         bdref = SUBSTRING(CAST(wdatfin AS VARCHAR(10)) FROM 6 FOR 2)||'/'|| SUBSTRING(CAST(wdatfin AS VARCHAR(10)) FROM 1 FOR 4);
         --alt:16006 - 18/11/2016 - Alterada regra para mostrar o valor compensado do que foi depreciado antes da baixa no campo "wdepreciacaoacumulada". Pedro
         --alt:8005 - Adicionado par?metros prvalorbaixa, prtotalmesesdepreciacao, prmesesdepreciados. Pedro
         /*SELECT prdepreciacaoperiodo "prdepreciacaoperiodo" , prvalorbaixa "prvalorbaixa" , PRDEPRECIACAOACUMULADAATUAL "prdepreciacaoacumuladaatual", PRDATABAIXA,
                prctadebitodepre, prtaxadepreciacaoanual, prdatataxadepreciacao, prvalorresidualcontabil, prvalorbaixa, prtotalmesesdepreciacao, prmesesdepreciados
                FROM sp_cons_calc_dep(:prcodemp, :bdcodbem, :wdatini, :wdatfin, 0, :prcontabilizacao)
                INTO :bddepreciacaoperiodo, :bdvalorbaixaperiodo, :wdepreciacaoacumulada, :wdatabaixa, :bdctadebitodepre, :bdtaxa, :bddatataxadep,
                     :bdvalorresidual, :wvalorbaixa, :wtotalmesesdepreciacao, :wmesesdepreciados;*/

         SELECT prdepreciacaoperiodo, prcompensacaobaixaperanterior, prdatabaixa, prctadebitodepre, prtaxadepreciacaoanual,
                prdatataxadepreciacao, prvalorresidualcontabil, prvalorbaixa, prtotalmesesdepreciacao, prmesesdepreciados
                FROM sp_cons_calc_dep(:prcodemp, :bdcodbem, :wdatini, :wdatfin, 0, :prcontabilizacao)
                INTO :bddepreciacaoperiodo, :wcompensacaobaixaperanterior, :wdatabaixa, :bdctadebitodepre, :bdtaxa,
                     :bddatataxadep, :bdvalorresidual, :wvalorbaixa, :wtotalmesesdepreciacao, :wmesesdepreciados;

         bdvalorbaixaperiodo = wvalorbaixa;
         --alt:8005 - Retira um m?s da contabiliza??o porque quando ? pra depreciar no m?s da aquisi??o do bem vem um m?s a mais do que deveria. Pedro
         --alt:9581 - Foi retirada essa verifica??o e deixado para sempre diminuir um m?s,
         --pois o datediff sempre retorna um m?s a mais e acaba causando diferen?a para os dois casos. Pedro
         --alt:13193 - 21/01/2016 - Trocado para FALSE novamente e adionada a mesma valida??o mais a baixo, pois estava com diverg?ncias de valores ainda. Pedro
         --alt:14624 - 27/05/2016 - Adicionada valida??o do "wdepmesbaixabem", porque se n?o for para depreciar no m?s da baixa, n?o deve subtrair um m?s, pois da procedure retorna zero meses depreciados, ficando com -1 meses depreciados aqui. Pedro
         IF ((UPPER(wdepmesaquibem) = 'FALSE') AND (UPPER(wdepmesbaixabem) = 'TRUE')) THEN
           wmesesdepreciados = wmesesdepreciados - 1;

         --alt:14256 - 06/07/2016 - Retirado este SQL e adicionado outro que j? retorna a data final da deprecia??o e todas as contas a serem lan?adas com os tratamentos feitos para buscar na deprecia??o, baixa ou prepara??o. Pedro
         -- gilberto - 03/02/2015 - ALT:#10901 - se o bem j? sofreu deprecia??o total, o valor da peprecia??o deve ser o valor da baixa, pois caso contr?rio o valor da deprecia??o ser? maior que o valor de aquisi??o do bem
         /*select first 1 tbem.BDDATORIAQUIBEM + ((100 / tdep.BDTAXADEP) * 365) + cast ((100 / tdep.BDTAXADEP) / 4 as Integer)
         from EMPRESAS_TBEM tbem
         inner join EMPRESAS_TDEPRECIACAO tdep on (tdep.BDCODEMP = tbem.BDCODEMP and tdep.BDCODBEM = tbem.BDCODBEM)
         where tbem.BDDATORIAQUIBEM <= :wdatfin
         and tbem.bdcodbem = :bdcodbem
         and tbem.BDCODEMP = :prcodemp
         order by tbem.BDDATORIAQUIBEM + ((100 / tdep.BDTAXADEP) * 365) + cast ((100 / tdep.BDTAXADEP) / 4 as Integer) desc
         into :wdatafimdep;*/

         --alt:14256 - 06/07/2016 - SQL que retorna a data final da deprecia??o e todas as contas a serem lan?adas com os tratamentos feitos para buscar na deprecia??o, baixa ou prepara??o. Pedro
         SELECT FIRST 1 bem.BDCODEMP, bem.BDCODBEM, bem.BDNOMBEM, bem.BDCODTPLA AS BDCODTPLABEM, bem.BDCODPLAPADRAO, COALESCE(bai.BDCODHIST, ibe.BDCODHIST),
          CASE WHEN dep.BDDATFIMCALCBEM IS NOT NULL THEN dep.BDDATFIMCALCBEM
               WHEN dep.BDCODDEP IS NOT NULL THEN DATEADD(MONTH, ((100 / dep.BDTAXADEP) * 12), bem.BDDATORIAQUIBEM)
               WHEN (bem.BDVIDAUTIL IS NOT NULL) AND (bem.BDVIDAUTIL > 0) THEN DATEADD(MONTH, bem.BDVIDAUTIL, bem.BDDATORIAQUIBEM) END AS BDDATAFINALCALCULO,
          CASE WHEN dep.BDCTADEBITODEPRE IS NULL THEN ibe.BDDEPDEBIBE ELSE dep.BDCTADEBITODEPRE END AS BDCTADEBITODEPRE, ibe.BDDEPCREIBE, ibe.BDDEPHISTIBE,
          COALESCE(bai.BDBAIDEPDEBBAI, ibe.BDBAIDEPDEBIBE), COALESCE(bai.BDBAIDEPCREBAI, ibe.BDBAIDEPCREIBE), COALESCE(bai.BDBAIDEPHISTBAI, ibe.BDBAIDEPHISTIBE),
          COALESCE(bai.BDBAIAQUIDEBBAI, ibe.BDBAIAQUIDEBIBE), COALESCE(bai.BDBAIAQUICREBAI, ibe.BDBAIAQUICREIBE), COALESCE(bai.BDBAIAQUIHISTBAI, ibe.BDBAIAQUIHISTIBE)
         FROM EMPRESAS_TBEM bem
         LEFT JOIN EMPRESAS_TDEPRECIACAO dep ON (dep.BDCODEMP = bem.BDCODEMP AND dep.BDCODBEM = bem.BDCODBEM AND dep.BDCONTABILIZACAO = :prContabilizacao AND
                                                 ((dep.BDDATINICALCBEM IS NULL) OR (dep.BDDATINICALCBEM <= :wdatfin)) AND
                                                 ((dep.BDDATFIMCALCBEM IS NULL) OR (dep.BDDATFIMCALCBEM >= :wdatfin)))
         LEFT JOIN EMPRESAS_TBAI bai ON (bai.BDCODEMP = bem.BDCODEMP AND bai.BDCODBEM = bem.BDCODBEM AND bai.BDCONTABILIZACAO = :prContabilizacao AND bai.BDDATBAI <= :wdatfin)
         LEFT JOIN EMPRESAS_TIBE ibe ON (ibe.BDCODEMP = bem.BDCODEMP AND ibe.BDCODPLAPADRAO = bem.BDCODPLAPADRAO AND ibe.BDCODTPLA = bem.BDCODTPLA AND ibe.BDCONTABILIZACAO = :prContabilizacao)
         WHERE bem.BDCODEMP = :prcodemp
           AND bem.BDCODBEM = :bdcodbem
         ORDER BY dep.BDDATFIMCALCBEM DESC, bai.BDDATBAI DESC
         INTO :prcodemp, :bdcodbem, :bdnombem, :bdcodtplabem,
              :bdcodplapadrao, :bdcodhist, :wdatafimdep,
              :bdctadebitodepre, :bdctacreditodepre, :bdhistoricodepre,
              :bdctadebitobaixa, :bdctacreditobaixa, :bdhistoricobaixa,
              :bdctadebitodepbai, :bdctacreditodepbai, :bdhistoricodepbai;
         --alt:14256 - Fim

         --alt:14624 - 27/05/2016 - Para a deprecia??o acumulada deve ser utilizado o valor retornado pela procedure. Pedro
         --if ((wdatafimdep is null) or (wdatafimdep < wdatfin)) then
         --   bddepreciacaoacumulada = bdvalorbaixaperiodo;

         --alt:14256 - 11/07/2016 - Voltada valida??o como era antes, apenas se h? baixa no per?odo, posteriormente ser? tratado a baixa antes ou depois do t?rmino da deprecia??o. Pedro
         IF (bdvalorbaixaperiodo > 0) THEN
         --if ((bdvalorbaixaperiodo > 0) and (not ((wdatafimdep is null) or (wdatafimdep < wdatfin)))) then
         ---------------------------------------------------------------------------------------------------------- gilberto - 03/02/2015 - ALT:#10901
           BEGIN
             --#alt:16963 - Removido o calculo do valor mensal, pois estava estourando a vari?vel e ela n?o estava sendo usada para mais nada. Ana - 27/01/2017
             --alt:8005 - Alterado porque estava trazendo a deprecia??o da baixa incorreta. Trazia a deprecia??o do valor do bem. Pedro
             --deprecia??o mensal
             --wvalormensal = (wvalorbaixa * bdtaxa / 100) / 12;

             --alt:8005 - Adiciona um m?s porque quando ? pra depreciar no m?s da baixa do bem vem com um m?s a menos do que deveria. Pedro
             --alt:9377 - Alterado de TRUE para FAlSE, pois aparentemente a regra estava invertida. Pedro
             --alt:9581 - Colocado True novamente, a deprecia??o foi recalculada e estava correta com True. Pedro
             --alt:13193 - 21/01/2016 - Adicionada valida??o do BDMESAQUIBEM tamb?m, pois estava com diverg?ncias de valores ainda. Pedro
             IF ((UPPER(wdepmesbaixabem) = 'TRUE') AND (UPPER(wdepmesaquibem) = 'FALSE')) THEN
                wmesesdepreciados = wmesesdepreciados + 1;
             --deprecia??o acumulada com o valor dos meses
             --alt:14624 - 27/05/2016 - Para a deprecia??o acumulada deve ser utilizado o valor retornado pela procedure. Pedro
             --bddepreciacaoacumulada = bddepreciacaoacumulada + (wvalormensal * wmesesdepreciados);

             --alt:14256 - 13/07/2016 - Retirado todo o calculo refeito aqui e simplesmente uso o valor da deprecia??o di?ria que a procedure j? me retorna corretamente. Pedro
             --deprecia no m?s de aquisi??o do bem e tem deprecia??o di?ria
             --(sempre vem com um m?s a mais quando ? pra depreciar no m?s de aquisi??o do bem, ent?o se n?o for di?ria n?o precisa calcular mais nada)
             /*IF ((UPPER(wdepmesaquibem) = 'TRUE') AND (UPPER(wdepdiaria) = 'TRUE')) THEN
                BEGIN
                  --se for para considerar o n?mero de dias no m?s
                  IF (wnumdias = 2) THEN
                     BEGIN
                       --alt:9581 - Alterada a vari?vel da quantidade de dias, pois estava causando erro na verifica??o do if acima quando tinha mais de uma baixa pro mesmo bem no per?odo selecionado. Pedro
                       wdiasnomes = (EXTRACT(DAY FROM (wdatoriaquibem - EXTRACT(DAY FROM wdatoriaquibem) + 32 - EXTRACT(DAY FROM wdatoriaquibem - EXTRACT(DAY FROM wdatoriaquibem) + 32))));
                       bddepreciacaoacumulada = bddepreciacaoacumulada + ((wvalormensal / wdiasnomes) * (wdiasnomes - CAST(SUBSTRING(wdatoriaquibem FROM 9 FOR 2) AS INTEGER) + 1));
                     END
                  --se for para considerar 30 dias em um m?s
                  ELSE
                     BEGIN
                       bddepreciacaoacumulada = bddepreciacaoacumulada + ((wvalormensal / 30) * (
                       (EXTRACT(DAY FROM (wdatoriaquibem - EXTRACT(DAY FROM wdatoriaquibem) + 32 - EXTRACT(DAY FROM wdatoriaquibem - EXTRACT(DAY FROM wdatoriaquibem) + 32))))
                       - CAST(SUBSTRING(wdatoriaquibem FROM 9 FOR 2) AS INTEGER) + 1));
                     END
                END*/

             --alt:14256 - 11/07/2016 - Alterada valida??o para s? buscar o valor da deprecia??o acumulada j? tenha encerrado a deprecia??o do bem. Pedro
             --#Alt:5105 -> Deprecia??o abaixada quando a op??o "Calcular deprecia??o no m?s da baixa" n?o esta selecionada
             --if (((wdepmesbaixabem = 'FALSE') or (wdepmesbaixabem is null)) and (bddepreciacaoacumulada = 0)) then
             IF ((wdatafimdep IS NOT NULL) AND (wdatafimdep < wdatfin) AND (COALESCE(wdepmesbaixabem, 'FALSE') <> 'TRUE')) THEN
               BEGIN
                 SELECT PRDEPRECIACAOACUMULADAATUAL "prdepreciacaoacumuladaatual"
                 FROM sp_cons_calc_dep(:prcodemp, :bdcodbem , addmonth(:wdatini,-1) , addmonth(:wdatfin,-1) ,0,:prcontabilizacao)
                 INTO :wcompensacaobaixaperanterior;
                 bddepreciacaoacumulada = bddepreciacaoacumulada + wcompensacaobaixaperanterior;
               END
             ELSE --alt:14624 - 27/05/2016 - Utiliza o valor retornado pela procedure para a deprecia??o acumulada, quando o bem ainda n?o foi totalmente depreciado. Pedro
               bddepreciacaoacumulada = bddepreciacaoacumulada + wcompensacaobaixaperanterior;
             --alt:8005 - Fim

             IF  (wdatabaixa BETWEEN :wdatini AND :wdatfin)  THEN
                 bdvalorbaixaperiodo = bdvalorbaixaperiodo;
             ELSE
                bdvalorbaixaperiodo = 0;
           END
         --bdctadebitodepre = wctadebitodepre;

         IF ((bddepreciacaoperiodo > 0) OR (bdvalorbaixaperiodo > 0)) THEN
            SUSPEND;

        wdatini = addmonth(wdatini, 1);
        wdatfin = addmonth(wdatini, 1)-1;
       END
   END
END
^

/* Alter (SP_EXP_SEFIP_REG_00) */
ALTER PROCEDURE SP_EXP_SEFIP_REG_00 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wdatarecinss DATE;
DECLARE VARIABLE wdatarecfgts DATE;
DECLARE VARIABLE windrecinss VARCHAR(1);
DECLARE VARIABLE windrecfgts VARCHAR(1);
DECLARE VARIABLE wmodalidade VARCHAR(1);
DECLARE VARIABLE wcodrec INTEGER;
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE waux VARCHAR(1000);
DECLARE VARIABLE wretorno VARCHAR(1000);
DECLARE VARIABLE wcnpjesc VARCHAR(1000);
DECLARE VARIABLE wnomesc VARCHAR(1000);
DECLARE VARIABLE wnomecont VARCHAR(1000);
DECLARE VARIABLE wlogra VARCHAR(1000);
DECLARE VARIABLE wbaiesc VARCHAR(1000);
DECLARE VARIABLE wcepesc VARCHAR(1000);
DECLARE VARIABLE wnomcid VARCHAR(1000);
DECLARE VARIABLE wsiglauf VARCHAR(1000);
DECLARE VARIABLE wfoneesc VARCHAR(1000);
DECLARE VARIABLE wemailesc VARCHAR(1000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wanomes INTEGER;
BEGIN
  SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_CODREC') FROM rdb$database INTO wcodrec;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_MODALIDADEATU') FROM rdb$database INTO WMODALIDADE;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_INDRECFGTS') FROM rdb$database INTO windrecfgts;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_INDRECINSS') FROM rdb$database INTO windrecinss;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_DATARECFGTS') FROM rdb$database INTO wDATArecfgts;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_DATARECINSS')FROM rdb$database INTO wDATArecinss;

  wordem = '0';

  IF (wcodrec IS NULL) THEN
     wcodrec = 0;

  IF (wemp IS NULL) THEN
     wemp = 0;

  wsql =  'select esc.bdcnpjesc, esc.bdnomesc, cp.bdnomecont, esc.bdlogresc||'||''''||' '||''''||'||esc.bdendesc bdlogra,'||
         'esc.bdbaiesc, esc.bdcepesc, cid.bdnomcid, uf.BDSIGLAUF, esc.bddddesc||'||''''||' '||''''||'||esc.bdfoneesc fone, esc.bdemailesc'||
         ' from vw_empresas_ref_atual emp left outer join tcontador_padrao cp on (cp.bdcodcont = emp.bdcodcont) left outer join tescritorio esc on (cp.bdcodesc = esc.bdcodesc) left outer join tcidade cid on (esc.bdcodcid = cid.bdcodcid) left outer join tuf uf on (cid.bdcoduf = uf.bdcoduf)'||
         ' where emp.bdcodemp = '||wemp;

  EXECUTE STATEMENT wsql INTO wcnpjesc, wnomesc, wnomecont, wlogra,wbaiesc, wcepesc, wnomcid, wSIGLAUF, wfoneesc, wemailesc;

    IF (wcnpjesc IS NULL) THEN
       wcnpjesc = '';
    IF (wnomesc IS NULL) THEN
       wnomesc = '';
    IF (wnomecont IS NULL) THEN
       wnomecont = '';
    IF (wlogra IS NULL) THEN
       wlogra = '';
    IF (wbaiesc IS NULL) THEN
       wbaiesc = '';
    IF (wcepesc IS NULL) THEN
       wcepesc = '';
    IF (wnomcid IS NULL) THEN
       wnomcid = '';
    IF (wSIGLAUF IS NULL) THEN
       wSIGLAUF = '';
    IF (wfoneesc IS NULL) THEN
       wfoneesc = '';
    IF (wemailesc IS NULL) THEN
       wemailesc = '';

  /* Procedure Text */
  --  001 a 002 002 N '00' tipo registro
  wRetorno = '00';

  --  003 a 053 051 A brancos
  SELECT bdretorno FROM preenche_direita('',51,' ') INTO waux;
  wRetorno = wRetorno||waux;

  --  054 a 054 001 N Tipo remessa Sefip = 1
  wRetorno = wRetorno||'1';

  waux = '';
  --  055 a 055 001 N Tipo inscri??o responsavel 1 = cnpj / 2 = cei / 3 = cpf
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  056 a 069 014 N Numero de inscri??o
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcnpjesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  070 a 099 030 A Nome responsavel (Raz?o social)
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',30,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  100 a 119 020 A Nome pessoa contado
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomecont||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  120 a 169 050 A Logradouro, rua...
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wlogra||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',50,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  170 a 189 020 A bairro
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wbaiesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  190 a 197 008 N CEP
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcepesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  198 a 217 020 A cidade
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomcid||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  218 a 219 002 A uf
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wSIGLAUF||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',2,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  220 a 231 012 N Telefone contato
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wfoneesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',12,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  232 a 291 060 A Endereco internet e-mail
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wemailesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  waux = wemailesc;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',60,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  292 a 297 006 N Compentecia AAAAMM
  IF (wanomes IS NULL) THEN
     wanomes = 0;
  wRetorno = wRetorno||CAST(wanomes AS VARCHAR(6));

  --  298 a 300 003 N Codigo recolhimento
  wRetorno = wRetorno||CAST(wcodrec AS VARCHAR(3));

  --  301 a 301 001 N Indicador recolhimento FGTS
  IF (windrecfgts IS NULL) THEN
     windrecfgts = '';

  wsql = 'select bdretorno from preenche_direita('||''''||windrecfgts||''''||',1,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  302 A 302 001 N modalidade do arquivo
  IF (wmodalidade IS NULL) THEN
     wmodalidade = '';

  wsql = 'select bdretorno from preenche_esquerda('||''''||wmodalidade||''''||',1,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  303 a 310 008 N Data recolhimento fgts
  IF (wdatarecfgts IS NULL) THEN
     SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
  ELSE
     waux = SUBSTRING(CAST(wdatarecfgts AS VARCHAR(10)) FROM 9 FOR 2)||SUBSTRING(CAST(wdatarecfgts AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(wdatarecfgts AS VARCHAR(10)) FROM 1 FOR 4);
  wRetorno = wRetorno||waux;

  --  311 a 311 001 N Indicador recolhimento previdencia social
  IF (windrecinss IS NULL) THEN
     windrecinss = '';

  wsql = 'select bdretorno from preenche_direita('||''''||windrecinss||''''||',1,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  312 a 319 008 N Data recolhimento previdencia social
  IF (wdatarecinss IS NULL) THEN
     SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
  ELSE
     waux = SUBSTRING(CAST(wdatarecinss AS VARCHAR(10)) FROM 9 FOR 2)||SUBSTRING(CAST(wdatarecinss AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(wdatarecinss AS VARCHAR(10)) FROM 1 FOR 4);
  wRetorno = wRetorno||waux;

  --  320 a 326 007 N Indicador de recolhimento em atraso da previdencia social
  SELECT bdretorno FROM preenche_direita('',7,' ') INTO waux;
  wRetorno = wRetorno||waux;

  --  327 a 327 001 N Tipo inscri??o fornecedor folha
  wRetorno = wRetorno||'1';

  --  328 a 341 014 N Inscri?ao fornecedor
  wRetorno = wRetorno||'82923160000177';

  --  342 a 359 018 A brancos
  SELECT bdretorno FROM preenche_direita('',18,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' fim do arquivo
  wRetorno = wRetorno||'*';

  bdReg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem;
  SUSPEND;
END
^

/* Alter (SP_EXP_SEFIP_REG_10) */
ALTER PROCEDURE SP_EXP_SEFIP_REG_10(PRSALFAM NUMERIC(15,6),
PRMATERNIDADE NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE WDDD INTEGER;
DECLARE VARIABLE WTIPOCALCULO INTEGER;
DECLARE VARIABLE WPERCISENCAO NUMERIC(15,6);
DECLARE VARIABLE WCODGPS INTEGER;
DECLARE VARIABLE WCODTERC INTEGER;
DECLARE VARIABLE WFPAS INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WSIMPLES INTEGER;
DECLARE VARIABLE WORDEM VARCHAR(60);
DECLARE VARIABLE WPERCRAT VARCHAR(2);
DECLARE VARIABLE WCENTRALIZA INTEGER;
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WCNAEEMP INTEGER;
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WSQL VARCHAR(31000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WAUX VARCHAR(360);
DECLARE VARIABLE WRETORNO VARCHAR(360);
DECLARE VARIABLE WNOMEMP VARCHAR(360);
DECLARE VARIABLE WLOGRA VARCHAR(360);
DECLARE VARIABLE WBAIRRO VARCHAR(360);
DECLARE VARIABLE WCEP VARCHAR(10);
DECLARE VARIABLE WNOMCIDADE VARCHAR(360);
DECLARE VARIABLE WUF VARCHAR(2);
DECLARE VARIABLE WFONE VARCHAR(20);
BEGIN
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;
  SELECT rdb$get_context('USER_TRANSACTION','W_CODREC') FROM rdb$database INTO wcodrec;
  SELECT rdb$get_context('USER_TRANSACTION','W_TIPOFOLHA') FROM rdb$database INTO wtipocalculo;

  wordem = '1';
--  // 001 a 002 002 N '10' tipo registro
  wretorno = '10';

  wsql =  'select emp.bdcnpjemp, remp.bdnomemp,'||
          'remp.bdlogremp||'||''''||' '||''''||'||remp.bdendemp||'||''''||' '||''''||'||remp.bdnumemp enderec,'||
          'remp.bdbaiemp, remp.bdcepemp, cid.bdnomcid, uf.bdsiglauf, remp.BDDDDEMP, remp.bdfoneemp fone, remp.bdcodcnae,'||
          'emps.bdcetrtalizaemp, substring(cast(cast(empg.bdcnaeratemp as integer) as varchar(10)) from 1 for 2),'||
          'tegps.bdsimplesgps, tegps.BDCODFPAS, tegps.bdcodterc, tegps.bdcodgps, emps.bdisenfilemp'||
          ' from vw_empresas_ref_atual remp'||
          ' left outer join tempresas emp on (emp.bdcodemp = remp.bdcodemp)'||
          ' left outer join VW_VRHF_BASE_TEMPSEFIP emps on (remp.bdcodemp = emps.bdcodemp)'||
          ' left outer join vw_vrhf_base_tempgps empg on (remp.bdcodemp = empg.bdcodemp)'||
          ' left outer join tcidade cid on (remp.bdcodcid = cid.bdcodcid)'||
          ' left outer join tuf uf on (cid.bdcoduf = uf.bdcoduf)'||
          ' left outer join VW_VRHF_BASE_TEMPGPS tegps on (tegps.bdcodemp = remp.bdcodemp)'||
          ' where emp.bdcodemp = '||wemp;

  EXECUTE STATEMENT wsql INTO
     wcnpjemp, wnomemp, wlogra,wbairro, wcep, wnomcidade, wuf, wddd, wfone, WCNAEEMP,
     WCENTRALIZA, wpercrat, wsimples, wfpas, wcodterc, wcodgps, wpercisencao;

  IF (wddd IS NULL) THEN
     wddd = 0;

  IF (wpercisencao IS NULL) THEN
     wpercisencao = 0;

  IF (wsimples IS NULL) THEN
     wsimples = 0;

  IF (wfpas IS NULL) THEN
     wfpas = 0;

  IF (wcodterc IS NULL) THEN
     wcodterc = 0;

  IF (wcodgps IS NULL) THEN
     wcodgps = 0;

  IF (wpercrat IS NULL) THEN
     wpercrat = '0';

  IF (wcentraliza IS NULL) THEN
     wcentraliza = 0;

  IF (wcnaeemp IS NULL) THEN
     wcnaeemp = 0;

  IF (wcnpjemp IS NULL) THEN
     wcnpjemp = '';

  IF (wnomemp IS NULL) THEN
     wnomemp = '';

  IF (wlogra IS NULL) THEN
     wlogra = '';

  IF (wbairro IS NULL) THEN
     wbairro = '';

  IF (wcep IS NULL) THEN
     wcep = '';

  IF (wnomcidade IS NULL) THEN
     wnomcidade = '';

  IF (wuf IS NULL) THEN
     wuf = '';

  IF (wfone IS NULL) THEN
     wfone = '';


--  003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

--  004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

--  018 a 053 036 N Zeros
  SELECT bdretorno FROM preenche_direita('',36,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  054 a 093 040 A Nome empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',40,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  094 a 143 050 A endere?o
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wlogra||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',50,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  144 a 163 020 A bairro
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wbairro||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  164 a 171 008 N Cep
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcep||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  172 a 191 020 A Cidade
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomcidade||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  192 a 193 002 A Uf
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wuf||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',2,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  194 a 205 012 N Telefone
  -- ddd 4
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wddd||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  --- fone 8
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wfone||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  206 a 206 001 A Indicador alteracao de endereco
  SELECT bdretorno FROM preenche_direita('',1,'N') INTO waux;
  wRetorno = wRetorno||waux;

--  207 a 213 007 N CNAE
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||WCNAEEMP||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',7,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  214 a 214 001 A Indicacaor alteracao CNAE
  IF (wtipocalculo = 2) THEN /* ck13.Checked */
     wRetorno = wRetorno||'N';
  ELSE
  IF (wAnoMes >= '200812') THEN
     BEGIN
       IF (wcentraliza IN (0, 1)) THEN
          wRetorno = wRetorno|| 'P';
       ELSE
          wRetorno = wRetorno||'N';
     END
  ELSE
     wRetorno = wRetorno||'N';

--  215 a 216 002 N Aliquota rat
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',2,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  217 a 217 001 N codigo centralizacao
  waux = CAST(wcentraliza AS VARCHAR(10));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',1,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  218 a 218 001 N Simples
  IF ((wanomes < '199612') OR (wcodrec = 640)) THEN
     wRetorno = wRetorno||' ';
  ELSE
     BEGIN
       IF (wanomes < '200701') THEN
          BEGIN
            wRetorno = wRetorno||CAST(wSimples + 1 AS VARCHAR(1)) ;
          END
       ELSE
          BEGIN
            IF ((wSimples + 1) IN (1,4,5)) THEN
               wRetorno = wRetorno||'1';
            ELSE
               wRetorno = wRetorno||'2';
          END
     END

--  219 a 221 003 N FPAS
  waux = CAST(wfpas AS VARCHAR(10));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',3,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  222 a 225 004 N Codigo outras entidades (terceiros empresa)
  waux = CAST(wcodterc AS VARCHAR(10));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  226 a 229 004 N Codigo gps
  IF ((wcodrec NOT IN (327,135)) AND (wcodgps = 0)) THEN
     waux = '    ';
  ELSE
     waux = CAST(wcodgps AS VARCHAR(10));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  230 a 234 005 N Per. insensao filantropia
  waux = CAST(CAST((wpercisencao * 100) AS INTEGER) AS VARCHAR(5));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',5,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  235 a 249 015 N Salario- familia
  waux = TRIM(CAST(CAST((prsalfam * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  250 a 264 015 N Salario-maternidade
  waux = TRIM(CAST(CAST((prmaternidade * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  265 a 279 015 N Contri. Desc. Segurados preencher com zeros
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  280 a 280 001 N Indicador valor negativo preencher com zero
  wRetorno = wRetorno||'0';

--  281 a 294 015 N Valor devido previdencia preencher com zeros
  SELECT bdretorno FROM preenche_direita('',14,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  295 a 297 003 N Banco
  SELECT bdretorno FROM preenche_esquerda('',3,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  298 a 301 004 N Agencia
  SELECT bdretorno FROM preenche_esquerda('',4,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  302 a 310 009 N Conta corrente
  SELECT bdretorno FROM preenche_esquerda('',9,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  311 a 355 045 N Zeros (implementa??o furura da sefip)
  SELECT bdretorno FROM preenche_direita('',45,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  356 a 359 004 A Brancos
  SELECT bdretorno FROM preenche_direita('',4,' ') INTO waux;
  wRetorno = wRetorno||waux;

--  360 a 360 001 A '*' final de linha
--  select bdretorno from preenche_direita('',18,' ') into waux;
  wRetorno = wRetorno||'*';

  /*ordem tomador*/
  wordem = wordem||'0'; -- tipo cnpj
  wordem = wordem||'00000000000000'; -- cnpj

  /*ordem trabalhador*/
  wordem = wordem||'00000000000'; --pis
  wordem = wordem||'00000000'; -- data adm
  wordem = wordem||'00'; -- categoria

  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'10';
  SUSPEND;
END
^

/* Alter (SP_EXP_SEFIP_REG_12) */
ALTER PROCEDURE SP_EXP_SEFIP_REG_12(BDDEDMAT13 NUMERIC(15,6),
BDRURALFISICA NUMERIC(15,6),
BDRURALJURIDICA NUMERIC(15,6),
BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULA NUMERIC(15,6),
BDACUMULATERC NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wretorno VARCHAR(360);
DECLARE VARIABLE waux VARCHAR(360);
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;

  wsql =  'select emp.bdcnpjemp from tempresas emp'||
          ' where emp.bdcodemp = '||wemp;

  wordem = '1';

  EXECUTE STATEMENT wsql INTO wcnpjemp;
  -- 001 a 002 002 N '12' tipo registro
  wretorno = '12';

  --  // 003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  --  // 004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 018 a 053 036 N Zeros
  SELECT bdretorno FROM preenche_direita('',36,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 054 a 068 015 V Dedu??o 13? salario maternidade
  waux = CAST(CAST((bddedmat13 * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 069 a 083 015 V Receita evento desportivo
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 084 a 084 001 A Indicador origem receita
  wRetorno = wRetorno||' ';

  -- 085 a 099 015 V Comercializacao da producao Pessoa fisica
  waux = CAST(CAST((bdruralfisica * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 100 a 114 015 V Comercializacao da producao Pessoa Juridica
  waux = CAST(CAST((bdruraljuridica * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 115 a 125 011 N Outras informacoes processos (obrigatorio 650 e 660) demais deixar em branco
  SELECT bdretorno FROM preenche_direita('',11,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 126 a 129 004 N Outras informacoes Ano deixar em branco quando nao informado
  SELECT bdretorno FROM preenche_direita('',4,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 130 a 134 005 N Outras informacoes Vara deixar em branco quando nao informado
  SELECT bdretorno FROM preenche_direita('',5,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 135 a 140 006 N Outras informacoes Periodo inicio deixar em branco quando nao informado
  SELECT bdretorno FROM preenche_direita('',6,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 141 a 146 006 N Outras informacoes Periodo fim deixar em branco quando nao informado
  SELECT bdretorno FROM preenche_direita('',6,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 147 a 161 015 V Compensacao
  waux = CAST(CAST((bdcompensacao * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 162 a 167 006 D Periodo inicio compensacao AAAAMM
  waux = CAST(bdinicomp AS VARCHAR(6));
  waux = SUBSTRING(waux FROM 3)||SUBSTRING(waux FROM 1 FOR 2);
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',6,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 168 a 173 006 D Periodo final compensacao AAAAMM
  waux = CAST(bdfimcomp AS VARCHAR(6));
  waux = SUBSTRING(waux FROM 3)||SUBSTRING(waux FROM 1 FOR 2);
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',6,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 174 a 188 015 V Recolhimento competencias anteriores valor inss
  waux = CAST(CAST((bdacumula * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 189 a 203 015 V Recolhimento competencias anteriores outras entidades
  waux = CAST(CAST((bdacumulaterc * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 204 a 218 015 V Recolhimento competencias anteriores Comercializacao da producao
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 219 a 233 015 V Recolhimento competencias anteriores Comercializacao da producao outras entidades
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 234 a 248 015 V Recolhimento competencias receita de eventos desportivos
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 249 a 263 015 V Parcelamento FGTS Base Categorias 1,2,3,5,6 (preencher com zeros)
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 264 a 278 015 V Parcelamento FGTS Base Categorias 4 e 7 (preencher com zeros)
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 279 a 293 015 V Parcelamento FGTS Valor (preencher com zeros)
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 294 a 308 015 V Valor paga cooperativas
  waux = CAST(CAST((bdnfcoop * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 309 a 353 045 N Preencher com zeros
  SELECT bdretorno FROM preenche_direita('',45,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 354 a 359 006 A Brancos
  SELECT bdretorno FROM preenche_direita('',6,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' finalizar registro
  wretorno = wretorno||'*';

  /*ordem tomador*/
  wordem = wordem||'0'; -- tipo cnpj
  wordem = wordem||'00000000000000'; -- cnpj

  /*ordem trabalhador*/
  wordem = wordem||'00000000000'; --pis
  wordem = wordem||'00000000'; -- data adm
  wordem = wordem||'00'; -- categoria

  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'12';
  SUSPEND;
END
^

/* Alter (SP_EXP_SEFIP_REG_20) */
ALTER PROCEDURE SP_EXP_SEFIP_REG_20(BDSALFAM INTEGER,
BDNOTASFISCAIS INTEGER)
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE wcodgps INTEGER;
DECLARE VARIABLE wtomador INTEGER;
DECLARE VARIABLE wcodrec INTEGER;
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wretorno VARCHAR(360);
DECLARE VARIABLE waux VARCHAR(360);
DECLARE VARIABLE wcnpjtom VARCHAR(360);
DECLARE VARIABLE wnometom VARCHAR(360);
DECLARE VARIABLE wenderecotom VARCHAR(360);
DECLARE VARIABLE wbairrotom VARCHAR(360);
DECLARE VARIABLE wceptom VARCHAR(360);
DECLARE VARIABLE wcidadetom VARCHAR(360);
DECLARE VARIABLE wuftom VARCHAR(360);
DECLARE VARIABLE wcodgpstom VARCHAR(360);
BEGIN
  bdinc = '';
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  SELECT rdb$get_context('USER_TRANSACTION','W_CODREC') FROM rdb$database INTO wcodrec;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_TOMADORSEFIP') FROM rdb$database INTO wtomador;

  wsql =  'select emp.bdcnpjemp, tegps.bdcodgps from tempresas emp'||
          ' left outer join VW_VRHF_BASE_TEMPGPS tegps on (tegps.bdcodemp = emp.bdcodemp)'||
          ' where emp.bdcodemp = '||wemp;

  EXECUTE STATEMENT wsql INTO :wcnpjemp, :wcodgps;

  wordem = '1';

  -- 001 a 002 002 N '20' tipo registro
  wretorno = '20';

  SELECT bdcnpj,bdnome, bdendereco, bdbairro, bdcep, bdcidade, bduf, bdcodgps FROM sp_tomador_sefip
  INTO
    wcnpjtom,
    wnometom,
    wenderecotom,
    wbairrotom,
    wceptom,
    wcidadetom,
    wuftom,
    wcodgpstom;

  IF (wnometom = '') THEN
     BEGIN
       bdinc = bdinc||'Dados do Tomador '||wtomador||' n?o cadastrados. $A$B';
     END

  --  // 003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  --  // 004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 018 a 018 001 N Tipo inscricao tomador
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjtom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 019 a 032 014 N Insricrao tomador
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 033 a 053 021 N Zeros
  SELECT bdretorno FROM preenche_direita('',21,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 054 a 093 040 A Nome do tomador
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnometom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',40,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 094 a 143 050 A Endereco
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wenderecotom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',50,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 144 a 163 020 A Bairro
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wbairrotom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 164 a 171 008 N Cep
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wceptom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 172 a 191 020 A Cidade
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcidadetom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 192 a 193 002 A Uf
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wuftom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',2,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 194 a 197 004 N Codigo GPS (n?o informado deixar em branco)
  IF ((wcodrec NOT IN (130,155,135,317,337,608,908,909,910))
      OR  (wcodrec IN (911,211))) THEN
     SELECT bdretorno FROM preenche_esquerda('',4,' ') INTO waux;
  ELSE
     BEGIN
       IF ((wtomador IS NULL) OR (wtomador = 0)) THEN
          BEGIN
            IF (wcodgps IS NULL) THEN
               wcodgps = 0;

            waux = CAST(wcodgps AS VARCHAR(10));
            wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
            EXECUTE STATEMENT wsql INTO waux;
            wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
            EXECUTE STATEMENT wsql INTO waux;
          END
       ELSE
          BEGIN
            waux = CAST(wcodgpstom AS VARCHAR(10));
            wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
            EXECUTE STATEMENT wsql INTO waux;
            wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
            EXECUTE STATEMENT wsql INTO waux;
          END
     END
  wRetorno = wRetorno||waux;

  -- 198 a 212 015 V Salario familia
  waux = CAST(CAST((bdsalfam * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 213 a 227 015 V Contribui?ao descontada empregado comp. 13 (preencher com zeros)
  SELECT bdretorno FROM preenche_esquerda('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 228 a 228 001 N Indicador valor negativo preencher com zero
  wRetorno = wRetorno||'0';

  -- 229 a 242 014 V Valor devido a previdencia social preencher com zeros
  SELECT bdretorno FROM preenche_direita('',14,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 243 a 257 015 V Valor reten??o (Notas fiscais)
  waux = CAST(CAST((bdnotasfiscais * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 258 a 272 015 V Valor faturas emitidas para o tomador
  SELECT bdretorno FROM preenche_esquerda('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 273 a 317 045 V preencher com zeros
  SELECT bdretorno FROM preenche_direita('',45,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 318 a 359 042 A Brancos
  SELECT bdretorno FROM preenche_direita('',42,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' finalizador de registro
  wretorno = wretorno||'*';

  /*ordem trabalhador*/
  wordem = wordem||'00000000000'; --pis
  wordem = wordem||'00000000'; -- data adm
  wordem = wordem||'00'; -- categoria

  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'20';
  SUSPEND;
END
^

/* Alter (SP_EXP_SEFIP_REG_21) */
ALTER PROCEDURE SP_EXP_SEFIP_REG_21(BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULA NUMERIC(15,6),
BDACUMULATERC NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wcnpjtom VARCHAR(20);
DECLARE VARIABLE wretorno VARCHAR(360);
DECLARE VARIABLE waux VARCHAR(360);
DECLARE VARIABLE wcnpjemp VARCHAR(20);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wemp INTEGER;
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;

  wsql =  'select emp.bdcnpjemp from tempresas emp'||
          ' where emp.bdcodemp = '||wemp;

  wordem = '1';

  EXECUTE STATEMENT wsql INTO wcnpjemp;
  -- Ini   fim Tam T Desc
  -- 001 a 002 002 N '21' tipo registro
  wRetorno = '21';

  --  // 003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  --  // 004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  SELECT bdcnpj FROM sp_tomador_sefip
  INTO
    wcnpjtom;

  -- 018 a 018 001 N Tipo inscricao tomador
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjtom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 019 a 032 014 N Insricrao tomador
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 033 a 053 021 N Zeros
  SELECT bdretorno FROM preenche_direita('',21,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 054 a 068 015 V Compensa?ao
  waux = CAST(CAST((bdcompensacao * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 069 a 074 006 D AAAAMM inicio compensacao
  waux = CAST(bdinicomp AS VARCHAR(6));
  waux = SUBSTRING(waux FROM 5)||SUBSTRING(waux FROM 1 FOR 4);
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',6,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 075 a 080 006 D AAAAMM fim compensacao
  waux = CAST(bdfimcomp AS VARCHAR(6));
  waux = SUBSTRING(waux FROM 5)||SUBSTRING(waux FROM 1 FOR 4);
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',6,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 081 a 095 015 V Recolhimento competencias anteriores Valor Inss
  waux = CAST(CAST((bdacumula * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 096 a 110 015 V Recolhimento competencias anteriores Valor outras entidades
  waux = CAST(CAST((bdacumulaterc * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 111 a 125 015 V Parcelamento preencher com zeros
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 126 a 140 015 V Parcelamento preencher com zeros
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 141 a 155 015 V Parcelamento preencher com zeros
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 156 a 359 204 A brancos
  SELECT bdretorno FROM preenche_direita('',204,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' finalizador de registros
  wRetorno = wRetorno||'*';

  /*ordem trabalhador*/
  wordem = wordem||'00000000000'; --pis
  wordem = wordem||'00000000'; -- data adm
  wordem = wordem||'00'; -- categoria

  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'21';
  SUSPEND;
END
^

/* Alter (SP_EXPORTA_BLOCOC) */
ALTER PROCEDURE SP_EXPORTA_BLOCOC(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRVALIDAREXPORTACAO DM_BOOLEAN,
PRARQUIVO VARCHAR(100))
 AS
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200 CHARACTER SET win1252;
DECLARE VARIABLE WTIPOEXPCODPART INTEGER;
DECLARE VARIABLE WPERFILSPED INTEGER;
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1; /*N?o achou o TipoExpCodPart*/

  SELECT SP.BDPERFILSPED FROM SP_CONSULTAEMPRESAS_SIS((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')), :PRCODEMP, NULL) SP INTO :wPerfilSped;    

  wPerfilSped = COALESCE(:wPerfilSped, -1);  

  /*ENTRADA*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_ENT(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :wPerfilSped);

  /*SAIDA*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :wPerfilSped);

  /*Se o perfil do sped da empresa for A, exporta registros C350, C370 e C390*/
  IF (:wPerfilSped IN (0)) THEN
    BEGIN
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_REG300(:PRCODEMP, :PRDTINI, :PRDTFIM,:PRARQUIVO, :wPerfilSped);
    END

  /*Cria as inconsistências*/
  IF (UPPER(:PRVALIDAREXPORTACAO) = 'TRUE') THEN
    EXECUTE PROCEDURE SP_VALIDA_EXPORTACAO_SPED(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, 'C100');

  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha);
    END

  CLOSEARQ(:PRARQUIVO);

  --Limpa os dados da exporta??o
  --DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

END
^

/* Alter (SP_EXPORTA_BLOCOC_CONTRIBUICOES) */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_CONTRIBUICOES(PRCODEMP VARCHAR(500),
PRCODPLAPADRAOREF INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100))
 AS
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WARQUIVOEMP VARCHAR(100);
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  PRCODEMP = PRCODEMP||',';
  WHILE (CHAR_LENGTH(:PRCODEMP) > 0) DO
    BEGIN
      wEmpAtu = TRIM(SUBSTRING(:PRCODEMP FROM 1 FOR POSITION(',', :PRCODEMP)-1));

      /*Cria arquivo da empresa que vai ser exportada*/
      wArquivoEmp = REPLACE(:PRARQUIVO, '.tmp', '_e='||:wEmpAtu||'.tmp');
      NEWFILE(:wArquivoEmp);

      /*SA?DA*/
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(:wEmpAtu, :PRCODPLAPADRAOREF, :PRDTINI, :PRDTFIM, :wArquivoEmp);

      PRCODEMP = SUBSTRING(:PRCODEMP FROM POSITION(',', :PRCODEMP)+1 FOR CHAR_LENGTH(:PRCODEMP));

      /*****************************************************************************
       *                           EXPORTANDO ARQUIVO                              *
       ****************************************************************************/
    
      OPENARQ(:wArquivoEmp);
    
      FOR SELECT E.BDLINHA
          FROM TEXPORTACAO_SPED E
          WHERE E.BDID = :wArquivoEmp
          ORDER BY E.BDCHAVEREG
          INTO :wLinha
      DO
        BEGIN
          WRITELNOA(:wLinha);
        END
    
      CLOSEARQ(:wArquivoEmp);
    END
END
^

/* Alter (SP_EXPORTA_BLOCOC_ENT) */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_ENT(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
BEGIN
  --22326
  /*****************************************************************************
   *-------------------------------->>ENTRADA<<--------------------------------*
   ****************************************************************************/

   /*
     OBS: A Orderna??o dos registros ? feita pelo campo BDCHAVEREG que ? uma classifica??o.
          Classifica??o: Empresa.Chave.Reg.Chave.Reg....
          EX: C170: 000010.0000012587.C100.C170.000001
              C195: 000010.0000012587.C100.C195.000001
              C197: 000010.0000012587.C100.C195.000001.C197.000001
   */

  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
  SELECT  :PRARQUIVO BDID,
          LPAD(ENT.BDCODEMP, 6, '0')||'.0.'||LPAD(ENT.BDCHAVE, 10, '0')||'.C100',
          'C100' BDREG,
          ('|C100|0|'||M.BDEMITENTE||         --IND_EMIT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))))|| --COD_PART
           '|'||MOD.BDMODELOSTR||             --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
           '|'||M.BDSERIE||                   --SER
           '|'||M.BDNUMDOCINI||               --NUM_DOC
           '|'||COALESCE(IIF(M.BDMODELO IN (55, 65), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAENTRADAENT, 'DDMMYYYY')))|| --DT_E_S
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(ENT.BDVLRCONTAB, '.', ','))|| --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))||   --IND_PGTO
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_DESC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_ABAT_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ','))||    --VL_MERC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN M.BDMODELO = 65 THEN '9' WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRFRETE, 0.00), '.', ','))||  --VL_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRSEGURO, 0.00), '.', ','))|| --VL_SEG
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLROUTDESP, 0.00), '.', ','))||--VL_OUT_DA
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRICMS, 0.00), '.', ','))||    --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(IIF(ENT.BDVLRST > 0, COALESCE(ENT.BDBASEST, 0.00), 0.00), '.', ',')))|| --VL_BC_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(ENT.BDVLRST, 0.00), '.', ',')))||           --VL_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(ENT.BDVLRIPI, 0.00), '.', ',')))||          --VL_IPI
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPIS, 0.00), '.', ',')))||      --VL_PIS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINS, 0.00), '.', ',')))||   --VL_COFINS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPISST, 0.00), '.', ',')))||    --VL_PIS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINSST, 0.00), '.', ',')))|| --VL_COFINS_ST
           '|') BDLINHA, IIF(((M.BDMODELO = 65) OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) ENT
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = ENT.BDCODEMP AND M.BDCHAVE = ENT.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = ENT.BDCODEMP AND C100.BDCHAVE = ENT.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE)
  LEFT OUTER JOIN (
                   SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM
                   FROM VEF_EMP_TMOVPROENT P
                   WHERE P.BDCODEMP = :PRCODEMP
                   GROUP BY P.BDCODEMP, P.BDCHAVE
                  ) PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   C101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C101.0000000001',
             'C101' BDREG,
             '|C101|'||REPLACE(COALESCE(C.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVENT M
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDMODELO = 55
            AND M.BDVALORNOTA > 0
            AND M.BDCODSITNF NOT IN(1, 7)
            AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
           ) MOV
      JOIN VEF_EMP_TC100ENT C ON(C.BDCODEMP = MOV.BDCODEMP AND C.BDCHAVE = MOV.BDCHAVE AND
                                 (((C.BDVLR_FCP_UF_DEST IS NOT NULL) AND (C.BDVLR_FCP_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_DEST IS NOT NULL) AND (C.BDVLRICMS_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_REM IS NOT NULL) AND (C.BDVLRICMS_UF_REM > 0))));
    END

  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C110                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODINFCOM, BDORDEMINFCOM)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0'),
             'C110' BDREG,
             '|C110|'||COALESCE(CADINF.BDCODINFCOM, '')||
             '|'||COALESCE(TRIM(REPLACE(SUBSTRING(MOVINF.BDDESCCOMPIC FROM 1 FOR 255), '|', '')), '')||'|',
             CADINF.BDCODINFCOM, CADINF.BDORDEMINFCOM
      FROM (
            SELECT INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON(CADINF.BDORDEMINFCOM = MOVINF.BDORDEMINFCOM AND CADINF.BDCODEMP = MOVINF.BDCODEMP);

      /*****************************************************************************
       *                                   C111                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C111.'||LPAD(REF.BDORDEMPROREF, 6, '0'),
             'C111',
             '|C111|'||COALESCE(TRIM(REF.BDNUMPROC), '')||
             '|'||IIF(REF.BDINDPROCESSO = '4', '9', COALESCE(REF.BDINDPROCESSO, ''))||'|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTPROREF REF ON(REF.BDCODEMP = MOVINF.BDCODEMP AND REF.BDCHAVE = MOVINF.BDCHAVE AND REF.BDORDEMIC = MOVINF.BDORDEMIC);
    
      /*****************************************************************************
       *                                   C112                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C112.'||LPAD(C112.BDORDEMDOCAREF, 6, '0'),
             'C112',
             '|C112'||
             '|'||COALESCE(C112.BDMODCODDA, 0)|| --COD_DA
             '|'||COALESCE(UF.BDSIGLAUF, '')||   --UF
             '|'||COALESCE(C112.BDNUMDA, '')||   --NUM_DA
             '|'||COALESCE(C112.BDCODAUT, '')||  --COD_AUT
             '|'||REPLACE(CAST(COALESCE(C112.BDVLRDA, 0.00) AS NUMERIC(15, 2)), '.', ',')|| --VL_DA
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTVCTO, 'DDMMYYYY'))||        --DT_VCTO
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTPGTO, 'DDMMYYYY'))||        --DT_PGTO
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTDOCAREF C112 ON(C112.BDCODEMP = MOVINF.BDCODEMP AND C112.BDCHAVE = MOVINF.BDCHAVE AND C112.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C112.BDCODUF);
    
      /*****************************************************************************
       *                                   C113                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C113.'||LPAD(C113.BDORDEMDOCFREF, 6, '0'),
             'C113',
             '|C113'||
             '|'||IIF(C113.BDINDOPER IS NULL, 0, C113.BDINDOPER)|| --IND_OPER
             '|'||COALESCE(C113.BDINDEMIT, 0)||   --IND_EMIT
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C113.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')|| --COD_MOD
             '|'||COALESCE(C113.BDSERIE, '')||    --SER
             '|'||COALESCE(C113.BDSUBSERIE, '')|| --SUB
             '|'||COALESCE(C113.BDNUMDOC, '')||   --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C113.BDDTEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||COALESCE(IIF(((DOCFIS.BDDOCFIS IN(55, 57, 65)) AND (:PRDTINI > '12/31/2016')), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_DOCe
             '|', C113.BDCODTER
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C113.BDCODDOCFIS)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER= C113.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C113.bdcodter);
    
      /*****************************************************************************
       *                                   C114                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C114.'||LPAD(C114.BDORDEMCUPREF, 6, '0'),
             'C114',
             '|C114'||
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')||   --COD_MOD
             '|'||COALESCE(C114.BDNRSERCAIXA, '')|| --ECF_FAB
             '|'||COALESCE(C114.BDNUMCAIXA, '')||   --ECF_CX
             '|'||COALESCE(C114.BDNUMDOC, '')||     --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C114.BDDTDOC, 'DDMMYYYY')), '')||
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTCUPREF C114 ON(C114.BDCODEMP = MOVINF.BDCODEMP AND C114.BDCHAVE = MOVINF.BDCHAVE AND C114.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C114.BDCODDOCFIS);

      /*****************************************************************************
       *                                   C120                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C120.'||LPAD(C120.BDORDEMOPIMP, 6, '0'),
             'C120',
             '|C120'||
             '|'||COALESCE(C120.BDCODDOCIMP, '')|| --COD_DOC_IMP
             '|'||COALESCE(C120.BDNUMDOCIMP, '')|| --NUM_DOC__IMP
             '|'||REPLACE(CAST(COALESCE(C120.BDVLRPAGOPIS, 0.00) AS NUMERIC(15, 2)), '.', ',')||    --PIS_IMP
             '|'||REPLACE(CAST(COALESCE(C120.BDVLRPAGOCOFINS, 0.00) AS NUMERIC(15, 2)), '.', ',')|| --COFINS_IMP
             '|'||COALESCE(C120.BDNUMDRAW, '')|| --NUM_ACDRAW
             '|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVENT M
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDMODELO IN (1, 4, 55, 65, 100)
            AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND m.bdcodsitnf NOT IN (2,3,4,5)
           ) MOV
      JOIN VEF_EMP_TMOVENTOPIMP C120 ON(C120.BDCODEMP = MOV.BDCODEMP AND C120.BDCHAVE = MOV.BDCHAVE);

      /*****************************************************************************
       *                                   C140                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.0.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C140',
             '|C140'||
             '|'||COALESCE(MOV.BDEMITENTE, '')|| --IND_EMIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN '00'
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN '01'
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN '02'
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN '03'
                       ELSE '99'
                  END|| --IND_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN ''
                       ELSE COALESCE(PAR.BDOUTROSPAR, '')
                  END|| --DESC_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN PAR.BDDUPLICATAPAR
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN PAR.BDCHEQUEPAR
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN PAR.BDPROMISSPAR
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN PAR.BDOUTROSPAR
                       ELSE COALESCE(PAR.BDOUTROSPAR, MOV.BDNUMDOCINI)
                  END|| --NUM_TIT
             '|'||COALESCE(TOTPAR.BDQTDPAR, '')|| --QTD_PARC
             '|'||REPLACE(COALESCE(TOTPAR.BDVALORDUPLICATA, 0.00), '.', ',')|| --VL_TIT
             '|'
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDEMITENTE,
                   ENT.BDVALORNOTA, ENT.BDNUMDOCINI
            FROM VEF_EMP_TMOVENT ENT
            WHERE ENT.BDCODEMP = :PRCODEMP
            AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND ENT.BDMODELO = 1 --somente modelo 1
            AND ent.bdcodsitnf NOT IN (2,3,4,5)
           ) MOV
      JOIN VEF_EMP_TMOVENTPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE AND PAR.BDORDEMPAR = (SELECT MIN(P.BDORDEMPAR) FROM VEF_EMP_TMOVENTPAR P WHERE P.BDCODEMP = PAR.BDCODEMP AND P.BDCHAVE = PAR.BDCHAVE))
      LEFT OUTER JOIN (
                       SELECT P.BDCODEMP, P.BDCHAVE, COUNT(P.BDORDEMPAR) BDQTDPAR, SUM(COALESCE(P.BDVALORPAR, 0)) BDVALORDUPLICATA
                       FROM VEF_EMP_TMOVENTPAR P
                       GROUP BY P.BDCODEMP, P.BDCHAVE
                      ) TOTPAR ON(TOTPAR.BDCODEMP = PAR.BDCODEMP AND TOTPAR.BDCHAVE = PAR.BDCHAVE);

      /*****************************************************************************
       *                                   C141                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.0.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.C141.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C141',
             '|C141'||
             '|'||PAR.BDORDEMPAR|| --NUM_PARC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(PAR.BDDATAVENCTOPAR, 'DDMMYYYY')), '')|| --DT_VCTO
             '|'||REPLACE(COALESCE(PAR.BDVALORPAR, 0.00), '.', ',')|| --VL_PARC
             '|'
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDEMITENTE,
                   ENT.BDVALORNOTA, ENT.BDNUMDOCINI
            FROM VEF_EMP_TMOVENT ENT
            WHERE ENT.BDCODEMP = :PRCODEMP
            AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND ENT.BDMODELO = 1 --somente modelo 1
            AND ent.bdcodsitnf NOT IN (2,3,4,5)
           ) MOV
      JOIN VEF_EMP_TMOVENTPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
      ORDER BY PAR.BDORDEMPAR;
    END

  /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCODNAT)
  SELECT  :PRARQUIVO BDID,
         LPAD(ENT.BDCODEMP, 6, '0')||'.0.'||LPAD(ENT.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
          'C170' BDREG,
          '|C170'||
--          '|'||PRO.BDORDEMPRO|| --NUM_ITEM
          '|'||GETORDEMSEQUENCIAL(PRO.BDCHAVE)|| --NUM_ITEM
          --#Alt:21967. Quando a empresa n?o possu?a o respectivo produto vinculado o registro estava levando vazio. Quando isso acontecer foi
          --tratado para levar a informa??o do produto ?nico. Esse tratamento ? feito para o c?digo e a descri??o.
          --'|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), COALESCE(VINC.BDCODPROD,''), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          --'|'||TRIM(REPLACE(COALESCE(VINC.BDDESCPROD, ''), '|', ''))|| --DESCR_COMPL
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                   IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                   COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          '|'||TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                                COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                                COALESCE(VINC.BDDESCPROD,'')), '|', ''))|| --DESCR_COMPL
          '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 5)), '.', ',')|| --QTD
          '|'||COALESCE(IIF(((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')), UN_REF.BDAPEUNIMED, UN.BDAPEUNIMED), '')|| --UNID
          '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
          '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
          '|'||IIF((UPPER(PRO.BDMOVFISICO) = 'TRUE'), 0, 1)|| --IND_MOV
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(I.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||COALESCE(I.BDCODNAT, '')|| --COD_NAT
          '|'||REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(COALESCE(PRO.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
          '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, COALESCE(PRO.BDBCST, 0.00)), '.', ',')||   --VL_BC_ICMS_ST
          '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2)), '.', ',')|| --ALIQ_ST
          '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, COALESCE(PRO.BDVLRST, 0.00)), '.', ',')||  --VL_ICMS_ST
          '|'|| --IND_APUR
          '|'||IIF(IPI.BDCODCSTIPI IS NULL, '', LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, 0))|| --CST_IPI
          '|'|| --COD_ENQ
          '|'||REPLACE(COALESCE(PRO.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQIPI, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_IPI
          '|'||REPLACE(COALESCE(PRO.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
          '|'||COALESCE(PIS.BDCSTPIS, '')|| --CST_PIS
          '|'||REPLACE(COALESCE(PRO.BDBCPIS, 0.00), '.', ',')|| --VL_BC_PIS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_PIS
          '|'||'0,00'|| --QUANT_BC_PIS
          '|'||'0,00'|| --ALIQ_PIS(em reais)
          '|'||REPLACE(COALESCE(PRO.BDVLRPIS, 0.00), '.', ',')|| --VL_PIS
          '|'||COALESCE(COF.BDCSTCOF, '')|| --CST_COFINS
          '|'||REPLACE(COALESCE(PRO.BDBCCOFINS, 0.00), '.', ',')|| --VL_BC_COFINS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_COFINS
          '|'||'0,00'|| --QUANT_BC_COFINS
          '|'||'0,00'|| --ALIQ_COFINS(em reais)
          '|'||REPLACE(COALESCE(PRO.BDVLRCOFINS, 0.00), '.', ',')|| --VL_COFINS
          '|'||COALESCE(PRO.BDCODCTA, '')|| --COD_CTA
          '|', PRO.BDCODPROD, I.BDCODNAT
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, SUM(COALESCE(I.BDVLRST, 0)) BDVLRST
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
        GROUP BY ENT.BDCODEMP, ENT.BDCHAVE
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
  /*Produto*/
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)
  LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD) --#Alt:21967.
--  LEFT OUTER JOIN TCADPRO_REF REF ON(REF.BDCODEMP = PRO.BDCODEMP AND REF.BDCODPROD = PRO.BDCODPROD AND ((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')))
  /*Produto por refer?ncia*/
  LEFT OUTER JOIN TCADPRO_VINC VINC_REF ON(VINC_REF.BDCODEMP = PRO.BDCODEMP AND VINC_REF.BDCODPROD = PRO.BDCODPROD)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN_REF ON(UN_REF.BDCODUNIMED = VINC_REF.BDCODUNIMED)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
  LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = PRO.BDCODCSTCOF);

  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C171                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
               LPAD(PRO.BDCODEMP, 6, '0')||'.0.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C171.'||LPAD(C171.BDORDEMC171, 6, '0'),
                'C171' BDREG,
                '|C171'||
                '|'||COALESCE(C171.BDNUMTANQUE, '')|| --NUM_TANQUE
                '|'||COALESCE(REPLACE(C171.BDQTDEVOLUME, '.', ','), '')||--QTDE
                '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVENT M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) ENT
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                 ) ENT
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TC171ENT C171 ON(C171.BDCODEMP = PRO.BDCODEMP AND C171.BDCHAVE = PRO.BDCHAVE AND C171.BDORDEM = PRO.BDORDEM AND C171.BDORDEMPRO = PRO.BDORDEMPRO);      
    
      /*****************************************************************************
       *                                   C173                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
               LPAD(PRO.BDCODEMP, 6, '0')||'.0.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C173.'||LPAD(C173.BDORDEMOPMED, 6, '0'),
                'C173' BDREG,
                '|C173'||
                '|'||COALESCE(C173.BDNRLOTE, '')|| --LOTE_MED
                '|'||REPLACE(COALESCE(C173.BDQTDITEM, 0.00), '.', ',')|| --QTD_ITEM
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTFABMED, 'DDMMYYYY')), '')|| --DT_FAB
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTVALMED, 'DDMMYYYY')), '')|| --DT_VAL
                '|'||COALESCE(C173.BDINDTIPOMED, '')|| --IND_MED
                '|'||COALESCE(C173.BDTIPOMED, '')||    --TP_PROD
                '|'||REPLACE(COALESCE(CAST(C173.BDVLRMAXMED AS DM_NUMERIC_15_2), 0.00), '.', ',')||   --VL_TAB_MAX
                '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVENT M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) ENT
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                 ) ENT
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TOPMEDENT C173 ON(C173.BDCODEMP = PRO.BDCODEMP AND C173.BDCHAVE = PRO.BDCHAVE AND C173.BDORDEM = PRO.BDORDEM AND C173.BDORDEMPRO = PRO.BDORDEMPRO);
    END

  /*****************************************************************************
   *                                   C190                                    *
   ****************************************************************************/
  /*Monta o C190 a partir do movimento de produto*/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
        LPAD(C190.BDCODEMP, 6, '0')||'.0.'||LPAD(C190.BDCHAVE, 10, '0')||'.C100.C190.'||LPAD(GETORDEMSEQUENCIAL(C190.BDCHAVE), 10, '0'),
        'C190' BDREG,
        '|C190'||
        '|'||COALESCE(C190.BDCSTICMS, '')|| --CST_ICMS
        '|'||COALESCE(C190.BDCODNAT, '')|| --CFOP
        '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),
                                                      (IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0.00), '.', ',')|| --VL_OPR
        '|'||REPLACE(COALESCE(C190.BDBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
        '|'||REPLACE(COALESCE(C190.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, IIF(ITEM.BDVLRSTITEM = 0, NULL, C190.BDBCST)), 0.00), '.', ',')|| --VL_BC_ICMS_ST
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, IIF(ITEM.BDVLRSTITEM = 0, NULL, C190.BDVLRST)), 0.00), '.', ',')|| --VL_ICMS_ST
--        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((COALESCE(C190.BDVLRITEM, 0) + COALESCE(C190.BDVLRDESPACESSORIA, 0) + COALESCE(C190.BDVLRIPI, 0) + COALESCE(C190.BDVLRST, 0)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
        '|'|| --COD_OBS
        '|'
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, MOV.BDCODNAT, MOV.BDALIQICMS, ENT.BDMODELO, MOV.BDVLRITEM,
               MOV.BDVLRDESC, MOV.BDVLRFRETE, MOV.BDVLRDESPACESSORIA, MOV.BDVLRIPI, MOV.BDVLRST, MOV.BDBCICMS,
               MOV.BDVLRICMS, MOV.BDBCST, MOV.BDREDBCICMS, ENT.BDVALORNOTA,
               (COALESCE(MOV.BDVLRFRETE, 0) + COALESCE(MOV.BDVLRITEM, 0) +
                COALESCE(MOV.BDVLRDESPACESSORIA, 0) + COALESCE(MOV.BDVLRIPI, 0) +
                COALESCE(MOV.BDVLRST, 0) - COALESCE(MOV.BDVLRDESC, 0)) BDVLRTOT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                     COALESCE(PRO.BDCODCSTICMS, 0) BDCODCSTICMS,
                     COALESCE(MOV.BDCODNAT, 0) BDCODNAT,
                     CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS,
                     SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                     SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                     SUM(COALESCE(PRO.BDVLRFRETE, 0)) BDVLRFRETE,
                     SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) BDVLRDESPACESSORIA,
                     SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI,
                     SUM(COALESCE(PRO.BDVLRST, 0)) BDVLRST,
                     SUM(COALESCE(PRO.BDBCST, 0)) BDBCST,
                     SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS,
                     SUM(COALESCE(PRO.BDVLRICMS, 0)) BDVLRICMS,
                     SUM(COALESCE(PRO.BDREDBCICMS, 0)) BDREDBCICMS
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                    FROM VEF_EMP_TMOVENT M
                    JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                   ) MOV
              JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
              GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
             ) MOV
        JOIN VEF_EMP_TMOVENT ENT ON(ENT.BDCODEMP = MOV.BDCODEMP AND ENT.BDCHAVE = MOV.BDCHAVE)
        LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
       ) C190
  LEFT OUTER JOIN (
                   SELECT C190_TOT.BDCODEMP, C190_TOT.BDCHAVE, SUM(C190_TOT.BDVLRDIF) BDVLRDIF, COUNT(C190_TOT.BDCHAVE) BDORDEMMAX
                   FROM (
                         SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                                ((SUM(COALESCE(PRO.BDVLRITEM, 0)) +
                                  SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) +
                                  SUM(COALESCE(PRO.BDVLRIPI, 0)) +
                                  SUM(COALESCE(PRO.BDVLRST, 0)) +
                                  SUM(COALESCE(PRO.BDVLRFRETE, 0))) -
                                 SUM(COALESCE(PRO.BDVLRDESC, 0))
                                 ) BDVLRDIF
                         FROM (
                               SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                               FROM VEF_EMP_TMOVENT M
                               JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                               WHERE M.BDCODEMP = :PRCODEMP
                               AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                               AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                               AND M.BDMODELO IN (1, 4, 55, 65, 100)
                               AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                              ) MOV
                         JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
                        ) C190_TOT
                   GROUP BY C190_TOT.BDCODEMP, C190_TOT.BDCHAVE
                  ) TOT ON(TOT.BDCODEMP = C190.BDCODEMP AND TOT.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN (
                   SELECT M.BDCODEMP, M.BDCHAVE, SUM(COALESCE(I.BDVLRST, 0)) BDVLRSTITEM
                   FROM VEF_EMP_TMOVENT M
                   JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                   WHERE M.BDCODEMP = :PRCODEMP
                   AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                   AND M.BDMODELO IN (1, 4, 55, 65, 100)
                   AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                   GROUP BY M.BDCODEMP, M.BDCHAVE
                  ) ITEM ON(ITEM.BDCODEMP = C190.BDCODEMP AND ITEM.BDCHAVE = C190.BDCHAVE);

  /*Monta o C190 a partir da tabela do C190*/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C190.'||LPAD(GETORDEMSEQUENCIAL(MOV.BDCHAVE), 6, '0'),
          'C190' BDREG,
          '|C190'||
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLROPER, 0.00), '.', ',')|| --VL_OPR
          '|'||REPLACE(COALESCE(C190.BDVLRBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLRBCICMSST, 0.00), '.', ',')|| --VL_BC_ICMS_ST
          '|'||REPLACE(COALESCE(C190.BDVLRICMSST, 0.00), '.', ',')|| --VL_ICMS_ST
          '|'||REPLACE(IIF((SUBSTRING(COALESCE(ICMS.BDCSTICMS, 0) FROM CHAR_LENGTH(ICMS.BDCSTICMS)-1 FOR 2)) IN(20, 70), (COALESCE(C190.BDVLROPER, 0) - COALESCE(C190.BDVLRBCICMS, 0)), 0.00), '.', ',')|| --VL_RED_BC
          '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
          '|'|| --COD_OBS
          '|'
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM, ENT.BDCODSITNF, I.BDCODNAT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODSITNF
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODSITNF
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND ((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) OR (M.BDCODSITNF = 6) OR ((M.BDCODSITNF = 8) AND (M.BDMODELO = 1))) /*Sol. 20290 Gabriel Ariel (13/11/2017) - Agora exporta o C190 caso possua modelo 1 e siua??o 8*/
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
        WHERE ((NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (ENT.BDCODSITNF = 6))
       ) MOV
  JOIN VEF_EMP_TC190ENT C190 ON(C190.BDCODEMP = MOV.BDCODEMP AND C190.BDCHAVE = MOV.BDCHAVE AND C190.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = C190.BDCODCSTICMS);

  /*****************************************************************************
   *                                   C195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C195.'||LPAD(C195.BDORDEMOBS, 6, '0'),
         'C195' BDREG,
         '|C195'||
         '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
         '|'||TRIM(COALESCE(REPLACE(C195.BDDESCCOMPL, '|', ''), ''))|| --TXT_COMPL
         '|',
          C195.BDCODOBS
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE
        FROM VEF_EMP_TMOVENT ENT
        WHERE ENT.BDCODEMP = :PRCODEMP
        AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND ENT.BDCODSITNF NOT IN(2, 3, 4, 5)
       ) MOV
  JOIN VEF_EMP_TC195ENT C195 ON(C195.BDCODEMP = MOV.BDCODEMP AND C195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = C195.BDCODOBS);

  /*****************************************************************************
   *                                   C197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C195.'||LPAD(C197.BDORDEMOBS, 6, '0')||'.C197.'||LPAD(C197.BDORDEMOUTOBR, 6, '0'),
         'C197' BDREG,
         '|C197'||
         '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
         '|'||TRIM(COALESCE(REPLACE(C197.BDDESCCOMPL, '|', ''), ''))|| --DESCR_COMPL_AJ
         '|'||COALESCE(IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), VINC.BDCODPROD, VINC.BDCODSAIDA), '')|| --COD_ITEM
         '|'||REPLACE(COALESCE(C197.BDBICMS, 0.00), '.', ',')|| --VL_BC_ICMS
         '|'||REPLACE(CAST(COALESCE(C197.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
         '|'||REPLACE(COALESCE(C197.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
         '|'||REPLACE(COALESCE(C197.BDOUTVLR, 0.00), '.', ',')|| --VL_OUTROS
         '|', C197.BDCODPROD
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE
        FROM VEF_EMP_TMOVENT ENT
        WHERE ENT.BDCODEMP = :PRCODEMP
        AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND ENT.BDCODSITNF NOT IN(2, 3, 4, 5)
       ) MOV
  JOIN VEF_EMP_TC195ENT C195 ON(C195.BDCODEMP = MOV.BDCODEMP AND C195.BDCHAVE = MOV.BDCHAVE AND C195.BDCODOBS IS NOT NULL)
  JOIN VEF_EMP_TC197ENT C197 ON(C197.BDCODEMP = C195.BDCODEMP AND C197.BDCHAVE = C195.BDCHAVE AND C197.BDORDEMOBS = C195.BDORDEMOBS)
  LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = C197.BDCODAJU)
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = MOV.BDCODEMP AND VINC.BDCODPROD = C197.BDCODPROD);
END
^

/* Alter (SP_EXPORTA_BLOCOC_SAI) */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
BEGIN
  --22326
  /*****************************************************************************
   *--------------------------------->>SA?DA<<---------------------------------*
   ****************************************************************************/

   /*
     OBS: A Orderna??o dos registros ? feita pelo campo BDCHAVEREG que ? uma classifica??o.
          Classifica??o: Empresa.Chave.Reg.Chave.Reg....
          EX: C170: 000010.0000012587.C100.C170.000001
              C195: 000010.0000012587.C100.C195.000001
              C197: 000010.0000012587.C100.C195.000001.C197.000001
   */

  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
  SELECT  :PRARQUIVO BDID,
          LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100',
          'C100' BDREG,
          ('|C100|1|'||M.BDEMITENTE||         --IND_EMIT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))))|| --COD_PART
           '|'||MOD.BDMODELOSTR||             --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
           '|'||M.BDSERIE||                   --SER
           '|'||M.BDNUMDOCINI||               --NUM_DOC
           '|'||COALESCE(IIF(M.BDMODELO IN (55, 65), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'DDMMYYYY')))|| --DT_E_S
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(SAI.BDVLRCONTAB, '.', ','))|| --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))|| --IND_PGTO
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))||   --VL_DESC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_ABAT_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ','))||    --VL_MERC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN M.BDMODELO = 65 THEN '9' WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRFRETE, 0.00), '.', ','))||  --VL_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRSEGURO, 0.00), '.', ','))|| --VL_SEG
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLROUTDESP, 0.00), '.', ','))||--VL_OUT_DA
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRICMS, 0.00), '.', ','))||    --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDBASEST, 0.00), '.', ',')))||          --VL_BC_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDVLRST, 0.00), '.', ',')))||           --VL_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDVLRIPI, 0.00), '.', ',')))||          --VL_IPI
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPIS, 0.00), '.', ',')))||      --VL_PIS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINS, 0.00), '.', ',')))||   --VL_COFINS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPISST, 0.00), '.', ',')))||    --VL_PIS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINSST, 0.00), '.', ',')))|| --VL_COFINS_ST
           '|') BDLINHA, IIF(((M.BDMODELO = 65) OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVsai M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) SAI
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = SAI.BDCODEMP AND C100.BDCHAVE = SAI.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE)
  LEFT OUTER JOIN (
                   SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM
                   FROM VEF_EMP_TMOVPROSAI P
                   WHERE P.BDCODEMP = :PRCODEMP
                   GROUP BY P.BDCODEMP, P.BDCHAVE
                  ) PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   C101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C101.0000000001',
             'C101' BDREG,
             '|C101|'||REPLACE(COALESCE(C.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVSAI M
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDMODELO = 55
            AND M.BDVALORNOTA > 0
            AND M.BDCODSITNF NOT IN(1, 7)
            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
           ) MOV
      JOIN VEF_EMP_TC100SAI C ON(C.BDCODEMP = MOV.BDCODEMP AND C.BDCHAVE = MOV.BDCHAVE AND
                                 (((C.BDVLR_FCP_UF_DEST IS NOT NULL) AND (C.BDVLR_FCP_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_DEST IS NOT NULL) AND (C.BDVLRICMS_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_REM IS NOT NULL) AND (C.BDVLRICMS_UF_REM > 0))));
    END

  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C110                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODINFCOM, BDORDEMINFCOM)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0'),
             'C110' BDREG,
             '|C110|'||COALESCE(CADINF.BDCODINFCOM, '')||
             '|'||COALESCE(TRIM(REPLACE(SUBSTRING(MOVINF.BDDESCCOMPIC FROM 1 FOR 255), '|', '')), '')||'|',
             CADINF.BDCODINFCOM, CADINF.BDORDEMINFCOM
      FROM (
            SELECT INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON(CADINF.BDORDEMINFCOM = MOVINF.BDORDEMINFCOM AND CADINF.BDCODEMP = MOVINF.BDCODEMP);
    
      /*****************************************************************************
       *                                   C111                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C111.'||LPAD(REF.BDORDEMPROREF, 6, '0'),
             'C111',
             '|C111|'||COALESCE(TRIM(REF.BDNUMPROC), '')||
             '|'||IIF(REF.BDINDPROCESSO = '4', '9', COALESCE(REF.BDINDPROCESSO, ''))||'|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIPROREF REF ON(REF.BDCODEMP = MOVINF.BDCODEMP AND REF.BDCHAVE = MOVINF.BDCHAVE AND REF.BDORDEMIC = MOVINF.BDORDEMIC);
    
      /*****************************************************************************
       *                                   C112                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C112.'||LPAD(C112.BDORDEMDOCAREF, 6, '0'),
             'C112',
             '|C112'||
             '|'||COALESCE(C112.BDMODCODDA, 0)|| --COD_DA
             '|'||COALESCE(UF.BDSIGLAUF, '')||   --UF
             '|'||COALESCE(C112.BDNUMDA, '')||   --NUM_DA
             '|'||COALESCE(C112.BDCODAUT, '')||  --COD_AUT
             '|'||REPLACE(CAST(COALESCE(C112.BDVLRDA, 0.00) AS NUMERIC(15, 2)), '.', ',')|| --VL_DA
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTVCTO, 'DDMMYYYY'))||        --DT_VCTO
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTPGTO, 'DDMMYYYY'))||        --DT_PGTO
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIDOCAREF C112 ON(C112.BDCODEMP = MOVINF.BDCODEMP AND C112.BDCHAVE = MOVINF.BDCHAVE AND C112.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C112.BDCODUF);
    
      /*****************************************************************************
       *                                   C113                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C113.'||LPAD(C113.BDORDEMDOCFREF, 6, '0'),
             'C113',
             '|C113'||
             '|'||IIF(C113.BDINDOPER IS NULL, 1, C113.BDINDOPER)|| --IND_OPER
             '|'||COALESCE(C113.BDINDEMIT, 0)||   --IND_EMIT
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C113.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')|| --COD_MOD
             '|'||COALESCE(C113.BDSERIE, '')||    --SER
             '|'||COALESCE(C113.BDSUBSERIE, '')|| --SUB
             '|'||COALESCE(C113.BDNUMDOC, '')||   --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C113.BDDTEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||COALESCE(IIF(((DOCFIS.BDDOCFIS IN(55, 57, 65)) AND (:PRDTINI > '12/31/2016')), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_DOCe
             '|', C113.BDCODTER
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C113.BDCODDOCFIS)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER= C113.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C113.bdcodter);
    
      /*****************************************************************************
       *                                   C114                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C114.'||LPAD(C114.BDORDEMCUPREF, 6, '0'),
             'C114',
             '|C114'||
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')||   --COD_MOD
             '|'||COALESCE(C114.BDNRSERCAIXA, '')|| --ECF_FAB
             '|'||COALESCE(C114.BDNUMCAIXA, '')||   --ECF_CX
             '|'||COALESCE(C114.BDNUMDOC, '')||     --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C114.BDDTDOC, 'DDMMYYYY')), '')||
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAICUPREF C114 ON(C114.BDCODEMP = MOVINF.BDCODEMP AND C114.BDCHAVE = MOVINF.BDCHAVE AND C114.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C114.BDCODDOCFIS);
    
      /*****************************************************************************
       *                                   C115                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(C115.BDCODEMP, 6, '0')||'.1.'||LPAD(C115.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(C115.BDORDEMIC, 6, '0')||'.C115.'||LPAD(C115.BDORDEMLOCCOL, 6, '0'),
             'C115',
             '|C115'||
             '|'||COALESCE(TIP.BDCODEXPTRAN, '')|| --IND_CARGA
             '|'||IIF(CHAR_LENGTH(COALESCE(TERCOL.BDCGCTER, '')) = 18, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna s? CNPJ*/, TERCOL.BDCODTER, TERCOL.BDCGCTER, '', '')), '')|| --CNPJ_COL
             '|'||COALESCE(REPLACE(REPLACE(UPPER((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERCOL.BDIETER))), 'ISENTO', ''), 'ISENTA', ''), '')|| --IE_COL
             '|'||IIF(CHAR_LENGTH(COALESCE(TERCOL.BDCGCTER, '')) = 18, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna s? CNPJ*/, TERCOL.BDCODTER, TERCOL.BDCGCTER, '', '')))|| --CPF_COL
             '|'||COALESCE(CIDCOL.BDCODIBGE, '')|| --COD_MUN_COL
             '|'||IIF(CHAR_LENGTH(COALESCE(TERENTG.BDCGCTER, '')) = 18, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna s? CNPJ*/, TERENTG.BDCODTER, TERENTG.BDCGCTER, '', '')), '')|| --CNPJ_ENTG
             '|'||COALESCE(REPLACE(REPLACE(UPPER((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERENTG.BDIETER))), 'ISENTO', ''), 'ISENTA', ''), '')|| --IE_ENTG
             '|'||IIF(CHAR_LENGTH(COALESCE(TERENTG.BDCGCTER, '')) = 18, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna s? CNPJ*/, TERENTG.BDCODTER, TERENTG.BDCGCTER, '', '')))|| --CPF_ENTG
             '|'||COALESCE(CIDENTG.BDCODIBGE, '')|| --COD_MUN_ENTG
             '|'
      FROM (
            SELECT C115.BDCODEMP, C115.BDCHAVE, C115.BDORDEMIC, C115.BDORDEMLOCCOL, C115.BDCODTRAN,
                   C115.BDCODTERCOLETA, C115.BDCODCIDCOLETA, C115.BDCODTERENTREGA, C115.BDCODCIDENTREGA
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE
                        FROM VEF_EMP_TMOVSAI M
                        WHERE M.BDCODEMP = :PRCODEMP
                        AND M.BDMODELO IN (1, 4, 55, 100)
                        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                       ) MOV
                  JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                 ) MOVINF
            JOIN VEF_EMP_TMOVSAILOCCOL C115 ON (C115.BDCODEMP = MOVINF.BDCODEMP AND C115.BDCHAVE = MOVINF.BDCHAVE AND C115.BDORDEMIC = MOVINF.BDORDEMIC)
           ) C115
      LEFT OUTER JOIN VEF_BASE_TTABTIPOTRAN TIP ON (TIP.BDCODTRAN = C115.BDCODTRAN)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERCOL ON (TERCOL.BDCODTER = C115.BDCODTERCOLETA)
      LEFT OUTER JOIN TCIDADE CIDCOL  ON (CIDCOL.BDCODCID  = C115.BDCODCIDCOLETA)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERENTG ON (TERENTG.BDCODTER = C115.BDCODTERENTREGA)
      LEFT OUTER JOIN TCIDADE CIDENTG ON (CIDENTG.BDCODCID = C115.BDCODCIDENTREGA);
    
      /*****************************************************************************
       *                                   C140                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.1.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C140',
             '|C140'||
             '|'||COALESCE(MOV.BDEMITENTE, '')|| --IND_EMIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN '00'
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN '01'
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN '02'
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN '03'
                       ELSE '99'
                  END|| --IND_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN ''
                       ELSE COALESCE(PAR.BDOUTROSPAR, '')
                  END|| --DESC_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN PAR.BDDUPLICATAPAR
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN PAR.BDCHEQUEPAR
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN PAR.BDPROMISSPAR
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN PAR.BDOUTROSPAR
                       ELSE COALESCE(PAR.BDOUTROSPAR, MOV.BDNUMDOCINI)
                  END|| --NUM_TIT
             '|'||COALESCE(TOTPAR.BDQTDPAR, '')|| --QTD_PARC
             '|'||REPLACE(COALESCE(TOTPAR.BDVALORDUPLICATA, 0.00), '.', ',')|| --VL_TIT
             '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDEMITENTE,
                   SAI.BDVALORNOTA, SAI.BDNUMDOCINI
            FROM VEF_EMP_TMOVSAI SAI
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO = 1 --somente modelo 1
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5)
           ) MOV
      JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE AND PAR.BDORDEMPAR = (SELECT MIN(P.BDORDEMPAR) FROM VEF_EMP_TMOVSAIPAR P WHERE P.BDCODEMP = PAR.BDCODEMP AND P.BDCHAVE = PAR.BDCHAVE))
      LEFT OUTER JOIN (
                       SELECT P.BDCODEMP, P.BDCHAVE, COUNT(P.BDORDEMPAR) BDQTDPAR, SUM(COALESCE(P.BDVALORPAR, 0)) BDVALORDUPLICATA
                       FROM VEF_EMP_TMOVSAIPAR P
                       GROUP BY P.BDCODEMP, P.BDCHAVE
                      ) TOTPAR ON(TOTPAR.BDCODEMP = PAR.BDCODEMP AND TOTPAR.BDCHAVE = PAR.BDCHAVE);
    
      /*****************************************************************************
       *                                   C141                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.1.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.C141.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C141',
             '|C141'||
             '|'||PAR.BDORDEMPAR|| --NUM_PARC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(PAR.BDDATAVENCTOPAR, 'DDMMYYYY')), '')|| --DT_VCTO
             '|'||REPLACE(COALESCE(PAR.BDVALORPAR, 0.00), '.', ',')|| --VL_PARC
             '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDEMITENTE,
                   SAI.BDVALORNOTA, SAI.BDNUMDOCINI
            FROM VEF_EMP_TMOVSAI SAI
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO = 1 --somente modelo 1
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5)
           ) MOV
      JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
      ORDER BY PAR.BDORDEMPAR;

      /*****************************************************************************
       *                                   C160                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(C160.BDCODEMP, 6, '0')||'.1.'||LPAD(C160.BDCHAVE, 10, '0')||'.C100.C160.0000000001',
             'C160',
             '|C160'||
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C160.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(REPLACE(C160.BDPLACAID, '-', ''), '')|| --VEIC_ID
             '|'||REPLACE(COALESCE(CAST(C160.BDQTDVOLTRAN AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --QTD_VOL
             '|'||REPLACE(COALESCE(CAST(C160.BDPESOBRUTO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_BRT
             '|'||REPLACE(COALESCE(CAST(C160.BDPESOLIQUIDO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_LIQ
             '|'||COALESCE(UF.BDSIGLAUF, '')|| --UD_ID
             '|', C160.BDCODTER
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE
            FROM VEF_EMP_TMOVSAI SAI
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO IN(1, 4)
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5)
           ) MOV
      JOIN VEF_EMP_TMOVSAIVLTRAN C160 ON(C160.BDCODEMP = MOV.BDCODEMP AND C160.BDCHAVE = MOV.BDCHAVE)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C160.BDCODUF)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = C160.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C160.BDCODTER);
    END

  /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCODNAT)
  SELECT  :PRARQUIVO BDID,
         LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
          'C170' BDREG,
          '|C170'||
          '|'||GETORDEMSEQUENCIAL(PRO.BDCHAVE)|| --NUM_ITEM
          --#Alt:21967. Quando a empresa n?o possu?a o respectivo produto vinculado o registro estava levando vazio. Quando isso acontecer foi
          --tratado para levar a informa??o do produto ?nico. Esse tratamento ? feito para o c?digo e a descri??o.
          --'|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), COALESCE(VINC.BDCODPROD,''), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          --'|'||TRIM(REPLACE(COALESCE(VINC.BDDESCPROD, ''), '|', ''))|| --DESCR_COMPL
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                   IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                   COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          '|'||TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                                COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                                COALESCE(VINC.BDDESCPROD, '')), '|', ''))|| --DESCR_COMPL
          '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 5)), '.', ',')|| --QTD
          '|'||COALESCE(IIF(((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')), UN_REF.BDAPEUNIMED, UN.BDAPEUNIMED), '')|| --UNID
          '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
          '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
          '|'||IIF((UPPER(PRO.BDMOVFISICO) = 'TRUE'), 0, 1)|| --IND_MOV
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(SAI.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||COALESCE(SAI.BDCODNAT, '')|| --COD_NAT
          '|'||REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(COALESCE(PRO.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
          '|'||REPLACE(COALESCE(PRO.BDBCST, 0.00), '.', ',')||   --VL_BC_ICMS_ST
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ST
          '|'||REPLACE(COALESCE(PRO.BDVLRST, 0.00), '.', ',')||  --VL_ICMS_ST
          '|'|| --IND_APUR
          '|'||IIF(IPI.BDCODCSTIPI IS NULL, '', LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, 0))|| --CST_IPI
          '|'|| --COD_ENQ
          '|'||REPLACE(COALESCE(PRO.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQIPI, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_IPI
          '|'||REPLACE(COALESCE(PRO.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
          '|'||COALESCE(PIS.BDCSTPIS, '')|| --CST_PIS
          '|'||REPLACE(COALESCE(PRO.BDBCPIS, 0.00), '.', ',')|| --VL_BC_PIS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_PIS
          '|'||'0,00'|| --QUANT_BC_PIS
          '|'||'0,00'|| --ALIQ_PIS(em reais)
          '|'||REPLACE(COALESCE(PRO.BDVLRPIS, 0.00), '.', ',')|| --VL_PIS
          '|'||COALESCE(COF.BDCSTCOF, '')|| --CST_COFINS
          '|'||REPLACE(COALESCE(PRO.BDBCCOFINS, 0.00), '.', ',')|| --VL_BC_COFINS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_COFINS
          '|'||'0,00'|| --QUANT_BC_COFINS
          '|'||'0,00'|| --ALIQ_COFINS(em reais)
          '|'||REPLACE(COALESCE(PRO.BDVLRCOFINS, 0.00), '.', ',')|| --VL_COFINS
          '|'||COALESCE(PRO.BDCODCTA, '')|| --COD_CTA
          '|', PRO.BDCODPROD, SAI.BDCODNAT
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
       ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
  /*Produto*/
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)
  LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD) --#Alt:21967.
--  LEFT OUTER JOIN TCADPRO_REF REF ON(REF.BDCODEMP = PRO.BDCODEMP AND REF.BDCODPROD = PRO.BDCODPROD AND ((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')))
  /*Produto por refer?ncia*/
  LEFT OUTER JOIN TCADPRO_VINC VINC_REF ON(VINC_REF.BDCODEMP = PRO.BDCODEMP AND VINC_REF.BDCODPROD = PRO.BDCODPROD)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN_REF ON(UN_REF.BDCODUNIMED = VINC_REF.BDCODUNIMED)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
  LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = PRO.BDCODCSTCOF);

  IF (:PRPERFIL NOT IN (2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C172                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT  :PRARQUIVO BDID,
             LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C172.0000000001',
              'C172' BDREG,
              '|C172'||
              '|'||REPLACE(COALESCE(PRO.BDBCISSQN, 0.00), '.', ',')|| --VL_BC_ISSQN
              '|'||REPLACE(COALESCE(CAST(PRO.BDALIQISSQN AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --ALIQ_ISSQN
              '|'||REPLACE(COALESCE(PRO.BDVLRISSQN, 0.00), '.', ',')|| --VL_ISSQN
              '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE
                        FROM VEF_EMP_TMOVSAI M
                        WHERE M.BDCODEMP = :PRCODEMP
                        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        AND M.BDMODELO = 1
                        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                        AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                       ) MOV
                 ) SAI
            JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
           ) SAI
      JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM AND COALESCE(PRO.BDVLRISSQN, 0) > 0);
    
      /*****************************************************************************
       *                                   C173                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
               LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C173.'||LPAD(C173.BDORDEMOPMED, 6, '0'),
                'C173' BDREG,
                '|C173'||
                '|'||COALESCE(C173.BDNRLOTE, '')|| --LOTE_MED
                '|'||REPLACE(COALESCE(C173.BDQTDITEM, 0.00), '.', ',')|| --QTD_ITEM
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTFABMED, 'DDMMYYYY')), '')|| --DT_FAB
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTVALMED, 'DDMMYYYY')), '')|| --DT_VAL
                '|'||COALESCE(C173.BDINDTIPOMED, '')|| --IND_MED
                '|'||COALESCE(C173.BDTIPOMED, '')||    --TP_PROD
                '|'||REPLACE(COALESCE(CAST(C173.BDVLRMAXMED AS DM_NUMERIC_15_2), 0.00), '.', ',')||   --VL_TAB_MAX
                '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                              AND ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1))
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TOPMEDSAI C173 ON(C173.BDCODEMP = PRO.BDCODEMP AND C173.BDCHAVE = PRO.BDCHAVE AND C173.BDORDEM = PRO.BDORDEM AND C173.BDORDEMPRO = PRO.BDORDEMPRO);
    END

  /*****************************************************************************
   *                                   C176                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODTERAUX)
  SELECT  :PRARQUIVO BDID,
         LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C176.'||LPAD(C176.BDORDEMC176, 6, '0'),
          'C176' BDREG,
          '|C176'||
          '|'||COALESCE(L.BDMODELOSTR, '')|| --COD_MOD_ULT_E
          '|'||COALESCE(C176.BDNUM_DOC_ULT_E, '')|| --NUM_DOC_ULT_E
          '|'||COALESCE(C176.BDSER_ULT_E, '')|| --SER_ULT_E
          '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C176.BDDT_ULT_E, 'DDMMYYYY')), '')|| --DT_ULT_E
          '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C176.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART_ULT_E
          '|'||REPLACE(COALESCE(C176.BDQUANT_ULT_E, 0.000), '.', ',')|| --QUANT_ULT_E
          '|'||REPLACE(COALESCE(C176.BDVL_UNIT_ULT_E, 0.000), '.', ',')|| --VL_UNIT_ULT_E
          '|'||REPLACE(COALESCE(C176.BDVL_UNIT_BC_ST, 0.000), '.', ',')|| --VL_UNIT_BC_ST
          '|'||COALESCE(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_ULT_E)), 44, ' '), '')|| --CHAVE_NFE_ULT_E
          '|'||COALESCE(C176.BDNUM_ITEM_ULT_E, '')|| --VL_UNIT_BC_ST
          '|'||IIF(COALESCE(C176.BDVL_UNIT_BC_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_BC_ICMS_ULT_E, 0.00), '.', ','), '')|| --VL_UNIT_BC_ICMS_ULT_E
          '|'||IIF(COALESCE(C176.BDALIQ_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDALIQ_ICMS_ULT_E, 0.00), '.', ','), '')|| --ALIQ_ICMS_ULT_E
          '|'||IIF(COALESCE(C176.BDVL_UNIT_LIM_BC_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_LIM_BC_ICMS_ULT_E, 0.00), '.', ','), '')|| --VL_UNIT_LIMITE_BC_ICMS_ULT_E
          '|'||IIF(COALESCE(C176.BDVL_UNIT_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_ICMS_ULT_E, 0.000), '.', ','), '')|| --VL_UNIT_ICMS_ULT_E
          '|'||IIF(COALESCE(C176.BDALIQ_ST_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDALIQ_ST_ULT_E, 0.00), '.', ','), '')|| --ALIQ_ST_ULT_E
          '|'||IIF(COALESCE(C176.BDVL_UNIT_RES, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_RES, 0.000), '.', ','), '')|| --VL_UNIT_RES 
          '|'||COALESCE(IIF(C176.BDCOD_RESP_RET = -1, '', C176.BDCOD_RESP_RET + 1), '')|| --COD_RESP_RET
          '|'||COALESCE(M.BDCODEXPMOT, '')|| --COD_MOT_RES
          '|'||COALESCE(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_RET)), 44, ' '), '')|| --CHAVE_NFE_RET
          '|'||IIF(COALESCE(C176.BDCODTER_NFE, 0) > 0, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C176.BDCODTER_NFE, TER_NFE.BDCGCTER, TER_NFE.BDIETER, TerEmp_NFE.BDCODIGOARQUIVO)), '')|| --COD_PART_NFE_RET
          '|'||COALESCE(C176.BDSER_NFE_RET, '')||  --SER_NFE_RET
          '|'||COALESCE(C176.BDNUM_NFE_RET, '')||  --NUM_NFE_RET
          '|'||COALESCE(C176.BDITEM_NFE_RET, '')|| --ITEM_NFE_RET
          '|'||COALESCE(IIF(C176.BDCOD_DA = -1, '', C176.BDCOD_DA), '')|| --COD_DA
          '|'||COALESCE(C176.BDNUM_DA, '')|| --NUM_DA
          '|', C176.BDCODTER, C176.BDCODTER_NFE
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN(1, 55)
                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
       ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
  JOIN VEF_EMP_TMOVSTC176 C176 ON(C176.BDCODEMP = PRO.BDCODEMP AND C176.BDCHAVE = PRO.BDCHAVE AND C176.BDORDEM = PRO.BDORDEM AND C176.BDORDEMPRO = PRO.BDORDEMPRO)
  LEFT OUTER JOIN VEF_BASE_TTABMOTRES M ON (M.BDORDEMMOTRES = C176.BDORDEMMOTRES)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN L ON (L.BDMODELO = C176.BDMODELO)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = C176.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = C176.bdcodter)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER_NFE ON(TER_NFE.BDCODTER = C176.BDCODTER_NFE)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp_NFE ON (TerEmp_NFE.bdcodter = C176.BDCODTER_NFE);

  IF (:PRPERFIL NOT IN (2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C177                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C177.0000000001',
             'C177' BDREG,
             '|C177'||
             '|'||COALESCE(C177.BDCODSELOIPI, '')|| --COD_SELO_IPI
             '|'||COALESCE(C177.BDQTDSELOIPI, '')|| --QT_SELO_IPI
             '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                              AND ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1))
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TMOVPROSAIC177 C177 ON(C177.BDCODEMP = PRO.BDCODEMP AND C177.BDCHAVE = PRO.BDCHAVE AND C177.BDORDEM = PRO.BDORDEM AND C177.BDORDEMPRO = PRO.BDORDEMPRO AND C177.BDCODSELOIPI > 0);
    
      /*****************************************************************************
       *                                   C178                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C178.0000000001',
             'C178' BDREG,
             '|C178'||
             '|'||COALESCE(CLIPI.BDCODCLASSEIPI, '')|| --CL_ENQ
             '|'||REPLACE(COALESCE(C178.BDVLRUNIDADE, 0.00), '.', ',')||  --VL_UNID
             '|'||REPLACE(COALESCE(CAST(C178.BDQTDUNIDADE AS DM_NUMERIC_18_3), 0.000), '.', ',')|| --QUANT_PAD
             '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                              AND ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1))
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TMOVPROSAIC178 C178 ON(C178.BDCODEMP = PRO.BDCODEMP AND C178.BDCHAVE = PRO.BDCHAVE AND C178.BDORDEM = PRO.BDORDEM AND C178.BDORDEMPRO = PRO.BDORDEMPRO)
      LEFT OUTER JOIN VEF_BASE_TTABCLASSEIPI CLIPI ON (CLIPI.BDORDEMCLAIPI = C178.BDORDEMCLAIPI)
      WHERE ((CLIPI.BDCODCLASSEIPI IS NOT NULL) AND (CLIPI.BDCODCLASSEIPI <> ''));
    END

  /*****************************************************************************
   *                                   C190                                    *
   ****************************************************************************/
   /*PARA FAZER O SELECT, NO LUGAR DO GETORDEM(0) COLOCAR (GETORDEM(0)+1), CASO FOR FAZER INSERT SELECT N?O COLOCAR O +1*/
  SETORDEMSEQUENCIAL(0);
  /*Monta o C190 a partir do movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
        LPAD(C190.BDCODEMP, 6, '0')||'.1.'||LPAD(C190.BDCHAVE, 10, '0')||'.C100.C190.'||LPAD(GETORDEMSEQUENCIAL(C190.BDCHAVE), 10, '0'),
        'C190' BDREG,
        '|C190'||
        '|'||COALESCE(C190.BDCSTICMS, '')|| --CST_ICMS
        '|'||COALESCE(C190.BDCODNAT, '')|| --CFOP
        '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),
                                                      (IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0.00), '.', ',')|| --VL_OPR
        '|'||REPLACE(COALESCE(C190.BDBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
        '|'||REPLACE(COALESCE(C190.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, C190.BDBCST), 0.00), '.', ',')|| --VL_BC_ICMS_ST
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, C190.BDVLRST), 0.00), '.', ',')|| --VL_ICMS_ST
--        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((COALESCE(C190.BDVLRITEM, 0) + COALESCE(C190.BDVLRDESPACESSORIA, 0) + COALESCE(C190.BDVLRIPI, 0) + COALESCE(C190.BDVLRST, 0)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
        '|'|| --COD_OBS
        '|'
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, MOV.BDCODNAT, MOV.BDALIQICMS, SAI.BDMODELO, MOV.BDVLRITEM,
               MOV.BDVLRDESC, MOV.BDVLRFRETE, MOV.BDVLRDESPACESSORIA, MOV.BDVLRIPI, MOV.BDVLRST, MOV.BDBCICMS,
               MOV.BDVLRICMS, MOV.BDBCST, MOV.BDREDBCICMS, SAI.BDVALORNOTA,
               (COALESCE(MOV.BDVLRFRETE, 0) + COALESCE(MOV.BDVLRITEM, 0) +
                COALESCE(MOV.BDVLRDESPACESSORIA, 0) + COALESCE(MOV.BDVLRIPI, 0) +
                COALESCE(MOV.BDVLRST, 0) - COALESCE(MOV.BDVLRDESC, 0)) BDVLRTOT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                     COALESCE(PRO.BDCODCSTICMS, 0) BDCODCSTICMS,
                     COALESCE(MOV.BDCODNAT, 0) BDCODNAT,
                     CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS,
                     SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                     SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                     SUM(COALESCE(PRO.BDVLRFRETE, 0)) BDVLRFRETE,
                     SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) BDVLRDESPACESSORIA,
                     SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI,
                     SUM(COALESCE(PRO.BDVLRST, 0)) BDVLRST,
                     SUM(COALESCE(PRO.BDBCST, 0)) BDBCST,
                     SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS,
                     SUM(COALESCE(PRO.BDVLRICMS, 0)) BDVLRICMS,
                     SUM(COALESCE(PRO.BDREDBCICMS, 0)) BDREDBCICMS
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                    FROM VEF_EMP_TMOVSAI M
                    JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                   ) MOV
              JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
              GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
             ) MOV
        JOIN VEF_EMP_TMOVSAI SAI ON(SAI.BDCODEMP = MOV.BDCODEMP AND SAI.BDCHAVE = MOV.BDCHAVE)
        LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
       ) C190
  LEFT OUTER JOIN (
                   SELECT C190_TOT.BDCODEMP, C190_TOT.BDCHAVE, SUM(C190_TOT.BDVLRDIF) BDVLRDIF, COUNT(C190_TOT.BDCHAVE) BDORDEMMAX
                   FROM (
                         SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                                ((SUM(COALESCE(PRO.BDVLRITEM, 0)) +
                                  SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) +
                                  SUM(COALESCE(PRO.BDVLRIPI, 0)) +
                                  SUM(COALESCE(PRO.BDVLRST, 0)) +
                                  SUM(COALESCE(PRO.BDVLRFRETE, 0))) -
                                 SUM(COALESCE(PRO.BDVLRDESC, 0))
                                 ) BDVLRDIF     
                         FROM (
                               SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                               FROM VEF_EMP_TMOVSAI M
                               JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                               WHERE M.BDCODEMP = :PRCODEMP
                               AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                               AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                               AND M.BDMODELO IN (1, 4, 55, 65, 100)
                               AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                              ) MOV
                         JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
                        ) C190_TOT
                   GROUP BY C190_TOT.BDCODEMP, C190_TOT.BDCHAVE
                  ) TOT ON(TOT.BDCODEMP = C190.BDCODEMP AND TOT.BDCHAVE = C190.BDCHAVE);

  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  /*Monta o C190 a partir da tabela do C190*/
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C190.'||LPAD(GETORDEMSEQUENCIAL(MOV.BDCHAVE), 6, '0'),
          'C190' BDREG,
          '|C190'||
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLROPER, 0.00), '.', ',')|| --VL_OPR
          '|'||REPLACE(COALESCE(C190.BDVLRBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLRBCICMSST, 0.00), '.', ',')|| --VL_BC_ICMS_ST
          '|'||REPLACE(COALESCE(C190.BDVLRICMSST, 0.00), '.', ',')|| --VL_ICMS_ST
          '|'||REPLACE(IIF((SUBSTRING(COALESCE(ICMS.BDCSTICMS, 0) FROM CHAR_LENGTH(ICMS.BDCSTICMS)-1 FOR 2)) IN(20, 70), (COALESCE(C190.BDVLROPER, 0) - COALESCE(C190.BDVLRBCICMS, 0)), 0.00), '.', ',')|| --VL_RED_BC
          '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
          '|'|| --COD_OBS
          '|'
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODSITNF, I.BDCODNAT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODSITNF
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODSITNF
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND ((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) OR (M.BDCODSITNF = 6) OR ((M.BDCODSITNF = 8) AND (M.BDMODELO = 1))) /*Sol. 20290 Gabriel Ariel (13/11/2017) - Agora exporta o C190 caso possua modelo 1 e siua??o 8*/
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
        WHERE ((NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (SAI.BDCODSITNF = 6))
       ) MOV
  JOIN VEF_EMP_TC190SAI C190 ON(C190.BDCODEMP = MOV.BDCODEMP AND C190.BDCHAVE = MOV.BDCHAVE AND C190.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = C190.BDCODCSTICMS);

  /*Estourou o tamanho m?ximo da sp, ent?o a exporta??o dos registros C195 e 197 est?o na SP abaixo.
    Exporta??o de novos registros devem ser feitos na nova SP_EXPORTA_BLOCOC_SAI_AUX*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_AUX(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :PRTIPOEXPCODPART, :PRPERFIL);
END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOC_CONTRIBUICOES for: SP_EXPORTA_BLOCOC_SAI_SPEDCONTR */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_CONTRIBUICOES(PRCODEMP VARCHAR(500),
PRCODPLAPADRAOREF INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_EXPORTA_BLOCOC_SAI_SPEDCONTR) */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(PRCODEMP INTEGER,
PRCODPLAPADRAOREF INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100))
 AS
/*DECLARE VARIABLE WCNPJEMP VARCHAR(18);*/
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WMIN INTEGER;
DECLARE VARIABLE WMAX INTEGER;
DECLARE VARIABLE WCHAVEREG VARCHAR(80);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WALIQPIS NUMERIC(15,6);
DECLARE VARIABLE WALIQCOFINS NUMERIC(15,6);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
BEGIN
  --Pega da matriz
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));  
  
  SELECT FIRST 1 SPED.BDINCTRIB, SPED.BDCODCRIT
  FROM (
        SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ
        FROM vw_tempresas_ref tbem
        JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP)
        WHERE TBEM.BDCODEMP = :PRCODEMP
        GROUP BY BDCODMATRIZ
       ) EMP
  JOIN VW_INT_SPEDPISCOFINS_REF SPED ON(SPED.BDCODEMP = EMP.BDCODMATRIZ AND SPED.BDREFERENCIA <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')))
  ORDER BY SPED.BDREFERENCIA DESC
  INTO :wIncTrib, :wCodCrit;

  IF (NOT((:wIncTrib = 1) AND (:wCodCrit IN(1, 2)))) THEN
    BEGIN
      /*****************************************************************************
       *                                   C860                                    *
       ****************************************************************************/
      /*Salva os n?meros de documento menores e maiores por data de emissao e modelo na DLL, na hora de montar o registro busca os dados na DLL*/
      FREEANDNIL_C800(0);
      FOR SELECT S.BDDATAEMISSAO, MIN(S.BDNUMDOCINI) BDMIN, MAX(S.BDNUMDOCINI) BDMAX
          FROM VEF_EMP_TMOVSAI S
          WHERE S.BDCODEMP = :PRCODEMP
          AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
          AND S.BDMODELO = 59
          AND S.BDCODSITNF NOT IN(2, 3, 4, 5)
          GROUP BY S.BDDATAEMISSAO, S.BDMODELO
          INTO :wData, :wMin, :wMax
      DO
        BEGIN
          SETNUMDOC_C800(:wData, 59, :wMin, :wMax);
        END
    
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO, 'C860.'||(MOV.BDCODEMP||'_'||COALESCE(MOV.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO),
             'C860' BDREG,
             '|C860|59'||
             '|'||COALESCE(MOV.BDNRSERIE, '')|| --NR_SAT
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||MOV.BDNUMDOCINI|| --DOC_INI
             '|'||MOV.BDNUMDOCFIM|| --DOC_FIM
             '|'
      FROM (
            SELECT M.BDCODEMP, M.BDDATAEMISSAO,
                   GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) BDNUMDOCINI,
                   GETNUMDOC_C800_MAX(M.BDDATAEMISSAO, 59) BDNUMDOCFIM,
                   EQ.BDNRSERIE
            FROM VEF_EMP_TMOVSAI M
            LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = M.BDCODEMP AND EQ.BDCODEQUIPSAT = M.BDCODEQUIPSAT)
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND M.BDMODELO = 59
            AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
            GROUP BY M.BDCODEMP, M.BDDATAEMISSAO, BDNUMDOCINI, BDNUMDOCFIM, EQ.BDNRSERIE
           ) MOV;
    
      /*****************************************************************************
       *                                   C870                                    *
       ****************************************************************************/
      /*Grava os dados cfop, al?quota pis, al?quota cofins na DLL*/
      FOR SELECT 'C860.'||(MOV.BDCODEMP||'_'||COALESCE(EQ.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||MOV.BDNUMDOCINI||'_'||COALESCE(PRO.BDCODPROD, '')||'_'||LPAD(COALESCE(PIS.BDCSTPIS, ''), 3, '0')||'_'||LPAD(COALESCE(COF.BDCSTCOF, ''), 3, '0')||'_'||LPAD(COALESCE(PRO.BDCODPLAPADRAO, ''), 9, '0')||'_'||LPAD(COALESCE(PRO.BDCODTPLA, ''), 9, '0')) BDCHAVEREG,
                 MOV.BDCODNAT, PRO.BDALIQPIS, PRO.BDALIQCOFINS, MOV.BDCHAVE, MOV.BDORDEM
          FROM (
                SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODEQUIPSAT,
                       SAI.BDDATAEMISSAO, I.BDCODNAT, SAI.BDNUMDOCINI
                FROM (
                      SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEQUIPSAT,
                             MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI
                      FROM (
                            SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODEQUIPSAT, M.BDDATAEMISSAO,
                                   (SELECT GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) FROM RDB$DATABASE) BDNUMDOCINI
                            FROM VEF_EMP_TMOVSAI M
                            WHERE M.BDCODEMP = :PRCODEMP
                            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                            AND M.BDMODELO = 59
                            AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                           ) MOV
                     ) SAI
                JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
               ) MOV
          LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = MOV.BDCODEMP AND EQ.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT)
          LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
          LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
          LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
          INTO :wChaveReg, :wCodNat, :wAliqPIS, :wAliqCofins, :wChave, :wOrdem
      DO
        BEGIN
          SET_C870(:wChaveReg, :wAliqPIS, :wAliqCofins, :wCodNat, :wChave, :wOrdem);
        END

      DELETE FROM TMP_TOL_VEF_EMP_TMOVSAI;
    
      INSERT INTO TMP_TOL_VEF_EMP_TMOVSAI(BDCHAVESAI, BDORDEM, BDCHAVE, BDCODEMP)
      SELECT T.BDCHAVESAI, T.BDORDEM, MIN(T.BDCHAVE) BDCHAVE, T.BDCODEMP
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDMODELO = 59
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
           ) S
      JOIN TOL_VEF_EMP_TMOVSAI T ON(T.BDCODEMP = S.BDCODEMP AND T.BDCHAVESAI = S.BDCHAVE)
      GROUP BY T.BDCHAVESAI, T.BDORDEM, T.BDCODEMP;

      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCHAVE, BDCODEMP)
      SELECT :PRARQUIVO, MOV.BDCHAVEREG,
             'C870' BDREG,
             '|C870'||
             '|'||COALESCE(IIF(COALESCE(PRO_VINC.BDCODSAIDA, '') = '', PRO_VINC.BDCODPROD, PRO_VINC.BDCODSAIDA), '')|| --COD_ITEM
             '|'||COALESCE(SUBSTRING(GETCFOP_C870(MOV.BDCHAVEREG) FROM 1 FOR 4), '')|| --CFOP
             '|'||REPLACE(MOV.BDVLRITEM, '.', ',')|| --VL_ITEM
             '|'||REPLACE(MOV.BDVLRDESC, '.', ',')|| --VL_DESC
             '|'||COALESCE(LPAD(MOV.BDCSTPIS, 2, '0'), '')|| --CST_PIS
             '|'||REPLACE(MOV.BDBCPIS, '.', ',')|| --VL_BC_PIS
             '|'||COALESCE(REPLACE(CAST(IIF(MOV.BDALIQPIS = '', '0', MOV.BDALIQPIS) AS NUMERIC(8, 4)), '.', ','), '')|| --ALIQ_PIS
             '|'||REPLACE(MOV.BDVLRPIS, '.', ',')|| --VL_PIS
             '|'||COALESCE(LPAD(MOV.BDCSTCOF, 2, '0'), '')|| --CST_COFINS
             '|'||REPLACE(MOV.BDBCCOFINS, '.', ',')|| --VL_BC_COFINS
             '|'||COALESCE(REPLACE(CAST(IIF(MOV.BDALIQCOFINS = '', '0', MOV.BDALIQCOFINS) AS NUMERIC(8, 4)), '.', ','), '')|| --ALIQ_COFINS
             '|'||REPLACE(MOV.BDVLRCOFINS, '.', ',')|| --VL_COFINS
             '|'||COALESCE(COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON), '')|| --COD_CTA
             '|', PRO_VINC.BDCODPROD, COALESCE(ccl.bdcodtpla,cclrat.bdcodtpla) bdcredito, (SELECT BDDATA FROM SP_PARSE_DATE(LAN.BDDATA, 'YYYY')) bdanocredito,
                  COALESCE(MOV.bdcodplapadrao, lan.bdcodplapadrao) bdcodplapadrao, COALESCE(cclep.BDCODTPLAREF, ccderatp.BDCODTPLAREF) bdcreditoref,
                  COALESCE(cclep.BDCODPLAPADRAOREF, ccderatp.BDCODPLAPADRAOREF) bdcreditoplapadraoref, COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON,
                  MOV.BDCHAVE, MOV.BDCODEMP
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, MOV.BDCODPROD, MOV.BDCSTPIS, MOV.BDCSTCOF, MOV.BDCODPLAPADRAO, MOV.BDCODTPLA,
                   GETCHAVE_C870(MOV.BDCHAVEREG) BDCHAVE, GETORDEM_C870(MOV.BDCHAVEREG) BDORDEM, MOV.BDCHAVEREG, MOV.BDVLRITEM, MOV.BDVLRDESC, MOV.BDBCPIS, MOV.BDVLRPIS,
                   MOV.BDBCCOFINS, MOV.BDVLRCOFINS, GETALIQPIS_C870(MOV.BDCHAVEREG) BDALIQPIS, GETALIQCOFINS_C870(MOV.BDCHAVEREG) BDALIQCOFINS
            FROM (
                  SELECT MOV.BDCODEMP, EQ.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, PRO.BDCODPROD, PIS.BDCSTPIS, COF.BDCSTCOF, PRO.BDCODPLAPADRAO, PRO.BDCODTPLA,
                         ('C860.'||MOV.BDCODEMP||'_'||COALESCE(EQ.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||MOV.BDNUMDOCINI||'_'||COALESCE(PRO.BDCODPROD, '')||'_'||LPAD(COALESCE(PIS.BDCSTPIS, ''), 3, '0')||'_'||LPAD(COALESCE(COF.BDCSTCOF, ''), 3, '0')||'_'||LPAD(COALESCE(PRO.BDCODPLAPADRAO, ''), 9, '0')||'_'||LPAD(COALESCE(PRO.BDCODTPLA, ''), 9, '0')) BDCHAVEREG,
                         SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                         SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                         SUM(COALESCE(PRO.BDBCPIS, 0)) BDBCPIS,
                         SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPIS,
                         SUM(COALESCE(PRO.BDBCCOFINS, 0)) BDBCCOFINS,
                         SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINS
                  FROM (
                        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODEQUIPSAT,
                               SAI.BDDATAEMISSAO, SAI.BDNUMDOCINI
                        FROM (
                              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEQUIPSAT,
                                     MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI
                              FROM (
                                     SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODEQUIPSAT, M.BDDATAEMISSAO,
                                           (SELECT GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) FROM RDB$DATABASE) BDNUMDOCINI
                                    FROM VEF_EMP_TMOVSAI M
                                    WHERE M.BDCODEMP = :PRCODEMP
                                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                                    AND M.BDMODELO = 59
                                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                                   ) MOV
                             ) SAI
                        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                       ) MOV
                  LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = MOV.BDCODEMP AND EQ.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT)
                  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                  LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
                  LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
                  GROUP BY MOV.BDCODEMP, EQ.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, PRO.BDCODPROD, PIS.BDCSTPIS, COF.BDCSTCOF, PRO.BDCODPLAPADRAO, PRO.BDCODTPLA
                 ) MOV
           ) MOV
      JOIN TCADPRO_VINC PRO_VINC ON(PRO_VINC.BDCODEMP = MOV.BDCODEMP AND PRO_VINC.BDCODPROD = MOV.BDCODPROD)
      LEFT OUTER JOIN TMP_TOL_VEF_EMP_TMOVSAI TOL ON(TOL.BDCHAVESAI = MOV.BDCHAVE AND TOL.BDORDEM = MOV.BDORDEM)
      LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.BDCODEMP = tol.bdcodemp AND lan.bdchave = tol.BDCHAVE)
      LEFT OUTER JOIN planos_tpla ccl ON (COALESCE(MOV.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) = ccl.bdcodplapadrao AND COALESCE(MOV.bdcodtpla, lan.bdcredito) = ccl.bdcodtpla)
      LEFT OUTER JOIN PLANOS_TPLA_ECF ccle ON (ccle.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                               AND ccle.bdano = (SELECT FIRST 1 BDANO
                                                                 FROM PLANOS_TPLA_ECF
                                                                 WHERE CAST(BDANO || '01' AS INTEGER) <= lan.bdreferencia
                                                                 AND BDCODTPLAREF IS NOT NULL
                                                                 AND CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                 AND CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                 AND CCLE.BDCODTPLA = BDCODTPLA
                                                                 ORDER BY BDANO DESC
                                                                )
                                               AND ccle.bdcodplapadrao = ccl.bdcodplapadrao AND ccle.bdcodtpla = ccl.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cclep ON (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF AND ccle.BDCODTPLAREF = cclep.BDCODTPLAREF)
     LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat ON (tolrat.bdcodemp = mov.bdcodemp AND tolrat.bdchavelan = mov.bdchave AND tolrat.bdordem = mov.bdordem)
     LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.BDCODEMP = tolrat.bdcodemp AND lanrat.bdchave = tolrat.BDCHAVE)
     LEFT OUTER JOIN planos_tpla cclrat ON (lanrat.BDCODPLAPADRAO = cclrat.bdcodplapadrao AND lanrat.bdcredito = cclrat.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON (CCDERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                                 CCDERAT.bdano =(SELECT FIRST 1 BDANO 
                                                                 FROM PLANOS_TPLA_ECF 
                                                                 WHERE CAST(BDANO || '01' AS INTEGER) <= lanrat.bdreferencia AND 
                                                                   BDCODTPLAREF IS NOT NULL AND 
                                                                   CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                                   CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                                   CCDERAT.BDCODTPLA = BDCODTPLA 
                                                                 ORDER BY BDANO DESC
                                                                ) AND
                                                 ccderat.bdcodplapadrao = cclrat.bdcodplapadrao AND ccderat.bdcodtpla = cclrat.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO ccderatp ON (ccderat.BDCODPLAPADRAOref = ccderatp.BDCODPLAPADRAOREF AND ccderat.BDCODTPLAREF = ccderatp.BDCODTPLAREF);

      /*****************************************************************************
       *                                   C890                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO, MOV.BDCHAVEREG,
             'C890' BDREG,
             '|C890'||
             '|'||COALESCE(MOV.BDNUMPROC, '')|| --NUM_PROC
             '|'||COALESCE(MOV.BDINDORIG, '')||  --IND_PROC
             '|'
      FROM (
            SELECT ('C860.'||MOV.BDCODEMP||'_'||COALESCE(MOV.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||'99999999_'||'99999999_'||'999_'||'999_999999999_999999999.C890.'||C890.BDNUMPROC||'_'||IND.BDINDORIG) BDCHAVEREG,
                   C890.BDNUMPROC, IND.BDINDORIG
            FROM (
                  SELECT M.BDCODEMP, M.BDDATAEMISSAO,
                         GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) BDNUMDOCINI,
                         GETNUMDOC_C800_MAX(M.BDDATAEMISSAO, 59) BDNUMDOCFIM,
                         EQ.BDNRSERIE,
                         EQ.BDCODEQUIPSAT
                  FROM VEF_EMP_TMOVSAI M
                  LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = M.BDCODEMP AND EQ.BDCODEQUIPSAT = M.BDCODEQUIPSAT)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDMODELO = 59
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                  GROUP BY M.BDCODEMP, M.BDDATAEMISSAO, M.BDCODEQUIPSAT, BDNUMDOCINI, BDNUMDOCFIM, EQ.BDNRSERIE, EQ.BDCODEQUIPSAT
                 ) MOV
            JOIN VEF_EMP_TPROCREFC890 C890 ON (C890.BDCODEMP = MOV.BDCODEMP AND C890.BDCHAVE = (SELECT FIRST 1 C.BDCHAVE
                                                                                                FROM VEF_EMP_TPROCREFC890 C
                                                                                                WHERE c.BDCODEMP = mov.BDCODEMP
                                                                                                AND c.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT
                                                                                                AND c.BDDTINIVIG <= mov.BDDATAEMISSAO
                                                                                                AND ((c.BDDTFINVIG IS NULL) OR (c.BDDTFINVIG >= mov.BDDATAEMISSAO))
                                                                                                ORDER BY C.BDDTINIVIG))
            LEFT OUTER JOIN VEF_BASE_TTABINDORIG IND ON (IND.BDORDEMINDORIG = C890.BDORDEMINDORIG)
           ) MOV;

      /*Destruindo a lista da DLL*/
--      FREEANDNIL_C800(0);
      DELETE FROM TMP_TOL_VEF_EMP_TMOVSAI;
    END
END
^

/* Alter (SP_EXPORTA_BLOCOD) */
ALTER PROCEDURE SP_EXPORTA_BLOCOD(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRVALIDAREXPORTACAO DM_BOOLEAN,
PRARQUIVO VARCHAR(100))
 AS
DECLARE VARIABLE WTIPOEXPCODPART INTEGER;
DECLARE VARIABLE WPERFILSPED INTEGER;
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200;
BEGIN

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1; /*N?o achou o TipoExpCodPart*/

  SELECT SP.BDPERFILSPED FROM SP_CONSULTAEMPRESAS_SIS((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')), :PRCODEMP, NULL) SP INTO :wPerfilSped;    

  wPerfilSped = COALESCE(:wPerfilSped, -1);  

  /*ENTRADA*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_ENT(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart);  

  /*SAIDA*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_SAI(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :wPerfilSped);

  /*Cria as inconsist?ncias*/
  IF (UPPER(:PRVALIDAREXPORTACAO) = 'TRUE') THEN
    EXECUTE PROCEDURE SP_VALIDA_EXPORTACAO_SPED(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, 'D100');  

  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha);
    END

  CLOSEARQ(:PRARQUIVO);

END
^

/* Alter (SP_EXPORTA_BLOCOD_SAI) */
ALTER PROCEDURE SP_EXPORTA_BLOCOD_SAI(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
BEGIN

  /*****************************************************************************
   *--------------------------------->>SA?DA<<---------------------------------*
   ****************************************************************************/

  /*****************************************************************************
   *                                   D100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODINFCOM, BDORDEMINFCOM)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100',
          'D100' BDREG,
          ('|D100|1'||
           '|'||M.BDEMITENTE||
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)))|| --COD_PART
           '|'||MOD.BDMODELOSTR||            --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')|| --COD_SIT
           '|'||COALESCE(M.BDSERIE, '')||    --SER
           '|'||COALESCE(M.BDSUBSERIE, '')|| --SUB
           '|'||M.BDNUMDOCINI||              --NUM_DOC
           '|'||COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), '')||       --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_A_P
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(IIF(M.BDMODELO IN(57, 67), D100.BDTIPOCTE, ''), ''))|| --TP_CT-e
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF)), ''))|| --CHV_CTE_REF
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(MOV.BDVLRCONTAB, '.', ','), ''))||                --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(M.BDDESCONTONOTA, '.', ','), ''))||              --VL_DESC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((IIF(((INDFRETED100.BDCODEXPFRETE = '') OR (INDFRETED100.BDCODEXPFRETE IS NULL)), '0', INDFRETED100.BDCODEXPFRETE)), ''))|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(MOV.BDVLRCONTAB, '.', ','), ''))||                --VL_SERV
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDBASEICMS, 0.00), '.', ','), ''))|| --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDVLRICMS, 0.00), '.', ','), ''))||  --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDISENTASICMS + MOV.BDOUTRASICMS, 0.00), '.', ','), ''))|| --VL_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(INFCOMD100.BDCODINFCOM, ''))|| --COD_INF
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(D100.BDCODCTA, ''))||          --COD_CTA
           --Campos exportados apartir de 01/01/2018
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'||COALESCE(COALESCE(CIDORIGD100.BDCODIBGE, ORIG.BDCODIBGE), '')))|| --COD_MUN_ORIG
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'||COALESCE(COALESCE(CIDDESTD100.BDCODIBGE, DEST.BDCODIBGE), '')))|| --COD_MUN_DEST
           '|'
           ), M.BDCODTER, INFCOMD100.BDCODINFCOM, INFCOMD100.BDORDEMINFCOM
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI,
               SUM(COALESCE(I.BDISENTASICMS, 0.00)) BDISENTASICMS,
               SUM(COALESCE(I.BDOUTRASICMS, 0.00)) BDOUTRASICMS
        FROM (
              SELECT S.BDCODEMP, S.BDCHAVE
              FROM VEF_EMP_TMOVSAI S
              WHERE S.BDCODEMP = :PRCODEMP
              AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TD100SAI D100 ON (D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETED100 ON (D100.BDINDFRETE = INDFRETED100.BDORDEMFRETE)
  LEFT OUTER JOIN VEF_BASE_TCADINFCOM INFCOMD100 ON (D100.BDORDEMINFCOM = INFCOMD100.BDORDEMINFCOM)
  LEFT OUTER JOIN TCIDADE CIDORIGD100 ON (CIDORIGD100.BDCODCID = D100.BDCIDORIGEM)
  LEFT OUTER JOIN TCIDADE CIDDESTD100 ON (CIDDESTD100.BDCODCID = D100.BDCIDDEST)

  LEFT OUTER JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = MOV.BDCODEMP AND D160.BDCHAVE = MOV.BDCHAVE AND ((D160.BDCODCIDREMETENTE IS NOT NULL) OR (D160.BDCODCIDDESTINATARIO IS NOT NULL)))
  LEFT OUTER JOIN TCIDADE ORIG ON (ORIG.BDCODCID = D160.BDCODCIDREMETENTE)
  LEFT OUTER JOIN TCIDADE DEST ON (DEST.BDCODCID = D160.BDCODCIDDESTINATARIO)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   D101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D101',
             'D101' BDREG,
             ('|D101'||
              '|'||REPLACE(COALESCE(D100.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
             )
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                   SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB
            FROM (
                  SELECT S.BDCODEMP, S.BDCHAVE
                  FROM VEF_EMP_TMOVSAI S
                  WHERE S.BDCODEMP = :PRCODEMP
                  AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND S.BDMODELO IN(57, 67)
                  AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
                 ) MOV
            LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
            GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
           ) M
      JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE AND ((D100.BDVLR_FCP_UF_DEST > 0) OR (D100.BDVLRICMS_UF_DEST > 0) OR (D100.BDVLRICMS_UF_REM > 0)))
      WHERE M.BDVLRCONTAB > 0;
    END

  /*****************************************************************************
   *                                   D110                                    *
   ****************************************************************************/
  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      SETORDEMSEQUENCIAL(0);
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D110.'||LPAD(D110.BDORDEMST, 6, '0'),
             'D110' BDREG,
             ('|D110'||
              '|'||GETORDEMSEQUENCIAL(0)||--NUM_ITEM
              '|'||IIF(((PRO_VINC.BDCODSAIDA IS NULL) OR (PRO_VINC.BDCODSAIDA = '')), PRO_VINC.BDCODPROD, PRO_VINC.BDCODSAIDA)|| --COD_ITEM
              '|'||REPLACE(COALESCE(D110.BDVLRSER, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D110.BDOUTVAL, 0.00), '.', ',')||
              '|'
             ), PRO_VINC.BDCODPROD
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(7)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD110SAI D110 ON(D110.BDCODEMP = M.BDCODEMP AND D110.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCADPRO_VINC PRO_VINC ON(PRO_VINC.BDCODEMP = D110.BDCODEMP AND PRO_VINC.BDCODPROD = D110.BDCODPROD);

      /*****************************************************************************
       *                                   D120                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D110.'||LPAD(D120.BDORDEMST, 6, '0')||'.D120.'||LPAD(D120.BDORDEMD120, 6, '0'),
             'D120' BDREG,
             ('|D120'||
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')||
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')||
              '|'||COALESCE(REPLACE(D120.BDPLACAVEICULO, '-', ''), '')||
              '|'||COALESCE(UF.BDSIGLAUF, '')||
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(7)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD120COMPCON D120 ON(D120.BDCODEMP = M.BDCODEMP AND D120.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D120.BDCODCIDORIG)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D120.BDCODCIDDEST)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF)
      LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = D120.BDCODUF);

      /*****************************************************************************
       *                                   D130                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODTERAUX)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D130',
             'D130' BDREG,
             ('|D130'||
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, D130.BDCODTERCONSIGNATARIO, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)), '')|| --COD_PART_CONSG
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, D130.BDCODTERREDESPACHANTE, TER_DES.BDCGCTER, TER_DES.BDIETER, TerEmp_DES.BDCODIGOARQUIVO)), '')|| --COD_PART_RED
              '|'||COALESCE(D130.BDINDFRETERED, '')|| --IND_FRT_RED
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')|| --COD_MUN_ORIG
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')|| --COD_MUN_DEST
              '|'||COALESCE(TRIM(REPLACE(D130.BDPLACAID, '-', '')), '')||          --VEIC_ID
              '|'||REPLACE(COALESCE(D130.BDVLRLIQFRETE, 0.00), '.', ',')||   --VL_LIQ_FRT
              '|'||REPLACE(COALESCE(D130.BDVLRSECCAT, 0.00), '.', ',')||     --VL_SEC_CAT
              '|'||REPLACE(COALESCE(D130.BDVLRDESPACHO, 0.00), '.', ',')||   --VL_DESP
              '|'||REPLACE(COALESCE(D130.BDVLRPEDAGIO, 0.00), '.', ',')||    --VL_PEDG
              '|'||REPLACE(COALESCE(D130.BDVLROUTVAL, 0.00), '.', ',')||     --VL_OUT
              '|'||REPLACE(COALESCE(D130.BDVLRTOTALFRETE, 0.00), '.', ',')|| --VL_FRT
              '|'||COALESCE(UF.BDSIGLAUF, '')||                              --UF_ID
              '|'
             ), D130.BDCODTERCONSIGNATARIO, D130.BDCODTERREDESPACHANTE
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(8, 800)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD130COMPCON D130 ON(D130.BDCODEMP = M.BDCODEMP AND D130.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D130.BDCODCIDORIGEM)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D130.BDCODCIDDESTINO)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF)
      LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = D130.BDCODUF)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = D130.BDCODTERCONSIGNATARIO)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                             ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = D130.BDCODTERCONSIGNATARIO)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER_DES ON(TER_DES.BDCODTER = D130.BDCODTERREDESPACHANTE)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp_DES ON (TerEmp_DES.bdcodter = D130.BDCODTERREDESPACHANTE);

      /*****************************************************************************
       *                                   D160                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D160.BDORDEMCARTRANS, 6, '0'),
             'D160' BDREG,
             ('|D160'||
              '|'||COALESCE(REPLACE(D160.BDNRDESPACHO, '|', ''), '')|| --DESPACHO
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos n?meros forem iguais retorna em branco*/, 0, TERREM.BDCGCTER, '', '')), '')|| --CNPJ_CPF_REM
              '|'||COALESCE(IIF(((POSITION(UPPER(TERREM.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERREM.BDIETER), 'ISENTA') > 0)), '', (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERREM.BDIETER))), '')|| --IE_REM
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')|| --COD_MUN_ORI
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos n?meros forem iguais retorna em branco*/, 0, TERDES.BDCGCTER, '', '')), '')|| --CNPJ_CPF_DEST
              '|'||COALESCE(IIF(((POSITION(UPPER(TERDES.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERDES.BDIETER), 'ISENTA') > 0)), '', (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERDES.BDIETER))), '')|| --IE_DEST
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')|| --COD_MUN_DEST
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERREM ON (TERREM.BDCODTER = D160.BDCODTERREMETENTE)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERDES ON (TERDES.BDCODTER = D160.BDCODTERDESTINATARIO)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D160.BDCODCIDREMETENTE)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D160.BDCODCIDDESTINATARIO)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF);

      /*****************************************************************************
       *                                   D161                                    *
       ****************************************************************************/
      IF (:PRPERFIL = 0) THEN /*Perfil A*/
        BEGIN
          INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
          SELECT :PRARQUIVO BDID,
                 LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D160.BDORDEMCARTRANS, 6, '0')||'.D161',
                 'D161' BDREG,
                 ('|D161'||
                  '|'||COALESCE(TRAN.BDCODEXPTRAN, '')||
                  '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos n?meros forem iguais retorna em branco*/, 0, TERCOL.BDCGCTER, '', '')), '')|| --CNPJ_CPF_COL
                  '|'||COALESCE(IIF(((POSITION(UPPER(TERCOL.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERCOL.BDIETER), 'ISENTA') > 0)), '', TERCOL.BDIETER), '')||       --IE_REM
                  '|'||COALESCE(IIF(UFCOL.BDSIGLAUF = 'EX', '9999999', CIDCOL.BDCODIBGE), '')|| --COD_MUN_COL
                  '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos n?meros forem iguais retorna em branco*/, 0, TERENT.BDCGCTER, '', '')), '')|| --CNPJ_CPF_ENT
                  '|'||COALESCE(IIF(((POSITION(UPPER(TERENT.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERENT.BDIETER), 'ISENTA') > 0)), '', TERENT.BDIETER), '')||       --IE_ENTG
                  '|'||COALESCE(IIF(UFENT.BDSIGLAUF = 'EX', '9999999', CIDENT.BDCODIBGE), '')|| --COD_MUN_ENTG
                  '|'
                 )
          FROM (
                SELECT S.BDCODEMP, S.BDCHAVE
                FROM VEF_EMP_TMOVSAI S
                WHERE S.BDCODEMP = :PRCODEMP
                AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
                AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
               ) M
          JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE AND D160.BDCODCIDCOLETA > 0)
          JOIN VEF_BASE_TTABTIPOTRAN TRAN ON(TRAN.BDCODTRAN = D160.BDCODTRAN AND TRAN.BDCODEXPTRAN IS NOT NULL)
          LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERCOL ON (TERCOL.BDCODTER = D160.BDCODTERCOLETA)
          LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERENT ON (TERENT.BDCODTER = D160.BDCODTERENTREGA)
          LEFT OUTER JOIN TCIDADE CIDCOL ON (CIDCOL.BDCODCID = D160.BDCODCIDCOLETA)
          LEFT OUTER JOIN TUF UFCOL ON (UFCOL.BDCODUF = CIDCOL.BDCODUF)
          LEFT OUTER JOIN TCIDADE CIDENT ON (CIDENT.BDCODCID = D160.BDCODCIDENTREGA)
          LEFT OUTER JOIN TUF UFENT ON (UFENT.BDCODUF = CIDENT.BDCODUF);
        END

      /*****************************************************************************
       *                                   D162                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(D162.BDCODEMP, 6, '0')||'.1.'||LPAD(D162.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D162.BDORDEMCARTRANS, 6, '0')||'.D162.'||LPAD(D162.BDORDEMDOCFIS, 6, '0'),
             'D162' BDREG,
             ('|D162'||
              '|'||COALESCE(DOC.BDDOCFIS, '')|| --COD_MOD
              '|'||COALESCE(D162.BDSERIE, '')|| --SER
              '|'||COALESCE(D162.BDNRDOC, '')|| --NUM_DOC
              '|'||(SELECT BDDATA FROM SP_PARSE_DATE(D162.BDDTDOC, 'DDMMYYYY'))|| --DT_DOC
              '|'||REPLACE(COALESCE(CAST(D162.BDVLRDOC AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --VL_DOC
              '|'||REPLACE(COALESCE(CAST(D162.BDVLRMER AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --VL_MER
              '|'||COALESCE(SUBSTRING(ROUND(D162.BDQTDVOL) FROM 1 FOR POSITION('.', D162.BDQTDVOL)), 0.00)|| --QTD_VOL
              '|'||REPLACE(COALESCE(CAST(D162.BDPESOBRUTO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_BRT
              '|'||REPLACE(COALESCE(CAST(D162.BDPESOLIQ AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_LIQ
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE/* AND D160.BDCODCIDCOLETA > 0*/)
      JOIN VEF_EMP_TD162DOCFIS D162 ON(D162.BDCODEMP = D160.BDCODEMP AND D162.BDCHAVE = D160.BDCHAVE AND D162.BDORDEMCARTRANS = D160.BDORDEMCARTRANS)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON(DOC.BDCODDOCFIS = D162.BDCODDOCFIS);
   END

  /*****************************************************************************
   *                                   D190                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D190.'||LPAD(GETORDEMSEQUENCIAL(M.BDCHAVE), 10, '0'),
          'D190' BDREG,
          ('|D190'||
           '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
           '|'||COALESCE(SUBSTRING(I.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
           '|'||COALESCE(REPLACE(CAST(I.BDALIQICMS AS NUMERIC(6, 2)), '.', ','), '')||  --ALIQ_ICMS
           '|'||COALESCE(REPLACE(I.BDVLRCONTAB, '.', ','), '')|| --VL_OPR
           '|'||COALESCE(REPLACE(I.BDBASEICMS, '.', ','), '')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(I.BDVLRICMS, '.', ','), '')|| --VL_ICMS
           '|'||REPLACE(IIF((SUBSTRING(ICMS.BDCSTICMS FROM 1 FOR 2) IN (20, 70)), (COALESCE(I.BDISENTASICMS, 0) + COALESCE(I.BDOUTRASICMS , 0)), '0,00'), '.', ',')|| --VL_RED_BC
           '|'||COALESCE(I.BDCODOBS, '')|| --COD_OBS
           '|'  
           )
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = I.BDCODCSTICMS);

  /*****************************************************************************
   *                                   D195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(D195.BDCODEMP, 6, '0')||'.1.'||LPAD(D195.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D195.BDORDEMOBS, 10, '0'),
         'D195' BDREG,
         ('|D195'||
          '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
          '|'||COALESCE(REPLACE(D195.BDDESCCOMPL, '|', ''), '')|| --TXT_COMPL
          '|'
         ), D195.BDCODOBS
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195SAI D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = D195.BDCODOBS);

  /*****************************************************************************
   *                                   D197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT  :PRARQUIVO BDID,
          LPAD(D197.BDCODEMP, 6, '0')||'.1.'||LPAD(D197.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D197.BDORDEMOBS, 10, '0')||'.D197.'||LPAD(D197.BDORDEMOUTOBR, 10, '0'),
          'D197' BDREG,
          ('|D197'||
           '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
           '|'||COALESCE(REPLACE(D197.BDDESCCOMPL, '|', ''), '')|| --DESCR_COMPL_AJ
           '|'||COALESCE(IIF(PRO.BDCODSAIDA <> '', PRO.BDCODSAIDA, PRO.BDCODPROD), '')|| --COD_ITEM
           '|'||COALESCE(REPLACE(D197.BDBICMS, '.', ','), '')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(CAST(D197.BDALIQICMS AS DM_NUMERIC_15_2), '.', ','), '')|| --ALIQ_ICMS
           '|'||COALESCE(REPLACE(D197.BDVLRICMS, '.', ','), '')|| --VL_ICMS
           '|'||COALESCE(REPLACE(D197.BDOUTVLR, '.', ','), '')|| --VL_OUTROS
           '|'
           ), D197.BDCODPROD
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195SAI D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD197SAI D197 ON(D197.BDCODEMP = D195.BDCODEMP AND D197.BDCHAVE = D195.BDCHAVE AND D197.BDORDEMOBS = D195.BDORDEMOBS)
  LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = D197.BDCODAJU)
  LEFT OUTER JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = D197.BDCODEMP AND PRO.BDCODPROD = D197.BDCODPROD);
END
^

/* Alter (SP_EXPORTA_BLOCOE) */
ALTER PROCEDURE SP_EXPORTA_BLOCOE(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRPERIODOAPUR INTEGER)
 AS
DECLARE VARIABLE WCODCONFIPI INTEGER;
DECLARE VARIABLE WCHAVE VARCHAR(30);
DECLARE VARIABLE WCHAVEANT VARCHAR(30);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200 CHARACTER SET win1252;
DECLARE VARIABLE WTIPOEXPCODPART INTEGER;
DECLARE VARIABLE WREFINI INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
BEGIN
  SELECT CAST(BDDATA AS INTEGER) FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM') INTO :wRefIni;
  SELECT CAST(BDDATA AS INTEGER) FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM') INTO :wRefFim;

  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1; /*N?o achou o TipoExpCodPart*/

  SELECT SP.BDCODCONFIPI FROM SP_CONSULTAEMPRESAS_SIS(:wRefFim, :PRCODEMP, NULL) SP INTO :wCodConfIPI;

  wCodConfIPI = COALESCE(:wCodConfIPI, -1);

  IF (:wCodConfIPI > 0) THEN
    BEGIN
       /*Se n?o houver E520(Apura??o de IPI), n?o exporta o bloco E500. Por isso ele vem antes dos outros registros, para n?o exportar registro desnecess?rio*/
      /*****************************************************************************
       *                                   E520                                    *
       ****************************************************************************/
       wChaveAnt = '';
       FOR SELECT LPAD(R.BDCODEMP, 6, '0')||'.'||'E500.E520.'||R.BDREFERENCIA||'.'||R.BDCODPERIODO||'.'||R.BDCODQIPI, CAST(SUM(COALESCE(R.BDVALOR, 0)) AS DM_NUMERIC_15_2) BDVALOR
           FROM VEF_EMP_TIPIGERREG R
           JOIN VEF_BASE_TCONFIPIQ Q ON(Q.BDCODQIPI = R.BDCODQIPI AND Q.BDCLASSIFICACAO = '01.04')
           WHERE R.BDCODEMP = :PRCODEMP
           AND R.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
           GROUP BY R.BDCODEMP, R.BDREFERENCIA, R.BDCODPERIODO, R.BDNUMCAMPO, R.BDCODQIPI
           ORDER BY R.BDNUMCAMPO
           INTO :wChave, :wValor
       DO
         BEGIN
           IF (:wChave <> :wChaveAnt) THEN
             BEGIN
               IF (:wChaveAnt <> '') THEN
                 INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA) VALUES(:PRARQUIVO, :wChave, 'E520', :wLinha);

               wChaveAnt = :wChave;
               wLinha    = '|E520|';
             END

           wLinha = wLinha || REPLACE(:wValor, '.', ',')||'|';
         END

       IF (:wLinha <> '') THEN
         INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA) VALUES(:PRARQUIVO, :wChave, 'E520', :wLinha);

       IF (ROW_COUNT = 0) THEN
         EXIT;

      /*****************************************************************************
       *                                   E500                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      VALUES(:PRARQUIVO, LPAD(:PRCODEMP, 6, '0')||'.E500', 'E500',
              '|E500|'||:PRPERIODOAPUR||'|'||(SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'DDMMYYYY'))||'|'||(SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'DDMMYYYY'))||'|');

      /*****************************************************************************
       *                                   E510                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(:PRCODEMP, 6, '0')||'.E500.E510.'||COALESCE(IPI.BDPREFIXONAT, '')||'|'||COALESCE(IPI.BDCODEXPCSTIPI, '') BDCHAVEREG,
             'E510' BDREG,
             '|E510'||
             '|'||COALESCE(IPI.BDPREFIXONAT, '')||   --CFOP
             '|'||LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, '0')|| --CST_IPI
             '|'||REPLACE(COALESCE(IPI.BDVLRITEM, 0.00), '.', ',')|| --VL_CONT_IPI
             '|'||REPLACE(COALESCE(IPI.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
             '|'||REPLACE(COALESCE(IPI.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
             '|'
      FROM (
            SELECT 0 BDMOV /*Entrada*/, ENT.BDPREFIXONAT, IPI.BDCODEXPCSTIPI,
                   SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                   SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI,
                   SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM, I.BDPREFIXONAT
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVENT M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                              AND M.BDMODELO IN (1, 4, 55, 65, 100)
--21769 n?o precisa olhar o modelo da nota para exportar o E510, segundo a Graci
--                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                             ) MOV
                       ) ENT
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                 ) ENT
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
            JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
            GROUP BY ENT.BDPREFIXONAT, IPI.BDCODEXPCSTIPI
            UNION ALL
            SELECT 1 BDMOV /*Sa?da*/, SAI.BDPREFIXONAT, IPI.BDCODEXPCSTIPI,
                   SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                   SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI,
                   SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDPREFIXONAT
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND M.BDMODELO IN (1, 4, 55, 65, 100)
--21769 n?o precisa olhar o modelo da nota para exportar o E510
--                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
            JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
            GROUP BY SAI.BDPREFIXONAT, IPI.BDCODEXPCSTIPI
           ) IPI
        ORDER BY IPI.BDMOV;

      /*****************************************************************************
       *                                   E530                                    *
       ****************************************************************************/
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
       SELECT :PRARQUIVO BDID,
              (LPAD(E530.BDCODEMP, 6, '0')||'.E500.E520.E530.'||LPAD(E530.BDCHAVE, 6, '0')),
              'E530',
              '|E530'||
              '|'||COALESCE((1 - IPI.BDDEBCRED), '')|| --IND_AJ
              '|'||REPLACE(COALESCE(CAST(E530.BDVALOR AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --VL_AJ
              '|'||LPAD(COALESCE(IPI.BDCODAJU, ''), 3, '0')|| --COD_AJ
              '|'||COALESCE(DOC.BDCODEXP, '')|| --IND_DOC
              '|'||REPLACE(COALESCE(E530.BDNUMDOC, ''), '|', '')|| --NUM_DOC
              '|'||REPLACE(COALESCE(E530.BDDESCAJU, ''), '|', '')|| --DESCR_AJ
              '|'
       FROM (
             SELECT E530.BDCODEMP, E530.BDCHAVE, E530.BDCODAJU, E530.BDVALOR,
                    E530.BDINDORIGEM, E530.BDNUMDOC, E530.BDDESCAJU
             FROM VEF_EMP_TAJUSTEIPIE530 E530
             WHERE E530.BDCODEMP = :PRCODEMP
             AND ((E530.BDREFERENCIA >= :wRefIni) AND (E530.BDREFERENCIA <= :wRefFim))
            ) E530
       JOIN VEF_BASE_TTABCODAJUAPUIPI IPI ON (IPI.BDCODAJU = E530.BDCODAJU)
       LEFT OUTER JOIN VEF_BASE_TTABINDDOC DOC ON (DOC.BDINDORIGEM = E530.BDINDORIGEM);

       /*Sol: 20474 Patrick T. S? 16/11/2017. Feito no banco, havia sido feito na classe*/
      /*****************************************************************************
       *                                   E531                                    *
       ****************************************************************************/
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODPROD)
       SELECT :PRARQUIVO BDID,
              (LPAD(E530.BDCODEMP, 6, '0')||'.E500.E520.E530.'||LPAD(E531.BDCHAVE, 6, '0')||'.E531.'||LPAD(E531.BDORDEM, 6, '0')),
              'E531',
              '|E531'||
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:wTipoExpCodPart, E531.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)), '')|| --COD_PART
              '|'||COALESCE(DOC.BDDOCFIS, '')|| --COD_MOD
              '|'||COALESCE(E531.BDSERIE, '')|| --SER
              '|'||COALESCE(E531.BDSUBSERIE, '')|| --SUB
              '|'||COALESCE(E531.BDNUMDOC, '')|| --NUM_DOC
              '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(E531.BDDATAEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
              '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), VINC.BDCODPROD, VINC.BDCODSAIDA)|| --COD_ITEM
              '|'||REPLACE(COALESCE(E531.BDVLRAJUSTE, 0.00), '.', ',')|| --VL_AJ_ITEM
              '|'||COALESCE(IIF(E531.BDCODDOCFIS = 30, (RPAD((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(E531.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_NFE
              '|', E531.BDCODTER, E531.BDCODPROD
       FROM (
             SELECT E530.BDCODEMP, E530.BDCHAVE
             FROM VEF_EMP_TAJUSTEIPIE530 E530
             WHERE E530.BDCODEMP = :PRCODEMP
             AND ((E530.BDREFERENCIA >= :wRefIni) AND (E530.BDREFERENCIA <= :wRefFim))
            ) E530
       JOIN VEF_EMP_TAJUSTEIPIE531 E531 ON(E531.BDCODEMP = E530.BDCODEMP AND E531.BDCHAVE = E530.BDCHAVE)
       LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON (DOC.BDCODDOCFIS = E531.BDCODDOCFIS)
       LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = E531.BDCODEMP AND VINC.BDCODPROD = E531.BDCODPROD)
       LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = E531.BDCODTER)
       LEFT OUTER JOIN (
                        SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                        FROM (
                              SELECT t.bdcodemp, t.bdcodter,
                                     COALESCE(
                                              (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= :wRefIni) ORDER BY e.bdreferencia DESC),
                                              (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                             ) BDCODIGO
                              FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                             ) tt
                        LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                       ) TerEmp ON (TerEmp.bdcodter = E531.bdcodter);
    END


  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha);
  --    WRITELN(:PRARQUIVO, :wLinha);
    END
  CLOSEARQ(:PRARQUIVO);
END
^

/* Alter (SP_EXPORTA_CONTEXTODB) */
ALTER PROCEDURE SP_EXPORTA_CONTEXTODB(PRFILE VARCHAR(1000))
 AS
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WCOMMAND VARCHAR(10000);
DECLARE VARIABLE WFIELDS VARCHAR(10000);
DECLARE VARIABLE WFIELDSSTR VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WFIELD VARCHAR(31);
DECLARE VARIABLE WTYPECOLUMN INTEGER;
BEGIN
  DELETE FROM TCONTEXTO_DB;

  FOR SELECT TRIM(RDB$RELATION_NAME)
      FROM RDB$RELATIONS
      WHERE RDB$SYSTEM_FLAG = 0
      AND ((RDB$RELATION_NAME LIKE 'TMP_%_TEMP%') OR (RDB$RELATION_TYPE IN (4,5) AND RDB$RELATION_NAME LIKE 'TMP_%'))
      ORDER BY RDB$RELATION_TYPE DESC, RDB$RELATION_NAME
      INTO :wTable
  DO
    BEGIN
      wField      = '';
      wFields     = '';
      wFieldsStr  = '';
      wCommand    = '';
      wSQL        = '';
      wTypeColumn = 0;

      INSERT INTO TCONTEXTO_DB(BDLINE) VALUES('DELETE FROM '||:wTable||';');

      wCommand = '''INSERT INTO '||:wTable||'(';

      FOR SELECT TRIM(RF.RDB$FIELD_NAME), F.RDB$FIELD_TYPE
          FROM RDB$RELATION_FIELDS RF
          JOIN RDB$FIELDS F ON(F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE)
          WHERE RDB$RELATION_NAME = :wTable
          INTO :wField, :wTypeColumn
      DO
        BEGIN
          wFields = wFields || :wField || ', ';

          /*7, 8, 9, 10, 16, 27 s?o campos num?rios*/
          IF (:wTypeColumn NOT IN(7, 8, 9, 10, 16, 27)) THEN
            wFieldsStr = :wFieldsStr || '''!@|''||'||'IIF('||:wField||' IS NULL, ''NULL'', '||:wField||')'||'||''!@|''';
          ELSE
            wFieldsStr = :wFieldsStr ||'IIF('||:wField||' IS NULL, ''NULL'', '||:wField||')';

          wFieldsStr = :wFieldsStr || '|| '', '' ||';
        END

      wFields    = (SUBSTRING(:wFields FROM 1 FOR CHAR_LENGTH(:wFields)-2));
      wFieldsStr = (SUBSTRING(:wFieldsStr FROM 1 FOR CHAR_LENGTH(:wFieldsStr)-10));

      wCommand = :wCommand || :wFields || ') VALUES ('' || ' || :wFieldsStr ||' || '');''';

      wSQL = 'INSERT INTO TCONTEXTO_DB(BDLINE) SELECT '|| :wCommand ||' FROM '||:wTable;

      EXECUTE STATEMENT :wSQL;
    END

  NEWFILE(:PRFILE);
  OPENARQ(:PRFILE);

  wCommand = '';
  FOR SELECT BDLINE FROM TCONTEXTO_DB INTO :wCommand DO
    BEGIN
      WRITELNOA(:wCommand);
    END

  CLOSEARQ(:PRFILE);

  DELETE FROM TCONTEXTO_DB;
END
^

/* Alter (SP_EXPORTA_DIMOB) */
ALTER PROCEDURE SP_EXPORTA_DIMOB(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRDECLRETIF VARCHAR(5),
PRNUMRECIBO VARCHAR(10),
PRSITUACAOESPECIAL VARCHAR(5),
PRDATAEVENTO DATE,
PRSITEVENTO INTEGER,
PRCONSOLIDAR VARCHAR(5))
 AS
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WDECLRETIF INTEGER;
DECLARE VARIABLE WCODSIT VARCHAR(2);
DECLARE VARIABLE WSITESPECIAL CHAR(1);
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200 CHARACTER SET UTF8;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  IF (:PRDECLRETIF = 'TRUE') THEN
    WDECLRETIF = 1;
  ELSE
    WDECLRETIF = 0;

  IF (:PRSITUACAOESPECIAL = 'TRUE') THEN
    WSITESPECIAL = 1;
  ELSE
    WSITESPECIAL = 0;

  WCODSIT = CASE
              WHEN :PRSITEVENTO = 0 THEN '01'
              WHEN :PRSITEVENTO = 1 THEN '02'
              WHEN :PRSITEVENTO = 2 THEN '03'
              WHEN :PRSITEVENTO = 3 THEN '04'
              ELSE '00'
            END;

  /*****************************************************************************
   *                                   HEADER                                  *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, 1, :PRCODEMP,
           'DIMOB' || -- 01 Fixo DIMOB
           LPAD('', 369, ' ')  -- 02 369 espa?os em branco
           ); -- 03 2 posi??es de EOL


  /*****************************************************************************
   *                                    R01                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  SELECT :PRARQUIVO BDID, :PRCODEMP BDCODEMP, 2 BDORDEMREG, :PRCODEMP BDORDEM,
         ('R01' || -- 01 Fixo R01
         (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(EMP.BDCNPJEMP,14)) || -- 02 CNPJ
         (EXTRACT(YEAR FROM :PRDTINI)) || -- 03 Ano da declara??o
         :WDECLRETIF || -- 04 Declara??o Retificadora
         LPAD(:PRNUMRECIBO,10,'0') || -- 05 N?mero do Recibo
         :WSITESPECIAL || -- 06 Situa??o Especial
         LPAD(COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(:PRDATAEVENTO,'DDMMYYYY')),''),8,' ') || -- 07 Data do evento situa??o especial
         :WCODSIT || -- 08 C?digo da situa??o especial
         RPAD(EMP.BDNOMEMP,60,' ') || -- 09 Nome Empresarial
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(SOC.BDCGCCEISOC)), ''),11,' ') || -- 10 CPF do Respons?vel
         RPAD(EMP.BDLOGREMP || ' ' || EMP.BDENDEMP,120,' ') || -- 11 Endere?o completo do contribuinte
         UF.BDSIGLAUF || -- 12 UF do Contribuinte
         LPAD(CID.BDCODFED, 4, '0') || -- 13 C?digo do Munic?pio do Contribuinte
         LPAD('', 20, ' ') || -- 14 Reservado ? 20 posi??es em branco
         LPAD('', 10, ' ') -- 15 Reservado ? 10 posi??es em branco
         ) BDLINHA -- 16 Delimitador de Registro ? 2 posi??es EOL
  FROM (SELECT EMP.BDCODEMP, EMP.BDCNPJEMP, REF.BDNOMEMP, REF.BDENDEMP, REF.BDCODCID, REF.BDLOGREMP
        FROM (SELECT BDCODEMP, BDCNPJEMP
              FROM TEMPRESAS
              WHERE BDCODEMP = :PRCODEMP) EMP
        LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (EMP.BDCODEMP = REF.BDCODEMP)) EMP
  LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
  LEFT OUTER JOIN(SELECT FIRST 1 BDCODEMP, BDCGCCEISOC
                  FROM VW_EMPRESAS_TSOC_REF
                  WHERE BDCODEMP = :PRCODEMP AND
                        BDRESPONSAVELSOC = 'TRUE') SOC ON (SOC.BDCODEMP = EMP.BDCODEMP);

  /*****************************************************************************
   *                                    R02                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  SELECT :PRARQUIVO BDID, EMP.BDCODEMP, 3 BDORDEMREG, IMOB.BDCHAVE BDORDEM,
         ('R02' || -- 01 Fixo R02
         (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(EMP.BDCNPJEMP,14)) || -- 02 CNPJ do declarante
         (EXTRACT(YEAR FROM :PRDTINI)) || -- 03 Ano-calend?rio
         LPAD(COALESCE(GETORDEMSEQUENCIAL(:WORDEM),'0'),5,'0') || -- 04 Sequencial da Loca??o
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(LOCADOR.BDCGCTER)), ''),14,' ') || -- 05 CPF/CNPJ do Locador
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LOCADOR.BDNOMETER)), ''),60,' ') || -- 06 Nome/Nome Empresarial do Locador
         RPAD(COALESCE(
         CASE
           WHEN (LOCATARIO.BDCODPAIS <> 30) THEN 'NDP'
           ELSE (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(LOCATARIO.BDCGCTER))
         END, ''), 14, ' ') || -- 07 CPF/CNPJ do Locat?rio
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LOCATARIO.BDNOMETER)), ''),60,' ') || -- 08 Nome/Nome Empresarial do Locat?rio
         RPAD(COALESCE(IMOB.BDNRCONTRATO, ''),6,' ') || -- 09 N?mero do Contrato
         COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(IMOB.BDDTCONTRATO,'DDMMYYYY')), '') || -- 10 Data do Contrato
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 1 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 11 Valor do Aluguel no m?s de Janeiro (campo valor da opera??o)
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 1 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 12 Valor da Comiss?o no m?s de Janeiro (campo novo valor comiss?o)
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 1 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 13 Valor do Imposto no m?s de Janeiro (soma das reten??es PIS/Cofins/CSLL/ISS/IR)
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 2 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 14 Valor do Aluguel no m?s de Fevereiro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 2 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 15 Valor da Comiss?o no m?s de Fevereiro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 2 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 16 Valor do Imposto no m?s de Fevereiro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 3 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 17 Valor do Aluguel no m?s de Mar?o
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 3 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 18 Valor da Comiss?o no m?s de Mar?o
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 3 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 19 Valor do Imposto no m?s de Mar?o
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 4 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 20 Valor do Aluguel no m?s de Abril
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 4 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 21 Valor da Comiss?o no m?s de Abril
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 4 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 22 Valor do Imposto no m?s de Abril
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 5 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 23 Valor do Aluguel no m?s de Maio
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 5 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 24 Valor da Comiss?o no m?s de Maio
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 5 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 25 Valor do Imposto no m?s de Maio
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 6 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 26 Valor do Aluguel no m?s de Junho
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 6 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 27 Valor da Comiss?o no m?s de Junho
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 6 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 28 Valor do Imposto no m?s de Junho
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 7 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 29 Valor do Aluguel no m?s de Julho
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 7 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 30 Valor da Comiss?o no m?s de Julho
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 7 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 31 Valor do Imposto no m?s de Julho
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 8 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 32 Valor do Aluguel no m?s de Agosto
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 8 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 33 Valor da Comiss?o no m?s de Agosto
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 8 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 34 Valor do Imposto no m?s de Agosto
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 9 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 35 Valor do Aluguel no m?s de Setembro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 9 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 36 Valor da Comiss?o no m?s de Setembro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 9 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 37 Valor do Imposto no m?s de Setembro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 10 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 38 Valor do Aluguel no m?s de Outubro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 10 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 39 Valor da Comiss?o no m?s de Outubro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 10 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 40 Valor do Imposto no m?s de Outubro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 11 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 41 Valor do Aluguel no m?s de Novembro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 11 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 42 Valor da Comiss?o no m?s de Novembro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 11 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 43 Valor do Imposto no m?s de Novembro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 12 THEN CAST(F.BDVL_OPER*100 AS INTEGER) ELSE 0 END), ''),14,'0') || -- 44 Valor do Aluguel no m?s de Dezembro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 12 THEN CAST(F.BDVLRCOMISSAO*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 45 Valor da Comiss?o no m?s de Dezembro
         LPAD(COALESCE(SUM(CASE WHEN F.BDMES = 12 THEN CAST(F.BDVLRRET*100 AS INTEGER) ELSE 0 END), ''),14,'0') ||-- 46 Valor do Imposto no m?s de Dezembro
         COALESCE(
         CASE
           WHEN UNID.BDTIPOIMOVEL = 0 THEN 'U'
           ELSE 'R'
         END, '') || -- 47 Tipo do Im?vel
         RPAD(UNID.BDLOGRADOUROUNID || ' ' || COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(UNID.BDENDERECOUNID)), ''),60,' ') || -- 48 Endere?o do Im?vel
         LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(UNID.BDCEPUNID)), ''),8,'0') || -- 49 CEP
         LPAD(COALESCE(CID.BDCODFED, ''), 4, '0') || -- 50 C?digo do Munic?pio do Im?vel
         LPAD('', 20, ' ') || -- 51 Reservado ? 20 posi??es em branco
         COALESCE(UF.BDSIGLAUF, '  ') || -- 52 UF
         LPAD('', 10, ' ')-- 53 Reservado ? 10 posi??es em branco
         ) BDLINHA -- 54 Delimitador de Registro ? 2 posi??es EOL
  FROM (SELECT F.BDCODEMP, F.BDCHAVECONT, CAST(NULL AS NUMERIC(15,2)) BDVL_OPER, CAST(NULL AS NUMERIC(15,2)) BDVLRCOMISSAO,
                COALESCE(SUM(PGTO.BDVALORRETPIS) + SUM(PGTO.BDVALORRETCOFINS) + SUM(PGTO.BDVALORRETCSLL),RET.BDVLRPIS + RET.BDVLRCOFINS + RET.BDVLRCSOCIAL) BDVLRRET,
                    (EXTRACT(MONTH FROM COALESCE(PGTO.BDDATAPGTOPAR, F.BDDT_OPER))) BDMES
             FROM VEF_EMP_TMOVDEMAISDOC_F100 F                                            
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = F.BDCODEMP)
             LEFT OUTER JOIN VW_VEF_BASE_TEMPPARGER PARG ON (PARG.BDCODEMP = EMPREF.BDCODEMP)
             LEFT OUTER JOIN VEF_EMP_TMOVDEMRET RET ON (RET.BDCODEMP = F.BDCODEMP AND RET.BDCHAVE = F.BDCHAVE) 
             LEFT OUTER JOIN VEF_EMP_TMOVF100PARPGTO PGTO ON (F.BDCODEMP = PGTO.BDCODEMP AND F.BDCHAVE = PGTO.BDCHAVE AND ((PARG.BDTIPOAPURACAORET = 1) AND (F.BDCONDPGTO = 1)))
             WHERE F.bdcodemp = :PRCODEMP AND
                   (F.BDIND_OPER IN (2, 3)) AND
                   (F.BDDT_OPER >= :PRDTINI AND
                   F.BDDT_OPER <= :PRDTFIM) AND
                   ((PGTO.BDVALORRETPIS > 0) OR
                    (PARG.BDTIPOAPURACAORET <> 1) OR (F.BDCONDPGTO <> 1))
             GROUP BY F.BDCODEMP, F.BDCHAVECONT, F.BDVL_OPER, F.BDVLRCOMISSAO, PARG.BDTIPOAPURACAORET, RET.BDVLRPIS, RET.BDVLRCOFINS, RET.BDVLRCSOCIAL, F.BDCONDPGTO,
                      BDMES
             UNION ALL
             SELECT F.BDCODEMP, F.BDCHAVECONT, CAST(NULL AS NUMERIC(15,2)) BDVL_OPER, CAST(NULL AS NUMERIC(15,2)) BDVLRCOMISSAO,
                   COALESCE(SUM(PGTO.BDVALORRETIRRF), RET.BDVLRIR)BDVLRRET,
                    (EXTRACT(MONTH FROM COALESCE(PGTO.BDDATAPGTOPAR, F.BDDT_OPER))) BDMES
             FROM VEF_EMP_TMOVDEMAISDOC_F100 F                                                            
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = F.BDCODEMP)
             LEFT OUTER JOIN VW_VEF_BASE_TEMPPARGER PARG ON (PARG.BDCODEMP = EMPREF.BDCODEMP)
             LEFT OUTER JOIN VEF_EMP_TMOVDEMRET RET ON (RET.BDCODEMP = F.BDCODEMP AND RET.BDCHAVE = F.BDCHAVE) 
             LEFT OUTER JOIN VEF_EMP_TMOVF100PARPGTO PGTO ON (F.BDCODEMP = PGTO.BDCODEMP AND F.BDCHAVE = PGTO.BDCHAVE AND ((PARG.BDTIPOAPURACAORETIR = 1) AND (F.BDCONDPGTO = 1)))
             WHERE F.bdcodemp = :PRCODEMP AND
                   (F.BDIND_OPER IN (2, 3)) AND
                   (F.BDDT_OPER >= :PRDTINI AND
                   F.BDDT_OPER <= :PRDTFIM) AND
                   ((PGTO.BDVALORRETIRRF > 0) OR
                    (PARG.BDTIPOAPURACAORETIR <> 1) OR (F.BDCONDPGTO <> 1))
             GROUP BY F.BDCODEMP, F.BDCHAVECONT, F.BDVL_OPER, F.BDVLRCOMISSAO, PARG.BDTIPOAPURACAORET, F.BDCONDPGTO, PARG.BDTIPOAPURACAORETIR, BDMES, RET.BDVLRIR
             UNION ALL
             SELECT F.BDCODEMP, F.BDCHAVECONT, CAST(NULL AS NUMERIC(15,2)) BDVL_OPER, CAST(NULL AS NUMERIC(15,2)) BDVLRCOMISSAO, RET.BDISSRET BDVLRRET,
                    (EXTRACT(MONTH FROM F.BDDT_OPER)) BDMES
             FROM VEF_EMP_TMOVDEMAISDOC_F100 F
             LEFT OUTER JOIN VEF_EMP_TMOVDEMRET RET ON (RET.BDCODEMP = F.BDCODEMP AND RET.BDCHAVE = F.BDCHAVE)
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = F.BDCODEMP)
             WHERE F.bdcodemp = :PRCODEMP AND
                   (F.BDIND_OPER IN (2, 3)) AND
                   (F.BDDT_OPER >= :PRDTINI AND
                   F.BDDT_OPER <= :PRDTFIM)
             UNION ALL
             SELECT F.BDCODEMP, F.BDCHAVECONT, F.BDVL_OPER, F.BDVLRCOMISSAO, CAST(NULL AS NUMERIC(15,2)) BDVLRRET,
                    (EXTRACT(MONTH FROM F.BDDT_OPER)) BDMES
             FROM VEF_EMP_TMOVDEMAISDOC_F100 F
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = F.BDCODEMP)
             WHERE F.bdcodemp = :PRCODEMP AND
                   (F.BDIND_OPER IN (2, 3)) AND
                   (F.BDDT_OPER >= :PRDTINI AND
                   F.BDDT_OPER <= :PRDTFIM)
             ) F
  LEFT OUTER JOIN TCONTRATO_IMOBILIARIO IMOB ON (F.BDCODEMP = IMOB.BDCODEMP AND F.BDCHAVECONT = IMOB.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TCADUNIDIMOBILIARIA UNID ON (IMOB.BDCODEMP = UNID.BDCODEMP AND IMOB.BDCODEMPREENDIMENTO = UNID.BDCODEMPREENDIMENTO AND IMOB.BDCODIGOUNIIMOB = UNID.BDCODIGOUNIIMOB)
  LEFT OUTER JOIN TCIDADE CID ON (UNID.BDCODCIDUNID = CID.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
  LEFT OUTER JOIN VW_TTERCEIRO LOCADOR ON (LOCADOR.BDCODTER = IMOB.BDCODLOCADOR)
  LEFT OUTER JOIN VW_TTERCEIRO LOCATARIO ON (LOCATARIO.BDCODTER = IMOB.BDCODLOCATARIO)   
  LEFT OUTER JOIN TEMPRESAS EMP ON (IMOB.BDCODEMP = EMP.BDCODEMP)
  GROUP BY EMP.BDCNPJEMP, LOCADOR.BDCODPAIS, LOCADOR.BDCGCTER, LOCADOR.BDNOMETER, LOCATARIO.BDCGCTER, LOCATARIO.BDCODPAIS, LOCATARIO.BDNOMETER, UNID.BDLOGRADOUROUNID,
           IMOB.BDNRCONTRATO, IMOB.BDDTCONTRATO, UNID.BDTIPOIMOVEL, UNID.BDENDERECOUNID, UNID.BDCEPUNID, CID.BDCODFED, UF.BDSIGLAUF, BDID, EMP.BDCODEMP, BDORDEM, BDORDEMREG;

  /*****************************************************************************
   *                                    R03                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
SELECT :PRARQUIVO BDID, EMP.BDCODEMP, 4 BDORDEMREG, LAN.BDCHAVE BDORDEM,
         ('R03' || -- 01 Fixo R03
         (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(EMP.BDCNPJEMP,14)) || -- 02 ? CNPJ do declarante
         (EXTRACT(YEAR FROM :PRDTINI)) || -- 03 ? Ano-calend?rio
         LPAD(COALESCE(GETORDEMSEQUENCIAL(:WORDEM), ''),5,'0') || -- 04 ? Sequencial da Venda
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TER.BDCGCTER)), ''),14,' ') || -- 05 ? CPF/CNPJ do Comprador
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(TER.BDNOMETER)), ''),60,' ') || -- 06 ? Nome/Nome Empresarial do Comprador
         RPAD(COALESCE(LAN.BDNRCONTRATO, ''), 6, ' ') || -- 07 ? N?mero do Contrato
         COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(LAN.BDDATACONTRATO, 'DDMMYYYY')), '') || -- 08 ? Data do Contrato
         LPAD(COALESCE(CAST(LAN.BDVLRINCIALVENDA * 100 AS INTEGER), ''), 14, '0') || -- 09 ? Valor da Opera??o
         LPAD(COALESCE(CAST(LAN.BDVLRTOTRECPAR * 100 AS INTEGER), ''), 14, '0') || -- 10 ? Valor Pago no Ano
         COALESCE(
         CASE
         WHEN LAN.BDTIPOIMOVEL = 0 THEN 'U'
           ELSE 'R'
         END, '') || -- 11 ? Tipo do Im?vel
       RPAD(LAN.BDLOGRADOUROUNID || ' ' || COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LAN.BDENDERECOUNID)), ''), 60, ' ') || -- 12 ? Endere?o do Im?vel
       LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(LAN.BDCEPUNID)), ''), 8, '0') || -- 13 ? CEP
         LPAD(COALESCE(CID.BDCODFED, ''), 4, '0') || -- 14 ? C?digo do Munic?pio do Im?vel
         LPAD('', 20, ' ') || -- 15 ? Reservado ? 20 posi??es em branco
         COALESCE(UF.BDSIGLAUF, '') || -- 16 ? UF
         LPAD('', 10, ' ') -- 17 ? Reservado ? 10 posi??es em branco
       ) BDLINHA -- 18 ? Delimitador de Registro ? 2 posi??es EOL
FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDNRCONTRATO, MOV.BDDATACONTRATO, MOV.BDVLRINCIALVENDA, MOV.BDCODTER,
             MOV.BDVLRTOTRECPAR, IMOB.BDTIPOIMOVEL, IMOB.BDLOGRADOUROUNID, IMOB.BDENDERECOUNID, IMOB.BDCEPUNID,
             IMOB.BDCODCIDUNID
      FROM (SELECT F200.BDCODEMP, F200.BDCHAVE, F200.BDNRCONTRATO, F200.BDDATACONTRATO, F200.BDVLRINCIALVENDA, F200.BDCODTER,
                   F200.BDCODEMPREENDIMENTO, F200.BDCODIGOUNIIMOB, SUM(PGTO.BDVLRTOTRECPAR) BDVLRTOTRECPAR
            FROM (SELECT BDCODEMP, BDCHAVE, BDNRCONTRATO, BDDATACONTRATO, BDVLRINCIALVENDA, BDCODTER, BDCODEMPREENDIMENTO,
                         BDCODIGOUNIIMOB
                  FROM VEF_EMP_TMOVOPIMOBILIARIA_F200
                  WHERE BDCODEMP = :PRCODEMP AND
                        BDDATACONTRATO >= :PRDTINI AND
                        BDDATACONTRATO <= :PRDTFIM) F200
            INNER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO PGTO ON (PGTO.BDCODEMP = F200.BDCODEMP AND PGTO.BDCHAVE = F200.BDCHAVE)
            GROUP BY F200.BDCODEMP, F200.BDCHAVE, F200.BDNRCONTRATO, F200.BDDATACONTRATO, F200.BDVLRINCIALVENDA, F200.BDCODTER, F200.BDCODEMPREENDIMENTO, F200.BDCODIGOUNIIMOB) MOV
      INNER JOIN VEF_BASE_TCADUNIDIMOBILIARIA IMOB ON (IMOB.BDCODEMP = MOV.BDCODEMP AND IMOB.BDCODEMPREENDIMENTO = MOV.BDCODEMPREENDIMENTO AND IMOB.BDCODIGOUNIIMOB = MOV.BDCODIGOUNIIMOB AND (IMOB.BDCODTER IS NULL OR (IMOB.BDCODTER = MOV.BDCODTER)))) LAN
LEFT OUTER JOIN TCIDADE CID ON (LAN.BDCODCIDUNID = CID.BDCODCID)
LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
LEFT OUTER JOIN VW_TTERCEIRO TER ON (LAN.BDCODTER = TER.BDCODTER)
LEFT OUTER JOIN TEMPRESAS EMP ON EMP.BDCODEMP = LAN.BDCODEMP
LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (EMP.BDCODEMP = REF.BDCODEMP);

  /*****************************************************************************
   *                                    R04                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  SELECT :PRARQUIVO BDID, EMP.BDCODEMP, 5 BDORDEMREG, F200.BDCHAVE BDORDEM,
         ('R04' || -- 01 Fixo R04
         (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(EMP.BDCNPJEMP,14)) || -- 02 ? CNPJ do declarante
         (EXTRACT(YEAR FROM :PRDTINI)) || -- 03 ? Ano-calend?rio
         LPAD(COALESCE(GETORDEMSEQUENCIAL(:WORDEM), ''),5,'0') || -- 04 ? Sequencial da Venda
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TERIMOB.BDCGCTER)), ''),14,' ') || -- 05 ? CPF/CNPJ do Comprador
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(TERIMOB.BDNOMETER)), ''),60,' ') || -- 06 ? Nome/Nome Empresarial do Comprador
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TER.BDCGCTER)), ''),14,' ') || -- 07 ? CPF/CNPJ do Vendedor
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(TER.BDNOMETER)), ''),60,' ') || -- 08 ? Nome/Nome Empresarial do Vendedor
         RPAD(COALESCE(F200.BDNRCONTRATO, ''),6,' ') || -- 09 ? N?mero do Contrato
         COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(F200.BDDATACONTRATO,'DDMMYYYY')), '') || -- 10 ? Data do Contrato
         LPAD(COALESCE(CAST(F200.BDVLRINCIALVENDA * 100 AS INTEGER), ''), 14, '0') || -- 11 ? Valor da Venda
         LPAD(COALESCE(CAST(F200.BDVLRCOMISSAO * 100 AS INTEGER), ''), 14, '0') || -- 12 ? Valor da Comiss?o
         COALESCE(
         CASE
           WHEN IMOB.BDTIPOIMOVEL = 0 THEN 'U'
           ELSE 'R'
         END, '') || -- 13 ? Tipo do Im?vel
         RPAD(IMOB.BDLOGRADOUROUNID || ' ' || COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(IMOB.BDENDERECOUNID)), ''),60,' ') || -- 14 ? Endere?o do Im?vel
         LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(IMOB.BDCEPUNID)), ''),8,'0') || -- 15 ? CEP
         LPAD(COALESCE(CID.BDCODFED,''), 4, '0') || -- 16 ? C?digo do Munic?pio do Im?vel
         LPAD('', 20, ' ') || -- 17 ? Reservado ? 20 posi??es Branco(s)
         COALESCE(UF.BDSIGLAUF, '') || -- 18 ? UF
         LPAD('', 10, ' ') -- 19 ? Reservado ? 10 posi??es Branco(s)
         ) BDLINHA-- 20 ? Delimitador de Registro ? 2 posi??es EOL
  FROM (SELECT BDCODEMP, BDCNPJEMP
        FROM TEMPRESAS
        WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP) EMP
  INNER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON (F200.BDCODEMP = EMP.BDCODEMP AND (F200.BDDATACONTRATO >= :PRDTINI AND F200.BDDATACONTRATO <= :PRDTFIM))
  INNER JOIN VEF_BASE_TCADUNIDIMOBILIARIA IMOB ON (IMOB.BDCODEMP = F200.BDCODEMP AND IMOB.BDCODEMPREENDIMENTO = F200.BDCODEMPREENDIMENTO AND IMOB.BDCODIGOUNIIMOB = F200.BDCODIGOUNIIMOB AND (IMOB.BDCODTER <> F200.BDCODTER))
  LEFT OUTER JOIN TCIDADE CID ON (IMOB.BDCODCIDUNID = CID.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (F200.BDCODTER = TER.BDCODTER)
  LEFT OUTER JOIN VW_TTERCEIRO TERIMOB ON (IMOB.BDCODTER = TERIMOB.BDCODTER)
  LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (EMP.BDCODEMP = REF.BDCODEMP);

  /*****************************************************************************
   *                                    T09                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, 6, :PRCODEMP, 'T9' || -- 01 Fixo T09
          LPAD('', 100, ' ') -- 02 ? Reservado ? 100 posi??es em branco
          ); -- 03 ? Delimitador ? 2 posi??es EOL


  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_DIMOB E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDORDEMREG
      INTO :WLINHA
  DO
  BEGIN
    WRITELNOA(:WLINHA);
  END

  CLOSEARQ(:PRARQUIVO);
  DELETE FROM TEXPORTACAO_DIMOB;
END
^

/* Alter (SP_EXPORTA_ISS_CURITIBA) */
ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRTIPOLANC INTEGER,
PRRETIFICADORA INTEGER,
PRARQUIVO VARCHAR(100))
 AS
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200 CHARACTER SET UTF8;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- REGISTRO HEADER ? ?H?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, r.bdCODEMP, 1, '000000',                                   -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                      OBSERVA??ES
--SELECT :prARQUIVO, r.bdCODEMP, 1, r.bdCODEMP,                                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                      OBSERVA??ES
         'H'||                                                                  -- H.01     1 -   1  Caracter(1)   C?digo do registro ?H?                                                         Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                  (COALESCE(r.bdIMEMP,''))), 10, '0')||         -- H.02     2 -  11  Num?rico(10)  N?mero da Inscri??o Municipal do Declarante                                    Formato: 9999999999 Exemplo: 65985-1 No arquivo ficar?: 0000659851 Campo N?o Obrigat?rio.
         LPAD(IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,'')))) >= 14,
                  (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,''))),
                  ''), 14, '0')||                                               -- H.03    12 -  25  Num?rico(14)  N?mero do CNPJ do Declarante no caso de pessoa jur?dica                        Formato: 99999999999999 Campo Obrigat?rio quando o campo H.02 ou H.04 n?o for preenchido
         LPAD(IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,'')))) < 14,
                  (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,''))),
                  ''), 11, '0')||                                               -- H.04    26 -  36  Num?rico(11)  N?mero do CPF do Declarante no caso de pessoa f?sica                           Obs.: Se o campo H.02 ou H.03 n?o for informado, ent?o este campo ser? obrigat?rio Formato: 99999999999
         RPAD(COALESCE(r.bdNOMEMP,''), 100, ' ')||                              -- H.05    37 - 136  Caracter(100) Nome/Raz?o Social do Declarante                                                Campo Obrigat?rio.
         'N'||                                                                  -- H.06   137 - 137  Caracter(1)   Tipo do Arquivo enviado para a Prefeitura, podendo ser: N ? normal, T ? Teste  Campo Obrigat?rio.
         SUBSTRING(:prREFERENCIA FROM 5 FOR 2)||                                -- H.07   138 - 139  Num?rico (2)  M?s de refer?ncia dos documentos declarados                                    Campo Obrigat?rio.
         SUBSTRING(:prREFERENCIA FROM 1 FOR 4)||                                -- H.08   140 - 143  Num?rico(4)   Ano de refer?ncia dos documentos declarados                                    Campo Obrigat?rio.
         RPAD('', 252, ' ')||                                                   -- H.09   144 - 395  Caracter(252) Brancos ? reservado para futuro                                                Campo Obrigat?rio.
         '.'                                                                    -- H.10   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                      Campo obrigat?rio que indica o final do registro.
  FROM VW_EMPRESAS_REF_ATUAL r
  WHERE r.bdCODEMP = :prCODEMP;

  -- REGISTRO DOCUMENTOS EMITIDOS CANCELADOS ? ?C?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, s.bdCODEMP, 2, LPAD(COALESCE((SELECT COUNT(*)              -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                        OBSERVA??ES
                                                   FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, s.bdCODEMP, 2, s.bdCODEMP||'.'||s.bdCHAVE,                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                        OBSERVA??ES
         'C'||                                                                  -- C.01     1 -   1  Caracter(1)   C?digo do registro ?C?                           Campo Obrigat?rio
         COALESCE((SUBSTRING(s.bdDATACANC FROM 9 FOR 2)||
                   SUBSTRING(s.bdDATACANC FROM 6 FOR 2)||
                   SUBSTRING(s.bdDATACANC FROM 1 FOR 4)),'00000000')||          -- C.02     2 -   9  Num?rico(8)   Data do cancelamento  da nota fiscal emitida.    Campo Obrigat?rio Formato: DDMMAAAAA
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCINI,'') FROM 1 FOR 8), 8, '0')||     -- C.03    10 -  17  Num?rico(8)   N?mero da nota fiscal inicial cancelada          Campo Obrigat?rio
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCFIM,'') FROM 1 FOR 8), 8, '0')||     -- C.04    18 -  25  Num?rico(8)   N?mero da nota fiscal final cancelada            Dever? ser informado somente quando houver um agrupamento de notas canceladas.
         RPAD(SUBSTRING(COALESCE(s.bdSERIE,'') FROM 1 FOR 3), 3, ' ')||         -- C.05    26 -  28  Caracter(3)   S?rie da Nota Fiscal cancelada                   Campo Obrigat?rio
         RPAD('', 361, ' ')||                                                   -- C.06    29 - 389  Caracter(361) Reservado para futuro
         LPAD(COALESCE((SELECT COUNT(*)
                        FROM TEXPORTACAO_ISS_CURITIBA),1), 6, '0')||            -- C.07   390 - 395  Num?rico(6)   N?mero seq?encial do registro dentro do arquivo. Campo Obrigat?rio.
         '.'                                                                    -- C.08   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                        Campo obrigat?rio que indica o final do registro.
  FROM VEF_EMP_TMOVSER s
  WHERE s.bdCODEMP = :prCODEMP
    AND s.bdTIPLAN = 0 -- Apenas servi?os Emitidos
    AND s.bdCODSITNF IN (2,3,4,5) -- Notas canceladas
    AND s.bdDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM;

  -- REGISTRO DOCUMENTOS EMITIDOS DECLARADOS ? ?E?
  IF (:prTIPOLANC IN (0,1)) THEN -- 0 = Ambos (emitidos/recebidos) / 1 = Somente emitidos
    EXECUTE PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (:prCODEMP, :prREFERENCIA, :prDTINI, :prDTFIM, :prTIPOLANC, :prRETIFICADORA, :prARQUIVO, 0);

  -- REGISTRO DOCUMENTOS RECEBIDOS DECLARADOS ? ?R?
  IF (:prTIPOLANC IN (0,2)) THEN -- 0 = Ambos (emitidos/recebidos) / 2 = Somente recebidos
    EXECUTE PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (:prCODEMP, :prREFERENCIA, :prDTINI, :prDTFIM, :prTIPOLANC, :prRETIFICADORA, :prARQUIVO, 1);

  -- REGISTRO HEADER ? ?T?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, c.bdCODEMP, 5, LPAD(COALESCE((SELECT COUNT(*)              -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                                                                        OBSERVA??ES
                                                   FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, c.bdCODEMP, 5, c.bdCODEMP,                                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                                                                        OBSERVA??ES
         'T'||                                                                  -- T.01     1 -   1  Caracter(1)   C?digo do registro ?T?                                                                                                           Campo Obrigat?rio
         LPAD(COUNT(*)+1, 8, '0')||                                             -- T.02     2 -   9  Num?rico(8)   Quantidade total de registros do arquivo, incluindo o header (H) e trailler (T)                                                  Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLREMIT,0)))), 15, '0')||        -- T.03    10 -  24  Num?rico(15)  Valor Total dos Documentos emitidos  pelo Prestador de Servi?os. Soma de todos os valores descritos nos campos E.11              Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRDEDEMIT,0)))), 15, '0')||     -- T.04    25 -  39  Num?rico(15)  Valor Total das Dedu??es dos Documentos emitidos pelo Prestador de Servi?os. Soma de todos os valores descritos nos campos E.12  Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRRECEB,0)))), 15, '0')||       -- T.05    40 -  54  Num?rico(15)  Valor Total dos Documentos recebidos  pelo tomador de Servi?os. Soma de todos os valores descritos nos campos R.11               Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRDEDRECEB,0)))), 15, '0')||    -- T.06    55 -  69  Num?rico(15)  Valor Total das Dedu??es dos Documentos recebidos  pelo tomador de Servi?os. Soma de todos os valores descritos nos campos R.12  Campo Obrigat?rio
         RPAD('', 326, ' ')||                                                   -- T.07    70 - 395  Caracter(326) Brancos ? reservado para futuro
         '.'                                                                    -- T.08   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                                                                        Campo obrigat?rio que indica o final do registro.
  FROM TEXPORTACAO_ISS_CURITIBA c
  WHERE c.bdCODEMP = :prCODEMP
  GROUP BY c.bdCODEMP;

  -- Exporta arquivo...
  OPENARQ(:prARQUIVO);

  FOR
    SELECT e.bdLINHA
    FROM TEXPORTACAO_ISS_CURITIBA E
    WHERE e.bdID = :prARQUIVO
    ORDER BY e.bdORDEMREG, e.bdORDEM
    INTO :wLINHA
  DO
    BEGIN
      WRITELNOA(:WLINHA);
    END

  CLOSEARQ(:prARQUIVO);

  DELETE FROM TEXPORTACAO_ISS_CURITIBA;

END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_ISS_CURITIBA for: SP_EXPORTA_ISS_CURITIBA_REG_E_R */
ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRTIPOLANC INTEGER,
PRRETIFICADORA INTEGER,
PRARQUIVO VARCHAR(100))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_EXPORTA_ISS_CURITIBA_REG_E_R) */
ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRTIPOLANC INTEGER,
PRRETIFICADORA INTEGER,
PRARQUIVO VARCHAR(100),
PRTIPOLANCEXP INTEGER)
 AS
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- REGISTRO DOCUMENTOS EMITIDOS DECLARADOS ? ?E?
  -- REGISTRO DOCUMENTOS RECEBIDOS DECLARADOS ? ?R?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdVLREMIT, bdVLRDEDEMIT, bdVLRRECEB, bdVLRDEDRECEB, bdLINHA)
  SELECT :prARQUIVO, s.bdCODEMP, 3+:prTIPOLANCEXP, LPAD(COALESCE((SELECT COUNT(*)
                                                                  FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, s.bdCODEMP, 3+:prTIPOLANCEXP, i.bdCODEMP||'.'||i.bdCHAVE||'.'||i.bdORDEM,
         CASE WHEN s.bdTIPLAN = 0 THEN COALESCE(i.bdVLRCONTAB, 0)     ELSE 0 END AS bdVLREMIT,
         CASE WHEN s.bdTIPLAN = 0 THEN COALESCE(i.bdACREDEDUIRSER, 0) ELSE 0 END AS bdVLRDEDEMIT,
         CASE WHEN s.bdTIPLAN = 1 THEN COALESCE(i.bdVLRCONTAB, 0)     ELSE 0 END AS bdVLRRECEB,
         CASE WHEN s.bdTIPLAN = 1 THEN COALESCE(i.bdACREDEDUIRSER, 0) ELSE 0 END AS bdVLRDEDRECEB,
--'|E.01|'||
         CASE

           WHEN s.bdTIPLAN = 0 THEN 'E'
           WHEN s.bdTIPLAN = 1 THEN 'R'                                         -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                                                                       OBSERVA??ES
         ELSE ' ' END||                                                         -- E.01    1 - 1     Caracter(1)   C?digo do registro ?E?                                                                                                          Campo Obrigat?rio
--'|E.02|'||
         (SUBSTRING(s.bdDATAEMISSAO FROM 9 FOR 2)||
          SUBSTRING(s.bdDATAEMISSAO FROM 6 FOR 2)||
          SUBSTRING(s.bdDATAEMISSAO FROM 1 FOR 4))||                            -- E.02    2 - 9     Num?rico(8)   Data de emiss?o do documento declarado.                                                                                         Campo Obrigat?rio Formato: DDMMAAAA
--'|E.03|'||
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCINI,'') FROM 1 FOR 8), 8, '0')||     -- E.03    10 - 17   Num?rico(8)   N?mero do documento inicial emitido                                                                                             Obs.: este campo ser? obrigat?rio somente quando o tipo de documento declarado (campo E.05) for nota fiscal ou conhecimento de transporte.
--'|E.04|'||
         RPAD('', 8, ' ')||                                                     -- E.04    18 - 25   Num?rico(8)   N?mero do documento final emitido                                                                                               Obs.: este campo dever? ser informado apenas quando caracterizar agrupamento de notas e quando o servi?o n?o caracterizar subst.tribut/ret.?rg?os p?bl. (campo E.07).
                                                                                --                                                                                                                                                                       Tamb?m dever? ser respeitado o valor m?nimo de cada documento. Poder?o ser agrupados apenas os documentos com valor unit?rio inferior a R$ 200,00. Limite de 20 documentos por agrupamento.
--'|E.05|'||
         COALESCE(tpnf.bdCODTPNFEXP,'0')||                                      -- E.05    26 - 26   Num?rico(1)   Identifica??o do Tipo de Documento emitido.                                                                                     Campo Obrigat?rio
                                                                                --                                   Pessoas Jur?dicas poder?o utilizar os seguintes c?digos: 1. Nota Fiscal, 4. Cupom Fiscal, 6. Conhecimento de Transporte
                                                                                --                                   Pessoas F?sicas poder?o utilizar os seguintes c?digos: 2. Recibo Comum, 3. RPA - Recibo Pagamento Aut?nomo
--'|E.06|'||
         RPAD(SUBSTRING(COALESCE(s.bdSERIE,'') FROM 1 FOR 3), 3, ' ')||         -- E.06    27 - 29   Caracter(3)   S?rie do Documento emitido quando o campo E.05 = Nota Fiscal                                                                    Obs.: Este n? ser? obrigat?rio somente quando o tipo de documento declarado (campo E.05) for nota fiscal.
--'|E.07|'||
         CASE                                                                   -- E.07    30 - 30   Caracter(1)   Identifica??o do Servi?o Prestado caracterizando Substitui??o Tribut?ria / Reten??o ?rg?o P?blico ou Doc.Fiscal Normal          Campo Obrigat?rio
           WHEN ic.bdCODIDNF = 0 THEN 'N'                                       --                                   N ? Doc.Fiscal Normal
           WHEN ic.bdCODIDNF = 1 THEN 'S'                                       --                                   S ? caracteriza substitui??o tribut?ria/reten??o ?rg?o p?blico
           WHEN ic.bdCODIDNF = 2 THEN 'R'                                       --                                   R - Caracteriza reten??o na fonte

         ELSE 'N' END||
--'|E.08|'||
         IIF(s.bdCODCID = 3281, 'D', 'F')||                                     -- E.08    31 - 31   Caracter(1)   Indicador do Local de Presta??o do Servi?o quando o servi?o prestado caracterizar substitui??o tribut?ria / reten??o ?rg?o p?blico, de acordo com o campo E.07.
                                                                                --                                   D ? Dentro do Munic?pio                                                                                                       Campo obrigat?rio somente quando o campo E.07 = Substitui??o tribut?ria / reten??o fonte ?rg?o p?blico
                                                                                --                                   F ? Fora do Munic?pio
--'|E.09|'||
         RPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                         (COALESCE(atv.bdCODMUNATVM,''))) FROM 1 FOR 2),2,' ')||-- E.09    32 - 33   Caracter(2)   C?digo do Item da Lista de Servi?os (Lei Complementar 116/2003)                                                                 Campo Obrigat?rio somente quando o servi?o prestado caracterizar substitui??o tribut?ria / reten??o ?rg?o p?blico, de acordo com o campo E.07.
--'|E.10|'||
         RPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                         (COALESCE(atv.bdCODMUNATVM,''))) FROM 3 FOR 2),2,' ')||-- E.10    34 - 35   Caracter(2)   C?digo do Sub-item da Lista de Servi?os (Lei Complementar 116/2003).                                                            Campo Obrigat?rio somente quando o servi?o prestado caracterizar substitui??o tribut?ria / reten??o ?rg?o p?blico, de acordo com o campo E.07
--'|E.11|'||
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                  (COALESCE(i.bdVLRCONTAB,0))), 15, '0')||      -- E.11    36 - 50   Num?rico(15)  Valor do documento emitido.                                                                                                     Campo Obrigat?rio
--'|E.12|'||
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                  (COALESCE(i.bdACREDEDUIRSER,0))), 15, '0')||  -- E.12    51 - 65   Num?rico(15)  Valor de dedu??o do documento emitido conforme legisla??o tribut?ria municipal pertinente.                                      Campo Obrigat?rio. Obs.: Caso n?o tenha valor de dedu??o informar 0 (zero).
--'|E.13|'||
         LPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                          (COALESCE(ter.bdIMTER,''))) FROM 1 FOR 8),  10, '0')||-- E.13    66 - 75   Num?rico(10)  N?mero da inscri??o municipal do tomador de servi?o.                                                                            Formato: 9999999999 Ex. 154-3 No arquivo ficar?: 0000001543
                                                                                --                                                                                                                                                                 Obs.: quando este campo for informado torna-se desnecess?rio os dados dos campos E.17 a E.24
                                                                                --                                                                                                                                                                 Este n?mero quando informado, obrigatoriamente dever? ser diferente do campo informado em H.02
--'|E.14|'||
         IIF((CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(ter.bdCGCTER,'')))) >= 14),
              LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                       (COALESCE(ter.bdCGCTER,''))), 14, '0'),  -- E.14    76 - 89   Num?rico(14)  N?mero do CNPJ do tomador de servi?o quando este for Pessoa Jur?dica                                                            Obs.: este n?mero quando informado, obrigatoriamente dever? ser diferente do campo informado em H.03.
               LPAD('',14,'0') )||                                              --                                                                                                                                                                 Campo obrigat?rio somente quando o campo E.07 = Substitui??o tribut?ria / reten??o fonte ?rg?o p?blico
--'|E.15|'||
         IIF((CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(ter.bdCGCTER,'')))) < 14),
              LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                       (COALESCE(ter.bdCGCTER,''))), 11, '0'),  -- E.15    90 - 100  Num?rico(11)  N?mero do CPF do tomador de servi?o quando este for Pessoa F?sica                                                               Obs.: se os campos E.13 e E.14 n?o forem informados ent?o este campo torna-se obrigat?rio, exceto quando o tomador de servi?o for uma pessoa f?sica sem identifica??o.
               LPAD('',11,'0') )||                                              --                                                                                                                                                                 Este n?mero quando informado, obrigatoriamente dever? ser diferente do campo informado em H.04.
--'|E.16|'||
         RPAD(SUBSTRING(COALESCE(ter.bdNOMETER,'') FROM 1 FOR 100), 100, ' ')|| -- E.16   101 - 200  Varchar(100)  Nome ou Raz?o Social do tomador de servi?o                                                                                      Campo Obrigat?rio, exceto quando o tomador de servi?o for uma pessoa f?sica sem identifica??o.
--'|E.17|'||
         RPAD((CASE                                                             -- E.17   201 - 205  Caracter(5)   Identifica??o do Tipo do Logradouro do Endere?o do tomador de servi?o                                                           Ex.: de Siglas a serem utilizadas:
                 WHEN ter.bdLOGRTER = 'Avenida'    THEN 'AV.'                   --                                                                                                                                                                       AV.   Avenida
                 WHEN ter.bdLOGRTER = 'R?tula'     THEN 'ROT.'                  --                                                                                                                                                                       ROT.  R?tula
                 WHEN ter.bdLOGRTER = 'Rua'        THEN 'R.'                    --                                                                                                                                                                       R.    Rua
                 WHEN ter.bdLOGRTER = 'Travessa'   THEN 'TV.'                   --                                                                                                                                                                       TV.   Travessa
                 WHEN ter.bdLOGRTER = 'Alameda'    THEN 'AL.'                   --                                                                                                                                                                       AL.   Alameda
                 WHEN ter.bdLOGRTER = 'Estrada'    THEN 'EST.'                  --                                                                                                                                                                       EST.  Estrada
                 WHEN ter.bdLOGRTER = 'Rodovia'    THEN 'ROD.'                  --                                                                                                                                                                       ROD.  Rodovia
                 WHEN ter.bdLOGRTER = 'Variante'   THEN 'VAR.'                  --                                                                                                                                                                       VAR.  Variante
                 WHEN ter.bdLOGRTER = 'Pra?a'      THEN 'PC.'                   --                                                                                                                                                                       PC.   Pra?a
                 WHEN ter.bdLOGRTER = 'Largo'      THEN 'LG.'                   --                                                                                                                                                                       LG.   Largo
                 WHEN ter.bdLOGRTER = 'Jardinete'  THEN 'JDTE.'                 --                                                                                                                                                                       JDTE. Jardinete
                 WHEN ter.bdLOGRTER = 'Parque'     THEN 'PQ.'                   --                                                                                                                                                                       PQ.   Parque
                 WHEN ter.bdLOGRTER = 'Rio'        THEN 'RIO'                   --                                                                                                                                                                       RIO   Rio
                 WHEN ter.bdLOGRTER = 'Terminal'   THEN 'TER.'                  --                                                                                                                                                                       TER.  Terminal
                 WHEN ter.bdLOGRTER = 'Alto'       THEN 'AT.'                   --                                                                                                                                                                       AT.   Alto
                 WHEN ter.bdLOGRTER = 'Beco'       THEN 'BC.'                   --                                                                                                                                                                       BC.   Beco
                 WHEN ter.bdLOGRTER = 'Conjunto'   THEN 'CJTO.'                 --                                                                                                                                                                       CJTO. Conjunto
                 WHEN ter.bdLOGRTER = 'Galeria'    THEN 'GL.'                   --                                                                                                                                                                       GL.   Galeria
                 WHEN ter.bdLOGRTER = 'Granja'     THEN 'GR.'                   --                                                                                                                                                                       GR.   Granja
                 WHEN ter.bdLOGRTER = 'Lagoa'      THEN 'LA'                    --                                                                                                                                                                       LA    Lagoa
                 WHEN ter.bdLOGRTER = 'Ladeira'    THEN 'LD.'                   --                                                                                                                                                                       LD.   Ladeira
                 WHEN ter.bdLOGRTER = 'Loteamento' THEN 'LT.'                   --                                                                                                                                                                       LT.   Loteamento
                 WHEN ter.bdLOGRTER = 'Pa?o'       THEN 'P?'                    --                                                                                                                                                                       P?    Pa?o
                 WHEN ter.bdLOGRTER = 'Vila'       THEN 'VILA'                  --                                                                                                                                                                       VILA  Vila
                 WHEN ter.bdLOGRTER = 'Salina'     THEN 'SL.'                   --                                                                                                                                                                       SL.   Salina
                 WHEN ter.bdLOGRTER = 'S?tio'      THEN 'SIT.'                  --                                                                                                                                                                       SIT.  S?tio
                 WHEN ter.bdLOGRTER = 'Viela'      THEN 'VEL.'                  --                                                                                                                                                                       VEL.  Viela
                 WHEN ter.bdLOGRTER = 'Viaduto'    THEN 'VIAD.'                 --                                                                                                                                                                       VIAD. Viaduto
                 WHEN ter.bdLOGRTER = 'Servid?o'   THEN 'SER.'                  --                                                                                                                                                                       SER.  Servid?o
                 WHEN ter.bdLOGRTER = 'Jardim'     THEN 'JAR.'                  --                                                                                                                                                                       JAR.  Jardim
               ELSE '' END),5,' ')||
--'|E.18|'||
         RPAD(SUBSTRING(COALESCE(ter.bdENDTER,'') FROM 1 FOR 50), 50, ' ')||    -- E.18   206 - 255  Caracter(50)  Nome do Logradouro do Endere?o do tomador de servi?o
--'|E.19|'||
         RPAD(SUBSTRING(COALESCE(ter.bdNUMTER,'') FROM 1 FOR 6), 6, ' ')||      -- E.19   256 - 261  Caracter(6)   N?mero do Endere?o do tomador de servi?o
--'|E.20|'||
         RPAD(SUBSTRING(COALESCE(ter.bdCOMPTER,'') FROM 1 FOR 20), 20, ' ')||   -- E.20   262 - 281  Caracter(20)  Complemento do Endere?o do tomador de servi?o
--'|E.21|'||
         RPAD(SUBSTRING(COALESCE(ter.bdBAITER,'') FROM 1 FOR 50), 50, ' ')||    -- E.21   282 - 331  Caracter(50)  Bairro do Endere?o do tomador de servi?o
--'|E.22|'||
         RPAD(SUBSTRING(COALESCE(terCid.bdNOMCID,'') FROM 1 FOR 44), 44, ' ')|| -- E.22   332 - 375  Caracter(44)  Cidade do Endere?o do tomador de servi?o
--'|E.23|'||
         RPAD(SUBSTRING(COALESCE(terUF.bdSIGLAUF,'') FROM 1 FOR 2), 2, ' ')||   -- E.23   376 - 377  Caracter(2)   Estado da Cidade do Endere?o do tomador de servi?o
--'|E.24|'||
         LPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                           (COALESCE(ter.bdCEPTER,''))) FROM 1 FOR 8), 8, '0')||-- E.24   378 - 385  Num?rico(8)   Cep do Endere?o do tomador de servi?o
--'|E.25|'||
         LPAD(COALESCE((SELECT COUNT(*)
                        FROM TEXPORTACAO_ISS_CURITIBA),1), 6, '0')||            -- E.25   386 - 391  Num?rico(6)   N?mero seq?encial do registro dentro do arquivo                                                                                 Campo Obrigat?rio Formato: 999999
--'|E.26|'||
         LPAD(SUBSTRING((SELECT RESULT
                         FROM SP_TIRATODOSSINAIS(
                                                 CASE
                                                   WHEN s.bdTIPLAN = 0 THEN -- Emitidos
                                                     CASE WHEN ic.bdCODIDNF = 0 THEN -- N ? Doc.Fiscal Normal
                                                       IIF((i.bdALIQREDISSSER < 10), '0'||i.bdALIQREDISSSER, i.bdALIQREDISSSER)
                                                     ELSE '' END
                                                   WHEN s.bdTIPLAN = 1 THEN -- Recebidos
                                                     CASE WHEN ic.bdCODIDNF <> 0 THEN -- N ? Doc.Fiscal Normal
                                                       IIF((i.bdALIQREDISSSER < 10), '0'||i.bdALIQREDISSSER, i.bdALIQREDISSSER)
                                                     ELSE '' END
                                                 ELSE '' END))
              FROM 1 FOR 4), 4, '0')||                                          -- E.26   392 - 395  Num?rico(4)   Valor percentual da Al?quota                                                                                                    Campo Obrigat?rio somente quando o servi?o tomador N?O caracterizar Substitui??o Tribut?ria / Reten??o ?rg?o P?blico, reten??o na fonte conforme item E.07.
                                                                                --                                                                                                                                                                 Caso contr?rio o campo deve vir preenchido com 0000.
                                                                                --                                                                                                                                                                 Quando esta informa??o for obrigat?ria ent?o o valor deve ser maior que 0000.
                                                                                --                                                                                                                                                                 Exemplo quando a al?quota for 5%: 0500
--'|E.27|'||
         '.'                                                                    -- E.27   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                                                                       Campo obrigat?rio que indica o final do registro.
  FROM VEF_EMP_TMOVSER s
  JOIN VEF_EMP_TMOVSERITENS i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE)
  LEFT OUTER JOIN TATVMUNICIPAL atv ON (atv.BDCODATVM = i.BDCODATVM)
  LEFT OUTER JOIN VEF_EMP_TMOVSERITENSCUR ic ON (ic.bdCODEMP = s.bdCODEMP AND ic.bdCHAVE = s.bdCHAVE AND ic.bdORDEM = i.bdORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABTPNF tpnf ON (tpnf.bdCODTPNF = s.bdCODTPNF)
  LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdCODTER = s.bdCODTER)
  LEFT OUTER JOIN TCIDADE terCid ON (terCid.bdCODCID = ter.bdCODCID)
  LEFT OUTER JOIN TUF terUF ON (terUF.bdCODUF = terCid.bdCODUF)
  WHERE s.bdCODEMP = :prCODEMP
    AND s.bdCODSITNF NOT IN (2,3,4,5) -- Notas canceladas
    AND s.bdTIPLAN = :prTIPOLANCEXP
    AND s.bdDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM
  ORDER BY i.bdCODEMP, i.bdCHAVE, i.bdORDEM;

END
^

/* Alter (SP_FERIAS_PROVISAO) */
ALTER PROCEDURE SP_FERIAS_PROVISAO(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDREFFE INTEGER,
BDCODVER INTEGER,
BDREFVRFE NUMERIC(15,6),
BDVALVRFE NUMERIC(15,6),
BDREFAUXVRFE NUMERIC(15,6),
BDCLAVER VARCHAR(20),
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(25000);
BEGIN
  /* N?o se esque?a de setar a compet?ncia */

  wsql = 'select '||
            'VFER.BDCODEMP, '||
            'VFER.BDCODCOL, '||
            'VFER.BDINIPERAQUISFE, '||
            'VFER.BDCODFE, '||
            'VFERIAS.BDREFFE, '||
            'VFERIAS.BDCODVER, '||
            'VFERIAS.BDREFVRFE, '||
            'VFERIAS.BDVALVRFE, '||
            'VFERIAS.BDREFAUXVRFE, '||
            'VERBAS.BDCLAVER, '||
            'VERBAS.BDTIPOCODVER, '||
            'VERBAS.BDINSSVER, '||
            'VERBAS.BDFGTSVER, '||
            'VERBAS.BDIRVER, '||
            'VERBAS.BDTIPOREFVER, '||
            'VERBAS.BDBASESFVER ';

  wsql = wsql||'from VRH_EMP_TFERIAS VFER '||
               'left outer join VRHF_EMP_TVERBARFE VFERIAS on (VFERIAS.BDCODEMP = VFER.BDCODEMP and VFERIAS.BDCODCOL = VFER.BDCODCOL and '||
                  'VFERIAS.BDINIPERAQUISFE = VFER.BDINIPERAQUISFE and VFERIAS.BDCODFE = VFER.BDCODFE) '||
               'left outer join VW_TVERBAS_REF VERBAS on (VFERIAS.BDCODVER = VERBAS.BDCODVER) ';

  wwhere = 'where (VFERIAS.BDREFFE <= '||:prref||' or ((VFERIAS.BDREFFE is null) and (VFER.BDREFFIMFE <= '||:prref||'))) and '||
           'not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC where RESC.BDCODEMP = VFER.BDCODEMP and RESC.BDCODCOL = VFER.BDCODCOL and RESC.BDREFRESCISAO < '||:prref||') ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||'and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||'and '||prcodcol;

  FOR EXECUTE STATEMENT wsql||wwhere
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDINIPERAQUISFE,
    :BDCODFE,
    :BDREFFE,
    :BDCODVER,
    :BDREFVRFE,
    :BDVALVRFE,
    :BDREFAUXVRFE,
    :BDCLAVER,
    :BDTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER
  DO
  SUSPEND;
END
^

/* Alter (SP_FICHA_REGISTROS_CARGOS) */
ALTER PROCEDURE SP_FICHA_REGISTROS_CARGOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRULTDIA DATE,
PRRETORNAVAZIO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATACOL DATE,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDCODCBO INTEGER,
BDNOMCOL VARCHAR(70),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50))
 AS
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATACOL date;
declare variable WCODPLAFUC integer;
declare variable WCODTFUC integer;
declare variable WDESCTFUC varchar(40);
declare variable WCODCBO integer;
declare variable WSQL varchar(30000);
declare variable WCONT integer;
declare variable WWHERE varchar(20000);
declare variable WCODMAS integer;
declare variable WDESCMAS varchar(50);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
BEGIN
  IF (PRRETORNAVAZIO = 1) THEN
     BEGIN
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL, T.BDDATACOL, T.BDCODPLAFUC, T.BDCODTFUC , COLFUNC.bddesctfuc , COLFUNC.bdcodcbo , X.BDCODMAS, Y.BDDESCMAS ';
       WSQL = WSQL || 'FROM VRH_EMP_TCOL_VINCDIA T join VRH_EMP_TCOLCON_CALCDIA X on (X.BDCODEMP = T.BDCODEMP and X.BDCODCOL = T.BDCODCOL and X.BDDATACOL = T.BDDATACOL) '||
         'left outer join VRH_BASE_TMOTAUMSAL Y on (Y.BDCODMAS = X.BDCODMAS) '||
         'left outer join VRH_FUNCOES_TFUC colfunc on (T.BDCODPLAFUC = colfunc.BDCODPLAFUC and T.BDCODTFUC = colfunc.BDCODTFUC) ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL||wwhere || ' order by T.BDCODEMP, T.BDCODCOL, T.BDDATACOL, T.BDCODTFUC';
     
       wempatu = 0;
       wcolatu = 0;

       WCONT = 0;
       FOR EXECUTE STATEMENT wsql INTO
         :WCODEMP,
         :WCODCOL,
         :WDATACOL,
         :WCODPLAFUC,
         :WCODTFUC,
         :Wdesctfuc,
         :Wcodcbo,
         :wcodmas,
         :wdescmas
       DO
       BEGIN
         IF (wcont = 0) THEN
            BEGIN
             BDCODEMP = WCODEMP;
             BDCODCOL = WCODCOL;
             BDDATACOL = WDATACOL;
             BDCODPLAFUC = WCODPLAFUC;
             BDCODTFUC = WCODTFUC;
             BDdesctfuc = Wdesctfuc;
             BDcodcbo = Wcodcbo;
             BDCODMAS = wcodmas;

             IF (wdescmas IS NULL) THEN
                wdescmas = 'Admiss?o';

             BDDESCMAS = wdescmas;

             if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                begin
                  wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                           ' and BDREFCOL <= '||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 6 FOR 2)||
                           ' order by BDREFCOL DESC';
                  execute statement wwhere into :BDNOMCOL;

                  wempatu = wcodemp;
                  wcolatu = wcodcol;
                end

             SUSPEND;
            END
         ELSE
            BEGIN
              IF ((BDCODEMP <> WCODEMP) OR (BDCODCOL <> WCODCOL) OR ((BDCODTFUC <> wCODTFUC) OR ((BDCODTFUC IS NULL) AND (wCODTFUC IS NOT NULL)) OR ((BDCODTFUC IS NOT NULL) AND (wCODTFUC IS NULL)))) THEN
                 BEGIN
                     IF (BDCODCOL <> WCODCOL AND wdescmas IS NULL) THEN
                        wdescmas = 'Admiss?o';

                     BDCODEMP = WCODEMP;
                     BDCODCOL = WCODCOL;
                     BDDATACOL = WDATACOL;
                     BDCODPLAFUC = WCODPLAFUC;
                     BDCODTFUC = WCODTFUC;
                     BDdesctfuc = Wdesctfuc;
                     BDcodcbo = Wcodcbo;
                     BDCODMAS = wcodmas;
                     BDDESCMAS = wdescmas;

                     if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                        begin
                          wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                   ' and BDREFCOL <= '||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 6 FOR 2)||
                                   ' order by BDREFCOL DESC';
                          execute statement wwhere into :BDNOMCOL;
        
                          wempatu = wcodemp;
                          wcolatu = wcodcol;
                        end

                     SUSPEND;
                 END
            END
     
         WCONT = 1;
       END
     END
   ELSE
     SUSPEND;
END
^

/* Alter (SP_FICHA_REGISTROS_SALARIOS) */
ALTER PROCEDURE SP_FICHA_REGISTROS_SALARIOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRREF INTEGER,
PRRETORNAVAZIO INTEGER,
PRTRAZERSALINI INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDSALINICOL NUMERIC(18,6),
BDDATACOL DATE,
BDSALBASECOL NUMERIC(18,6),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODTFUC INTEGER,
BDCODSHE INTEGER,
BDDESCSHE VARCHAR(50),
BDSALBASEANT NUMERIC(18,6))
 AS
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATAADMCOL date;
declare variable WSALINICOL numeric(18,6);
declare variable WDATACOL date;
declare variable WSALBASECOL numeric(18,6);
declare variable WCODMAS integer;
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(30000);
declare variable WCONT integer;
declare variable WDESCMAS varchar(50);
declare variable WCODTFUC integer;
declare variable WCODSHE integer;
declare variable WTIPOCOL integer;
declare variable WDESCSHE varchar(50);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WWHERE varchar(500);
BEGIN
  BDSALBASEANT = 0;

  IF (PRRETORNAVAZIO = 1) THEN
     BEGIN
       EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);
       WSQL = ' select BDCODEMP, BDCODCOL, BDTIPOCOL from VW_VRHF_EMP_TCOL_CALC COL ';

       -- 14269 - Marcelo B. M. - 23/06/2016: Ajustado para aceitar mais de uma empresa e/ou colaborador
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
             WSQL = WSQL || ' where '||prcodemp;
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' and '||PRCODCOL;
          END
       ELSE
          BEGIN
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' where '||PRCODCOL;
          END

       FOR EXECUTE STATEMENT wsql INTO
         WCODEMP,
         WCODCOL,
         WTIPOCOL
       DO
       BEGIN
         --Sol. 17643 - Bruno L. R. - 01/08/2017
         IF (WTIPOCOL = 4) THEN
            BEGIN
              WSQL2 = 'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, SHE.BDSALSHE bdsalinicol, SHE.BDDATASHE BDDATACOL, SHE.BDSALSHE BDSALBASECOL, SHE.bdcodshe bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe,  CAST(null as varchar(50)) BDDESCSHE  ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_SHE SHE on (SHE.bdcodemp = COL.bdcodemp and SHE.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = SHE.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = SHE.bdcodemp and VINCDIA.bdcodcol = SHE.bdcodcol and VINCDIA.BDDATACOL = SHE.BDDATASHE) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              WSQL2 = WSQL2 || ' union select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, '||
                      ' HIST.BDSALBASEHAUMHE,  HIST.bdcodshe bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = col.bdcodemp and VINCDIA.bdcodcol = col.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUMHE) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              /*
              WCAMPOSSHE = ' HIST.BDSALBASEANTHAUMHE bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, HIST.BDSALBASEHAUMHE BDSALBASECOL, HIST.bdcodmas, MAUMSAL.BDDESCMAS,'||
                           ' VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE ';
              WJOINSHE = ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) '||
                         ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = HIST.bdcodmas) '||
                         ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WCAMPODATA = 'HIST.BDDATAHAUMHE';      */
            END
          ELSE
            BEGIN
              WSQL2 = 'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, CALC.BDDATACOL, CALC.BDSALBASECOL, CALC.bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOLCON_CALCDIA CALC on (CALC.bdcodemp = COL.bdcodemp and CALC.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = CALC.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = CALC.bdcodemp and VINCDIA.bdcodcol = CALC.bdcodcol and VINCDIA.BDDATACOL = CALC.BDDATACOL) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              WSQL2 = WSQL2 || ' union select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUM BDDATACOL, HIST.BDSALBASEHAUM, '||
                      ' HIST.bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUM HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = COL.bdcodemp and VINCDIA.bdcodcol = COL.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUM) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;
            END
         --Sol. 17643 - Bruno L. R. - 01/08/2017

           wempatu = 0;
           wcolatu = 0;

           WCONT = 0;
           FOR EXECUTE STATEMENT WSQL2 INTO
             WCODEMP,
             WCODCOL,
             WDATAADMCOL,
             WSALINICOL,
             WDATACOL,
             WSALBASECOL,
             WCODMAS,
             WDESCMAS,
             WCODTFUC,
             WCODSHE,
             WDESCSHE
           DO
           BEGIN
             IF (wcont = 0) THEN
                BEGIN
                   BDCODEMP = WCODEMP;
                   BDCODCOL = WCODCOL;
                   BDDATAADMCOL = WDATAADMCOL;
                   IF (WSALINICOL IS NULL) THEN
                      BDSALINICOL = 0;
                   ELSE
                      BDSALINICOL = WSALINICOL;
                   BDDATACOL = WDATACOL;
                   BDSALBASEANT = NULL;   --Sol. 17798 - Bruno L. R. - 05/04/2017
                   BDSALBASECOL = WSALBASECOL;

                   IF ((WDATACOL = WDATAADMCOL) OR (BDSALBASEANT IS NULL)) THEN   --Sol. 18509 - Bruno L. R. - 26/07/2017
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admiss?o';

                        --IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                          -- BDSALBASECOL = BDSALINICOL;

                       -- IF (BDSALBASECOL IS NOT NULL) THEN
                         --  BDSALINICOL = BDSALBASECOL;
                      END
                   ELSE
                     BEGIN
                       BDCODMAS = WCODMAS;
                       BDDESCMAS = WDESCMAS;
                     END

                   IF (BDDATACOL IS NULL) THEN
                      BDDATACOL = BDDATAADMCOL;

                   IF (BDSALBASEANT = BDSALINICOL) THEN
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admiss?o';
                        BDDATACOL = WDATAADMCOL;
                      END

                   BDCODSHE = WCODSHE;
                   BDDESCSHE = WDESCSHE;
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL = BDSALINICOL) AND (WTIPOCOL = 4))) THEN
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL <> BDSALINICOL) OR (BDSALBASECOL IS NULL))) THEN
                   IF ((PRTRAZERSALINI = 1) AND (BDSALINICOL <> 0)) THEN
                      begin
                        if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                           begin
                             wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                      ' and BDREFCOL <= '||prref||
                                      ' order by BDREFCOL DESC';
                             execute statement wwhere into :BDNOMCOL;
           
                             wempatu = wcodemp;
                             wcolatu = wcolatu;
                           end

                        SUSPEND;
                      end
                END
             ELSE
                BEGIN
                --  IF ((BDCODEMP <> WCODEMP) OR (BDCODCOL <> WCODCOL) OR (BDSALBASECOL <> WSALBASECOL) OR (BDCODMAS <> WCODMAS)) THEN   --Sol. 18509 - Bruno L. R. - 03/07/2017
                 -- BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        BDDATAADMCOL = WDATAADMCOL;
                        IF (WSALINICOL IS NULL) THEN
                           BDSALINICOL = 0;
                        ELSE
                           BDSALINICOL = WSALINICOL;
                        BDDATACOL = WDATACOL;
                        BDSALBASEANT = BDSALBASECOL;     --Sol. 17798 - Bruno L. R. - 04/04/2017
                        BDSALBASECOL = WSALBASECOL;

                       IF ((WDATACOL = WDATAADMCOL) OR (BDSALBASEANT IS NULL)) THEN    --Sol. 18509 - Bruno L. R. - 10/07/2017
                          BEGIN
                            BDCODMAS = 0;
                            BDDESCMAS = 'Admiss?o';

                         --   IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                           --    BDSALBASECOL = BDSALINICOL;
                          END
                       ELSE
                         BEGIN
                           BDCODMAS = WCODMAS;
                           BDDESCMAS = WDESCMAS;
                         END

                        BDCODTFUC = WCODTFUC;
                        BDCODSHE = WCODSHE;
                        BDDESCSHE = WDESCSHE;

                        IF (BDDATACOL IS NULL) THEN
                           BDDATACOL = BDDATAADMCOL;

                        IF (BDSALBASEANT = BDSALINICOL) THEN
                           BEGIN
                             BDCODMAS = 0;
                             BDDESCMAS = 'Admiss?o';
                       --      BDDATACOL = WDATAADMCOL;
                           END

                        IF (BDSALBASEANT <> BDSALBASECOL) THEN
                           BEGIN
                             BDCODMAS = WCODMAS;
                             BDDESCMAS = WDESCMAS;
                           END

                       IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND ((BDSALBASECOL <> BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR
                          ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN
                          begin
                            if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                               begin
                                 wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                          ' and BDREFCOL <= '||prref||
                                          ' order by BDREFCOL DESC';
                                 execute statement wwhere into :BDNOMCOL;
               
                                 wempatu = wcodemp;
                                 wcolatu = wcolatu;
                               end

                            SUSPEND;
                          end
                   --  END
                END
    
             WCONT = 1;
           END
       END
     END
   ELSE
     SUSPEND;
END
^

/* Alter (SP_GERA_ADVERTENCIAS) */
ALTER PROCEDURE SP_GERA_ADVERTENCIAS AS
DECLARE VARIABLE WAUXINT INTEGER;
BEGIN
  /* Procedure Text */
--  suspend;
  FOR SELECT FIRST 1 p.bdcodplapadrao FROM tplano_conf_online p
      JOIN tconf_contas_online c ON (p.bdcodplanoonline = c.bdcodplanoonline)
      WHERE p.bdcodplapadrao <> c.bdcodplapadrao INTO WAUXINT DO
    BEGIN
      EXECUTE PROCEDURE sp_insere_advertencia('Configura??o online: Items da configura??o online com plano de contas diferente do plano de contabiliza??o!');
    END


  FOR SELECT FIRST 1 p.bdcodplapadrao FROM tplano_conf_online p
      JOIN tconf_contas_online c ON (p.bdcodplanoonline = c.bdcodplanoonline)
      WHERE p.bdcodhist <> c.bdcodtphi INTO WAUXINT DO
    BEGIN
      EXECUTE PROCEDURE sp_insere_advertencia('Configura??o online: Items da configura??o online com plano de hist?ricos diferente do plano de contabiliza??o!');
    END

END
^

/* Alter (SP_GERAR_INCON_TCADPRO) */
ALTER PROCEDURE SP_GERAR_INCON_TCADPRO(PRSESSAO INTEGER,
PRCODEMP INTEGER,
PRCODPLANOINCO INTEGER,
PRREF INTEGER,
PRIDTERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOUNIMED INTEGER;
DECLARE VARIABLE WNCMINVALIDO DM_BOOLEAN;
DECLARE VARIABLE WISINDUSTRIA DM_BOOLEAN;
DECLARE VARIABLE WNCMPADRAO INTEGER;
DECLARE VARIABLE WCODUNIMEDPADRAO INTEGER;
DECLARE VARIABLE WAPEUNIMEDPADRAO VARCHAR(5);
BEGIN
  DELETE FROM VEF_INCON_TCADPRO WHERE BDSESSAO = :PRSESSAO;

  SELECT I.BDPRODNCMVAZIO, I.BDNCMPROD, I.BDCODUNIMED
  FROM VEF_BASE_TACOESINCONS I
  WHERE I.BDCODPLANOINCONS = :PRCODPLANOINCO
  INTO :wNcmInvalido, :wNcmPadrao, :wCodUnimedPadrao;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREF);
  /*Faz esse select pra ver se a empresa n?o ? industria*/
  SELECT IIF(((a.bdcodconficmssped > 0) AND (a.BDATIVIDADESPED = 0) AND (a.bddtobrigspedcont IS NOT NULL) AND (a.BDINDATIV = 1)), 'TRUE', 'FALSE') BDISINDUSTRIA
  FROM VW_VEF_BASE_TEMPPARFED a
  WHERE a.bdcodemp = :PRCODEMP
  INTO :wIsIndustria;

  /*Transforma ncm's inv?lidas para vazio*/
  IF (:wNcmInvalido = 'TRUE') THEN
    BEGIN
      /*Verifica se a empresa n?o ? Ind?stria, industria deve ter ncm v?lido, sen?o tiver ? inconsistente*/
      IF (:wIsIndustria = 'FALSE') THEN
        BEGIN
          /*Altera na tabela TMP*/
          UPDATE TMP_TCADPRO P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );

          /*Altera na tabela TEMP*/
          UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );
        END
    END

  /*Muda as ncm's inv?lidas para ncm padr?o, se a empresa for ind?stria principalmente(obrigat?rio)*/
  IF ((:wNcmPadrao IS NOT NULL) OR (:wNcmPadrao > 0)) THEN
    BEGIN
      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se j? alterou, n?o vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se j? alterou, n?o vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );
    END

  /*Se tiver uma unidade de medida padr?o, coloca ela nos produtos que n?o tem unidade de medida*/
  IF ((:wCodUnimedPadrao IS NOT NULL) OR (:wCodUnimedPadrao > 0)) THEN
    BEGIN
      /*Busca apelido, apenas para mostrar na grid*/
      SELECT U.BDAPEUNIMED FROM TUNIDADEMEDIDA U WHERE U.BDCODUNIMED = :wCodUnimedPadrao INTO :wApeUnimedPadrao;

      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDCODUNIMED IS NULL) OR (P.BDCODUNIMED = 0))
      AND P.BDCODUNIMED <> :wCodUnimedPadrao; /*Se j? alterou, n?o vai alterar denovo*/

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDALTCODUNIMED = :wCodUnimedPadrao, P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0))
      AND P.BDALTCODUNIMED <> :wCodUnimedPadrao;
    END

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TUNIDADEMEDIDA_TEMP'
  INTO :wSessaoUniMed;

  /*49 - C?digo de unidade de medida n?o cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 49 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TUNIDADEMEDIDA U ON(U.BDCODUNIMED = P.BDALTCODUNIMED)
  LEFT OUTER JOIN TMP_TUNIDADEMEDIDA_TEMP T ON(T.BDEDITCHAVE = P.BDALTCODUNIMED AND T.BDSESSAO = :wSessaoUniMed)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDALTCODUNIMED IS NOT NULL) AND (P.BDALTCODUNIMED > 0))
  AND (U.BDCODUNIMED IS NULL) AND (T.BDCODUNIMED IS NULL);

  /*77 - O campo Unidade de medida n?o pode ficar em branco caso a empresa tenha Sped!*/
  IF (:wIsIndustria = 'TRUE') THEN
    BEGIN
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 77 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/  
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0));

      /*50 - C?digo de NCM n?o cadastrado*/
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/  
      AND ((P.BDNCMPROD IS NULL) OR ((P.BDNCMPROD IS NOT NULL) AND (N.BDNCMPROD IS NULL)));
    END

  /*50 - C?digo de NCM n?o cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
  WHERE P.BDSESSAO = :PRSESSAO
--  AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/
  AND P.BDNCMPROD IS NOT NULL
  AND N.BDNCMPROD IS NULL;

  /*73 - Situa??o como N?o relacionado(Est? inconsistencia n?o aparece para o usu?rio, ? somente para o controle de commit's)*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 73 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDSITUACAO IS NULL) OR (P.BDSITUACAO = 0));

  /*63 - Descri??o do produto n?o pode estar vazia*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 63 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDDESCPROD IS NULL) OR (P.BDDESCPROD = ''));

  /*62 - Apelido do produto n?o pode estar vazio*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 62 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDAPEPROD IS NULL) OR (P.BDAPEPROD = ''));

  /*118 - NCM n?o possui o c?digo de exce??o.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 118 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TCODEXTIPI EX ON(EX.BDNCMPROD = P.BDNCMPROD AND EX.BDCODTIPI = P.BDCODTIPI)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDCODTIPI IS NOT NULL) AND (P.BDCODTIPI > 0))
  AND EX.BDCODTIPI IS NULL;
END
^

/* Alter (SP_GERAR_INCON_TERCEIRO) */
ALTER PROCEDURE SP_GERAR_INCON_TERCEIRO(PRSESSAO INTEGER,
PRREF INTEGER,
PRCODEMP INTEGER)
 AS
DECLARE VARIABLE FCODPLANOINCO INTEGER;
DECLARE VARIABLE FPARTIEISE VARCHAR(5);
BEGIN
  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> 0)) THEN
    SELECT SP.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :FCODPLANOINCO;

  IF ((:FCODPLANOINCO IS NULL) OR (:FCODPLANOINCO = 0)) THEN
    SELECT INCO.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS INCO WHERE UPPER(INCO.BDPLANODEFAULT) = 'TRUE' INTO :FCODPLANOINCO;

  IF ((:FCODPLANOINCO IS NOT NULL) OR (:FCODPLANOINCO > 0)) THEN
    BEGIN
      SELECT UPPER(INCO.BDPARTIEISE) FROM VEF_BASE_TACOESINCONS INCO WHERE INCO.BDCODPLANOINCONS = :FCODPLANOINCO INTO :FPARTIEISE;
      IF (:FPARTIEISE = 'TRUE') THEN
        UPDATE TMP_TTERCEIRO_TEMP T SET T.BDIETER = 'ISENTO', T.BDIEVALIDA = 'TRUE' WHERE T.BDSESSAO = :PRSESSAO AND T.BDIEVALIDA = 'FALSE';
    END

  /*1 - Apelido vazio*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 1 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND ((TRIM(T.BDAPELIDOTER) = '') OR (T.BDAPELIDOTER IS NULL));

  /*3 - Nome vazio*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 3 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND ((TRIM(T.BDNOMETER) = '') OR (T.BDNOMETER IS NULL));

  /*4 - CPF/CNPJ vazio*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 4 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODPAIS <> 30 /*Participante do exterior n?o tem cnpj mesmo*/
  AND ((TRIM(T.BDCGCTER) = '') OR (T.BDCGCTER IS NULL));

  /******************Validar CPF e CNPJ******************/
  /*CPF*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 5 BDCODINCONSISTENCIA, BDSESSAO, BDCODTER
  FROM (
        SELECT T.BDSESSAO, T.BDCODTER, (SELECT SP.BDISVALID FROM SP_VALIDA_CPF(T.BDCGCTER) SP) BDISVALID
        FROM (
              SELECT T.BDCODTER, T.BDSESSAO, CHAR_LENGTH(T.BDCGCTER) BDTIPO, BDCGCTER
              FROM TMP_TTERCEIRO_TEMP T
              WHERE T.BDSESSAO = :PRSESSAO
              AND ((T.BDCGCTER IS NOT NULL) OR (TRIM(T.BDCGCTER) <> ''))
             ) T
        WHERE T.BDTIPO = 14
       )
  WHERE BDISVALID = 'FALSE';

  /*CNPJ*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 5 BDCODINCONSISTENCIA, BDSESSAO, BDCODTER
  FROM (
        SELECT T.BDCODTER, T.BDSESSAO, (SELECT SP.BDISVALID FROM SP_VALIDA_CNPJ(T.BDCGCTER) SP)
        FROM (
              SELECT T.BDCODTER, T.BDSESSAO, CHAR_LENGTH(T.BDCGCTER) BDTIPO, BDCGCTER
              FROM TMP_TTERCEIRO_TEMP T
              WHERE T.BDSESSAO = :PRSESSAO
              AND ((T.BDCGCTER IS NOT NULL) OR (TRIM(T.BDCGCTER) <> ''))
             ) T
        WHERE T.BDTIPO = 18
       )
  WHERE BDISVALID = 'FALSE';
  /************************************/

  /*7 - Cidade inv?lida - Valida cidades*/
--  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
--  SELECT 7 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
--  FROM TMP_TTERCEIRO_TEMP T
--  LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = T.BDCODCID)
--  WHERE T.BDSESSAO = :PRSESSAO
--  AND C.BDCODCID IS NULL
--  AND ((T.BDCODCID IS NOT NULL) AND (T.BDCODCID > 0));

  /*7 - Cidade inv?lida - Valida participantes sem cidade*/
--  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
--  SELECT 7 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
--  FROM TMP_TTERCEIRO_TEMP T
--  WHERE T.BDSESSAO = :PRSESSAO
--  AND ((T.BDCODCID IS NULL) OR (T.BDCODCID = 0));

  /*8 - Inscri??o Estadual vazia*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 8 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER  
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND TRIM(T.BDIETER) = '';

  /*9 - Inscri??o estadual inv?lida*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 9 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND TRIM(T.BDIEVALIDA) = 'FALSE';

  /*119 - Pa?s n?o existente ou inv?lido.*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 119 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  JOIN TPAIS P ON(P.BDCODPAIS = T.BDCODPAIS)
  WHERE T.BDSESSAO = :PRSESSAO
  AND (P.BDCODPAIS IS NULL);
END
^

/* Alter (SP_GERAR_PARCELAS_AUT) */
ALTER PROCEDURE SP_GERAR_PARCELAS_AUT(PRSESSAO INTEGER,
PRTIPOMOV VARCHAR(3),
PRCODEMP INTEGER,
PRREF INTEGER)
 AS
DECLARE VARIABLE WCODIGOPLA INTEGER;
DECLARE VARIABLE WQTDPARCELA INTEGER;
DECLARE VARIABLE WBDRETPARPIS DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARCOFINS DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARCSLL DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARIRRF DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARISSQN DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARINSS DM_BOOLEAN;
DECLARE VARIABLE WMANTERPARCELAS DM_BOOLEAN;
DECLARE VARIABLE WSQL VARCHAR(1200);
DECLARE VARIABLE WTABLEMOV VARCHAR(40);
DECLARE VARIABLE WTABLEITENS VARCHAR(40);
DECLARE VARIABLE WTABLERET VARCHAR(40);
DECLARE VARIABLE WTABLEPAR VARCHAR(40);
DECLARE VARIABLE WINTERVALO INTEGER;
DECLARE VARIABLE WORDEMPAR INTEGER;
DECLARE VARIABLE WNUMDIASPAR INTEGER;
BEGIN
  /*
    Sol: 14207 Patrick T. S? 26/10/2016. Criado parcelamento autom?tico com hugefilefortpintegracao com sess?o.
    Tabela TMP_TPARCELAMENTO_TEMP cont?m os valores que ir?o ser parcelados.
    Tabela TMP_TPARCELAS_TEMP cont?m as parcelas geradas, antes de dar commit na tabela real.
    Esta sp deve ser usada para entradas, sa?das e servi?os.
  */

  DELETE FROM TMP_TPARCELAMENTO_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_TPARCELAS_TEMP WHERE BDSESSAO = :PRSESSAO;

  SELECT SP.BDCODIGOPLA, SP.BDRETPARPIS, SP.BDRETPARCOFINS, SP.BDRETPARCSLL,
         SP.BDRETPARIRRF, SP.BDRETPARISSQN, SP.BDRETPARINSS, SP.BDMANTERPARCELAS
  FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP
  INTO :wCodigoPla, :wBDRETPARPIS, :wBDRETPARCOFINS, :wBDRETPARCSLL,
       :wBDRETPARIRRF, :wBDRETPARISSQN, :wBDRETPARINSS, :wManterParcelas;

  SELECT P.BDNUMPARPLA, P.BDNUMDIASPLA FROM TPLANO_PAGAMENTO P WHERE P.BDCODIGOPLA = :wCodigoPla INTO :wQtdParcela, :wNumDiasPar;

  IF (:PRTIPOMOV = 'ENT') THEN
    BEGIN
      wTableMov   = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItens = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTablePar   = 'TMP_VEF_EMP_TMOVENTPAR_TEMP';
    END
  ELSE
  IF (:PRTIPOMOV = 'SAI') THEN
    BEGIN
      wTableMov   = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItens = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      wTablePar   = 'TMP_VEF_EMP_TMOVSAIPAR_TEMP';
    END
  ELSE
  IF (:PRTIPOMOV = 'SER') THEN
    BEGIN
      wTableMov   = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItens = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      wTablePar   = 'TMP_VEF_EMP_TMOVSERPAR_TEMP';
    END

  /*Insere na tabela de parcelamento o valor total da nota com reten??es somadas, e insere todas as reten??es individuais*/
  wSQL =         'INSERT INTO TMP_TPARCELAMENTO_TEMP(BDSESSAO, BDCODEMP, BDCHAVE, BDDUPLICATAPAR, BDDATAVENCTOPAR, BDVLRCONTAB, BDVLRBRUTO, BDVLRPIS, BDVLRCOFINS, BDVLRCSOCIAL, BDVLRIR, BDVLRISS, BDVLRINSS) ';
  wSQL = wSQL || 'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, M.BDNUMDOCINI, ';

  IF (:PRTIPOMOV = 'ENT') THEN
    wSQL = wSQL ||        'M.BDDATAENTRADAENT, ';
  ELSE
    wSQL = wSQL ||        'M.BDDATAEMISSAO, ';

  wSQL = wSQL ||        'SUM(COALESCE(I.BDVLRCONTAB, 0)) BDVLRCONTAB, ';
  wSQL = wSQL ||        'SUM(COALESCE(I.BDVLRCONTAB, 0)) BDVLRBRUTO, ';
  wSQL = wSQL ||        'SUM(COALESCE(R.BDVLRPIS, 0)) BDVLRPIS, ';
  wSQL = wSQL ||        'SUM(COALESCE(R.BDVLRCOFINS, 0)) BDVLRCOFINS, ';
  wSQL = wSQL ||        'SUM(COALESCE(R.BDVLRCSOCIAL, 0)) BDVLRCSOCIAL, ';
  wSQL = wSQL ||        'SUM(COALESCE(R.BDVLRIR, 0)) BDVLRIR, ';
  wSQL = wSQL ||        'SUM(COALESCE(R.BDISSRET, 0)) BDISSRET, ';
  wSQL = wSQL ||        'SUM(COALESCE(R.BDINSSRET, 0)) BDINSSRET ';
  wSQL = wSQL || 'FROM '||:wTableItens||' I ';
  wSQL = wSQL || 'LEFT OUTER JOIN '||:wTableMov||' M ON(M.BDSESSAO = I.BDSESSAO AND M.BDCODEMP = I.BDCODEMP AND M.BDCHAVE = I.BDCHAVE) ';
  wSQL = wSQL || 'LEFT OUTER JOIN '||:wTableRet||' R ON(R.BDSESSAO = I.BDSESSAO AND R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE) ';
  wSQL = wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';

  IF (:wManterParcelas = 'TRUE') THEN
    BEGIN
      wSQL = wSQL || 'AND NOT EXISTS (SELECT P.BDORDEMPAR FROM '||:wTablePar||' P ';
      wSQL = wSQL ||                 'WHERE P.BDSESSAO = I.BDSESSAO ';
      wSQL = wSQL ||                 'AND P.BDCODEMP = I.BDCODEMP ';
      wSQL = wSQL ||                 'AND P.BDCHAVE = I.BDCHAVE) ';
    END

  IF (:PRTIPOMOV = 'ENT') THEN
    wSQL = wSQL || 'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, M.BDNUMDOCINI, M.BDDATAENTRADAENT;';
  ELSE
    wSQL = wSQL || 'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, M.BDNUMDOCINI, M.BDDATAEMISSAO;';

  EXECUTE STATEMENT :wSQL;

  /*Faz update somente das dedu??es que s?o marcadas no cadastro da empresa*/
  IF (:wBDRETPARPIS = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRPIS) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARCOFINS = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRCOFINS) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARCSLL = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRCSOCIAL) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARIRRF = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRIR) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARISSQN = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRISS) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARINSS = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRINSS) WHERE P.BDSESSAO = :PRSESSAO;

  /*Se tiver intervalo no plano de parcelas, vai inserir os intervalos nessa tabela tempor?ria*/
  INSERT INTO TMP_TINTERVALO_PARC(BDCODIGOPLA, BDORDEM, BDINTERVALO)
  SELECT I.BDCODIGOPLA, I.BDORDEM, I.BDINTERVALODIAS
  FROM TPLANO_PAGAMENTO_INTDIAS I
  WHERE I.BDCODIGOPLA = :wCodigoPla;

  /*Se entrar nesse if ? porque n?o havia intervalo de dias no plano, ent?o vai gerar as parcelas. EX: numDeParcelas = 4, numDias = 30. Vai gerar 1 - 30, 2 - 30, 3 - 30, 4 - 40*/
  IF (ROW_COUNT = 0) THEN
    BEGIN
      wOrdemPar = 1;
      WHILE (:wOrdemPar <= :wQtdParcela) DO
        BEGIN
          INSERT INTO TMP_TINTERVALO_PARC(BDCODIGOPLA, BDORDEM, BDINTERVALO) VALUES(:wCodigoPla, :wOrdemPar, :wNumDiasPar);
          wOrdemPar = :wOrdemPar + 1;
        END
    END

  /*Gera as parcelas, sem datas, apenas com valor*/
  INSERT INTO TMP_TPARCELAS_TEMP(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMPAR, BDDATAVENCTOPAR, BDDUPLICATAPAR, BDVALOR, BDVALORBRUTO, BDVALORTOTAL, BDVALORRETPIS,
                                 BDVALORRETCOFINS, BDVALORRETCSLL, BDVALORRETIRRF, BDVALORRETISSQN, BDVALORRETINSS)
  SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, I.BDORDEM, P.BDDATAVENCTOPAR, P.BDDUPLICATAPAR,
         CAST(P.BDVLRCONTAB / :wQtdParcela AS NUMERIC(15, 2)) BDVALOR, /*Valor arredondado*/
         CAST(P.BDVLRBRUTO / :wQtdParcela AS NUMERIC(15, 2)) BDVALORBRUTO, /*Valor bruto*/
         COALESCE(P.BDVLRCONTAB, 0), /*Valor cont?bil da nota*/
         COALESCE(P.BDVLRPIS, 0),
         COALESCE(P.BDVLRCOFINS, 0),
         COALESCE(P.BDVLRCSOCIAL, 0),
         COALESCE(P.BDVLRIR, 0),
         COALESCE(P.BDVLRISS, 0),
         COALESCE(P.BDVLRINSS, 0)
  FROM TMP_TPARCELAMENTO_TEMP P
  LEFT OUTER JOIN TMP_TINTERVALO_PARC I ON(I.BDCODIGOPLA = :wCodigoPla)
  WHERE P.BDSESSAO = :PRSESSAO;

  /*Colocar o resto na primeira parcela*/
  UPDATE TMP_TPARCELAS_TEMP P
  SET BDVALOR = (
                 SELECT FIRST 1 CAST(P.BDVALOR + (PARC.BDVLRCONTAB - (P.BDVALOR * :wQtdParcela)) AS NUMERIC(15, 2)) BDVALOR
                 FROM TMP_TPARCELAMENTO_TEMP PARC
                 WHERE PARC.BDSESSAO = P.BDSESSAO
                 AND PARC.BDCODEMP = P.BDCODEMP
                 AND PARC.BDCHAVE = P.BDCHAVE
                ),
      BDVALORBRUTO = (
                      SELECT FIRST 1 CAST(P.BDVALORBRUTO + (PARC.BDVLRBRUTO - (P.BDVALORBRUTO * :wQtdParcela)) AS NUMERIC(15, 2)) BDVALORBRUTO
                      FROM TMP_TPARCELAMENTO_TEMP PARC
                      WHERE PARC.BDSESSAO = P.BDSESSAO
                      AND PARC.BDCODEMP = P.BDCODEMP
                      AND PARC.BDCHAVE = P.BDCHAVE
                     )
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDORDEMPAR = 1;

  /*Colocando a data de vencimento da parcela*/
  wOrdemPar = NULL;
  FOR SELECT D.BDORDEM, D.BDINTERVALO
      FROM TMP_TINTERVALO_PARC D
      WHERE d.bdcodigopla = :wCodigoPla
      ORDER BY D.BDORDEM
      INTO :wOrdemPar, :wIntervalo
  DO
    BEGIN
      IF (:wOrdemPar > 1) THEN
        BEGIN
          UPDATE TMP_TPARCELAS_TEMP P SET P.BDDATAVENCTOPAR = (
                                                               SELECT FIRST 1 PD.BDDATAVENCTOPAR
                                                               FROM TMP_TPARCELAS_TEMP PD
                                                               WHERE PD.BDSESSAO = P.BDSESSAO
                                                               AND PD.BDCODEMP   = P.BDCODEMP
                                                               AND PD.BDCHAVE    = P.BDCHAVE
                                                               AND PD.BDORDEMPAR = (:wOrdemPar-1)
                                                              )
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDORDEMPAR = :wOrdemPar;
        END

      UPDATE TMP_TPARCELAS_TEMP P SET P.BDDATAVENCTOPAR = DATEADD(:wIntervalo DAY TO P.BDDATAVENCTOPAR)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDORDEMPAR = :wOrdemPar;
    END

  DELETE FROM TMP_TINTERVALO_PARC WHERE BDCODIGOPLA > 0;

  /*Colocar reten??es nas parcelas(PIS, Cofins, CSLL, IRRF, ISSQN, INSS)*/
  /*PIS*/
  IF (:wBDRETPARPIS = 'TRUE') THEN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETPIS = CAST(((P.BDVALORRETPIS * ((P.BDVALORBRUTO / P.BDVALORTOTAL) * 100)) / 100) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETPIS > 0;

  /*COFINS*/
  IF (:wBDRETPARCOFINS = 'TRUE') THEN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETCOFINS = CAST(((P.BDVALORRETCOFINS * ((P.BDVALORBRUTO / P.BDVALORTOTAL) * 100)) / 100) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETCOFINS > 0;

   /*CSLL*/
  IF (:wBDRETPARCSLL = 'TRUE') THEN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETCSLL = CAST(((P.BDVALORRETCSLL * ((P.BDVALORBRUTO / P.BDVALORTOTAL) * 100)) / 100) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETCSLL > 0;

  /*IRRF*/
  IF (:wBDRETPARIRRF = 'TRUE') THEN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETIRRF = CAST(((P.BDVALORRETIRRF * ((P.BDVALORBRUTO / P.BDVALORTOTAL) * 100)) / 100) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETIRRF > 0;

  /*ISSQN*/
  IF (:wBDRETPARISSQN = 'TRUE') THEN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETISSQN = CAST(((P.BDVALORRETISSQN * ((P.BDVALORBRUTO / P.BDVALORTOTAL) * 100)) / 100) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETISSQN > 0;

  /*INSS*/
  IF (:wBDRETPARINSS = 'TRUE') THEN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETINSS = CAST(((P.BDVALORRETINSS * ((P.BDVALORBRUTO / P.BDVALORTOTAL) * 100)) / 100) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETINSS > 0;

  /*Insere na tabela temporaria do parcelamento*/
  wSQL =         'INSERT INTO '||:wTablePar||'(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMPAR, BDCODIGOPLA, BDPARCELAPAR, BDDUPLICATAPAR, ';
  wSQL = wSQL ||                              'BDVALORPAR, BDDATAVENCTOPAR, BDVALORRETPIS, BDVALORRETCOFINS, BDVALORRETCSLL, ';
  wSQL = wSQL ||                              'BDVALORRETIRRF, BDVALORRETISSQN, BDVALORRETINSS, BDVALORBRUTO, BDNRDOC) ';
  wSQL = wSQL || 'SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, '||:wCodigoPla||' BDCODIGOPLA, P.BDORDEMPAR, P.BDDUPLICATAPAR, ';
  wSQL = wSQL ||        'P.BDVALOR, P.BDDATAVENCTOPAR, P.BDVALORRETPIS, P.BDVALORRETCOFINS, P.BDVALORRETCSLL, P.BDVALORRETIRRF, ';
  wSQL = wSQL ||        'P.BDVALORRETISSQN, P.BDVALORRETINSS, P.BDVALORBRUTO, P.BDDUPLICATAPAR ';
  wSQL = wSQL || 'FROM TMP_TPARCELAS_TEMP P ';
  wSQL = wSQL || 'WHERE P.BDSESSAO = '||:PRSESSAO;
  EXECUTE STATEMENT :wSQL;
END
^

/* empty dependent procedure body */
/* Clear: SP_INSERT_OR_UPDATE_TCADPRO for: SP_GET_ACOES_INCONSISTENCIA */
ALTER PROCEDURE SP_INSERT_OR_UPDATE_TCADPRO(PRSESSAO INTEGER,
PRREF INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_GET_ACOES_INCONSISTENCIA) */
ALTER PROCEDURE SP_GET_ACOES_INCONSISTENCIA(PRCODEMP INTEGER,
PRREF INTEGER)
 RETURNS(BDCODPLANOINCONS INTEGER,
BDNCMPROD INTEGER,
BDSAICFOPNCAD INTEGER,
BDENTCFOPCANC INTEGER,
BDCODUNIMED INTEGER,
BDENTCFOPNCAD INTEGER,
BDSAICFOPCANC INTEGER,
BDDESCRICAO VARCHAR(100),
BDPLANODEFAULT DM_BOOLEAN,
BDATUPROD DM_BOOLEAN,
BDATUPART DM_BOOLEAN,
BDATUUNIDMED DM_BOOLEAN,
BDATUINFCOM DM_BOOLEAN,
BDATUOBS DM_BOOLEAN,
BDATUMAQREDZ DM_BOOLEAN,
BDATUBICO DM_BOOLEAN,
BDATUBOMBA DM_BOOLEAN,
BDATUTANQUE DM_BOOLEAN,
BDATUFATCONV DM_BOOLEAN,
BDPARTIEISE DM_BOOLEAN,
BDCADPROAUTO DM_BOOLEAN,
BDENTAJUCFOP DM_BOOLEAN,
BDENTIMPIPIDIF DM_BOOLEAN,
BDENTIMPICMSDIF DM_BOOLEAN,
BDSAIAJUCFOP DM_BOOLEAN,
BDSAIIMPIPIDIF DM_BOOLEAN,
BDSAIIMPICMSDIF DM_BOOLEAN,
BDSERAJUCFOP DM_BOOLEAN,
BDSERIMPISSDIF DM_BOOLEAN,
BDPARTBUSCASITE DM_BOOLEAN,
BDPRODNCMVAZIO DM_BOOLEAN,
BDREDZCODTER INTEGER)
 AS
DECLARE VARIABLE WCODPLANOINCO INTEGER;
BEGIN
  wCodPlanoInco = NULL;

  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP > 0)) THEN
    SELECT SP.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :wCodPlanoInco;

  IF ((:wCodPlanoInco IS NULL) OR (:wCodPlanoInco = 0)) THEN
    SELECT A.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS A WHERE UPPER(A.BDPLANODEFAULT) = 'TRUE' INTO :wCodPlanoInco;


  IF (((:wCodPlanoInco IS NOT NULL) OR (:wCodPlanoInco > 0))) THEN
    SELECT A.BDCODPLANOINCONS,
           A.BDNCMPROD,
           A.BDSAICFOPNCAD,
           A.BDENTCFOPCANC,
           A.BDCODUNIMED,
           A.BDENTCFOPNCAD,
           A.BDSAICFOPCANC,
           UPPER(A.BDDESCRICAO),
           UPPER(A.BDPLANODEFAULT),
           UPPER(A.BDATUPROD),
           UPPER(A.BDATUPART),
           UPPER(A.BDATUUNIDMED),
           UPPER(A.BDATUINFCOM),
           UPPER(A.BDATUOBS),
           UPPER(A.BDATUMAQREDZ),
           UPPER(A.BDATUBICO),
           UPPER(A.BDATUBOMBA),
           UPPER(A.BDATUTANQUE),
           UPPER(A.BDATUFATCONV),
           UPPER(A.BDPARTIEISE),
           UPPER(A.BDCADPROAUTO),
           UPPER(A.BDENTAJUCFOP),
           UPPER(A.BDENTIMPIPIDIF),
           UPPER(A.BDENTIMPICMSDIF),
           UPPER(A.BDSAIAJUCFOP),
           UPPER(A.BDSAIIMPIPIDIF),
           UPPER(A.BDSAIIMPICMSDIF),
           UPPER(A.BDSERAJUCFOP),
           UPPER(A.BDSERIMPISSDIF),
           UPPER(A.BDPARTBUSCASITE),
           UPPER(A.BDPRODNCMVAZIO),
           A.BDREDZCODTER
    FROM VEF_BASE_TACOESINCONS A
    WHERE A.BDCODPLANOINCONS = :wCodPlanoInco
    INTO :BDCODPLANOINCONS,
         :BDNCMPROD,
         :BDSAICFOPNCAD,
         :BDENTCFOPCANC,
         :BDCODUNIMED,
         :BDENTCFOPNCAD,
         :BDSAICFOPCANC,
         :BDDESCRICAO,
         :BDPLANODEFAULT,
         :BDATUPROD,
         :BDATUPART,
         :BDATUUNIDMED,
         :BDATUINFCOM,
         :BDATUOBS,
         :BDATUMAQREDZ,
         :BDATUBICO,
         :BDATUBOMBA,
         :BDATUTANQUE,
         :BDATUFATCONV,
         :BDPARTIEISE,
         :BDCADPROAUTO,
         :BDENTAJUCFOP,
         :BDENTIMPIPIDIF,
         :BDENTIMPICMSDIF,
         :BDSAIAJUCFOP,
         :BDSAIIMPIPIDIF,
         :BDSAIIMPICMSDIF,
         :BDSERAJUCFOP,
         :BDSERIMPISSDIF,
         :BDPARTBUSCASITE,
         :BDPRODNCMVAZIO,
         :BDREDZCODTER;
  ELSE
    BEGIN
      BDCODPLANOINCONS = 0;
      BDNCMPROD        = 0;
      BDSAICFOPNCAD    = 0;
      BDENTCFOPCANC    = 0;
      BDCODUNIMED      = 0;
      BDENTCFOPNCAD    = 0;
      BDSAICFOPCANC    = 0;
      BDDESCRICAO      = '';
      BDPLANODEFAULT   = 'FALSE';
      BDATUPROD        = 'FALSE';
      BDATUPART        = 'FALSE';
      BDATUUNIDMED     = 'FALSE';
      BDATUINFCOM      = 'FALSE';
      BDATUOBS         = 'FALSE';
      BDATUMAQREDZ     = 'FALSE';
      BDATUBICO        = 'FALSE';
      BDATUBOMBA       = 'FALSE';
      BDATUTANQUE      = 'FALSE';
      BDATUFATCONV     = 'FALSE';
      BDPARTIEISE      = 'FALSE';
      BDCADPROAUTO     = 'FALSE';
      BDENTAJUCFOP     = 'FALSE';
      BDENTIMPIPIDIF   = 'FALSE';
      BDENTIMPICMSDIF  = 'FALSE';
      BDSAIAJUCFOP     = 'FALSE';
      BDSAIIMPIPIDIF   = 'FALSE';
      BDSAIIMPICMSDIF  = 'FALSE';
      BDSERAJUCFOP     = 'FALSE';
      BDSERIMPISSDIF   = 'FALSE';
      BDPARTBUSCASITE  = 'FALSE';
      BDPRODNCMVAZIO   = 'FALSE';
      BDREDZCODTER     = 0;
    END

  SUSPEND;
END
^

/* Alter (SP_GET_PRODUTO_IMP) */
ALTER PROCEDURE SP_GET_PRODUTO_IMP(PRCODEMP INTEGER,
PRSESSAO INTEGER,
PRSESSAOTER INTEGER,
PRCODPRODARQ VARCHAR(60),
PRCNPJTER VARCHAR(18),
PRDESCPROD VARCHAR(200),
PRNOMETER VARCHAR(100),
PRVER_ENT_E_SAI VARCHAR(5),
PRCODTER INTEGER,
PRCODPRODVINC INTEGER)
 RETURNS(BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200))
 AS
BEGIN
  BDCODPROD = NULL;
  PRVER_ENT_E_SAI = UPPER(:PRVER_ENT_E_SAI);

  IF ((:PRCODPRODARQ IS NOT NULL) OR (:PRCODPRODARQ <> '')) THEN
    BEGIN
      /*1? tentativa - busca por participante */
      IF ((:PRCNPJTER <> '') AND (:PRCNPJTER <> '#')) THEN
        BEGIN
          IF (TRIM(:PRDESCPROD) <> '') THEN
            BEGIN
              SELECT FIRST 1 PRO.BDCODPROD, PRO.BDDESCPRODBUSCA
              FROM (
                    SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                    FROM (
                          SELECT FIRST 1 P.BDCODPROD, P.BDDESCPRODBUSCA
                          FROM (
                                SELECT PP.BDEDITCHAVE BDCODPROD, PP.BDCODTER, PP.BDCODENTRADA, TRIM(PP.BDDESCPRODBUSCA) BDDESCPRODBUSCA, PP.BDCODEMP
                                FROM TMP_TCADPRO_PART pp
                                WHERE pp.BDCODENTRADA = :PRCODPRODARQ
                                AND ((pp.BDCODEMP = :PRCODEMP) OR (pp.BDCODEMP IS NULL))
                                AND UPPER(pp.bddescprodbusca) = UPPER(:PRDESCPROD)
                               ) P
            --            JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDCGCTER = :PRCNPJTER)
                          JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDCGCTER = :PRCNPJTER AND T.BDEDITCHAVE = P.BDCODTER)
                          JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = P.BDCODPROD)
                          ORDER BY P.BDCODEMP DESC
                         ) P
                    UNION ALL
                    SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                    FROM (
                          SELECT FIRST 1 P.BDCODPROD, P.BDDESCPRODBUSCA
                          FROM (
                                SELECT PP.BDEDITCHAVE BDCODPROD, PP.BDCODTER, PP.BDCODENTRADA, TRIM(PP.BDDESCPRODBUSCA) BDDESCPRODBUSCA, PP.BDCODEMP
                                FROM TMP_TCADPRO_PART pp
                                WHERE pp.BDCODENTRADA = :PRCODPRODARQ
                                AND UPPER(pp.bddescprodbusca) = UPPER(:PRDESCPROD)
                               ) P
            --            JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDCGCTER = :PRCNPJTER)
                          JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDCGCTER = :PRCNPJTER AND T.BDEDITCHAVE = P.BDCODTER)
                          JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = P.BDCODPROD)
                         ) P
                   ) PRO
              INTO :BDCODPROD, :BDDESCPROD;
            END
          ELSE
            BEGIN
              /*Se n?o tem descri??o pega o primeiro produto*/
              SELECT FIRST 1 PRO.BDCODPROD, PRO.BDDESCPRODBUSCA
              FROM (
                    SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                    FROM (
                          SELECT FIRST 1 PP.BDEDITCHAVE BDCODPROD, PP.BDDESCPRODBUSCA
                          FROM TMP_TCADPRO_PART pp
                          JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDCGCTER = :PRCNPJTER AND T.BDEDITCHAVE = PP.BDCODTER)
                          JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = PP.BDCODPROD)
                          WHERE pp.bdcodentrada = :PRCODPRODARQ
                          AND ((pp.BDCODEMP = :PRCODEMP) OR (pp.BDCODEMP IS NULL))
                          ORDER BY pp.BDCODEMP DESC
                         ) P
                    UNION ALL
                    SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                    FROM (
                          SELECT FIRST 1 PP.BDEDITCHAVE BDCODPROD, PP.BDDESCPRODBUSCA
                          FROM TMP_TCADPRO_PART pp
                          JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDCGCTER = :PRCNPJTER AND T.BDEDITCHAVE = PP.BDCODTER)
                          JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = PP.BDCODPROD)
                          WHERE pp.bdcodentrada = :PRCODPRODARQ
                         ) P
                   ) PRO
              INTO :BDCODPROD, :BDDESCPROD;
            END
        END
      ELSE
        BEGIN
          IF ((:PRNOMETER <> '') AND (:PRNOMETER <> '#') AND (COALESCE(:BDCODPROD, 0) = 0)) THEN
            BEGIN
              IF (TRIM(:PRDESCPROD) <> '') THEN
                BEGIN
                  SELECT FIRST 1 PRO.BDCODPROD, PRO.BDDESCPRODBUSCA
                  FROM (
                        SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                        FROM (
                              SELECT FIRST 1 P.BDCODPROD, P.BDDESCPRODBUSCA
                              FROM (
                                    SELECT pp.BDEDITCHAVE BDCODPROD, pp.BDCODTER, TRIM(pp.BDDESCPRODBUSCA) BDDESCPRODBUSCA, pp.BDCODEMP
                                    FROM TMP_TCADPRO_PART pp
                                    WHERE UPPER(pp.BDDESCPRODBUSCA) = UPPER(:PRDESCPROD)
                                    AND ((pp.BDCODEMP = :PRCODEMP) OR (pp.BDCODEMP IS NULL))
                                   ) P
        --                      JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND UPPER(T.BDNOMETER) = UPPER(:PRNOMETER))
                              JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND UPPER(T.BDNOMETER) = UPPER(:PRNOMETER) AND T.BDEDITCHAVE = P.BDCODTER)
                              JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = P.BDCODPROD)
                              ORDER BY P.BDCODEMP DESC
                             ) P
                        UNION ALL
                        SELECT FIRST 1 P.BDCODPROD, P.BDDESCPRODBUSCA
                        FROM (
                              SELECT pp.BDEDITCHAVE BDCODPROD, pp.BDCODTER, TRIM(pp.BDDESCPRODBUSCA) BDDESCPRODBUSCA, pp.BDCODEMP
                              FROM TMP_TCADPRO_PART pp
                              WHERE UPPER(pp.BDDESCPRODBUSCA) = UPPER(:PRDESCPROD)
                             ) P
    --                    JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND UPPER(T.BDNOMETER) = UPPER(:PRNOMETER))
                        JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND UPPER(T.BDNOMETER) = UPPER(:PRNOMETER) AND T.BDEDITCHAVE = P.BDCODTER)
                        JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = P.BDCODPROD)
                       ) PRO
                  INTO :BDCODPROD, :BDDESCPROD;
                END
              ELSE
                BEGIN
                  SELECT FIRST 1 PRO.BDCODPROD, PRO.BDDESCPRODBUSCA
                  FROM (
                        SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                        FROM (
                              SELECT FIRST 1 pp.BDEDITCHAVE BDCODPROD, pp.BDDESCPRODBUSCA
                              FROM TMP_TCADPRO_PART pp
                              JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDNOMETER = :PRNOMETER AND T.BDEDITCHAVE = PP.BDCODTER)
                              JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = PP.BDCODPROD)
                              AND ((pp.BDCODEMP = :PRCODEMP) OR (pp.BDCODEMP IS NULL))
                              ORDER BY pp.BDCODEMP DESC
                             ) P
                        UNION ALL
                        SELECT FIRST 1 pp.BDEDITCHAVE BDCODPROD, pp.BDDESCPRODBUSCA
                        FROM TMP_TCADPRO_PART pp
                        JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDNOMETER = :PRNOMETER AND T.BDEDITCHAVE = PP.BDCODTER)
                        JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = PP.BDCODPROD)
                       ) PRO
                  INTO :BDCODPROD, :BDDESCPROD;
                END
            END
        END
        /*Essa valida??o n?o vai mais ser feita nesse novo tipo de importa??o por que na memoria s? tem o c?digo sequencial do terceiro*/
          /*begin
            prDAOProdPart.SearchKey(['bdCODTER','bdCODENTRADA'],[prCodTer,prCodProdArq]);
            while not prDAOProdPart.Eof do
              begin
                if (prDAOProdPart.FN('bdCODTER').AsInteger <> prCodTer) or (AnsiUpperCase(prDAOProdPart.FN('BDCODENTRADA').AsString) <> AnsiUpperCase(prCodProdArq)) then
                  break;

                if prDescProdArqLay = '' then
                  begin
                    wOK := True;
                    break;
                  end;

                if (AnsiUpperCase(prDAOProdPart.FN('BDDESCPROD').AsString) = AnsiUpperCase(prDescProdArqLay)) or
                   (AnsiUpperCase(prDAOProdPart.FN('BDDESCPRODBUSCA').AsString) = AnsiUpperCase(prDescProdArqLay)) then
                  begin
                    wOK := True;
                    break;
                  end;

                prDAOProdPart.Next;
              end;
          end;*/

--      IF (:BDCODPROD > 0) THEN
      IF ((:BDCODPROD > 0) AND ((:BDDESCPROD IS NULL) OR (:BDDESCPROD = ''))) THEN
        BEGIN
          SELECT FIRST 1 CT.BDDESCPROD
          FROM TMP_TCADPRO_TEMP CT
          WHERE CT.BDSESSAO = :PRSESSAO
          AND CT.BDCODEMP = :PRCODEMP
          AND CT.BDEDITCHAVE = :BDCODPROD
          INTO :BDDESCPROD;
        END
      /*ELSE
        BEGIN
          if (Assigned(prDAOProdPart.InstanceFactory.FindField('bdCODPRODVINC'))) and (prDAOProdPart.FN('bdCODPRODVINC').AsInteger > 0) and
                      (prDAOProdVinc.SearchKeyPos(['bdCODEMP','bdCODPRODVINC'],[prCodEmp,prDAOProdPart.FN('bdCODPRODVINC').AsInteger])) then
            begin
              prFieldDesc := prDAOProdVinc.FN('BDDESCPROD').AsString;
              wAchou      := True;
            end;
        END*/

      IF (((:BDCODPROD IS NULL) OR (:BDCODPROD = 0)) AND (UPPER(:PRVER_ENT_E_SAI) = 'TRUE')) THEN
        BEGIN
          SELECT FIRST 1 P.BDEDITCHAVE BDCODPROD, P.BDDESCPROD
          FROM TMP_TCADPRO/*_TEMP*/ P
          WHERE P.BDCODSAIDA = :PRCODPRODARQ
          AND P.BDcodemp = :PRCODEMP
          INTO :BDCODPROD, :BDDESCPROD;
        END

      IF (((:BDCODPROD IS NULL) OR (:BDCODPROD = 0)) AND (COALESCE(:PRCODPRODVINC, 0) > 0)) THEN
        BEGIN
          SELECT CT.BDEDITCHAVE BDCODPROD, CT.BDDESCPROD
          FROM TMP_TCADPRO_TEMP CT
          WHERE CT.BDSESSAO = :PRSESSAO
          AND CT.BDCODEMP = :PRCODEMP
          AND CT.BDCODPRODVINC = :PRCODPRODVINC
          INTO :BDCODPROD, :BDDESCPROD;
        END

      IF ((:BDCODPROD IS NULL) OR (:BDCODPROD = 0)) THEN
        SELECT FIRST 1 P.bdCODPROD, P.BDDESCPRODBUSCA FROM TCADPRO_PART P WHERE P.bdcodter = :PRCODTER AND P.bdCODENTRADA = :PRCODPRODARQ INTO :BDCODPROD, :BDDESCPROD;

      /*Sol: 14207 Patrick T. S? 07/03/2017. Busca pela descri??o do produto na empresa feita para uma situa??o que faz errado na vers?o do site.
        Para teste usar a nota de entrada que est? em "computador do elizeu\Repositorio\iguacu teste\unica\1" */
      IF (((:BDCODPROD IS NULL) OR (:BDCODPROD = 0)) AND (:PRDESCPROD <> '')) THEN
        SELECT FIRST 1 P.BDEDITCHAVE, P.BDDESCPROD FROM TMP_TCADPRO P WHERE P.BDCODEMP = :PRCODEMP AND P.BDDESCPROD = :PRDESCPROD INTO :BDCODPROD, :BDDESCPROD;
    END

    SUSPEND;
END
^

/* Alter (SP_GRAVA_AJUSTE_E115) */
ALTER PROCEDURE SP_GRAVA_AJUSTE_E115(PRSESSAO INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAE115 INTEGER;
BEGIN
   -- Grava lan?amentos no ajustes E115
   INSERT INTO VEF_EMP_TAJUICMSE115 (BDCODEMP, BDORDEME115, BDREFERENCIA, BDVLRINFADI, BDDESCINFADI, BDCODTIPO, BDORDEM52)
   SELECT t.BDCODEMP, t.BDEDITCHAVE, t.BDREFERENCIA, t.BDVLRINFADI, t.BDDESCINFADI, t.BDCODTIPO, t.BDORDEM52
   FROM TMP_VEF_EMP_TAJUICMSE115_TEMP t
   JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP i ON (i.BDCODEMP = t.BDCODEMP AND i.BDCHAVE = t.BDCHAVESAI AND i.BDORDEM = t.BDORDEM AND i.BDSESSAO = t.BDSESSAO)
   LEFT OUTER JOIN VEF_INCON_TMOVSAI inc ON (inc.BDCODEMP = i.BDCODEMP AND inc.BDCHAVE = i.BDCHAVE AND inc.BDSESSAO = i.BDSESSAO)
   WHERE t.BDSESSAO = :prSESSAO
     AND inc.BDCODINCONSISTENCIA IS NULL -- Apenas lan?amentos n?o inconsistentes...
   ORDER BY i.BDCODEMP, i.BDCHAVE, i.BDORDEM;

   -- Cria lan?amento da Tol...
   INSERT INTO TOL_VEF_EMP_TMOVSAIE115 (BDORDEME115, BDCODEMP, BDCHAVE, BDORDEM)
   SELECT t.BDEDITCHAVE, i.BDCODEMP, i.BDEDITCHAVE, i.BDORDEM
   FROM TMP_VEF_EMP_TAJUICMSE115_TEMP t
   JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP i ON (i.BDCODEMP = t.BDCODEMP AND i.BDCHAVE = t.BDCHAVESAI AND i.BDORDEM = t.BDORDEM AND i.BDSESSAO = t.BDSESSAO)
   LEFT OUTER JOIN VEF_INCON_TMOVSAI inc ON (inc.BDCODEMP = i.BDCODEMP AND inc.BDCHAVE = i.BDCHAVE AND inc.BDSESSAO = i.BDSESSAO)
   WHERE t.BDSESSAO = :prSESSAO
     AND inc.BDCODINCONSISTENCIA IS NULL -- Apenas lan?amentos n?o inconsistentes...
   ORDER BY i.BDCODEMP, i.BDCHAVE, i.BDORDEM;
END
^

/* Alter (SP_IMPORTACAO_SEM_PART) */
ALTER PROCEDURE SP_IMPORTACAO_SEM_PART(PRSESSAO INTEGER,
PRCODPARTDEFAULT INTEGER)
 AS
BEGIN
  /*sp executada quando o usu?rio quer importar s? os lan?amentos, o participante j? deve ter sido importado,
    sen?o ir? ficar com inconsistencia no lan?amento*/

  PRCODPARTDEFAULT = COALESCE(:PRCODPARTDEFAULT, 0);

  /*Atualiza o c?digo do participante*/
  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP S
  SET S.BDCODTER = COALESCE((SELECT FIRST 1 T.BDCODTER FROM VW_TTERCEIRO T WHERE T.BDCGCTER = S.BDCNPJ), :PRCODPARTDEFAULT)
  WHERE S.BDSESSAO = :PRSESSAO;

  /*Atualiza o nome do participante*/
  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP S
  SET S.BDNOMETER = (
                     SELECT FIRST 1 T.BDNOMETER FROM VW_TTERCEIRO T
                     WHERE T.BDCODTER = S.BDCODTER
                    ),
      S.BDALTCODTER = S.BDCODTER,
      S.BDSIGLAUFTER = (
                        SELECT FIRST 1 UF.BDSIGLAUF FROM VW_TTERCEIRO_SIMPLES T
                        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = T.BDCODCID)
                        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
                        WHERE T.BDCODTER = S.BDCODTER
                       )
  WHERE S.BDSESSAO = :PRSESSAO;

  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP S
  SET S.BDCODCID = (
                    SELECT FIRST 1 T.BDCODCID FROM VW_TTERCEIRO_SIMPLES T
                    WHERE T.BDCODTER = S.BDCODTER
                   )
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDCODCID IS NULL;
END
^

/* Alter (SP_INS_UPT_TMP_TCADPRO) */
ALTER PROCEDURE SP_INS_UPT_TMP_TCADPRO(PRSESSAO INTEGER,
PRCODSAIDA VARCHAR(60),
PRCODENTRADA VARCHAR(60),
PRCODPROD INTEGER,
PRCODEMP INTEGER,
PRCODTER INTEGER,
PRCNPJTER VARCHAR(20),
PRDESCPROD VARCHAR(200),
PRORIGEMPROD INTEGER,
PROPERATION VARCHAR(4),
PRSEQ_PART INTEGER,
PRINS_PROUNICO DM_BOOLEAN)
 AS
DECLARE VARIABLE WORIGEMPROD INTEGER;
DECLARE VARIABLE WCODTERLAYOUT INTEGER;
DECLARE VARIABLE WCNPJTERLAYOUT VARCHAR(18);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODSAIDA VARCHAR(60) COLLATE WIN_PTBR;
DECLARE VARIABLE WAPEPROD VARCHAR(30) COLLATE WIN_PTBR;
DECLARE VARIABLE WDESCPROD VARCHAR(200) COLLATE WIN_PTBR;
DECLARE VARIABLE WAPELIDOUNICO VARCHAR(30) COLLATE WIN_PTBR;
DECLARE VARIABLE WDESCRICAOUNICA VARCHAR(200) COLLATE WIN_PTBR;
DECLARE VARIABLE WCODIGOEAN VARCHAR(20) COLLATE WIN_PTBR;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCODENTRADA VARCHAR(60) COLLATE WIN_PTBR;
DECLARE VARIABLE WCODTIPO INTEGER;
DECLARE VARIABLE WCODGEN INTEGER;
DECLARE VARIABLE WCODSER INTEGER;
DECLARE VARIABLE WCODCOMBANP INTEGER;
DECLARE VARIABLE WCODUNIMED INTEGER;
DECLARE VARIABLE WAPEUNIMED VARCHAR(5) COLLATE WIN_PTBR;
DECLARE VARIABLE WNCMPROD INTEGER;
DECLARE VARIABLE WCODTABINCID INTEGER;
DECLARE VARIABLE WGRUPO INTEGER;
DECLARE VARIABLE WORDEMMARCA INTEGER;
DECLARE VARIABLE WCODCSTIPISAI INTEGER;
DECLARE VARIABLE WCODCSTIPIENT INTEGER;
DECLARE VARIABLE WCODCSTICMS INTEGER;
DECLARE VARIABLE WCODCSTPISSAI INTEGER;
DECLARE VARIABLE WCODCSTPISENT INTEGER;
DECLARE VARIABLE WCODCSTCOFENT INTEGER;
DECLARE VARIABLE WCODCSTCOFSAI INTEGER;
BEGIN
  /*Sol: 14207 Patrick T. S? 10/10/2016. Est? sp ? usada na SP_ATUALIZAR_TMP_TCADPRO para inserir ou atualizar os produtos na importa??o.*/
  PROPERATION = UPPER(:PROPERATION);
  PRCODPROD   = COALESCE(:PRCODPROD, 0);
  PRCODSAIDA  = COALESCE(:PRCODSAIDA, '');
  PRCODENTRADA= COALESCE(:PRCODENTRADA, '');
  PRDESCPROD  = COALESCE(:PRDESCPROD, '');
  PRCNPJTER   = COALESCE(:PRCNPJTER, '');

  IF (:PROPERATION = 'INS') THEN  /*Inserir novo*/
    BEGIN
      IF (:PRORIGEMPROD = 1) THEN
        BEGIN
          /*Insere produto unico*/
          IF (:PRINS_PROUNICO = 'TRUE') THEN
            BEGIN
              INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA,
                                      BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, BDCODCOMBANP,
                                      BDCODSAIDA, BDCODENTRADA, BDDESCPROD, BDCODTERLAYOUT)
              SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA,
                              A.BDCODIGOEAN, A.BDCODTIPO, A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP,
                              A.BDCODSAIDA, A.BDCODENTRADA, A.BDDESCPROD, A.BDCODTERLAYOUT
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA;
            END

          /*Insere na empresa*/
          INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDORIGEMPROD, BDCODTERLAYOUT, BDCNPJTERLAYOUT, BDCODEMP, BDCODSAIDA, BDAPEPROD,
                                  BDDESCPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODTIPO, BDCODGEN,
                                  BDCODSER, BDCODCOMBANP, BDCODUNIMED, BDAPEUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA,
                                  BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT, BDCODCSTCOFENT, BDCODCSTCOFSAI)
          SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDORIGEMPROD, A.BDCODTERLAYOUT, A.BDCNPJTERLAYOUT, A.BDCODEMP, A.BDCODSAIDA,
                         A.BDAPEPROD, A.BDDESCPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA, A.BDCODIGOEAN, A.BDCODTER, A.BDCODENTRADA, A.BDCODTIPO,
                         A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP, A.BDCODUNIMED, A.BDAPEUNIMED, A.BDNCMPROD, A.BDCODTABINCID, A.BDGRUPO, A.BDORDEMMARCA,
                         A.BDCODCSTIPISAI, A.BDCODCSTIPIENT, A.BDCODCSTICMS, A.BDCODCSTPISSAI, A.BDCODCSTPISENT, A.BDCODCSTCOFENT, A.BDCODCSTCOFSAI
          FROM TMP_TCADPRO_A_VALIDAR A
          WHERE A.BDCODSAIDA = :PRCODSAIDA
          AND A.BDCODENTRADA = :PRCODENTRADA;
        END
      ELSE
        BEGIN
          /*Insere produto unico*/
          IF (:PRINS_PROUNICO = 'TRUE') THEN
            BEGIN
              INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA,
                                      BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, BDCODCOMBANP,
                                      BDCODSAIDA, BDCODENTRADA, BDDESCPROD, BDCODTERLAYOUT)
              SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA,
                              A.BDCODIGOEAN, A.BDCODTIPO, A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP,
                              A.BDCODSAIDA, A.BDCODENTRADA, A.BDDESCPROD, A.BDCODTERLAYOUT
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA
              AND A.BDDESCPROD = :PRDESCPROD
              AND A.BDCNPJTERLAYOUT = :PRCNPJTER;
            END

          /*Insere na empresa*/
          INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDORIGEMPROD, BDCODTERLAYOUT, BDCNPJTERLAYOUT, BDCODEMP, BDCODSAIDA, BDAPEPROD,
                                  BDDESCPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODTIPO, BDCODGEN,
                                  BDCODSER, BDCODCOMBANP, BDCODUNIMED, BDAPEUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA,
                                  BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT, BDCODCSTCOFENT, BDCODCSTCOFSAI, BDSEQ_PART)
          SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDORIGEMPROD, A.BDCODTERLAYOUT, A.BDCNPJTERLAYOUT, A.BDCODEMP, A.BDCODSAIDA,
                         A.BDAPEPROD, A.BDDESCPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA, A.BDCODIGOEAN, A.BDCODTER, A.BDCODENTRADA, A.BDCODTIPO,
                         A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP, A.BDCODUNIMED, A.BDAPEUNIMED, A.BDNCMPROD, A.BDCODTABINCID, A.BDGRUPO, A.BDORDEMMARCA,
                         A.BDCODCSTIPISAI, A.BDCODCSTIPIENT, A.BDCODCSTICMS, A.BDCODCSTPISSAI, A.BDCODCSTPISENT, A.BDCODCSTCOFENT, A.BDCODCSTCOFSAI, :PRSEQ_PART
          FROM TMP_TCADPRO_A_VALIDAR A
          WHERE A.BDCODSAIDA = :PRCODSAIDA
          AND A.BDCODENTRADA = :PRCODENTRADA
          AND A.BDDESCPROD = :PRDESCPROD
          AND A.BDCNPJTERLAYOUT = :PRCNPJTER;

          INSERT INTO TMP_TCADPRO_PART(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODTER, BDCODENTRADA, BDDESCPRODBUSCA, BDCODEMP, BDSEQ_PART)
          SELECT FIRST 1 :PRSESSAO, A.BDEDITCHAVE, :PRCODPROD, A.BDCODTERLAYOUT, A.BDCODENTRADA, A.BDDESCPROD, A.BDCODEMP, :PRSEQ_PART
          FROM TMP_TCADPRO_A_VALIDAR A
          WHERE A.BDCODSAIDA = :PRCODSAIDA
          AND A.BDCODENTRADA = :PRCODENTRADA
          AND A.BDCNPJTERLAYOUT = :PRCNPJTER
          AND TRIM(A.BDDESCPROD) = :PRDESCPROD    
          AND A.BDORIGEMPROD = 0
          AND NOT EXISTS (
                          SELECT PP.BDEDITCHAVE
                          FROM TMP_TCADPRO_PART PP
                          WHERE PP.BDCODTER = :PRCODTER
                          AND PP.BDCODENTRADA = :PRCODENTRADA
                          AND PP.BDDESCPRODBUSCA = :PRDESCPROD
                         );
        END
    END
  ELSE
    BEGIN
      IF ((:PROPERATION = 'UPT') AND ((:PRCODPROD IS NOT NULL) OR (:PRCODPROD > 0))) THEN /*Atualizar existente*/
        BEGIN
          IF (:PRORIGEMPROD = 1) THEN
            BEGIN
              SELECT FIRST 1 COALESCE(A.BDORIGEMPROD, 0),
                             COALESCE(A.BDCODTERLAYOUT, 0),
                             COALESCE(A.BDCNPJTERLAYOUT, ''),
                             COALESCE(A.BDCODEMP, 0),
                             COALESCE(A.BDCODSAIDA, ''),
                             COALESCE(A.BDAPEPROD, ''),
                             COALESCE(A.BDDESCPROD, ''),
                             COALESCE(A.BDAPELIDOUNICO, ''),
                             COALESCE(A.BDDESCRICAOUNICA, ''),
                             COALESCE(A.BDCODIGOEAN, ''),
                             COALESCE(A.BDCODTER, 0),
                             COALESCE(A.BDCODENTRADA, ''),
                             A.BDCODTIPO,
                             A.BDCODGEN,
                             A.BDCODSER,
                             A.BDCODCOMBANP,
                             A.BDCODUNIMED,
                             COALESCE(A.BDAPEUNIMED, ''),
                             A.BDNCMPROD,
                             A.BDCODTABINCID,
                             A.BDGRUPO,
                             A.BDORDEMMARCA,
                             A.BDCODCSTIPISAI,
                             A.BDCODCSTIPIENT,
                             A.BDCODCSTICMS,
                             A.BDCODCSTPISSAI,
                             A.BDCODCSTPISENT,
                             A.BDCODCSTCOFENT,
                             A.BDCODCSTCOFSAI
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA
              INTO :wORIGEMPROD,
                   :wCODTERLAYOUT,
                   :wCNPJTERLAYOUT,
                   :wCODEMP,
                   :wCODSAIDA,
                   :wAPEPROD,
                   :wDESCPROD,
                   :wAPELIDOUNICO,
                   :wDESCRICAOUNICA,
                   :wCODIGOEAN,
                   :wCODTER,
                   :wCODENTRADA,
                   :wCODTIPO,
                   :wCODGEN,
                   :wCODSER,
                   :wCODCOMBANP,
                   :wCODUNIMED,
                   :wAPEUNIMED,
                   :wNCMPROD,
                   :wCODTABINCID,
                   :wGRUPO,
                   :wORDEMMARCA,
                   :wCODCSTIPISAI,
                   :wCODCSTIPIENT,
                   :wCODCSTICMS,
                   :wCODCSTPISSAI,
                   :wCODCSTPISENT,
                   :wCODCSTCOFENT,
                   :wCODCSTCOFSAI;
            END
          ELSE
            BEGIN
              SELECT FIRST 1 COALESCE(A.BDORIGEMPROD, 0),
                             COALESCE(A.BDCODTERLAYOUT, 0),
                             COALESCE(A.BDCNPJTERLAYOUT, ''),
                             COALESCE(A.BDCODEMP, 0),
                             COALESCE(A.BDCODSAIDA, ''),
                             COALESCE(A.BDAPEPROD, ''),
                             COALESCE(A.BDDESCPROD, ''),
                             COALESCE(A.BDAPELIDOUNICO, ''),
                             COALESCE(A.BDDESCRICAOUNICA, ''),
                             COALESCE(A.BDCODIGOEAN, ''),
                             COALESCE(A.BDCODTER, 0),
                             COALESCE(A.BDCODENTRADA, ''),
                             A.BDCODTIPO,
                             A.BDCODGEN,
                             A.BDCODSER,
                             A.BDCODCOMBANP,
                             A.BDCODUNIMED,
                             COALESCE(A.BDAPEUNIMED, ''),
                             A.BDNCMPROD,
                             A.BDCODTABINCID,
                             A.BDGRUPO,
                             A.BDORDEMMARCA,
                             A.BDCODCSTIPISAI,
                             A.BDCODCSTIPIENT,
                             A.BDCODCSTICMS,
                             A.BDCODCSTPISSAI,
                             A.BDCODCSTPISENT,
                             A.BDCODCSTCOFENT,
                             A.BDCODCSTCOFSAI
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA
              AND A.BDDESCPROD = :PRDESCPROD
              AND A.BDCNPJTERLAYOUT = :PRCNPJTER
              INTO :wORIGEMPROD,
                   :wCODTERLAYOUT,
                   :wCNPJTERLAYOUT,
                   :wCODEMP,
                   :wCODSAIDA,
                   :wAPEPROD,
                   :wDESCPROD,
                   :wAPELIDOUNICO,
                   :wDESCRICAOUNICA,
                   :wCODIGOEAN,
                   :wCODTER,
                   :wCODENTRADA,
                   :wCODTIPO,
                   :wCODGEN,
                   :wCODSER,
                   :wCODCOMBANP,
                   :wCODUNIMED,
                   :wAPEUNIMED,
                   :wNCMPROD,
                   :wCODTABINCID,
                   :wGRUPO,
                   :wORDEMMARCA,
                   :wCODCSTIPISAI,
                   :wCODCSTIPIENT,
                   :wCODCSTICMS,
                   :wCODCSTPISSAI,
                   :wCODCSTPISENT,
                   :wCODCSTCOFENT,
                   :wCODCSTCOFSAI;
            END

          UPDATE TMP_TCADPRO P SET P.BDORIGEMPROD = :wORIGEMPROD,
                                   P.BDCODTERLAYOUT = :wCodTerLayout,
                                   P.BDCNPJTERLAYOUT = :wCnpjTerLayout,
                                   P.BDCODEMP = :wCodEmp,
                                   P.BDCODSAIDA = :wCodSaida,
                                   P.BDAPEPROD = :wApeProd,
                                   P.BDDESCPROD = :wDescProd,
                                   P.BDAPELIDOUNICO = :wApelidoUnico,
                                   P.BDDESCRICAOUNICA = :wDescricaoUnica,
                                   P.BDCODIGOEAN = :wCodigoEan,
                                   P.BDCODTER = :wCodTer,
                                   P.BDCODENTRADA = :wCodEntrada,
                                   P.BDCODTIPO = :wCodTipo,
                                   P.BDCODGEN = :wCodGen,
                                   P.BDCODSER = :wCodSer,
                                   P.BDCODCOMBANP = :wCodCombAnp,
                                   P.BDCODUNIMED = :wCodUnimed,
                                   P.BDAPEUNIMED = :wApeUnimed,
                                   P.BDNCMPROD= :wNcmProd,
                                   P.BDCODTABINCID = :wCodTabIncid,
                                   P.BDGRUPO = :wGrupo,
                                   P.BDORDEMMARCA = :wOrdemMarca,
                                   P.BDCODCSTIPISAI = :wCodCstIpiSai,
                                   P.BDCODCSTIPIENT = :wCodCstIpiEnt,
                                   P.BDCODCSTICMS = :wCodCstIcms,
                                   P.BDCODCSTPISSAI = :wCodCstPisSai,
                                   P.BDCODCSTPISENT = :wCodCstPisEnt,
                                   P.BDCODCSTCOFENT = :wCodCstCofEnt,
                                   P.BDCODCSTCOFSAI = :wCodCstCofSai,
                                   P.BDSEQ_PART     = :PRSEQ_PART
          WHERE P.BDCODPROD = :PRCODPROD;

          IF (:wOrigemProd = 0) THEN
            BEGIN
              UPDATE TMP_TCADPRO_PART C SET C.BDEDITCHAVE = :PRCODPROD, C.BDCODPROD = :PRCODPROD, C.BDDESCPRODBUSCA = :WDESCPROD, C.BDCODEMP = :WCODEMP, C.BDSEQ_PART = :PRSEQ_PART
              WHERE C.BDSESSAO = :PRSESSAO
              AND C.BDCODENTRADA = :WCODENTRADA
              AND C.BDCODTER = :PRCODTER;
            END
        END
      ELSE
        BEGIN
          IF (:PROPERATION = 'INUP') THEN
            BEGIN
              SELECT COALESCE(A.bdcodsaida, '') BDCODsaida,
                     A.bdapeprod bdapeprod,
                     A.bddescprod bddescproD,
                     A.bdapelidounico bdAPELIDOUNICO,
                     A.bddescricaounica BDDESCRICAOUNICA,
                     A.bdcodigoean BDCODIGOEAN,
                     A.BDCODTIPO,
                     A.BDCODGEN,
                     A.BDCODSER,
                     A.BDCODCOMBANP,
                     A.BDCODUNIMED,
                     A.BDNCMPROD,
                     A.bdcodtabincid,
                     A.bdgrupo,
                     A.bdordemmarca,
                     A.BDCODCSTIPISAI,
                     A.BDCODCSTIPIENT,
                     A.BDCODCSTICMS,
                     A.BDCODCSTPISSAI,
                     A.BDCODCSTPISENT,
                     A.BDCODCSTCOFENT,
                     A.BDCODCSTCOFSAI,
                     COALESCE(A.BDORIGEMPROD, 0) BDORIGEMPROD
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODPROD = :PRCODPROD
              INTO :wCodSaida,
                   :wApeProd,
                   :wDescProd,
                   :wApelidoUnico,
                   :wDescricaoUnica,
                   :wCodigoEan,
                   :wCodTipo,
                   :wCodGen,
                   :wCodSer,
                   :wCodCombAnp,
                   :wCodUnimed,
                   :wNcmProd,
                   :wCodTabIncid,
                   :wGrupo,
                   :wOrdemMarca,
                   :wCodCstIpiSai,
                   :wCodCstIpiEnt,
                   :wCodCstIcms,
                   :wCodCstPisSai,
                   :wCodCstPisEnt,
                   :wCodCstCofEnt,
                   :wCodCstCofSai,
                   :wOrigemProd;

              UPDATE OR INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODEMP, BDCODSAIDA, BDAPEPROD, BDDESCPROD,
                                                BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER,
                                                BDCODCOMBANP, BDCODUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA,
                                                BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT,
                                                BDCODCSTCOFENT, BDCODCSTCOFSAI, BDSEQ_PART)
              VALUES(0, :PRCODPROD, :PRCODPROD, IIF(:PRCODEMP = 0, NULL, :PRCODEMP), :wCodSaida, :WAPEPROD, :WDESCPROD, :WAPELIDOUNICO,
                    :WDESCRICAOUNICA, :WCODIGOEAN, :wCodTipo, :WCODGEN, :WCODSER, :wCodCombAnp, :wCodUnimed,
                    :wncmprod, :wCodtabincid, :wgrupo, :wOrdemMarca, :wCodCstIpiSai, :wCodCstIpiEnt, :wCodCstIcms,
                    :wCodCstPisSai, :wCodCstPisEnt, :wCodCstCofEnt, :wCodCstCofSai, :PRSEQ_PART)
              MATCHING(BDCODEMP, BDCODPROD, BDEDITCHAVE);

              IF ((:wOrigemProd = 0) AND (TRIM(:wDescProd) <> '')) THEN
                BEGIN
                  UPDATE OR INSERT INTO TMP_TCADPRO_PART(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODTER, BDCODENTRADA, BDDESCPRODBUSCA, BDCODEMP, BDSEQ_PART)
                  VALUES(:PRSESSAO, :PRCODPROD, :PRCODPROD, :PRCODTER, :PRCODENTRADA, :wDescProd, :wCodEmp, :PRSEQ_PART) MATCHING(BDCODPROD, BDCODENTRADA, BDDESCPRODBUSCA, BDCODTER);
                END
            END
        END
    END
END
^

/* empty dependent procedure body */
/* Clear: SP_INSERIR_LOG_ATUALIZACAO for: SP_INSERIR_LOG */
ALTER PROCEDURE SP_INSERIR_LOG_ATUALIZACAO(PRSISTEMA INTEGER,
PRACAO BLOB SUB_TYPE 1)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_INSERIR_LOG) */
ALTER PROCEDURE SP_INSERIR_LOG(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCODUSU INTEGER,
BDCODIMP INTEGER,
BDCODSIS INTEGER,
BDCODCOL INTEGER,
BDDATASISTEMA DATE,
BDHORAINICIAL TIME,
BDACAO BLOB SUB_TYPE 1,
BDACESSOID INTEGER,
BDTIPOACAO INTEGER,
PRNOME_MICRO VARCHAR(80),
PRIP_MICRO VARCHAR(15),
PRNOMETELA VARCHAR(100),
PRCAPTIONTELA VARCHAR(150),
BDCODRESP INTEGER,
PRTABELA VARCHAR(50),
BDTIPOIMPRESSAO SMALLINT,
BDERRO_PROCESSO VARCHAR(5),
BDDATACOMPETENCIA DATE,
BDCODUSUINTRANET INTEGER = NULL,
BDNOMUSUINTRANET VARCHAR(80) = NULL)
 AS
DECLARE VARIABLE WCODIGO_TABELA INTEGER;
DECLARE VARIABLE WCODIGO_TELA INTEGER;
DECLARE VARIABLE WCODIGO_NOMEMICRO INTEGER;
DECLARE VARIABLE WCAPTION VARCHAR(150);
DECLARE VARIABLE WVERSAOFDB VARCHAR(10);
DECLARE VARIABLE WSQL DM_MAXVARCHAR;
BEGIN
  wversaofdb = NULL;
  SELECT FIRST 1 BDVERSAO FROM TVERSAOFDB INTO :wversaofdb;

  IF (:prTabela <> '') THEN
     BEGIN
       SELECT FIRST 1 BDCODTABLOG FROM ttabelas_log WHERE BDTABELA = UPPER(:prTabela) INTO wcodigo_tabela;

       IF (wcodigo_tabela IS NULL) THEN
          BEGIN
            wcodigo_tabela = GEN_ID(gen_ttabelas_log_id, 1);
            INSERT INTO ttabelas_log (BDCODTABLOG, BDTABELA) VALUES (:wcodigo_tabela, UPPER(:prTabela));
          END
     END

  IF (:prnome_micro <> '' AND :prip_micro <> '') THEN
     BEGIN
       SELECT FIRST 1 BDCODNOMMICRO FROM TNOMEMICROLOG WHERE (BDNOME_MICRO = UPPER(:prnome_micro)) AND (BDIP_MICRO = UPPER(:prip_micro)) INTO WCODIGO_NOMEMICRO;

       IF (wcodigo_nomemicro IS NULL) THEN
          BEGIN
            WCODIGO_NOMEMICRO = GEN_ID(GEN_TNOMEMICROLOG, 1);
            INSERT INTO TNOMEMICROLOG (BDCODNOMMICRO, BDNOME_MICRO, BDIP_MICRO) VALUES (:WCODIGO_NOMEMICRO, UPPER(:prnome_micro), UPPER(:prip_micro));
          END
     END

  IF (:prnometela <> '') THEN
     BEGIN
      SELECT FIRST 1 BDCODTELASIS,BDCAPTIONTELA FROM ttela_sistema WHERE BDNOMETELA = UPPER(:prnometela) AND BDCAPTIONTELA = :prcaptiontela INTO :wcodigo_tela,:wcaption;

       IF (wcodigo_tela IS NULL) THEN
          BEGIN
          wcodigo_tela = GEN_ID(gen_ttela_sistema_id, 1);
            INSERT INTO ttela_sistema (BDCODTELASIS, BDNOMETELA, BDCAPTIONTELA) VALUES (:wcodigo_tela, UPPER(:prnometela), :prcaptiontela);
          END
       ELSE IF (wcaption <> prcaptiontela) THEN
            UPDATE ttela_sistema SET bdcaptiontela = :prcaptiontela WHERE bdcodtelasis = :wcodigo_tela;
          END

  --#Alt:18972 - 13/06/2016 - Inclu?do o campo BDDATACOMPETENCIA.
  --alt:15642 - 13/09/2016 - Registros do tipo "exclus?o de lan?amentos cont?beis" (13) tamb?m devem ser agrupados. Pedro
  --alt:15307 - 15/08/2016 - Alterado m?todo de grava??o do log. As funcionalidade anteriores foram implementadas diretamente em uma ?nica rotina.
  --Quando for impress?o de relat?rio (5) em v?deo (0), deve agrupar o registro com outros do mesmo usu?rio, empresa, data e sistema. Pedro
  wSQL = CASE WHEN ((BDTIPOACAO = 5) AND (BDTIPOIMPRESSAO = 0)) OR (BDTIPOACAO = 13) THEN 'update or' ELSE '' END;
  wSQL = wSQL||' insert into TLOG (BDCODEMP, BDCODTER, BDCODUSU, BDCODIMP, BDCODSIS, BDCODCOL, BDCODRESP,';
  wSQL = wSQL||' BDDATASISTEMA, BDDATA, BDHORAINICIAL, BDHORAFINAL, BDACAO, BDACESSOID, BDTIPOACAO,';
  wSQL = wSQL||' BDTIPOIMPRESSAO, BDERRO_PROCESSO, BDCODTELASIS, BDCODNOMMICRO, BDCODTABLOG, BDVERSAO, BDCODUSUINTRANET, BDNOMUSUINTRANET,';
  wSQL = wSQL||' BDDATACOMPETENCIA)';
  wSQL = wSQL||' values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ';
  wSQL = wSQL||CASE WHEN ((BDTIPOACAO = 5) AND (BDTIPOIMPRESSAO = 0)) OR (BDTIPOACAO = 13) THEN 'matching (BDCODEMP, BDCODUSU, BDCODSIS, BDDATASISTEMA, BDTIPOIMPRESSAO, BDCODTELASIS)' ELSE '' END||';';

  EXECUTE STATEMENT (wSQL) (:BDCODEMP, :BDCODTER, :BDCODUSU, :BDCODIMP, :BDCODSIS, :BDCODCOL, :BDCODRESP, 
                            :BDDATASISTEMA, CURRENT_DATE, :BDHORAINICIAL, CURRENT_TIME, ''||:BDACAO||'', :BDACESSOID, :BDTIPOACAO,
                            :BDTIPOIMPRESSAO, :BDERRO_PROCESSO, :wCodigo_Tela, :wCodigo_NomeMicro, :wCodigo_Tabela, :wVersaoFDB,
                            :bdcodusuintranet, :bdnomusuintranet, :BDDATACOMPETENCIA);

  /*     IF (wcodigo_tabela IS NULL) THEN
          BEGIN
            INSERT INTO tlog ( bdcodemp,  bdcodter,  bdcodusu,  bdcodimp,  bdcodsis,  bdcodcol,
                               bddata, bddatasistema, bdhorainicial,  bdhorafinal,  bdacao,  bdacessoid, bdtipoacao, 
                               BDCODTELASIS,  BDCODNOMMICRO, bdcodresp, BDTIPOIMPRESSAO, BDERRO_PROCESSO, BDVERSAO)
                      VALUES (:bdcodemp, :bdcodter, :bdcodusu, :bdcodimp, :bdcodsis, :bdcodcol, 
                              CURRENT_DATE, :bddatasistema, :bdhorainicial, CURRENT_TIME, :bdacao, :bdacessoid, :bdtipoacao,
                              :wcodigo_tela, :WCODIGO_NOMEMICRO, :bdcodresp, :BDTIPOIMPRESSAO, :BDERRO_PROCESSO, :wversaofdb);
          END
       ELSE
            INSERT INTO tlog ( bdcodemp,  bdcodter,  bdcodusu,  bdcodimp,  bdcodsis,  bdcodcol,    
                               bddata, bddatasistema,   bdhorainicial,  bdhorafinal,  bdacao,  bdacessoid,  bdtipoacao,
                               BDCODTELASIS,  BDCODNOMMICRO, bdcodresp, BDCODTABLOG, BDTIPOIMPRESSAO, BDERRO_PROCESSO, BDVERSAO)
                      VALUES (:bdcodemp, :bdcodter, :bdcodusu, :bdcodimp, :bdcodsis, :bdcodcol, 
                              CURRENT_DATE, :bddatasistema, :bdhorainicial, CURRENT_TIME, :bdacao, :bdacessoid, :bdtipoacao,
                              :wcodigo_tela, :WCODIGO_NOMEMICRO, :bdcodresp, :wcodigo_tabela, :BDTIPOIMPRESSAO, :BDERRO_PROCESSO, :wversaofdb);

     END
  ELSE
       IF (wcodigo_tabela IS NULL) THEN
          BEGIN
            INSERT INTO tlog ( bdcodemp,  bdcodter,  bdcodusu,  bdcodimp,  bdcodsis,  bdcodcol,    
                               bddata,  bddatasistema,  bdhorainicial,  bdhorafinal,  bdacao,  bdacessoid,  bdtipoacao,
                               BDCODNOMMICRO, bdcodresp, BDTIPOIMPRESSAO, BDERRO_PROCESSO, BDVERSAO)
                      VALUES (:bdcodemp, :bdcodter, :bdcodusu, :bdcodimp, :bdcodsis, :bdcodcol, 
                              CURRENT_DATE, :bddatasistema, :bdhorainicial, CURRENT_TIME, :bdacao, :bdacessoid, :bdtipoacao,
                              :WCODIGO_NOMEMICRO, :bdcodresp, :BDTIPOIMPRESSAO, :BDERRO_PROCESSO, :wversaofdb);
          END
       ELSE
            INSERT INTO tlog ( bdcodemp,  bdcodter,  bdcodusu,  bdcodimp,  bdcodsis,  bdcodcol,    
                               bddata,  bddatasistema,  bdhorainicial,  bdhorafinal,  bdacao,  bdacessoid,  bdtipoacao,
                               BDCODNOMMICRO, bdcodresp, BDCODTABLOG, BDTIPOIMPRESSAO, BDERRO_PROCESSO, BDVERSAO)
                      VALUES (:bdcodemp, :bdcodter, :bdcodusu, :bdcodimp, :bdcodsis, :bdcodcol, 
                              CURRENT_DATE, :bddatasistema, :bdhorainicial, CURRENT_TIME, :bdacao, :bdacessoid, :bdtipoacao,
                              :WCODIGO_NOMEMICRO, :bdcodresp, :wcodigo_tabela, :BDTIPOIMPRESSAO, :BDERRO_PROCESSO, :wversaofdb);*/
  --alt:15307 - Fim
END
^

/* Alter (SP_INSERIR_LOG_ATUALIZACAO) */
ALTER PROCEDURE SP_INSERIR_LOG_ATUALIZACAO(PRSISTEMA INTEGER,
PRACAO BLOB SUB_TYPE 1)
 AS
BEGIN
  EXECUTE PROCEDURE sp_inserir_log(NULL, NULL, 1, NULL, :prSistema, NULL, CURRENT_DATE, CURRENT_TIME, :prAcao, 0, 4, 'SERVIDOR', 'SERVIDOR', 'UPDATESISTEMA', 'Processo de atualiza??o do ?nico', NULL, NULL, NULL, 'FALSE', CURRENT_DATE);
END
^

/* Alter (SP_INSERIR_OBS_FINANCEIRA) */
ALTER PROCEDURE SP_INSERIR_OBS_FINANCEIRA(PRCODESC INTEGER)
 AS
BEGIN
  INSERT INTO VFIN_ESC_TCONFIGVAROBS (bdcodesc, bdchaveconfig, bdcodtipconfig, bdobsconfig) VALUES (:prcodesc, NULL, 1, 'Recebimento de fatura do cliente: *CODCLI-*NOMCLI, refer?ncia: *REFFAT, servi?o: *CODSER-*NOMSER, forma de pagamento: *FORMPGTO.');
  SUSPEND;
END
^

/* Alter (SP_INSERT_ATIVIDADE_BLUMENAU) */
ALTER PROCEDURE SP_INSERT_ATIVIDADE_BLUMENAU AS
DECLARE VARIABLE CID INTEGER;
BEGIN

    SELECT bdcodcid FROM tcidade WHERE bdcodest = 80470 INTO cid;

--    bdcodcid = CID;

INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.01','An?lise E Desenvolvimento De Sistemas.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.02','Programa??o.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.03','Processamento De Dados E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.04','Elabora??o De Programas De Computadores  Inclusive De Jogos Eletr?nicos.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.05','Licenciamento Ou Cess?o De Direito De Uso De Programas De Computa??o.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.06','Assessoria E Consultoria Em Inform?tica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.07','Suporte T?cnico Em Inform?tica  Inclusive Instala??o  Configura??o E Manuten??o De Programas De Computa??o E Bancos De Dados.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.08','Planejamento  Confec??o  Manuten??o E Atualiza??o De P?ginas Eletr?nicas.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'2.01','Servi?os De Pesquisas E Desenvolvimento De Qualquer Natureza.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.01','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.02','Cess?o De Direito De Uso De Marcas E De Sinais De Propaganda.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.03','Explora??o De Sal?es De Festas  Centro De Conven??es  Escrit?rios Virtuais  Stands  Quadras Esportivas  Est?dios  Gin?sios  Audit?rios  Casas De Espet?culos  Parques De Divers?es  Canchas E Cong?neres  Para Realiza??o De Eventos Ou Neg?cios De Qualquer Natureza.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.04','Loca??o  Subloca??o  Arrendamento  Direito De Passagem Ou Permiss?o De Uso  Compartilhado Ou N?o  De Ferrovia  Rodovia  Postes  Cabos  Dutos E Condutos De Qualquer Natureza.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.05','Cess?o De Andaimes  Palcos  Coberturas E Outras Estruturas De Uso Tempor?rio.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.01','Medicina E Biomedicina.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.02','An?lises Cl?nicas  Patologia  Eletricidade M?dica  Radioterapia  Quimioterapia  Ultra-Sonografia  Resson?ncia Magn?tica  Radiologia  Tomografia E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.03','Hospitais  Cl?nicas  Laborat?rios  Sanat?rios  Manic?mios  Casas De Sa?de  Prontos-Socorros  Ambulat?rios E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.04','Instrumenta??o Cir?rgica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.05','Acupuntura.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.06','Enfermagem  Inclusive Servi?os Auxiliares.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.07','Servi?os Farmac?uticos.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.08','Terapia Ocupacional  Fisioterapia E Fonoaudiologia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.09','Terapias De Qualquer Esp?cie Destinadas Ao Tratamento F?sico  Org?nico E Mental.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.10','Nutri??o.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.11','Obstetr?cia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.12','Odontologia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.13','Ort?ptica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.14','Pr?teses Sob Encomenda.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.15','Psican?lise.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.16','Psicologia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.17','Casas De Repouso E De Recupera??o  Creches  Asilos E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.18','Insemina??o Artificial  Fertiliza??o In Vitro E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.19','Bancos De Sangue  Leite  Pele  Olhos  ?vulos  S?men E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.20','Coleta De Sangue  Leite  Tecidos  S?men  ?rg?os E Materiais Biol?gicos De Qualquer Esp?cie.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.21','Unidade De Atendimento  Assist?ncia Ou Tratamento M?vel E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.22','Planos De Medicina De Grupo Ou Individual E Conv?nios Para Presta??o De Assist?ncia M?dica  Hospitalar  Odontol?gica E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.23','Outros Planos De Sa?de Que Se Cumpram Atrav?s De Servi?os De Terceiros Contratados  Credenciados  Cooperados Ou Apenas Pagos Pelo Operador Do Plano Mediante Indica??o Do Benefici?rio.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.01','Medicina Veterin?ria E Zootecnia.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.02','Hospitais  Cl?nicas  Ambulat?rios  Prontos-Socorros E Cong?neres  Na ?rea Veterin?ria.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.03','Laborat?rios De An?lise Na ?rea Veterin?ria.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.04','Insemina??o Artificial  Fertiliza??o In Vitro E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.05','Bancos De Sangue E De ?rg?os E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.06','Coleta De Sangue  Leite  Tecidos  S?men  ?rg?os E Materiais Biol?gicos De Qualquer Esp?cie.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.07','Unidade De Atendimento  Assist?ncia Ou Tratamento M?vel E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.08','Guarda  Tratamento  Amestramento  Embelezamento  Alojamento E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.09','Planos De Atendimento E Assist?ncia M?dico-Veterin?ria.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.01','Barbearia  Cabeleireiros  Manicuros  Pedicuros E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.02','Esteticistas  Tratamento De Pele  Depila??o E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.03','Banhos  Duchas  Sauna  Massagens E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.04','Gin?stica  Dan?a  Esportes  Nata??o  Artes Marciais E Demais Atividades F?sicas.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.05','Centros De Emagrecimento  Spa E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.01','Engenharia  Agronomia  Agrimensura  Arquitetura  Geologia  Urbanismo  Paisagismo E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.02','Execu??o  Por Administra??o  Empreitada Ou Subempreitada  De Obras De Constru??o Civil  Hidr?ulica Ou El?trica E De Outras Obras Semelhantes  Inclusive Sondagem  Perfura??o De Po?os  Escava??o  Drenagem E Irriga??o  Terraplanagem  Pavimenta??o  Concretagem E A Instala??o E Montagem De Produtos  Pe?as E Equipamento Exceto O Fornecimento De Mercadorias Produzidas Pelo Prestador De Servi?os Fora Do Local Da Presta??o Dos Servi?os  Que Fica Sujeito Ao Icms).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.03','Elabora??o De Planos Diretores  Estudos De Viabilidade  Estudos Organizacionais E Outros  Relacionados Com Obras E Servi?os De Engenharia  Elabora??o De Anteprojetos  Projetos B?sicos E Projetos Executivos Para Trabalhos De Engenharia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.04','Demoli??o.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.05','Repara??o  Conserva??o E Reforma De Edif?cios  Estradas  Pontes  Portos E Cong?nere (Exceto O Fornecimento De Mercadorias Produzidas Pelo Prestador Dos Servi?os  Fora Do Local Da Presta??o Dos Servi?os  Que Fica Sujeito Ao Icms).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.06','Coloca??o E Instala??o De Tapetes  Carpetes  Assoalhos  Cortinas  Revestimentos De Parede  Vidros  Divis?rias  Placas De Gesso E Cong?neres  Com Material Fornecido Pelo Tomador Do Servi?o.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.07','Recupera??o  Raspagem  Polimento E Lustra??o De Pisos E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.08','Calafeta??o.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.09','Varri??o  Coleta  Remo??o  Incinera??o  Tratamento  Reciclagem  Separa??o E Destina??o Final De Lixo  Rejeitos E Outros Res?duos Quaisquer.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.10','Limpeza  Manuten??o E Conserva??o De Vias E Logradouros P?blicos  Im?veis  Chamin?s  Piscinas  Parques  Jardins E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.11','Decora??o E Jardinagem  Inclusive Corte E Poda De ?rvores.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.12','Controle E Tratamento De Efluentes De Qualquer Natureza E De Agentes F?sicos  Qu?micos E Biol?gicos.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.13','Dedetiza??o  Desinfec??o  Desinsetiza??o  Imuniza??o  Higieniza??o  Desratiza??o  Pulveriza??o E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.14','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.15','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.16','Florestamento  Reflorestamento  Semeadura  Aduba??o E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.17','Escoramento  Conten??o De Encostas E Servi?os Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.18','Limpeza E Dragagem De Rios  Portos  Canais  Ba?as  Lagos  Lagoas  Represas  A?udes E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.19','Acompanhamento E Fiscaliza??o Da Execu??o De Obras De Engenharia  Arquitetura E Urbanismo.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.20','Aerofotogrametria (Inclusive Interpreta??o)  Cartografia  Mapeamento  Levantamentos Topogr?ficos  Batim?tricos  Geogr?ficos  Geod?sicos  Geol?gicos  Geof?sicos E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.21','Pesquisa  Perfura??o  Cimenta??o  Mergulho  Perfilagem  Concreta??o  Testemunhagem  Pescaria  Estimula??o E Outros Servi?os Relacionados Com A Explora??o E Explota??o De Petr?leo  G?s Natural E De Outros Recursos Minerais.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.22','Nuclea??o E Bombardeamento De Nuvens E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'8.01','Ensino Regular Pr?-Escolar  Fundamental  M?dio E Superior.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'8.02','Instru??o  Treinamento  Orienta??o Pedag?gica E Educacional  Avalia??o De Conhecimentos De Qualquer Natureza.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'9.01','Hospedagem De Qualquer Natureza Em Hot?is  Apart-Service Condominiais  Flat  Apart-Hot?is  Hot?is Resid?ncia  Residence-Service  Suite Service  Hotelaria Mar?tima  Mot?is  Pens?es E Cong?neres  Ocupa??o Por Temporada Com Fornecimento De Servi?o (O Valor Da Alimenta??o E Gorjeta  Quando Inclu?do No Pre?o Da Di?ria  Fica Sujeito Ao Imposto Sobre Servi?os).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'9.02','Agenciamento  Organiza??o  Promo??o  Intermedia??o E Execu??o De Programas De Turismo  Passeios  Viagens  Excurs?es  Hospedagens E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'9.03','Guias De Turismo.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.01','Agenciamento  Corretagem Ou Intermedia??o De C?mbio  De Seguros  De Cart?es De Cr?dito  De Planos De Sa?de E De Planos De Previd?ncia Privada.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.02','Agenciamento  Corretagem Ou Intermedia??o De T?tulos Em Geral  Valores Mobili?rios E Contratos Quaisquer.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.03','Agenciamento  Corretagem Ou Intermedia??o De Direitos De Propriedade Industrial  Art?stica Ou Liter?ria.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.04','Agenciamento  Corretagem Ou Intermedia??o De Contratos De Arrendamento Mercantil (Leasing)  De Franquia (Franchising) E De Faturiza??o (Factoring).',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.05','Agenciamento  Corretagem Ou Intermedia??o De Bens M?veis Ou Im?veis  N?o Abrangidos Em Outros Itens Ou Subitens  Inclusive Aqueles Realizados No ?mbito De Bolsas De Mercadorias E Futuros  Por Quaisquer Meios.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.06','Agenciamento Mar?timo.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.07','Agenciamento De Not?cias.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.08','Agenciamento De Publicidade E Propaganda  Inclusive O Agenciamento De Veicula??o Por Quaisquer Meios.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.09','Representa??o De Qualquer Natureza  Inclusive Comercial.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.10','Distribui??o De Bens De Terceiros.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'11.01','Guarda E Estacionamento De Ve?culos Terrestres Automotores  De Aeronaves E De Embarca??es.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'11.02','Vigil?ncia  Seguran?a Ou Monitoramento De Bens E Pessoas.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'11.03','Escolta  Inclusive De Ve?culos E Cargas.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'11.04','Armazenamento  Dep?sito  Carga  Descarga  Arruma??o E Guarda De Bens De Qualquer Esp?cie.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.01','Espet?culos Teatrais.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.02','Exibi??es Cinematogr?ficas.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.03','Espet?culos Circenses.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.04','Programas De Audit?rio.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.05','Parques De Divers?es  Centros De Lazer E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.06','Boates  Taxi-Dancing E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.07','Shows  Ballet  Dan?as  Desfiles  Bailes  ?peras  Concertos  Recitais  Festivais E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.08','Feiras  Exposi??es  Congressos E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.09','Bilhares  Boliches E Divers?es Eletr?nicas Ou N?o.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.10','Corridas E Competi??es De Animais.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.11','Competi??es Esportivas Ou De Destreza F?sica Ou Intelectual  Com Ou Sem A Participa??o Do Espectador.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.12','Execu??o De M?sica.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.13','Produ??o  Mediante Ou Sem Encomenda Pr?via  De Eventos  Espet?culos  Entrevistas  Shows  Ballet  Dan?as  Desfiles  Bailes  Teatros  ?peras  Concertos  Recitais  Festivais E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.14','Fornecimento De M?sica Para Ambientes Fechados Ou N?o  Mediante Transmiss?o Por Qualquer Processo.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.15','Desfiles De Blocos Carnavalescos Ou Folcl?ricos  Trios El?tricos E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.16','Exibi??o De Filmes  Entrevistas  Musicais  Espet?culos  Shows  Concertos  Desfiles  ?peras  Competi??es Esportivas  De Destreza Intelectual Ou Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.17','Recrea??o E Anima??o  Inclusive Em Festas E Eventos De Qualquer Natureza.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.01','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.02','Fonografia Ou Grava??o De Sons  Inclusive Trucagem  Dublagem  Mixagem E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.03','Fotografia E Cinematografia  Inclusive Revela??o  Amplia??o  C?pia  Reprodu??o  Trucagem E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.04','Reprografia  Microfilmagem E Digitaliza??o.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.05','Composi??o Gr?fica  Fotocomposi??o  Clicheria  Zincografia  Litografia  Fotolitografia.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.01','Lubrifica??o  Limpeza  Lustra??o  Revis?o  Carga E Recarga  Conserto  Restaura??o  Blindagem  Manuten??o E Conserva??o De M?quinas  Ve?culos  Aparelhos  Equipamentos  Motores  Elevadores Ou De Qualquer Objeto (Exceto Pe?as E Partes Empregadas  Que Ficam Sujeitas Ao Icms).',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.02','Assist?ncia T?cnica.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.03','Recondicionamento De MotoreS Exceto Pe?as E Partes Empregadas  Que Ficam Sujeitas Ao Icms).',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.04','Recauchutagem Ou Regenera??o De Pneus.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.05','Restaura??o  Recondicionamento  Acondicionamento  Pintura  Beneficiamento  Lavagem  Secagem  Tingimento  Galvanoplastia  Anodiza??o  Corte  Recorte  Polimento  Plastifica??o E Cong?neres  De Objetos Quaisquer.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.06','Instala??o E Montagem De Aparelhos  M?quinas E Equipamentos  Inclusive Montagem Industrial  Prestados Ao Usu?rio Final  Exclusivamente Com Material Por Ele Fornecido.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.07','Coloca??o De Molduras E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.08','Encaderna??o  Grava??o E Doura??o De Livros  Revistas E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.09','Alfaiataria E Costura  Quando O Material For Fornecido Pelo Usu?rio Final  Exceto Aviamento.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.10','Tinturaria E Lavanderia.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.11','Tape?aria E Reforma De Estofamentos Em Geral.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.12','Funilaria E Lanternagem.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.13','Carpintaria E Serralheria.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.01','Administra??o De Fundos Quaisquer  De Cons?rcio  De Cart?o De Cr?dito Ou D?bito E Cong?neres  De Carteira De Clientes  De Cheques Pr?-Datados E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.02','Abertura De Contas Em Geral  Inclusive Conta-Corrente  Conta De Investimentos E Aplica??o E Caderneta De Poupan?a  No Pa?s E No Exterior  Bem Como A Manuten??o Das Referidas Contas Ativas E Inativas.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.03','Loca??o E Manuten??o De Cofres Particulares  De Terminais Eletr?nicos  De Terminais De Atendimento E De Bens E Equipamentos Em Geral.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.04','Fornecimento Ou Emiss?o De Atestados Em Geral  Inclusive Atestado De Idoneidade  Atestado De Capacidade Financeira E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.05','Cadastro  Elabora??o De Ficha Cadastral  Renova??o Cadastral E Cong?neres  Inclus?o Ou Exclus?o No Cadastro De Emitentes De Cheques Sem Fundos   Ccf Ou Em Quaisquer Outros Bancos Cadastrais.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.06','Emiss?o  Reemiss?o E Fornecimento De Avisos  Comprovantes E Documentos Em Geral  Abono De Firmas  Coleta E Entrega De Documentos  Bens E Valores  Comunica??o Com Outra Ag?ncia Ou Com A Administra??o Central  Licenciamento Eletr?nico De Ve?culos  Transfer?ncia De Ve?culos  Agenciamento Fiduci?rio Ou Deposit?rio  Devolu??o De Bens Em Cust?dia.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.07','Acesso  Movimenta??o  Atendimento E Consulta A Contas Em Geral  Por Qualquer Meio Ou Processo  Inclusive Por Telefone  Fac-S?mile  Internet E Telex  Acesso A Terminais De Atendimento  Inclusive Vinte E Quatro Horas  Acesso A Outro Banco E A Rede Compartilhada  Fornecimento De Saldo  Extrato E Demais Informa??es Relativas A Contas Em Geral  Por Qualquer Meio Ou Processo.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.08','Emiss?o  Reemiss?o  Altera??o  Cess?o  Substitui??o  Cancelamento E Registro De Contrato De Cr?dito  Estudo  An?lise E Avalia??o De Opera??es De Cr?dito  Emiss?o  Concess?o  Altera??o Ou Contrata??o De Aval  Fian?a  Anu?ncia E Cong?neres  Servi?os Relativos A Abertura De Cr?dito  Para Quaisquer Fins.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.09','Arrendamento Mercantil (Leasing) De Quaisquer Bens  Inclusive Cess?o De Direitos E Obriga??es  Substitui??o De Garantia  Altera??o  Cancelamento E Registro De Contrato  E Demais Servi?os Relacionados Ao Arrendamento Mercantil (Leasing).',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.10','Servi?os Relacionados A Cobran?as  Recebimentos Ou Pagamentos Em Geral  De T?tulos Quaisquer  De Contas Ou Carn?s  De C?mbio  De Tributos E Por Conta De Terceiros  Inclusive Os Efetuados Por Meio Eletr?nico  Autom?tico Ou Por M?quinas De Atendimento  Fornecimento De Posi??o De Cobran?a  Recebimento Ou Pagamento  Emiss?o De Carn?s  Fichas De Compensa??o  Impressos E Documentos Em Geral.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.11','Devolu??o De T?tulos  Protesto De T?tulos  Susta??o De Protesto  Manuten??o De T?tulos  Reapresenta??o De T?tulos  E Demais Servi?os A Eles Relacionados.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.12','Cust?dia Em Geral  Inclusive De T?tulos E Valores Mobili?rios.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.13','Servi?os Relacionados A Opera??es De C?mbio Em Geral  Edi??o  Altera??o  Prorroga??o  Cancelamento E Baixa De Contrato De C?mbio  Emiss?o De Registro De Exporta??o Ou De Cr?dito  Cobran?a Ou Dep?sito No Exterior  Emiss?o  Fornecimento E Cancelamento De Cheques De Viagem  Fornecimento  Transfer?ncia  Cancelamento E Demais Servi?os Relativos A Carta De Cr?dito De Importa??o  Exporta??o E Garantias Recebidas  Envio E Recebimento De Mensagens Em Geral Relacionadas A Opera??es De C?mbio.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.14','Fornecimento  Emiss?o  Reemiss?o  Renova??o E Manuten??o De Cart?o Magn?tico  Cart?o De Cr?dito  Cart?o De D?bito  Cart?o Sal?rio E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.15','Compensa??o De Cheques E T?tulos Quaisquer  Servi?os Relacionados A Dep?sito  Inclusive Dep?sito Identificado  A Saque De Contas Quaisquer  Por Qualquer Meio Ou Processo  Inclusive Em Terminais Eletr?nicos E De Atendimento.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.16','Emiss?o  Reemiss?o  Liquida??o  Altera??o  Cancelamento E Baixa De Ordens De Pagamento  Ordens De Cr?dito E Similares  Por Qualquer Meio Ou Processo  Servi?os Relacionados ? Transfer?ncia De Valores  Dados  Fundos  Pagamentos E Similares  Inclusive Entre Contas Em Geral.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.17','Emiss?o  Fornecimento  Devolu??o  Susta??o  Cancelamento E Oposi??o De Cheques Quaisquer  Avulso Ou Por Tal?o.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.18','Servi?os Relacionados A Cr?dito Imobili?rio  Avalia??o E Vistoria De Im?vel Ou Obra  An?lise T?cnica E Jur?dica  Emiss?o  Reemiss?o  Altera??o  Transfer?ncia E Renegocia??o De Contrato  Emiss?o E Reemiss?o Do Termo De Quita??o E Demais Servi?os Relacionados A Cr?dito Imobili?rio.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'16.01','Servi?os De Transporte De Natureza Municipal.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.01','Assessoria Ou Consultoria De Qualquer Natureza  N?o Contida Em Outros Itens Desta Lista  An?lise  Exame  Pesquisa  Coleta  Compila??o E Fornecimento De Dados E Informa??es De Qualquer Natureza  Inclusive Cadastro E Similares.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.02','Datilografia  Digita??o  Estenografia  Expediente  Secretaria Em Geral  Resposta Aud?vel  Reda??o  Edi??o  Interpreta??o  Revis?o  Tradu??o  Apoio E Infra-Estrutura Administrativa E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.03','Planejamento  Coordena??o  Programa??o Ou Organiza??o T?cnica  Financeira Ou Administrativa.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.04','Recrutamento  Agenciamento  Sele??o E Coloca??o De M?o-De-Obra.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.05','Fornecimento De M?o-De-Obra  Mesmo Em Car?ter Tempor?rio  Inclusive De Empregados Ou Trabalhadores  Avulsos Ou Tempor?rios  Contratados Pelo Prestador De Servi?o.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.06','Propaganda E Publicidade  Inclusive Promo??o De Vendas  Planejamento De Campanhas Ou Sistemas De Publicidade  Elabora??o De Desenhos  Textos E Demais Materiais Publicit?rios.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.07','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.08','Franquia (Franchising).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.09','Per?cias  Laudos  Exames T?cnicos E An?lises T?cnicas.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.10','Planejamento  Organiza??o E Administra??o De Feiras  Exposi??es  Congressos E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.11','Organiza??o De Festas E Recep??es  Buf? (Exceto O Fornecimento De Alimenta??o E Bebidas  Que Fica Sujeito Ao Icms).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.12','Administra??o Em Geral  Inclusive De Bens E Neg?cios De Terceiros.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.13','Leil?o E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.14','Advocacia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.15','Arbitragem De Qualquer Esp?cie  Inclusive Jur?dica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.16','Auditoria.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.17','An?lise De Organiza??o E M?todos.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.18','Atu?ria E C?lculos T?cnicos De Qualquer Natureza.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.19','Contabilidade  Inclusive Servi?os T?cnicos E Auxiliares.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.20','Consultoria E Assessoria Econ?mica Ou Financeira.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.21','Estat?stica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.22','Cobran?a Em Geral.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.23','Assessoria  An?lise  Avalia??o  Atendimento  Consulta  Cadastro  Sele??o  Gerenciamento De Informa??es  Administra??o De Contas A Receber Ou A Pagar E Em Geral  Relacionados A Opera??es De Faturiza??o (Factoring).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.24','Apresenta??o De Palestras  Confer?ncias  Semin?rios E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'18.01','Servi?os De Regula??o De Sinistros Vinculados A Contratos De Seguros  Inspe??o E Avalia??o De Riscos Para Cobertura De Contratos De Seguros  Preven??o E Ger?ncia De Riscos Segur?veis E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'19.01','Servi?os De Distribui??o E Venda De Bilhetes E Demais Produtos De Loteria  Bingos  Cart?es  Pules Ou Cupons De Apostas  Sorteios  Pr?mios  Inclusive Os Decorrentes De T?tulos De Capitaliza??o E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'20.01','Servi?os Portu?rios  Ferroportu?rios  Utiliza??o De Porto  Movimenta??o De Passageiros  Reboque De Embarca??es  Rebocador Escoteiro  Atraca??o  Desatraca??o  Servi?os De Praticagem  Capatazia  Armazenagem De Qualquer Natureza  Servi?os Acess?rios  Movimenta??o De Mercadorias  Servi?os De Apoio Mar?timo  De Movimenta??o Ao Largo  Servi?os De Armadores  Estiva  Confer?ncia  Log?stica E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'20.02','Servi?os Aeroportu?rios  Utiliza??o De Aeroporto  Movimenta??o De Passageiros  Armazenagem De Qualquer Natureza  Capatazia  Movimenta??o De Aeronaves  Servi?os De Apoio Aeroportu?rios  Servi?os Acess?rios  Movimenta??o De Mercadorias  Log?stica E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'20.03','Servi?os De Terminais Rodovi?rios  Ferrovi?rios  Metrovi?rios  Movimenta??o De Passageiros  Mercadorias  Inclusive     Suas Opera??es  Log?stica E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'21.01','Servi?os De Registros P?blicos  Cartor?rios E Notariais.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'22.01','Servi?os De Explora??o De Rodovia Mediante Cobran?a De Pre?o Ou Ped?gio Dos Usu?rios  Envolvendo Execu??o De Servi?os De Conserva??o  Manuten??o  Melhoramentos Para Adequa??o De Capacidade E Seguran?a De Tr?nsito  Opera??o  Monitora??o  Assist?ncia Aos Usu?rios E Outros Servi?os Definidos Em Contratos  Atos De Concess?o Ou De Permiss?o Ou Em Normas Oficiais.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'23.01','Servi?os De Programa??o E Comunica??o Visual  Desenho Industrial E Cong?neres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'24.01','Servi?os De Chaveiros  Confec??o De Carimbos  Placas  Sinaliza??o Visual  Banners  Adesivos E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'25.01','Funerais  Inclusive Fornecimento De Caix?o  Urna Ou Esquifes  Aluguel De Capela  Transporte Do Corpo Cadav?rico  Fornecimento De Flores  Coroas E Outros Paramentos  Desembara?o De Certid?o De ?bito  Fornecimento De V?u  Essa E Outros Adornos  Embalsamento  Embelezamento  Conserva??o Ou Restaura??o De Cad?veres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'25.02','Crema??o De Corpos E Partes De Corpos Cadav?ricos.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'25.03','Planos Ou Conv?nio Funer?rios.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'25.04','Manuten??o E Conserva??o De Jazigos E Cemit?rios.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'26.01','Servi?os De Coleta  Remessa Ou Entrega De Correspond?ncias  Documentos  Objetos  Bens Ou Valores  Inclusive Pelos Correios E Suas Ag?ncias Franqueadas  Courrier E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'27.01','Servi?os De Assist?ncia Social.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'28.01','Servi?os De Avalia??o De Bens E Servi?os De Qualquer Natureza.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'29.01','Servi?os De Biblioteconomia.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'30.01','Servi?os De Biologia  Biotecnologia E Qu?mica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'31.01','Servi?os T?cnicos Em Edifica??es  Eletr?nica  Eletrot?cnica  Mec?nica  Telecomunica??es E Cong?neres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'32.01','Servi?os De Desenhos T?cnicos.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'33.01','Servi?os De Desembara?o Aduaneiro  Comiss?rios  Despachantes E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'34.01','Servi?os De Investiga??es Particulares  Detetives E Cong?neres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'35.01','Servi?os De Reportagem  Assessoria De Imprensa  Jornalismo E Rela??es P?blicas.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'36.01','Servi?os De Meteorologia.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'37.01','Servi?os De Artistas  Atletas  Modelos E Manequins.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'38.01','Servi?os De Museologia.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'39.01','Servi?os De Ourivesaria E Lapida??o (Quando O Material For Fornecido Pelo Tomador Do Servi?o).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'40.01','Obras De Arte Sob Encomenda.',3);

END
^

/* Alter (SP_INSERT_FOLHAAVULSA_ONLINE) */
ALTER PROCEDURE SP_INSERT_FOLHAAVULSA_ONLINE(PRCODTCA INTEGER)
 AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WCLASS VARCHAR(8);
DECLARE VARIABLE WCLASS2 VARCHAR(8);
DECLARE VARIABLE WGRUPOCOL INTEGER;
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    :wplano
  DO
    BEGIN
      -- insere a conta da classifica??o de t?tulo
      SELECT x.bdretorno FROM preenche_esquerda(:prcodtca, 8, '0') x INTO :wclass;
      wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodtca,bdclassificacao,bdformula) values('||
                                              wplano||',408,'||prcodtca||','''||'02.001.000000010.T'||wclass||''','''||'LiqFolAvu('||prcodtca||',0)'''||') ';
      EXECUTE STATEMENT wsql;

      FOR SELECT bdcodgrupocla FROM tgrupoclassecol
      INTO
        :wgrupocol
      DO
        BEGIN
          SELECT x.bdretorno FROM preenche_esquerda(:wgrupocol, 8, '0') x INTO :wclass2;
          wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodtca,bdcodgrupocla,bdclassificacao,bdformula) values('||
                                                  wplano||',408,'||prcodtca||','||:wgrupocol||','''||'02.001.000000010.T'||wclass||'.A'||wclass2||''','''||'LiqFolAvu('||prcodtca||','||wgrupocol||')'''||') ';
          EXECUTE STATEMENT wsql;
        END
    END
--  suspend;
END
^

/* empty dependent procedure body */
/* Clear: SP_VALIDA_CONTA_ONLINE_TEMP for: SP_INSERT_INCONSISTENCIAS_CONTA */
ALTER PROCEDURE SP_VALIDA_CONTA_ONLINE_TEMP(PRCODPLANOONLINE INTEGER,
PRSESSAO INTEGER,
PRENQFED INTEGER,
PRCODCONFIRLP INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_INSERT_INCONSISTENCIAS_CONTA) */
ALTER PROCEDURE SP_INSERT_INCONSISTENCIAS_CONTA(PRSESSAO INTEGER,
PRCODPLANOONLINE INTEGER,
PRENQFED INTEGER,
PRCODCONFIRLP INTEGER)
 AS
DECLARE VARIABLE FCONTABILIZAICMS INTEGER;
DECLARE VARIABLE FCONTABILIZACOFINS INTEGER;
DECLARE VARIABLE FCONTABILIZAPIS INTEGER;
BEGIN
  SELECT P.BDTIPOINTICMS,  P.BDTIPOINTPIS, P.BDTIPOINTCOFINS
  FROM TPLANO_CONF_ONLINE P
  WHERE P.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :FCONTABILIZAICMS, :FCONTABILIZAPIS, :FCONTABILIZACOFINS;

  /*--------------------------------------------Valor cont?bil--------------------------------------------*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 27 BDINCONSISTENCIA
  FROM (
        SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
       ) MOV
  JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRCONTAB > 0)
  JOIN (
        SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
        FROM TCONTAS_ONLINE_TEMP C
        --WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (111, 117, 170) /*Valor cont?bil*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
        WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 111 /*Valor cont?bil - A vista*/
                                                                                                        WHEN C.BDCODTIPOCONTA =  51 THEN 117 /*Valor cont?bil - Prazo*/
                                                                                                        WHEN C.BDCODTIPOCONTA = 406 THEN 170 /*Valor cont?bil - Outras*/
                                                                                                   END)
       ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                              END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
  /*------------------------------------------------------------------------------------------------------*/

  IF (:FCONTABILIZAICMS = 0) THEN /*0 - nota a nota, deve exigir a conta de icms*/
    BEGIN
      IF (:PRENQFED NOT IN(1, 2)) THEN
        BEGIN
          /*-------------------------------------------------ICMS-------------------------------------------------*/
          INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
          SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 28 BDINCONSISTENCIA
          FROM (
                SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
                FROM TMP_VEF_EMP_TMOVSAI_TEMP S
                WHERE S.BDSESSAO = :PRSESSAO
               ) MOV
          JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRICMS > 0)
          JOIN (
                SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
                FROM TCONTAS_ONLINE_TEMP C
                --WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (112, 118, 171) /*ICMS*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 112 /*ICMS - A vista*/
                                                                                                                WHEN C.BDCODTIPOCONTA =  51 THEN 118 /*ICMS - Prazo*/
                                                                                                                WHEN C.BDCODTIPOCONTA = 406 THEN 171 /*ICMS - Outras*/
                                                                                                           END)
               ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                           WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                           WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                      END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
          /*------------------------------------------------------------------------------------------------------*/
        END

      /*------------------------------------------------ICMS ST-----------------------------------------------*/
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
      SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 32 BDINCONSISTENCIA
      FROM (
            SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
            FROM TMP_VEF_EMP_TMOVSAI_TEMP S
            WHERE S.BDSESSAO = :PRSESSAO
           ) MOV
      JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRST > 0)
      JOIN (
            SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
            FROM TCONTAS_ONLINE_TEMP C
            --WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (113, 119, 172) /*ICMS ST*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
            WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 113 /*ICMS ST - A vista*/
                                                                                                            WHEN C.BDCODTIPOCONTA =  51 THEN 119 /*ICMS ST - Prazo*/
                                                                                                            WHEN C.BDCODTIPOCONTA = 406 THEN 172 /*ICMS ST - Outras*/
                                                                                                       END)
           ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                       WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                       WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                  END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
      /*------------------------------------------------------------------------------------------------------*/
    END

  IF (:PRENQFED NOT IN(1, 2)) THEN
    BEGIN
      /*-------------------------------------------------IPI--------------------------------------------------*/
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
      SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 31 BDINCONSISTENCIA
      FROM (
            SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
            FROM TMP_VEF_EMP_TMOVSAI_TEMP S
            WHERE S.BDSESSAO = :PRSESSAO
           ) MOV
      JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRIPI > 0)
      JOIN (
            SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
            FROM TCONTAS_ONLINE_TEMP C
            --WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (114, 120, 173) /*IPI*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
            WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 114 /*IPI - A vista*/
                                                                                                            WHEN C.BDCODTIPOCONTA =  51 THEN 120 /*IPI - Prazo*/
                                                                                                            WHEN C.BDCODTIPOCONTA = 406 THEN 173 /*IPI - Outras*/
                                                                                                       END)   
           ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                       WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                       WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                  END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
      /*------------------------------------------------------------------------------------------------------*/
    
      IF ((:FCONTABILIZAPIS = 0) AND ((:PRCODCONFIRLP IS NULL) OR (:PRCODCONFIRLP = 0))) THEN /*0 - nota a nota, deve exigir a conta de PIS*/
        BEGIN
          /*-------------------------------------------------PIS--------------------------------------------------*/
          INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
          SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 29 BDINCONSISTENCIA
          FROM (
                SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
                FROM TMP_VEF_EMP_TMOVSAI_TEMP S
                WHERE S.BDSESSAO = :PRSESSAO
               ) MOV
          JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRPIS > 0)
          JOIN (
                SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
                FROM TCONTAS_ONLINE_TEMP C
                --WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (115, 121, 174) /*PIS*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 115 /*PIS - A vista*/
                                                                                                                WHEN C.BDCODTIPOCONTA =  51 THEN 121 /*PIS - Prazo*/
                                                                                                                WHEN C.BDCODTIPOCONTA = 406 THEN 174 /*PIS - Outras*/
                                                                                                           END)       
               ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                           WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                           WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                      END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
        END
      /*------------------------------------------------------------------------------------------------------*/
    
      IF ((:FCONTABILIZACOFINS = 0) AND ((:PRCODCONFIRLP IS NULL) OR (:PRCODCONFIRLP = 0))) THEN /*0 - nota a nota, deve exigir a conta de Cofins*/
        BEGIN
          /*-----------------------------------------------COFINS-------------------------------------------------*/
          INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
          SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 30 BDINCONSISTENCIA
          FROM (
                SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
                FROM TMP_VEF_EMP_TMOVSAI_TEMP S
                WHERE S.BDSESSAO = :PRSESSAO
               ) MOV
          JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRCOFINS > 0)
          JOIN (
                SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
                FROM TCONTAS_ONLINE_TEMP C
                --WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (116, 122, 175) /*Cofins*/ -- Alt.: 18904 - Deve buscar a conta de acordo com a condi??o de pagamento
                WHERE ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 116 /*Cofins - A vista*/
                                                                                                                WHEN C.BDCODTIPOCONTA =  51 THEN 122 /*Cofins - Prazo*/
                                                                                                                WHEN C.BDCODTIPOCONTA = 406 THEN 175 /*Cofins - Outras*/
                                                                                                           END)           
               ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                           WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                           WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                      END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
        END
      /*------------------------------------------------------------------------------------------------------*/
    END

  /*-------------------------------------------PIS(Reten??o)----------------------------------------------*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 39 BDINCONSISTENCIA
  FROM (
        SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDVLRPIS > 0)
        WHERE S.BDSESSAO = :PRSESSAO
       ) MOV
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO)
  JOIN (
        SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
        FROM TCONTAS_ONLINE_TEMP C
        WHERE C.BDCONTADEBPROV IS NULL AND C.BDCODITEMONLINE = 89 /*P?s reten??o*/
       ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                              END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
  /*------------------------------------------------------------------------------------------------------*/

  /*------------------------------------------Cofins(Reten??o)--------------------------------------------*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 40 BDINCONSISTENCIA
  FROM (
        SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDVLRCOFINS > 0)
        WHERE S.BDSESSAO = :PRSESSAO
       ) MOV
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO)
  JOIN (
        SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
        FROM TCONTAS_ONLINE_TEMP C
        WHERE C.BDCONTADEBPROV IS NULL AND C.BDCODITEMONLINE = 90 /*Cofins reten??o*/
       ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                              END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
  /*------------------------------------------------------------------------------------------------------*/

  /*-----------------------------------Contribui??o social(Reten??o)--------------------------------------*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 41 BDINCONSISTENCIA
  FROM (
        SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDVLRCSOCIAL > 0)
        WHERE S.BDSESSAO = :PRSESSAO
       ) MOV
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO)
  JOIN (
        SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
        FROM TCONTAS_ONLINE_TEMP C
        WHERE C.BDCONTADEBPROV IS NULL AND C.BDCODITEMONLINE = 91 /*CS reten??o*/
       ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                              END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
  /*------------------------------------------------------------------------------------------------------*/

  /*--------------------------------------------IR(Reten??o)----------------------------------------------*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 44 BDINCONSISTENCIA
  FROM (
        SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDVLRIR > 0)
        WHERE S.BDSESSAO = :PRSESSAO
       ) MOV
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO)
  JOIN (
        SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
        FROM TCONTAS_ONLINE_TEMP C
        WHERE C.BDCONTADEBPROV IS NULL AND C.BDCODITEMONLINE = 92 /*IR reten??o*/
       ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                              END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
  /*------------------------------------------------------------------------------------------------------*/

  /*--------------------------------------------INSS(Reten??o)----------------------------------------------*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 42 BDINCONSISTENCIA
  FROM (
        SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDINSSRET > 0)
        WHERE S.BDSESSAO = :PRSESSAO
       ) MOV
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO)
  JOIN (
        SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
        FROM TCONTAS_ONLINE_TEMP C
        WHERE C.BDCONTADEBPROV IS NULL AND C.BDCODITEMONLINE = 93 /*INSS reten??o*/
       ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                              END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
  /*------------------------------------------------------------------------------------------------------*/

  /*--------------------------------------------ISS(Reten??o)----------------------------------------------*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 43 BDINCONSISTENCIA
  FROM (
        SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        JOIN TMP_VEF_EMP_TMOVSAIRET_TEMP R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDISSRET > 0)
        WHERE S.BDSESSAO = :PRSESSAO
       ) MOV
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO)
  JOIN (
        SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov
        FROM TCONTAS_ONLINE_TEMP C
        WHERE C.BDCONTADEBPROV IS NULL AND C.BDCODITEMONLINE = 94 /*ISS reten??o*/
       ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                              END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));
  /*------------------------------------------------------------------------------------------------------*/

  /*---------------------------------------BLOQUEIO DE CONTAS---------------------------------------------*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 128 BDINCONSISTENCIA
  FROM (SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, coalesce(S.BDCONDPGTO, 0) BDCONDPGTO, S.BDDATAEMISSAO
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :prsessao) MOV
  inner JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO)
  JOIN TCONTAS_ONLINE_TEMP O ON (O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE
                                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                                 END))
  JOIN TBLOQCTA_USUARIO TUSU ON (TUSU.BDCODEMP = I.BDCODEMP AND TUSU.BDCODUSU = (SELECT BDCODUSU FROM SP_GET_USUARIO))
  WHERE EXISTS (SELECT FIRST 1 tbloq.bdcodemp FROM TBLOQCTA TBLOQ WHERE (TBLOQ.BDCODEMP = MOV.BDCODEMP AND tbloq.bdcodplapadrao = tusu.bdcodplapadrao
                                                                       AND ((TBLOQ.BDCODTPLA = O.BDCONTADEBPROV) OR (TBLOQ.BDCODTPLA = O.BDCONTACREDPROV))
                                                                       AND TBLOQ.BDCODBLQ = TUSU.BDCODBLQ) and (MOV.BDDATAEMISSAO between TBLOQ.BDDATAINICIAL and TBLOQ.BDDATAFINAL));
  /*------------------------------------------------------------------------------------------------------*/
END
^

/* Alter (SP_INSERT_OR_UPDATE_TCADPRO) */
ALTER PROCEDURE SP_INSERT_OR_UPDATE_TCADPRO(PRSESSAO INTEGER,
PRREF INTEGER)
 AS
DECLARE VARIABLE FCODPROD INTEGER;
DECLARE VARIABLE FCODGEN INTEGER;
DECLARE VARIABLE FCODSER INTEGER;
DECLARE VARIABLE FCODTIPOSER INTEGER;
DECLARE VARIABLE FCODCOMBANP INTEGER;
DECLARE VARIABLE FAPELIDOUNICO VARCHAR(30) COLLATE WIN_PTBR;
DECLARE VARIABLE FDESCRICAOUNICA VARCHAR(200) COLLATE WIN_PTBR;
DECLARE VARIABLE FCODIGOEAN VARCHAR(20) COLLATE WIN_PTBR;
DECLARE VARIABLE FCODTIPO INTEGER;
DECLARE VARIABLE FCODEMP INTEGER;
DECLARE VARIABLE FCODSAIDA VARCHAR(60) COLLATE WIN_PTBR;
DECLARE VARIABLE FDESCPROD VARCHAR(200) COLLATE WIN_PTBR;
DECLARE VARIABLE FAPEPROD VARCHAR(30) COLLATE WIN_PTBR;
DECLARE VARIABLE FCODUNIMED INTEGER;
DECLARE VARIABLE FNCMPROD INTEGER;
DECLARE VARIABLE FGRUPO INTEGER;
DECLARE VARIABLE FCODCSTIPIENT INTEGER;
DECLARE VARIABLE FCODCSTCOFENT INTEGER;
DECLARE VARIABLE FCODCSTPISENT INTEGER;
DECLARE VARIABLE FCODCSTPISSAI INTEGER;
DECLARE VARIABLE FCODCSTCOFSAI INTEGER;
DECLARE VARIABLE FCODCSTIPISAI INTEGER;
DECLARE VARIABLE FCODCSTICMS INTEGER;
DECLARE VARIABLE FCODTABINCID INTEGER;
DECLARE VARIABLE FORDEMMARCA INTEGER;
DECLARE VARIABLE FALIQICMS NUMERIC(7,4);
DECLARE VARIABLE FALIQICMSST NUMERIC(7,4);
DECLARE VARIABLE FALIQIPI NUMERIC(7,4);
DECLARE VARIABLE FALIQPIS NUMERIC(7,4);
DECLARE VARIABLE FALIQPISENT NUMERIC(7,4);
DECLARE VARIABLE FALIQCOF NUMERIC(7,4);
DECLARE VARIABLE FALIQCOFENT NUMERIC(7,4);
DECLARE VARIABLE FCAPVOL INTEGER;
DECLARE VARIABLE FINATIVO VARCHAR(5);
DECLARE VARIABLE FCODPRODBASE INTEGER;
DECLARE VARIABLE FREFPROD INTEGER;
DECLARE VARIABLE FORDEM INTEGER;
DECLARE VARIABLE FQTDCONSUMO NUMERIC(17,6);
DECLARE VARIABLE FPERDA DM_NUMERIC_7_4_ALIQ;
DECLARE VARIABLE FDATAINIVAL DATE;
DECLARE VARIABLE FDATAFIMVAL DATE;
DECLARE VARIABLE FCADPROAUTO VARCHAR(5);
DECLARE VARIABLE FATUPROD VARCHAR(5);
DECLARE VARIABLE FPRODEXISTENTE VARCHAR(5);
DECLARE VARIABLE FPRODVINCEXISTENTE VARCHAR(5);
DECLARE VARIABLE FSITUACAO INTEGER;
DECLARE VARIABLE FCODTER INTEGER;
DECLARE VARIABLE FCODENTRADA VARCHAR(60);
DECLARE VARIABLE FCODCEST INTEGER;
DECLARE VARIABLE FCODTIPI INTEGER;
DECLARE VARIABLE FORDEMEXIST INTEGER;
DECLARE VARIABLE FORIGEM INTEGER;
DECLARE VARIABLE FDESCORIGINAL VARCHAR(200);
BEGIN
  SELECT SP.BDCADPROAUTO, SP.BDATUPROD FROM SP_GET_ACOES_INCONSISTENCIA(:FCODEMP, :PRREF) SP INTO :FCADPROAUTO, :FATUPROD;

  FOR SELECT P.BDCODPROD, P.BDCODGEN, IIF(P.BDCODSER = 0, NULL, P.BDCODSER), P.BDCODTIPOSER, P.BDCODCOMBANP, P.BDAPELIDOUNICO, P.BDDESCRICAOUNICA,
             P.BDCODIGOEAN, P.BDCODTIPO , P.BDCODEMP, P.BDCODSAIDA, P.BDDESCPROD, p.BDAPEPROD,
             IIF(COALESCE(p.BDALTCODUNIMED, 0) = 0, NULL, P.BDALTCODUNIMED), IIF(p.BDNCMPROD = 0, NULL, p.BDNCMPROD),
             p.BDGRUPO, p.BDCODCSTIPIENT, p.BDCODCSTCOFENT, p.BDCODCSTPISENT, p.BDCODCSTPISSAI, p.BDCODCSTCOFSAI, p.BDCODCSTIPISAI,
             p.BDCODCSTICMS, IIF(p.BDCODTABINCID = 0,NULL, p.BDCODTABINCID) BDCODTABINCID, p.BDORDEMMARCA, p.BDALIQICMS, p.BDALIQICMSST, p.BDALIQIPI, p.BDALIQPIS,
             p.BDALIQPISENT, p.BDALIQCOF, p.BDALIQCOFENT, p.BDCAPVOL, p.BDINATIVO, P.BDEDITCHAVE, P.bdrefprodlay,
             IIF(PRO.BDCODPROD IS NULL, 'FALSE', 'TRUE') BDPRODEXISTENTE, P.BDSITUACAO, IIF(PV.BDCODPROD IS NULL, 'FALSE', 'TRUE') BDPRODVINCEXISTEBASE,
             P.BDCODTERLAYOUT, P.BDCODENTRADA, P.BDCODCEST, P.BDCODTIPI, P.BDORDEM, P.BDORIGEMPROD, P.BDDESCORIGINAL
      FROM TMP_TCADPRO_TEMP P
      LEFT OUTER JOIN TCADPRO_VINC PV ON(PV.BDCODEMP = P.BDCODEMP AND PV.BDCODPROD = P.BDEDITCHAVE /*AND P.BDPRODEXISTEBASE <> 'TRUE'*/)
      LEFT OUTER JOIN TCADPRO PRO ON(PRO.BDCODPROD = P.BDEDITCHAVE)
      WHERE P.bdsessao = :PRSESSAO 
      AND ((P.bdinconsistente IS NULL) OR (P.bdinconsistente = 0)) 
      AND P.BDEDITCHAVE IS NOT NULL
      AND NOT EXISTS (
                      SELECT I.BDCODINCONSISTENCIA FROM VEF_INCON_TCADPRO I
                      WHERE I.BDSESSAO = :PRSESSAO
                      AND I.BDCODPROD = P.BDCODPROD
                     )      
      INTO :FCODPROD, :FCODGEN, :FCODSER, :FCODTIPOSER, :FCODCOMBANP, :FAPELIDOUNICO, :FDESCRICAOUNICA,
           :FCODIGOEAN, :FCODTIPO, :FCODEMP, :FCODSAIDA, :FDESCPROD, :FAPEPROD,
           :FCODUNIMED, :FNCMPROD,  :FGRUPO,  :FCODCSTIPIENT , :FCODCSTCOFENT,  :FCODCSTPISENT, :FCODCSTPISSAI,
           :FCODCSTCOFSAI, :FCODCSTIPISAI,  :FCODCSTICMS, :FCODTABINCID, :FORDEMMARCA, :FALIQICMS, :FALIQICMSST,
           :FALIQIPI,:FALIQPIS,:FALIQPISENT,:FALIQCOF,:FALIQCOFENT, :FCAPVOL, :FINATIVO, :FCODPRODBASE,
           :FREFPROD, :FPRODEXISTENTE, :FSITUACAO, :FPRODVINCEXISTENTE, :FCODTER, :FCODENTRADA, :FCODCEST, :FCODTIPI, :FORDEM, :FORIGEM, :FDESCORIGINAL
      DO
  BEGIN
    /*Verifica se ? pra cadastrar os produtos novos automaticamente*/
    IF ((:FCADPROAUTO = 'TRUE') OR (COALESCE(:FSITUACAO, 0) IN (1, 2))) THEN
      BEGIN
        /*Verifica se ? pra atualizar o cadastro de produto, se for, simplesmente da update or insert em todos os produtos*/
        IF (:FATUPROD = 'TRUE') THEN
          BEGIN
            UPDATE OR INSERT INTO TCADPRO (BDCODPROD, BDCODGEN, BDCODSER, BDCODTIPOSER, BDCODCOMBANP, BDAPELIDOUNICO,BDDESCRICAOUNICA, BDCODIGOEAN,BDCODTIPO)
            VALUES(:FCODPROD, :FCODGEN, :FCODSER, :FCODTIPOSER, :FCODCOMBANP,:FAPELIDOUNICO, :FDESCRICAOUNICA, :FCODIGOEAN, :FCODTIPO) MATCHING(BDCODPROD);

            UPDATE OR INSERT INTO TCADPRO_VINC (BDCODPROD, BDCODEMP, BDCODSAIDA, BDDESCPROD, BDAPEPROD, BDCODUNIMED, BDNCMPROD,
                                                BDGRUPO, BDCODCSTIPIENT, BDCODCSTCOFENT, BDCODCSTPISENT, BDCODCSTPISSAI,
                                                BDCODCSTCOFSAI, BDCODCSTIPISAI, BDCODCSTICMS, BDCODTABINCID, BDORDEMMARCA,
                                                BDALIQICMS, BDALIQICMSST, BDALIQIPI, BDALIQPIS, BDALIQPISENT, BDALIQCOF,
                                                BDALIQCOFENT, BDCAPVOL, BDINATIVO, BDCODTIPO, BDCODTIPOSER, BDCODGEN, BDCODSER,
                                                BDCODCOMBANP, BDCODCEST, BDCODTIPI)
            VALUES(
                   :FCODPROD, :FCODEMP, :FCODSAIDA, :FDESCPROD, :FAPEPROD, :FCODUNIMED, :FNCMPROD, :FGRUPO, :FCODCSTIPIENT,
                   :FCODCSTCOFENT, :FCODCSTPISENT, :FCODCSTPISSAI, :FCODCSTCOFSAI, :FCODCSTIPISAI, :FCODCSTICMS, :FCODTABINCID,
                   :FORDEMMARCA, :FALIQICMS, :FALIQICMSST, :FALIQIPI, :FALIQPIS, :FALIQPISENT, :FALIQCOF, :FALIQCOFENT, :FCAPVOL,
                   :FINATIVO, :FCODTIPO, :FCODTIPOSER, :FCODGEN, :FCODSER, :FCODCOMBANP, :FCODCEST, :FCODTIPI
                  ) MATCHING(BDCODPROD, BDCODEMP);

            UPDATE OR INSERT INTO TCADPRO_REF (BDCODPROD,BDCODEMP,BDREFPROD,BDDESCPROD) VALUES (:FCODPROD, :FCODEMP, :FREFPROD, :FDESCPROD) MATCHING(BDCODPROD, BDREFPROD, BDCODEMP);

            IF (:FORIGEM = 0) THEN
              BEGIN
                FORDEMEXIST = NULL;
                SELECT COALESCE((
                                 SELECT FIRST 1 P.BDORDEM
                                 FROM TCADPRO_PART P
                                 WHERE P.BDCODPROD = :FCODPROD
                                 AND P.BDCODTER = :FCODTER
                                 AND CAST(P.BDCODENTRADA AS DM_DESC_WINPTBR) = CAST(:FCODENTRADA AS DM_DESC_WINPTBR)
                                 AND CAST(P.BDDESCPRODBUSCA AS DM_DESC_WINPTBR) = CAST(:FDESCORIGINAL AS DM_DESC_WINPTBR)
                                ),
                                (
                                 SELECT FIRST 1 P.BDORDEM
                                 FROM TCADPRO_PART P
                                 WHERE P.BDCODPROD = :FCODPROD
                                 AND P.BDCODTER = :FCODTER
                                 AND UPPER(CAST(P.BDCODENTRADA AS DM_DESC_WINPTBR)) = UPPER(CAST(:FCODENTRADA AS DM_DESC_WINPTBR))
                                 AND UPPER(CAST(P.BDDESCPRODBUSCA AS DM_DESC_WINPTBR)) = UPPER(CAST(:FDESCORIGINAL AS DM_DESC_WINPTBR)))
                                ) BDORDEM
                FROM RDB$DATABASE
                INTO :FORDEMEXIST;

                IF ((:FORDEMEXIST IS NULL) OR (:FORDEMEXIST = 0)) THEN
                  BEGIN
                    INSERT INTO TCADPRO_PART(BDCODPROD, BDCODTER, BDORDEM, BDCODENTRADA, BDDESCPRODBUSCA)
                    VALUES(:FCODPROD, :FCODTER, :FORDEM, :FCODENTRADA, :FDESCORIGINAL);
              END
          END
          END
        ELSE
          BEGIN 
            /*Se chegou aqui n?o ? pra atualizar os produtos existentes, apenas inserir os novos.*/
            IF (:FPRODEXISTENTE <> 'TRUE') THEN
              BEGIN
                UPDATE OR INSERT INTO TCADPRO (BDCODPROD, BDCODGEN, BDCODSER, BDCODTIPOSER, BDCODCOMBANP, BDAPELIDOUNICO,BDDESCRICAOUNICA, BDCODIGOEAN,BDCODTIPO)
                VALUES(:FCODPROD, :FCODGEN, :FCODSER, :FCODTIPOSER, :FCODCOMBANP,:FAPELIDOUNICO, :FDESCRICAOUNICA, :FCODIGOEAN, :FCODTIPO) MATCHING(BDCODPROD);
              END
            IF (:FPRODVINCEXISTENTE = 'FALSE') THEN
              BEGIN
                UPDATE OR INSERT INTO TCADPRO_VINC (BDCODPROD, BDCODEMP, BDCODSAIDA, BDDESCPROD, BDAPEPROD, BDCODUNIMED, BDNCMPROD,
                                                    BDGRUPO, BDCODCSTIPIENT, BDCODCSTCOFENT, BDCODCSTPISENT, BDCODCSTPISSAI,
                                                    BDCODCSTCOFSAI, BDCODCSTIPISAI, BDCODCSTICMS, BDCODTABINCID, BDORDEMMARCA,
                                                    BDALIQICMS, BDALIQICMSST, BDALIQIPI, BDALIQPIS, BDALIQPISENT, BDALIQCOF,
                                                    BDALIQCOFENT, BDCAPVOL, BDINATIVO, BDCODTIPO, BDCODTIPOSER, BDCODGEN, BDCODSER,
                                                    BDCODCOMBANP, BDCODCEST, BDCODTIPI)
                VALUES(
                       :FCODPROD, :FCODEMP, :FCODSAIDA, :FDESCPROD, :FAPEPROD, :FCODUNIMED, :FNCMPROD, :FGRUPO, :FCODCSTIPIENT,
                       :FCODCSTCOFENT, :FCODCSTPISENT, :FCODCSTPISSAI, :FCODCSTCOFSAI, :FCODCSTIPISAI, :FCODCSTICMS, :FCODTABINCID,
                       :FORDEMMARCA, :FALIQICMS, :FALIQICMSST, :FALIQIPI, :FALIQPIS, :FALIQPISENT, :FALIQCOF, :FALIQCOFENT, :FCAPVOL,
                       :FINATIVO, :FCODTIPO, :FCODTIPOSER, :FCODGEN, :FCODSER, :FCODCOMBANP, :FCODCEST, :FCODTIPI
                      ) MATCHING(BDCODPROD, BDCODEMP);

                UPDATE OR INSERT INTO TCADPRO_REF (BDCODPROD,BDCODEMP,BDREFPROD,BDDESCPROD) VALUES (:FCODPROD, :FCODEMP, :FREFPROD, :FDESCPROD) MATCHING(BDCODPROD, BDREFPROD, BDCODEMP);
              END

            IF (:FORIGEM = 0) THEN
              BEGIN
                FORDEMEXIST = NULL;
                SELECT COALESCE((
                                 SELECT FIRST 1 P.BDORDEM
                                 FROM TCADPRO_PART P
                                 WHERE P.BDCODPROD = :FCODPROD
                                 AND P.BDCODTER = :FCODTER
                                 AND CAST(P.BDCODENTRADA AS DM_DESC_WINPTBR) = CAST(:FCODENTRADA AS DM_DESC_WINPTBR)
                                 AND CAST(P.BDDESCPRODBUSCA AS DM_DESC_WINPTBR) = CAST(:FDESCORIGINAL AS DM_DESC_WINPTBR)
                                ),
                                (
                                 SELECT FIRST 1 P.BDORDEM
                                 FROM TCADPRO_PART P
                                 WHERE P.BDCODPROD = :FCODPROD
                                 AND P.BDCODTER = :FCODTER
                                 AND UPPER(CAST(P.BDCODENTRADA AS DM_DESC_WINPTBR)) = UPPER(CAST(:FCODENTRADA AS DM_DESC_WINPTBR))
                                 AND UPPER(CAST(P.BDDESCPRODBUSCA AS DM_DESC_WINPTBR)) = UPPER(CAST(:FDESCORIGINAL AS DM_DESC_WINPTBR)))
                                ) BDORDEM
                FROM RDB$DATABASE
                INTO :FORDEMEXIST;

                IF ((:FORDEMEXIST IS NULL) OR (:FORDEMEXIST = 0)) THEN
                  BEGIN
                    INSERT INTO TCADPRO_PART(BDCODPROD, BDCODTER, BDORDEM, BDCODENTRADA, BDDESCPRODBUSCA)
                    VALUES(:FCODPROD, :FCODTER, :FORDEM, :FCODENTRADA, :FDESCORIGINAL);
              END
          END
      END
  END
  END

  FOR SELECT I.BDALTCODPROD, I.BDCODEMP, I.BDORDEM, I.BDREFERENCIA, I.BDCODPROINSUMO,
             I.BDQTDCONSUMO, I.BDPERDA, I.BDDATAINIVAL, I.BDDATAFIMVAL
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND NOT EXISTS(
                     SELECT INCO.BDCODINCONSISTENCIA
                     FROM VEF_INCON_TCADPRO_INSUMO INCO
                     WHERE INCO.BDSESSAO = I.BDSESSAO
                     AND INCO.BDCODSAIDA = I.BDCODSAIDA
                     AND INCO.BDCODEMP = I.BDCODEMP
                     AND INCO.BDORDEM = I.BDORDEM
                    )
      INTO :FCODPROD, :FCODEMP, :FORDEM, :FREFPROD, :FCODPRODBASE,
           :FQTDCONSUMO, :FPERDA, :FDATAINIVAL, :FDATAFIMVAL
  DO
    BEGIN
      UPDATE OR INSERT INTO TCADPRO_INSUMOS(BDCODPROD, BDCODEMP, BDORDEM, BDREFERENCIA, BDCODPROINSUMO, BDQTDCONSUMO, BDPERDA, BDDATAINIVAL, BDDATAFIMVAL)
      VALUES(:FCODPROD, :FCODEMP, :FORDEM, :FREFPROD, :FCODPRODBASE, :FQTDCONSUMO, :FPERDA, :FDATAINIVAL, :FDATAFIMVAL) MATCHING(BDCODPROD, BDCODEMP, BDORDEM);
    END
END
^

/* Alter (SP_INSERT_OR_UPDATE_TTERCEIRO) */
ALTER PROCEDURE SP_INSERT_OR_UPDATE_TTERCEIRO(PRSESSAO INTEGER,
PRREFEMP INTEGER,
PRCODEMP INTEGER)
 AS
DECLARE VARIABLE FCODPLANOINCO INTEGER;
DECLARE VARIABLE FATUALIZACAD VARCHAR(5);
DECLARE VARIABLE FCODTER INTEGER;
DECLARE VARIABLE FCGCTER VARCHAR(18);
DECLARE VARIABLE FIETER VARCHAR(20);
DECLARE VARIABLE FAPELIDOTER VARCHAR(20);
DECLARE VARIABLE FNOMETER VARCHAR(100);
DECLARE VARIABLE FCODCID INTEGER;
DECLARE VARIABLE FCODPAIS INTEGER;
DECLARE VARIABLE FCODTIPO INTEGER;
DECLARE VARIABLE FLOGRTER DM_LOGRADOURO;
DECLARE VARIABLE FENDTER DM_BDENDERECO;
DECLARE VARIABLE FCOMPTER DM_BDCOMPENDERECO;
DECLARE VARIABLE FCEPTER VARCHAR(9);
DECLARE VARIABLE FBAITER VARCHAR(60);
DECLARE VARIABLE FDDDTER VARCHAR(3);
DECLARE VARIABLE FFONETER DM_BDTELEFONE;
DECLARE VARIABLE FEMAILTER DM_BDEMAIL;
DECLARE VARIABLE FFAXTER DM_BDTELEFONE;
DECLARE VARIABLE FDATACADTER DATE;
DECLARE VARIABLE FIMTER VARCHAR(16);
DECLARE VARIABLE FPRURALTER VARCHAR(5);
DECLARE VARIABLE FENQSIMPLESFEDTER INTEGER;
DECLARE VARIABLE FINSCSUFRAMATER VARCHAR(10);
DECLARE VARIABLE FCODGPS INTEGER;
DECLARE VARIABLE FDDDFAXTER VARCHAR(3);
DECLARE VARIABLE FNUMTER INTEGER;
BEGIN

  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> 0)) THEN
    SELECT S.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREFEMP, :PRCODEMP, NULL) S INTO :FCodPlanoInco;

  IF ((:FCodPlanoInco IS NULL) OR (:FCodPlanoInco = 0)) THEN
    SELECT I.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS I WHERE UPPER(I.BDPLANODEFAULT) = 'TRUE' INTO :FCodPlanoInco;

  FAtualizaCad = 'FALSE';
  IF ((:FCodPlanoInco IS NOT NULL) OR (:FCodPlanoInco <> 0)) THEN
    SELECT COALESCE(I.BDATUPART, 'FALSE') BDATUPART FROM VEF_BASE_TACOESINCONS I WHERE I.BDCODPLANOINCONS = :FCodPlanoInco INTO :FAtualizaCad;

  /*Deve atualizar os cadastros com os dados da importa??o*/
  IF (:FAtualizaCad = 'TRUE') THEN
    BEGIN
      FOR SELECT T.bdeditchave BDCODTER, T.bdcgcter, T.bdieter, T.bdapelidoter, T.bdnometer, T.bdcodcid, T.bdcodpais, T.bdcodtipo,
                 T.bdrefemp, T.bdlogrter, T.bdendter, T.bdcompter, T.bdcepter, T.bdbaiter, T.bddddter, T.bdfoneter,
                 T.bdemailter, T.bdfaxter, T.bddatacadter, T.bdimter, T.bdpruralter, T.bdenqsimplesfedter, T.bdinscsuframater,
                 T.bdcodgps, T.bddddfaxter, T.bdnumter
          FROM TMP_TTERCEIRO_TEMP T
          WHERE T.bdsessao = :PRSESSAO
          AND ((T.bdinconsistente IS NULL) OR (T.bdinconsistente = 0))
          AND T.BDEDITCHAVE IS NOT NULL
          AND NOT EXISTS(
                         SELECT TI.BDCODINCONSISTENCIA
                         FROM VEF_INCON_TTERCEIROS TI
                         WHERE TI.BDSESSAO = T.BDSESSAO
                         AND TI.BDCODTER = T.BDCODTER
                        )
          INTO :FCODTER,  :FCGCTER, :FIETER,  :FAPELIDOTER, :FNOMETER, :FCODCID,    :FCODPAIS, :FCODTIPO,     :PRREFEMP, :FLOGRTER, :FENDTER,
               :FCOMPTER, :FCEPTER, :FBAITER, :FDDDTER,     :FFONETER, :FEMAILTER,  :FFAXTER,  :FDATACADTER , :FIMTER,  :FPRURALTER,
               :FENQSIMPLESFEDTER,  :FINSCSUFRAMATER,       :FCODGPS,  :FDDDFAXTER, :FNUMTER DO
        BEGIN
          UPDATE OR INSERT INTO TTERCEIRO (BDCODTER, BDCODPLAPADRAO, BDCODTPLA, BDCGCTER, BDCODTIPO) VALUES(:FCODTER, NULL, NULL, :FCGCTER, :FCODTIPO) MATCHING(BDCODTER);

          UPDATE OR INSERT INTO TTERCEIRO_REF (BDCODTER, BDREFEMP, BDAPELIDOTER, BDNOMETER, BDLOGRTER, BDENDTER, BDCOMPTER, BDCEPTER, BDBAITER, BDDDDTER, BDFONETER,
                                               BDFAXTER, BDEMAILTER, BDIETER, BDDATACADTER, BDIMTER, BDPRURALTER, BDENQSIMPLESFEDTER, BDINSCSUFRAMATER, BDCODGPS,
                                               BDCODCID, BDCODPAIS, BDDDDFAXTER, BDNUMTER, BDCGCTER)
          VALUES(:FCODTER, :PRREFEMP, :FAPELIDOTER, :FNOMETER, :FLOGRTER, :FENDTER, :FCOMPTER, :FCEPTER, :FBAITER, :FDDDTER, :FFONETER, :FFAXTER, :FEMAILTER, :FIETER, :FDATACADTER, :FIMTER, :FPRURALTER, :FENQSIMPLESFEDTER, :FINSCSUFRAMATER, :FCODGPS, :FCODCID, :FCODPAIS, :FDDDFAXTER, :FNUMTER, :FCGCTER) MATCHING(BDCODTER, BDREFEMP);
        END
    END
  ELSE /*N?o deve atualizar os cadastros com os dados da importa??o*/
    BEGIN
      INSERT INTO TTERCEIRO (BDCODTER, BDCODPLAPADRAO, BDCODTPLA, BDCGCTER, BDCODTIPO)
      SELECT TER.BDCODTER, TER.BDCODPLAPADRAO, TER.BDCODTPLA, TER.BDCGCTER, TER.BDCODTIPO
      FROM (
            SELECT T.BDEDITCHAVE BDCODTER, T.BDCODPLAPADRAO, T.BDCODTPLA, T.BDCGCTER, T.BDCODTIPO, T.BDIETER, T.BDREF_MAX
            FROM TMP_TTERCEIRO_TEMP T
            WHERE T.BDSESSAO = :PRSESSAO
            /*Se estiver com o BDEDITCHAVE como NULL ? porque o registro ? inconsistente, n?o precisa fazer o not exists com a tabela de inconsistencias(VEF_INCON_TTERCEIROS)*/
            AND ((T.BDEDITCHAVE IS NOT NULL) OR (T.BDEDITCHAVE <> 0))
            AND NOT EXISTS(
                           SELECT TI.BDCODINCONSISTENCIA
                           FROM VEF_INCON_TTERCEIROS TI
                           WHERE TI.BDSESSAO = :PRSESSAO
                           AND TI.BDCODTER = T.BDCODTER
                          )
           ) TER
------------------------------
--                                m?todo antigo
--      LEFT OUTER JOIN TTERCEIRO T ON (T.BDCODTER = TER.BDCODTER)
--      LEFT OUTER JOIN TTERCEIRO_REF REF ON (REF.BDCGCTER = TER.BDCGCTER AND REF.BDIETER = TER.BDIETER)
--      WHERE REF.BDCGCTER IS NULL;
--      AND T.BDCGCTER IS NULL;
--      WHERE T.BDCODTER IS NULL;
-----------------------------------------
--                                       m?todo antigo 2
--      LEFT OUTER JOIN TTERCEIRO T ON (T.BDCGCTER = TER.BDCGCTER)
--      LEFT OUTER JOIN TTERCEIRO_REF REF ON (REF.BDCGCTER = TER.BDCGCTER AND REF.BDIETER = TER.BDIETER)
--      WHERE ref.BDCGCTER IS NULL
--      and t.bdcgcter is null;
-----------------------------------------
--      LEFT OUTER JOIN TTERCEIRO T ON (T.BDCGCTER = TER.BDCGCTER)
--      LEFT OUTER JOIN TTERCEIRO_REF REF ON (REF.BDCGCTER = TER.BDCGCTER AND REF.BDIETER = TER.BDIETER AND REF.BDREFEMP = TER.BDREF_MAX)
      LEFT OUTER JOIN TTERCEIRO T ON (T.BDCODTER = TER.BDCODTER)
      LEFT OUTER JOIN TTERCEIRO_REF REF ON (REF.BDCODTER = TER.BDCODTER AND REF.BDREFEMP = TER.BDREF_MAX)
--      WHERE ref.BDCGCTER IS NULL
      WHERE T.BDCODTER IS NULL
      GROUP BY TER.BDCODTER, TER.BDCODPLAPADRAO, TER.BDCODTPLA, TER.BDCGCTER, TER.BDCODTIPO;

      INSERT INTO TTERCEIRO_REF (BDCODTER, BDREFEMP, BDAPELIDOTER, BDNOMETER, BDLOGRTER, BDENDTER, BDCOMPTER, BDCEPTER, BDBAITER, BDDDDTER, BDFONETER,
                                 BDFAXTER, BDEMAILTER, BDIETER, BDDATACADTER, BDIMTER, BDPRURALTER, BDENQSIMPLESFEDTER, BDINSCSUFRAMATER, BDCODGPS,
                                 BDCODCID, BDCODPAIS, BDDDDFAXTER, BDNUMTER, BDCGCTER)
      SELECT TR.BDCODTER, TR.BDREFEMP, TR.BDAPELIDOTER, TR.BDNOMETER, TR.BDLOGRTER, TR.BDENDTER, TR.BDCOMPTER, TR.BDCEPTER, TR.BDBAITER, TR.BDDDDTER, TR.BDFONETER,
             TR.BDFAXTER, TR.BDEMAILTER, TR.BDIETER, TR.BDDATACADTER, TR.BDIMTER, TR.BDPRURALTER, TR.BDENQSIMPLESFEDTER, TR.BDINSCSUFRAMATER, TR.BDCODGPS,
             TR.BDCODCID, TR.BDCODPAIS, TR.BDDDDFAXTER, TR.BDNUMTER, TR.BDCGCTER
      FROM (
            SELECT T.BDEDITCHAVE BDCODTER, T.BDREFEMP, T.BDAPELIDOTER, T.BDNOMETER, T.BDLOGRTER, T.BDENDTER, T.BDCOMPTER, T.BDCEPTER, T.BDBAITER, T.BDDDDTER, T.BDFONETER,
                   T.BDFAXTER, T.BDEMAILTER, T.BDIETER, T.BDDATACADTER, T.BDIMTER, T.BDPRURALTER, T.BDENQSIMPLESFEDTER, T.BDINSCSUFRAMATER, T.BDCODGPS,
                   T.BDCODCID, T.BDCODPAIS, T.BDDDDFAXTER, T.BDNUMTER, T.BDCGCTER, T.BDREF_MAX
            FROM TMP_TTERCEIRO_TEMP T
            WHERE T.BDSESSAO = :PRSESSAO
            AND ((T.BDEDITCHAVE IS NOT NULL) OR (T.BDEDITCHAVE <> 0))
            AND NOT EXISTS(
                           SELECT TI.BDCODINCONSISTENCIA
                           FROM VEF_INCON_TTERCEIROS TI
                           WHERE TI.BDSESSAO = :PRSESSAO
                           AND TI.BDCODTER = T.BDCODTER
                          )
           ) TR
--      LEFT OUTER JOIN TTERCEIRO_REF T ON(T.BDCODTER = TR.BDCODTER)
      LEFT OUTER JOIN TTERCEIRO_REF R ON (TR.BDCODTER = R.BDCODTER AND R.BDREFEMP = TR.BDREF_MAX)
--      LEFT OUTER JOIN TTERCEIRO_REF R ON (/*TR.BDCODTER = R.BDCODTER AND */R.BDCGCTER = TR.BDCGCTER AND R.BDIETER = TR.BDIETER AND R.BDREFEMP = TR.BDREF_MAX)
      WHERE R.BDCODTER IS NULL;
--      AND T.BDCODTER IS NOT NULL;
--      WHERE T.BDCODTER IS NULL;
    END
END
^

/* Alter (SP_LANCA_AJUSTE_E115) */
ALTER PROCEDURE SP_LANCA_AJUSTE_E115(PRSESSAO INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAE115 INTEGER;
BEGIN
  FOR
      SELECT DISTINCT(BDCODEMP) FROM TMP_VEF_EMP_TMOVSAI_TEMP INTO :wCODEMP
  DO
    BEGIN
      /* Se a empresa tiver um plano de importa??o E115 cadastrado usa este... */
      SELECT pla.BDCODPLAE115 FROM VEF_BASE_TPLAIMPE115 pla WHERE pla.BDCODPLAE115 = (SELECT e.BDCODPLAE115 FROM VW_VEF_BASE_TEMPPARINTEG e WHERE e.BDCODEMP = :wCODEMP)
                                                              and (pla.bdexecplano = 0) /*Nota a nota*/ INTO :wCODPLAE115;
      /* ...Caso contr?rio buscar o plano default */
      IF ((:wCODPLAE115 = 0) OR (:wCODPLAE115 IS NULL)) THEN
        SELECT pla.BDCODPLAE115 FROM VEF_BASE_TPLAIMPE115 pla WHERE pla.BDPLANODEFAULT = 'TRUE' INTO :wCODPLAE115;

      IF (:wCODPLAE115 > 0) THEN
        BEGIN
          /* Lan?amentos de ajuste do E115 na tabela tempor?ria */
          INSERT INTO TMP_VEF_EMP_TAJUICMSE115_TEMP (BDCODEMP, BDORDEME115, BDREFERENCIA, BDVLRINFADI, BDDESCINFADI, BDCODTIPO, BDORDEM52, BDCHAVESAI, BDORDEM, BDSESSAO, BDEDITCHAVE)
          SELECT mov.BDCODEMP,                                                                                                                                   -- BDCODEMP
                 (COALESCE((SELECT MAX(BDORDEME115)+1 FROM TMP_VEF_EMP_TAJUICMSE115_TEMP l WHERE l.BDCODEMP = mov.BDCODEMP),1)),                                 -- BDORDEME115
                 mov.BDREFLAN,                                                                                                                                   -- BDREFERENCIA
                 CASE WHEN (gia.BDCODCAMPOGIARS = 1) THEN i.BDVLRIPI        -- IPI
                      WHEN (gia.BDCODCAMPOGIARS = 2) THEN i.BDVLRST         -- Substitui??o tribut?ria
                      WHEN (gia.BDCODCAMPOGIARS = 3) THEN i.BDISENTASICMS   -- Isentas
                      WHEN (gia.BDCODCAMPOGIARS = 4) THEN i.BDOUTRASICMS    -- Outras
                      ELSE i.BDVLRCONTAB                                    -- Frete e Exclus?es                                                                 -- BDVLRINFADI
                 END,
                 SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||', documento '||mov.BDNUMDOCINI||' '||
                           SUBSTRING(acao.BDINFCOMP FROM 1 FOR (255-StrLen(SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||', documento '||mov.BDNUMDOCINI||' '))),          -- BDDESCINFADI
                 100,                                                                                                                                            -- BDCODTIPO
                 acao.BDORDEM52,                                                                                                                                 -- BDORDEM52
                 i.BDCHAVE,                                                                                                                                      -- BDCHAVESAI
                 i.BDORDEM,                                                                                                                                      -- BDORDEM
                 :prSESSAO,                                                                                                                                      -- BDSESSAO
                 (COALESCE((SELECT MAX(BDORDEME115)+1 FROM TMP_VEF_EMP_TAJUICMSE115_TEMP l WHERE l.BDCODEMP = mov.BDCODEMP),1))                                  -- BDEDITCHAVE
          FROM (
                 SELECT m.BDCODEMP, m.BDREFLAN, m.BDCHAVE, m.BDSESSAO, m.BDNUMDOCINI
                 FROM TMP_VEF_EMP_TMOVSAI_TEMP m
                 LEFT OUTER JOIN VEF_INCON_TMOVSAI inc ON (inc.BDCODEMP = m.BDCODEMP AND inc.BDCHAVE = m.BDCHAVE AND inc.BDSESSAO = m.BDSESSAO)
                 WHERE m.BDCODEMP = :wCODEMP
                   AND m.BDSESSAO = :prSESSAO
                   AND inc.BDCODINCONSISTENCIA IS NULL -- S? grava os lan?amento que n?o estejam inconsistentes...
                ) mov
          JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE AND i.BDSESSAO = mov.BDSESSAO)
          JOIN VW_EMPRESAS_REF_ATUAL ref ON (ref.BDCODEMP = mov.bdCODEMP)
          JOIN TCIDADE cid ON (cid.BDCODCID = ref.BDCODCID)
          JOIN TUF uf ON (uf.BDCODUF = cid.BDCODUF)
          JOIN VEF_BASE_TACOESIMPE115 acao ON (acao.BDCODPLAE115 = :wCODPLAE115 AND acao.BDCODNAT = i.BDCODNAT)
          LEFT OUTER JOIN VEF_BASE_TTABINFAD52 gia ON (gia.BDORDEM52 = acao.BDORDEM52)
          WHERE uf.BDCODUF  = 23 -- Apenas o estado de RS por enquanto...
            AND (((gia.BDCODCAMPOGIARS = 1) AND (i.BDVLRIPI > 0)) OR                                                -- IPI
                 ((gia.BDCODCAMPOGIARS = 2) AND (i.BDVLRST > 0)) OR                                                 -- Substitui??o tribut?ria
                 ((gia.BDCODCAMPOGIARS = 3) AND (i.BDISENTASICMS > 0)) OR                                           -- Isentas
                 ((gia.BDCODCAMPOGIARS = 4) AND (i.BDOUTRASICMS > 0)) OR                                            -- Outras
                 (((gia.BDCODCAMPOGIARS NOT IN (1, 2, 3, 4)) OR (gia.BDCODCAMPOGIARS IS NULL)) AND (i.BDVLRCONTAB > 0)))  -- Frete e Exclus?es
          ORDER BY mov.BDCODEMP, mov.BDCHAVE, i.BDORDEM;
        END
    END
END
^

/* Alter (SP_PRODEXISTENTES) */
ALTER PROCEDURE SP_PRODEXISTENTES(BDCODEMP INTEGER,
BDEAN VARCHAR(20),
BDCODTER INTEGER,
BDCODENTRADA VARCHAR(60),
BDDESCPRODBUSCA VARCHAR(200))
 RETURNS(CODPROD INTEGER,
ORDEMCADPART INTEGER,
CODSAIDA VARCHAR(60),
CODNCM INTEGER)
 AS
DECLARE VARIABLE WEAN13 VARCHAR(20);
DECLARE VARIABLE WTMP INTEGER;
DECLARE VARIABLE WPRIMVEZ INTEGER;
DECLARE VARIABLE WIGNORA INTEGER;
DECLARE VARIABLE WEAN VARCHAR(20);
DECLARE VARIABLE WDESCPRODBUSCA VARCHAR(200);
DECLARE VARIABLE WCODENTRADA VARCHAR(60);
DECLARE VARIABLE WACHOU INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WTMPORDEM INTEGER;
BEGIN
  CODPROD = 0;
  ordemcadpart = 0;
  codsaida = '';
  codncm = 0;

  --Metodo 1
  FOR SELECT BDCODPROD, BDCODENTRADA, BDDESCPRODBUSCA, bdORDEM
      FROM TCADPRO_PART
      WHERE
      BDCODTER=:BDCODTER AND BDCODENTRADA=:BDCODENTRADA
      ORDER BY BDCODPROD,BDORDEM
  INTO WCODTER, WCODENTRADA, WDESCPRODBUSCA, WTMPORDEM
  DO
  BEGIN
    IF (UPPER(WDESCPRODBUSCA) = UPPER(BDDESCPRODBUSCA)) THEN
    BEGIN
      CODPROD = wCODTER;
      BREAK;
    END
  END

  --Metodo2
  IF ((CODPROD = 0) AND (BDEAN <> '') AND (BDEAN <> '#')) THEN
  BEGIN
    --select BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODPROD from TCADPRO where
    wIgnora = 0;
    wPrimVez = 1;
    FOR SELECT cadpro.BDCODIGOEAN, part.BDCODTER, part.BDCODENTRADA, cadpro.BDDESCRICAOUNICA, cadpro.BDCODPROD, part.bdORDEM
    FROM TCADPRO CADPRO
    LEFT OUTER JOIN TCADPRO_PART part ON (part.bdcodprod = cadpro.bdcodprod)
    WHERE cadpro.BDCODIGOEAN=:BDEAN AND part.BDCODTER=:BDCODTER AND part.BDCODENTRADA=:BDCODENTRADA
    INTO :wean, :wcodter, :wcodentrada, :wdescprodbusca, :wTmp, :WTMPORDEM DO
    BEGIN
      IF (wPrimVez = 1) THEN
      BEGIN
        IF (UPPER(wdescprodbusca) <> UPPER(bddescprodbusca)) THEN
        BEGIN
          wIgnora = 1;
        END
      END

      IF (wIgnora = 0) THEN --not wIgnora
      BEGIN
        IF (UPPER(wdescprodbusca) = UPPER(bddescprodbusca)) THEN
        BEGIN
          CODPROD = wTmp;
          BREAK;
        END
      END

      wIgnora = 0;
      wPrimVez = 0;
    END
  END

  IF (codprod > 0) THEN
    ordemcadpart = :wtmpordem;

  --feito o ean ser o terceiro metodo de pesquisa (GetEAN)
  IF ((CODPROD = 0) AND (BDEAN <> '') AND (BDEAN <> '#')) THEN
  BEGIN
    IF ((CHARACTER_LENGTH(BDEAN) = 14) AND (SUBSTRING(bdean FROM 1 FOR 1) = '0')) THEN
       wEAN13 = SUBSTRING(bdean FROM 2 FOR 13);
     ELSE
       wEAN13 = BDEAN;

     wIgnora = 0;
     FOR SELECT BDCODPROD, BDCODIGOEAN, BDDESCRICAOUNICA FROM TCADPRO WHERE BDCODIGOEAN = :wEAN13
     INTO :wTMP, :wEAN, :WDESCPRODBUSCA DO
     BEGIN
       CODPROD = :wTMP;
       IF (UPPER(wdescprodbusca) = UPPER(bddescprodbusca)) THEN
         wIgnora = 1;

       IF (wIgnora = 0) THEN --not wIgnora
       BEGIN
         IF (UPPER(wdescprodbusca) = UPPER(bddescprodbusca)) THEN
         BEGIN
           CODPROD = :wTMP;
           BREAK;
         END
       END

       wIgnora = 0;
     END

     --if FDAOCadPart.DAOProdutosExistentes.SearchKey(['BDCODTER', 'BDCODENTRADA','BDDESCPRODBUSCA'], [FCodTer, FCodProdLay, FDescProdLay]) then //alt.:9666
     FOR SELECT CADPRO.BDDESCRICAOUNICA, part.BDORDEM
     FROM TCADPRO_PART part
     LEFT OUTER JOIN TCADPRO CADPRO ON (part.bdcodprod = cadpro.bdcodprod)
     WHERE BDCODTER=:BDCODTER AND BDCODENTRADA=:BDCODENTRADA AND BDDESCPRODBUSCA = :BDDESCPRODBUSCA
     INTO :wDESCPRODBUSCA, :wTmpOrdem DO
     BEGIN
       ordemcadpart = :wTmpOrdem;
       IF (UPPER(wDESCPRODBUSCA) = UPPER(BDDESCPRODBUSCA)) THEN
       BEGIN
         BREAK;
       END
     END
  END

  --met?do 3
  IF ((CODPROD = 0)) THEN
  BEGIN
    --Procura pela descricao naquela empresa
--    select first 1 coalesce(CADPRO.bdcodprod, 0)
--    from TCADPRO CADPRO
--    left outer join TCADPRO_VINC VINC on (vinc.bdcodprod = cadpro.bdcodprod and vinc.bdcodemp = :BDCODEMP)
--    where (CADPRO.BDDESCRICAOUNICA collate WIN1252) = :bddescprodbusca into :CODPROD;
    SELECT FIRST 1 COALESCE(CADPRO.bdcodprod, 0)
    FROM (
          SELECT *
          FROM TCADPRO
          WHERE BDDESCRICAOUNICA = :bddescprodbusca
          )CADPRO
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (vinc.bdcodprod = cadpro.bdcodprod AND vinc.bdcodemp = :BDCODEMP)
    INTO :CODPROD;
  --alt:14920 - Elizeu - 27/06/16 - criado op??o pra n?o carregar os dados cadastrais dos produtos na mem?ria

    --Se nao achar procura unicamente pela descricao
    IF (CODPROD = 0) THEN
    BEGIN
      SELECT FIRST 1 CADPRO.bdcodprod
      FROM TCADPRO CADPRO
      WHERE CADPRO.BDDESCRICAOUNICA  = :bddescprodbusca INTO :CODPROD;
    END
  END

  IF (CODPROD > 0) THEN
  BEGIN
    SELECT bdCODSAIDA, bdNCMPROD FROM TCADPRO_VINC WHERE bdcodemp=:BDCODEMP AND bdcodprod = :codprod INTO :codsaida, :codNCM;
  END

  SUSPEND;
END
^

/* Alter (SP_PRODEXISTENTES_SAIDA) */
ALTER PROCEDURE SP_PRODEXISTENTES_SAIDA(BDCODEMP INTEGER,
BDEAN VARCHAR(20),
BDCODSAIDA VARCHAR(60),
BDDESCPRODBUSCA VARCHAR(200))
 RETURNS(CODPROD INTEGER,
CODSAIDA VARCHAR(60),
CODNCM INTEGER)
 AS
DECLARE VARIABLE WTMP INTEGER;
DECLARE VARIABLE WPRIMVEZ INTEGER;
DECLARE VARIABLE WIGNORA INTEGER;
DECLARE VARIABLE WEAN VARCHAR(20);
DECLARE VARIABLE WDESCPRODBUSCA VARCHAR(200);
BEGIN
  CODPROD = 0;
  codsaida = '';
  codncm = 0;


  --alt:14920 - Elizeu - 27/06/16 - criado op??o pra n?o carregar os dados cadastrais dos produtos na mem?ria
  --Metodo 1 direto o codigo de sa?da
  SELECT FIRST 1 v.bdcodprod,v.bdcodsaida,v.bdncmprod FROM tcadpro_vinc v WHERE V.BDCODEMP = :bdcodemp AND v.bdcodsaida = :BDCODSAIDA
  INTO :CODPROD ,:CODSAIDA ,:CODNCM;


  --Metodo2 por ncm
  IF ((CODPROD = 0) AND (BDEAN <> '') AND (BDEAN <> '#')) THEN
  BEGIN
    --select BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODPROD from TCADPRO where
    wIgnora = 0;
    wPrimVez = 1;
    FOR SELECT cadpro.BDCODIGOEAN, cadpro.BDDESCRICAOUNICA, cadpro.BDCODPROD
    FROM TCADPRO CADPRO
    WHERE cadpro.BDCODIGOEAN=:BDEAN
    INTO :wean, :wdescprodbusca, :wTmp DO
    BEGIN
      IF (wPrimVez = 1) THEN
      BEGIN
        IF (UPPER(wdescprodbusca) <> UPPER(bddescprodbusca)) THEN
        BEGIN
          wIgnora = 1;
        END
      END

      IF (wIgnora = 0) THEN --not wIgnora
      BEGIN
        IF (UPPER(wdescprodbusca) = UPPER(bddescprodbusca)) THEN
        BEGIN
          CODPROD = wTmp;
          BREAK;
        END
      END

      wIgnora = 0;
      wPrimVez = 0;
    END
  END


--met?do 3
  IF ((CODPROD = 0)) THEN
  BEGIN
    --Procura pela descricao naquela empresa

    SELECT FIRST 1 COALESCE(CADPRO.bdcodprod, 0)
    FROM (
          SELECT bdcodprod
          FROM TCADPRO
          WHERE BDDESCRICAOUNICA  = :bddescprodbusca
          ) CADPRO
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (vinc.bdcodprod = cadpro.bdcodprod AND vinc.bdcodemp = :BDCODEMP)
    INTO :CODPROD;

    --Se nao achar procura unicamente pela descricao
    IF (CODPROD = 0) THEN
    BEGIN
      SELECT FIRST 1 CADPRO.bdcodprod
      FROM TCADPRO CADPRO
      WHERE CADPRO.BDDESCRICAOUNICA  = :bddescprodbusca
      INTO :CODPROD;
    END
  END


  IF (CODPROD > 0) THEN
  BEGIN
    SELECT bdCODSAIDA, bdNCMPROD FROM TCADPRO_VINC WHERE bdcodemp=:BDCODEMP AND bdcodprod = :codprod INTO :codsaida, :codNCM;
  END


  SUSPEND;

END
^

/* Alter (SP_QUADRO_INTERMITENTE_CONTRATO) */
ALTER PROCEDURE SP_QUADRO_INTERMITENTE_CONTRATO(PREMPRESA INTEGER NOT NULL,
PRCOLABORADOR INTEGER NOT NULL,
PRCONTRATO INTEGER NOT NULL)
 RETURNS(QUADRO VARCHAR(1000))
 AS
declare variable SQL varchar(345);
declare variable EMPRESA integer;
declare variable COLABORADOR integer;
declare variable QUADROREGISTRO varchar(100);
declare variable WAUXBDDESQHH varchar(50);
declare variable WAUXBDCODQHH integer;
declare variable WAUXBDDATADTI date;
declare variable QUADROFINAL varchar(1000);
declare variable CONTRATO integer;
begin
  /*Passo os par?metros de entrada para as respectivas vari?veis*/
  CONTRATO    = PRCONTRATO;
  EMPRESA     = PREMPRESA;
  COLABORADOR = PRCOLABORADOR;
  QUADROFINAL = '';


  /*SQL que busca os quadros de hor?rios informados no contrato*/
  SQL = ' SELECT'||
        ' QH_INTERM.BDDATADTI,'||
        ' QH_INTERM.BDCODQHH,'||
        ' QH.bddesqhh'||
        ' FROM VRH_EMP_TINTERMITENTE_QHDIAS QH_INTERM'||
        ' LEFT JOIN VRH_BASE_TQH_HORARIO QH ON (QH_INTERM.BDCODQHH = QH.BDCODQHH)'||
        ' WHERE'||
        ' QH_INTERM.BDCODEMP = '   || CAST(EMPRESA AS VARCHAR(10))    ||' AND '||
        ' QH_INTERM.BDCODCOL = '   || CAST(COLABORADOR AS VARCHAR(10))||' AND '||
        ' QH_INTERM.BDCODCONTTI = '|| CAST(CONTRATO AS VARCHAR(10));

  FOR EXECUTE STATEMENT SQL INTO
    :WAUXBDDATADTI,
    :WAUXBDCODQHH,
    :WAUXBDDESQHH
  DO
    BEGIN
        IF (WAUXBDCODQHH IS NOT NULL) THEN
            BEGIN
                /*Se salvou o quadro de hor?rio*/
                EXECUTE PROCEDURE ddmmaaaa(WAUXBDDATADTI) returning_values :QUADROREGISTRO;
                QUADROREGISTRO =  QUADROREGISTRO ||' - '||WAUXBDDESQHH;
           END
        ELSE
            BEGIN
                /*Se n?o estiver com o link de registro para o quadro de hor?rio*/
                EXECUTE PROCEDURE ddmmaaaa(WAUXBDDATADTI) returning_values :QUADROREGISTRO ;
                QUADROREGISTRO = QUADROREGISTRO ||' - '||'Quadro n?o informado para est? data';
            END

        /*Passa o quadro de hor?rio encontrado no registro para o quadro de hor?rio final*/
        QUADROFINAL = QUADROFINAL || QUADROREGISTRO||ascii_char(13);
    END

    /*Passa valor de retorno e suspende a fun??o*/
    QUADRO = QUADROFINAL;
    SUSPEND;

end
^

/* Alter (SP_REL_CONSULTA_CONFIGURAVEL) */
ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL(PRCOLUNAS INTEGER,
PRMATRIZ INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDCODMATRIZ INTEGER,
BDQUEBRAQUADRO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WMES CHAR(2);
DECLARE VARIABLE WANO CHAR(4);
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WREF INTEGER;
BEGIN
  /*
    #6566:
    modifica??o para aceitar mais de 8 colunas no relat?rio
  */

  /* giovanni */

  /* Procedure Text */

--  wsql = 'select bdcodemp, bdref, bdcodqplaconsconf,  bdvalor from VEF_REL_CONS_ANUAL_CONF where bdordem < 9 order by bdcodemp, bdref , bdcodplaconsconf, bdcodqplaconsconf, bdordem ';


  /* prmatriz > 0 quer dizer que esta detalhando matriz e filial e o conteudo e o da matriz*/

  IF (prmatriz IS NULL) THEN
     prmatriz = 0;


  wsql = 'select bdcodemp, bdref, bdcodqplaconsconf,  bdvalor, bdcodmatriz from VEF_REL_CONS_ANUAL_CONF order by bdcodemp, bdref , bdcodplaconsconf, bdcodqplaconsconf, bdordem ';

  --#6566
  --if (prcolunas > 8) then
  --   prcolunas = 8;

  windice = 1;
  bdquebraquadro = 0;
  wemp = 0;
  wref = 0;

  bdcol01 = NULL;
  bdcol02 = NULL;
  bdcol03 = NULL;
  bdcol04 = NULL;
  bdcol05 = NULL;
  bdcol06 = NULL;
  bdcol07 = NULL;
  bdcol08 = NULL;


  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdref,
    wcodquadro,
    wvalor,
    bdcodmatriz
  DO
   BEGIN

    --#6566, se mudou de empresa precisa voltar o indice para 1, e a quebra de quadros para 0
    IF ((wemp <> bdcodemp) OR (wref <> bdref)) THEN
      BEGIN
        wemp = :bdcodemp;
        wref = :bdref;
        windice = 1;
        bdquebraquadro = 0;
      END

    IF (prmatriz > 0) THEN
       bdcodemp = prmatriz;

    wano = SUBSTRING(bdref FROM 1 FOR 4);
    wmes = SUBSTRING(bdref FROM 5 FOR 2);

    IF  (windice <= prcolunas)  THEN
      BEGIN

        IF (windice = 1 + (bdquebraquadro * 8)) THEN
           bdcol01 = wvalor;
        ELSE
        IF (windice = 2 + (bdquebraquadro * 8)) THEN
           bdcol02 = wvalor;
        ELSE
        IF (windice = 3 + (bdquebraquadro * 8)) THEN
           bdcol03 = wvalor;
        ELSE
        IF (windice = 4 + (bdquebraquadro * 8)) THEN
           bdcol04 = wvalor;
        ELSE
        IF (windice = 5 + (bdquebraquadro * 8)) THEN
           bdcol05 = wvalor;
        ELSE
        IF (windice = 6 + (bdquebraquadro * 8)) THEN
           bdcol06 = wvalor;
        ELSE
        IF (windice = 7 + (bdquebraquadro * 8)) THEN
           bdcol07 = wvalor;
        ELSE
        IF (windice = 8 + (bdquebraquadro * 8)) THEN
           bdcol08 = wvalor;
      END

    --#6566
--    if  (windice = prcolunas)  then
    IF  ((MOD(windice, 8) = 0) OR (windice = prcolunas)) THEN
      BEGIN
        IF (wmes = '01') THEN
           bdmesextenso =  'Janeiro / ' || wano;
        ELSE
        IF (wmes = '02') THEN
           bdmesextenso =  'Fevereiro / ' || wano;
        ELSE
        IF (wmes = '03') THEN
           bdmesextenso =  'Mar?o / ' || wano;
        ELSE
        IF (wmes = '04') THEN
           bdmesextenso =  'Abril / ' || wano;
        ELSE
        IF (wmes = '05') THEN
           bdmesextenso =  'Maio / ' || wano;
        ELSE
        IF (wmes = '06') THEN
           bdmesextenso =  'Junho / ' || wano;
        ELSE
        IF (wmes = '07') THEN
           bdmesextenso =  'Julho / ' || wano;
        ELSE
        IF (wmes = '08') THEN
           bdmesextenso =  'Agosto / ' || wano;
        ELSE
        IF (wmes = '09') THEN
           bdmesextenso =  'Setembro / ' || wano;
        ELSE
        IF (wmes = '10') THEN
           bdmesextenso =  'Outubro / ' || wano;
        ELSE
        IF (wmes = '11') THEN
           bdmesextenso =  'Novembro / ' || wano;
        ELSE
        IF (wmes = '12') THEN
           bdmesextenso =  'Dezembro / ' || wano;

        SUSPEND;
--        windice = 1; #6566
        windice = windice + 1;
        bdquebraquadro = ((windice - 1) / 8);

        bdcol01 = NULL;
        bdcol02 = NULL;
        bdcol03 = NULL;
        bdcol04 = NULL;
        bdcol05 = NULL;
        bdcol06 = NULL;
        bdcol07 = NULL;
        bdcol08 = NULL;
      END
     ELSE
       windice = windice + 1;
   END
END
^

/* Alter (SP_REL_CONSULTA_CONFIGURAVEL2) */
ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL2 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDCODPLANO INTEGER,
BDCODQUADRO INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDLINHA INTEGER,
BDTITULOS VARCHAR(640))
 AS
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wcolunaatual INTEGER;
DECLARE VARIABLE wmes CHAR(2);
DECLARE VARIABLE wano CHAR(4);
DECLARE VARIABLE windice INTEGER;
DECLARE VARIABLE wnumcolunas INTEGER;
DECLARE VARIABLE wnumlinhas INTEGER;
DECLARE VARIABLE wlinhaatual INTEGER;
DECLARE VARIABLE wdescricao VARCHAR(80);
BEGIN
  /*
    #6566:
    modifica??o para aceitar mais de 8 colunas no relat?rio
  */
  bdcol01 = NULL;
  bdcol02 = NULL;
  bdcol03 = NULL;
  bdcol04 = NULL;
  bdcol05 = NULL;
  bdcol06 = NULL;
  bdcol07 = NULL;
  bdcol08 = NULL;
  bdtitulos = '';

  FOR SELECT c.bdcodmatriz,c.bdcodemp,c.bdcodplaconsconf,c.bdcodqplaconsconf,
             c.bdref,COUNT(c.bdordem) AS "BDNUMCOLUNAS"
      FROM vef_rel_cons_anual_conf c
      INNER JOIN tempresas e ON e.bdcodemp = c.bdcodemp
      GROUP BY bdcodmatriz, c.bdcodemp, c.bdcodplaconsconf, c.bdcodqplaconsconf, c.bdref
      ORDER BY bdcodmatriz, c.bdcodemp, c.bdcodplaconsconf, c.bdcodqplaconsconf, c.bdref
  INTO
    :bdcodmatriz,
    :bdcodemp,
    :bdcodplano,
    :bdcodquadro,
    :bdref, 
    :wnumcolunas
  DO
    BEGIN
      wano = SUBSTRING(:bdref FROM 1 FOR 4);
      wmes = SUBSTRING(:bdref FROM 5 FOR 2);
      SELECT FIRST 1 bdanomes FROM sp_retorna_mesano_extenso(:wmes, :wano,  '/') INTO :bdmesextenso;

      --N?mero de linhas para cada quadro (n?mero de formulas no quadro / 8) arredondado para cima
      wNumLinhas = CEIL((CAST(:wnumcolunas AS NUMERIC(15,2))/CAST(8 AS NUMERIC(15,2))));
      wColunaAtual = 1;
      wIndice = 0;
      wLinhaAtual = 0;

      WHILE (:wLinhaAtual < wNumLinhas) DO
        BEGIN                                                   --TCONFCONSFORM.BDDESCRICAO ? um varchar(80), garante que vai ter no m?ximo 80 caracteres a descri??o
          FOR SELECT FIRST 8 SKIP (:wLinhaAtual * 8) f.bdvalor, LEFT(f.bddescricao, 80) AS "BDDESCRICAO"
              FROM vef_rel_cons_anual_conf f
              WHERE f.bdcodmatriz       = :bdcodmatriz AND
                    f.bdcodemp          = :bdcodemp AND
                    f.bdcodplaconsconf  = :bdcodplano AND
                    f.bdcodqplaconsconf = :bdcodquadro AND
                    f.bdref             = :bdref
              ORDER BY f.bdordem
          INTO
            :wvalor,
            :wdescricao
          DO
            BEGIN
              wIndice = :wIndice + 1;
    
              IF (:wColunaAtual = 1) THEN
                bdcol01 = :wvalor;
              ELSE IF (:wColunaAtual = 2) THEN
                bdcol02 = :wvalor;
              ELSE IF (:wColunaAtual = 3) THEN
                bdcol03 = :wvalor;
              ELSE IF (:wColunaAtual = 4) THEN
                bdcol04 = :wvalor;
              ELSE IF (:wColunaAtual = 5) THEN
                bdcol05 = :wvalor;
              ELSE IF (:wColunaAtual = 6) THEN
                bdcol06 = :wvalor;
              ELSE IF (:wColunaAtual = 7) THEN
                bdcol07 = :wvalor;
              ELSE IF (:wColunaAtual = 8) THEN
                bdcol08 = :wvalor;

              bdtitulos = :bdtitulos || LPAD(:wdescricao, 80);

              IF ((MOD(:wColunaAtual, 8) = 0) OR (:wIndice = :wnumcolunas)) THEN
                BEGIN
                  bdlinha = :wlinhaatual;
                  bdtitulos = RPAD(:bdtitulos, 640);
                  SUSPEND;
    
                  wColunaAtual = 1;
                  bdcol01 = NULL;
                  bdcol02 = NULL;
                  bdcol03 = NULL;
                  bdcol04 = NULL;
                  bdcol05 = NULL;
                  bdcol06 = NULL;
                  bdcol07 = NULL;
                  bdcol08 = NULL;
                  bdtitulos = '';
                END
              ELSE
                wColunaAtual = :wColunaAtual + 1;
            END
          wLinhaAtual = :wLinhaAtual + 1;
        END
    END
END
^

/* Alter (SP_REL_RESUMO_IMPOSTOS) */
ALTER PROCEDURE SP_REL_RESUMO_IMPOSTOS(PRCODEMP VARCHAR(10000),
PRCODIMP VARCHAR(10000),
PRCODSIS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRDTVCTOINI DATE,
PRDTVCTOFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(200),
BDCODREC INTEGER,
BDCODSIS INTEGER,
BDCODPERIODO INTEGER,
BDDESCPERIODO VARCHAR(40),
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDMESEXTENSO VARCHAR(20),
BDQUOTA INTEGER,
BDCODCOL INTEGER,
BDCODEMPCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDPERIODO DATE,
BDNUMREFDOC VARCHAR(20),
BDDATAVCTO DATE,
BDVALOR NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDJUROS NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDOBS BLOB,
BDORDEMCOMPL INTEGER,
BDBASEIMP NUMERIC(15,6),
BDALIQIMP NUMERIC(15,6),
BDVLRIMPORIGINAL NUMERIC(15,6),
BDVLRACUMULO NUMERIC(15,6),
BDVLRMULTAJUROS NUMERIC(15,6),
BDVLROUTENTIDADE NUMERIC(15,6),
BDTIPOIMPOSTO INTEGER,
BDCOMPENSACAO NUMERIC(15,6),
BDVLRACUOUTENT NUMERIC(15,6),
BDREFPAG INTEGER,
BDDTPGTO DATE)
 AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WMES CHAR(10);
DECLARE VARIABLE WANO CHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wSql = 'select DARF.BDCODEMP, ';
  wSql = wSql || 'DARF.BDCODIMP, ';
  wSql = wSql || 'IMP.BDDESCIMP, ';
  wSql = wSql || 'IMP.BDCODREC, ';
  wSql = wSql || 'IMP.BDCODSIS, ';
  wSql = wSql || 'DARF.BDCODPERIODO, ';
  wSql = wSql || 'periodo.bddescricao, ';
  wSql = wSql || 'DARF.BDREFERENCIA, ';
  wSql = wSql || 'DARF.BDQUOTA, ';
  wSql = wSql || 'DARF.BDDATAVCTO , ';

  wSql = wSql || 'DARF.BDBASEIMP , ';
  wSql = wSql || 'DARF.BDALIQIMP , ';
  wSql = wSql || 'DARF.BDVLRIMPORIGINAL , ';
  wSql = wSql || 'DARF.BDVALOR , ';
  wSql = wSql || 'DARF.BDMULTA , ';
  wSql = wSql || 'DARF.BDJUROS , ';
  wSql = wSql || 'DARF.BDTOTAL , ';
  wSql = wSql || 'DARF.BDOBS , ';
  wSql = wSql || 'DARF.BDORDEMCOMPL , ';
  wSql = wSql || 'DARF.BDVLRMULTAJUROS , ';
  wSql = wSql || 'DARF.BDVLROUTENTIDADE, ';
  wSql = wSql || 'DARF.BDORDEM, ';
  wSql = wSql || 'DARF.BDCHAVEDARF ';

  wsql = wsql || 'from tdarfpadrao DARF , timposto IMP , ttiposperiodo periodo, VW_EMPRESAS_REF_ATUAL emp ';

  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wWhere||PRCODEMP||' ';

  IF ((prcodimp IS NOT NULL) OR (prcodimp > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||prcodimp||' ';
     END

  IF ((prcodsis IS NOT NULL) OR (prcodsis > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||prcodsis||' ';
     END

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.BDREFERENCIA >= '||prrefini||' ';
     END

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.BDREFERENCIA <= '||prreffin||' ';
     END

  IF (prdtvctoini IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.bddatavcto >= '||''''||prdtvctoini||'''';
     END

  IF (prdtvctofim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.bddatavcto <= '||''''||prdtvctofim||'''';
     END

  IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

  wwhere = wwhere||' and (imp.bdcodimp = darf.bdcodimp) and (emp.bdcodemp = darf.bdcodemp) and (darf.bdcodperiodo = periodo.bdcodperiodo)';

  wgroupby = '';
  worderby = 'order by DARF.BDCODIMP, DARF.BDORDEM, DARF.bdreferencia, DARF.BDCODPERIODO';

  wsql = wsql||wwhere||wgroupby||worderby;

  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodemp,
      :BDCODIMP,
      :BDDESCIMP,
      :bdcodrec,
      :bdcodsis,
      :BDCODPERIODO,
      :bddescperiodo,
      :BDREFERENCIA,
      :BDQUOTA,
      :BDDATAVCTO ,
      :BDBASEIMP ,
      :BDALIQIMP ,
      :BDVLRIMPORIGINAL ,
      :BDVALOR ,
      :BDMULTA ,
      :BDJUROS ,
      :BDTOTAL ,
      :BDOBS ,
      :BDORDEMCOMPL ,
      :BDVLRMULTAJUROS ,
      :BDVLROUTENTIDADE,
      :BDORDEM,
      :BDCHAVEDARF  DO
      BEGIN


    wano = SUBSTRING(bdreferencia FROM 1 FOR 4);
    wmes = SUBSTRING(bdreferencia FROM 5 FOR 2);

    IF (wmes = '01') THEN
       bdmesextenso =  'Janeiro / ' || wano;
    IF (wmes = '02') THEN
       bdmesextenso =  'Fevereiro / ' || wano;
    IF (wmes = '03') THEN
       bdmesextenso =  'Mar?o / ' || wano;
    IF (wmes = '04') THEN
       bdmesextenso =  'Abril / ' || wano;
    IF (wmes = '05') THEN
       bdmesextenso =  'Maio / ' || wano;
    IF (wmes = '06') THEN
       bdmesextenso =  'Junho / ' || wano;
    IF (wmes = '07') THEN
       bdmesextenso =  'Julho / ' || wano;
    IF (wmes = '08') THEN
       bdmesextenso =  'Agosto / ' || wano;
    IF (wmes = '09') THEN
       bdmesextenso =  'Setembro / ' || wano;
    IF (wmes = '10') THEN
       bdmesextenso =  'Outubro / ' || wano;
    IF (wmes = '11') THEN
       bdmesextenso =  'Novembro / ' || wano;
    IF (wmes = '12') THEN
       bdmesextenso =  'Dezembro / ' || wano;


        SELECT MAX(pgto.bddatapgto) FROM tdarfgerpgto pgto
               WHERE (PGTO.bdcodemp = :bdcodemp AND PGTO.BDCHAVEDARF = :BDCHAVEDARF) INTO :BDDTPGTO;

        SUSPEND;
      END
END
^

/* Alter (SP_RELDEMRECDESP) */
ALTER PROCEDURE SP_RELDEMRECDESP(PRCODESC VARCHAR(500),
PRTIPODEM INTEGER,
PRDATAINICIAL VARCHAR(10),
PRDATAFINAL VARCHAR(10),
PRCHAVECTABAN VARCHAR(500),
PRCODOBRSER VARCHAR(10240),
PRCODDESP VARCHAR(10240),
PRNIVEL INTEGER,
PRTIPORECDESP INTEGER,
PRDEMLANCREEMBOLSO DM_BOOLEAN)
 RETURNS(BDCODSERDESP INTEGER,
BDCLASSIFICACAO VARCHAR(60),
BDDESCRICAO VARCHAR(100),
BDTIPO INTEGER,
BDPERIODO01 VARCHAR(12),
BDVLRPERIODO01 NUMERIC(15,2),
BDPERIODO02 VARCHAR(12),
BDVLRPERIODO02 NUMERIC(15,2),
BDPERIODO03 VARCHAR(12),
BDVLRPERIODO03 NUMERIC(15,2),
BDPERIODO04 VARCHAR(12),
BDVLRPERIODO04 NUMERIC(15,2),
BDPERIODO05 VARCHAR(12),
BDVLRPERIODO05 NUMERIC(15,2),
BDPERIODO06 VARCHAR(12),
BDVLRPERIODO06 NUMERIC(15,2),
BDPERIODO07 VARCHAR(12),
BDVLRPERIODO07 NUMERIC(15,2),
BDPERIODO08 VARCHAR(12),
BDVLRPERIODO08 NUMERIC(15,2),
BDPERIODO09 VARCHAR(12),
BDVLRPERIODO09 NUMERIC(15,2),
BDPERIODO10 VARCHAR(12),
BDVLRPERIODO10 NUMERIC(15,2),
BDPERIODO11 VARCHAR(12),
BDVLRPERIODO11 NUMERIC(15,2),
BDPERIODO12 VARCHAR(12),
BDVLRPERIODO12 NUMERIC(15,2),
BDVLRTOTPERIODO NUMERIC(15,2))
 AS
declare variable VULTDIAMES integer;
declare variable VPERIODOFINAL varchar(10);
declare variable VPERIODOINICIAL varchar(10);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSERDESP varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODSERDESP integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
begin
  vguardaserdesp = '';
  vclassaux = '';
  vcodserdespaux = 0;
  vsql = '';
  vsqlserdesp = '';
  vultdiames = 0;
  vnumperiodo = 0;
  vperiodoinicial = '';
  vperiodofinal = '';

  vperiodo01 = '';
  vvlrperiodo01 = 0;
  vperiodo02 = '';
  vvlrperiodo02 = 0;
  vperiodo03 = '';
  vvlrperiodo03 = 0;
  vperiodo04 = '';
  vvlrperiodo04 = 0;
  vperiodo05 = '';
  vvlrperiodo05 = 0;
  vperiodo06 = '';
  vvlrperiodo06 = 0;
  vperiodo07 = '';
  vvlrperiodo07 = 0;
  vperiodo08 = '';
  vvlrperiodo08 = 0;
  vperiodo09 = '';
  vvlrperiodo09 = 0;
  vperiodo10 = '';
  vvlrperiodo10 = 0;
  vperiodo11 = '';
  vvlrperiodo11 = 0;
  vperiodo12 = '';
  vvlrperiodo12 = 0;
  DELETE FROM TMP_DEMRECDESP_ANALITICAS;

  IF (prtiporecdesp = 0) THEN -- Servi?os
     BEGIN
       /* Antes de tudo, obter os servi?os selecionados de acordo com as op??es "t?tulos" e "anal?ticas".
       prnivel = 0: apenas a op??o "t?tulos" est? checada.
       prnivel = 1: apenas a op??o "anal?ticas" est? checada.
       prnivel = 2: ambas op??es est?o checadas. */

       IF (prnivel = 0) THEN
          BEGIN
            vsqlserdesp = 'select s.bdcodobrser, s.bdclassificacao, s.bddescricao, s.bdtipo ';
            vsqlserdesp = vsqlserdesp || 'from (';
            vsqlserdesp = vsqlserdesp || '       select bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
            vsqlserdesp = vsqlserdesp || '       from vct_base_servico ';

            IF (:prcodobrser <> '') THEN
                vsqlserdesp = vsqlserdesp || 'where bdcodobrser in ('||:prcodobrser||') ';

            vsqlserdesp = vsqlserdesp || '      ) ser ';
            vsqlserdesp = vsqlserdesp || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'') ';

            /* Se prnivel = 0 ent?o apenas a op??o "t?tulo" est? selecionada. Neste caso
            iremos trazer tamb?m as anal?ticas para que seja feito o c?lculo dos per?odos.
            Posteriormente apenas exibimos as t?tulos no relat?rio. */

            vsqlserdesp = vsqlserdesp || 'group by bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
            vsqlserdesp = vsqlserdesp || 'order by bdclassificacao ';
          END
       ELSE
         IF (prnivel = 1) THEN
            BEGIN
              /* Se apenas a op??o "anal?ticas" est? selecionada, ent?o basta
              trazer as pr?prias anal?ticas selecionadas. */
              vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
              vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
              vsqlserdesp = vsqlserdesp || 'where ser.bdtipo = 1';
      
              IF (:prcodobrser <> '') THEN
                 vsqlserdesp = vsqlserdesp || 'and ser.bdcodobrser in ('||:prcodobrser||') ';

              vsqlserdesp = vsqlserdesp || 'order by bdclassificacao ';
            END
         ELSE -- Ent?o possui t?tulos e anal?ticas selecionadas
           IF (prnivel = 2) THEN
              BEGIN
                if (prcodobrser = '') then
                   begin
                     vguardaserdesp = '';
                     vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                     vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
                     vsqlserdesp = vsqlserdesp || 'order by bdclassificacao';
                   end
                else
                   begin
                    /* Se t?tulos e anal?ticas foram selecionadas, dever? trazer as anal?ticas das t?tulos
                    que est?o selecionadas e tamb?m dever? trazer as t?tulos das anal?ticas que foram selecionadas.*/
        
                    -- Primeiramente pegar as t?tulos que foram selecionadas
                    vsql = 'select list(ser.bdcodobrser) from vct_base_servico ser ';
                    vsql = vsql || 'where ser.bdtipo = 0 ';
    
                    IF (:prcodobrser <> '') THEN
                       vsql = vsql || 'and ser.bdcodobrser in ('||:prcodobrser||') ';
                    EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
        
                    IF (vguardaserdesp IS NOT NULL) THEN
                       BEGIN
                         -- Em seguida, obter as anal?ticas destas t?tulos e guardar em vguardaservicos.
                         vsql = 'select s.bdcodobrser, s.bdclassificacao ';
                         vsql = vsql || 'from (';
                         vsql = vsql || '       select bdcodobrser, bdclassificacao, bddescricao ';
                         vsql = vsql || '       from vct_base_servico ';
                         vsql = vsql || '       where bdcodobrser in('||:vguardaserdesp||') ';
                         vsql = vsql || '      ) ser ';
                         vsql = vsql || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'')';
                  
                         vguardaserdesp = '';
        
                         FOR
                         EXECUTE STATEMENT :vsql
                         INTO
                         :vcodserdesp,
                         :vclassserdesp
                         DO
                         BEGIN
                           vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                         END
                       END
                    ELSE
                      vguardaserdesp = '';
    
    
                    -- Obtendo somente as anal?ticas selecionadas
                    vsql = 'select ser.bdcodobrser, ser.bdclassificacao ';
                    vsql = vsql || 'from (';
                    vsql = vsql || 'select bdcodobrser, bdclassificacao ';
                    vsql = vsql || 'from vct_base_servico ';
                    vsql = vsql || 'where bdtipo = 1 ';
    
                    IF (:prcodobrser <> '') THEN
                    vsql = vsql || 'and bdcodobrser in ('||:prcodobrser||') ';
    
                    vsql = vsql || ') ser ';
              
                    FOR
                    EXECUTE STATEMENT :vsql
                    INTO
                    :vcodserdesp,
                    :vclassserdesp
                    DO
                    BEGIN
                      vstop = 'FALSE';
                      vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                      vclassaux = :vclassserdesp;
          
                      /* A implementa??o abaixo vai removendo sempre o ?ltimo n?vel da classifica??o
                      para obter todas as t?tulos que compoem a anal?tica, e vai guardando o c?digo
                      de cada t?tulo na vari?vel vguardaserdesp. */
                      WHILE (UPPER(:vstop) = 'FALSE') DO
                        BEGIN
                          SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
    
                          IF (vposicaoponto > 0) THEN
                             BEGIN
                               SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classifica??o
                               SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a invers?o seria o ?ltimo ponto)
                               SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                               SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente

                               SELECT COALESCE(bdcodobrser,0) FROM vct_base_servico WHERE bdclassificacao = :vclassaux INTO :vcodserdespaux;
    
                               IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                  vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                             END
                          ELSE
                            BEGIN
                              vstop = 'TRUE';
                            END
                        END
                    END
                    vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
        
                    -- Por fim, junta todos os servi?os relacionados em um sql.
                    vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                    vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
                    vsqlserdesp = vsqlserdesp || 'where ser.bdcodobrser in ('||:vguardaserdesp||') ';
                    vsqlserdesp = vsqlserdesp || 'order by bdclassificacao';
                 end
              END


       -- Depois de ter obtido todos os servi?os, trazer apenas os que possuem rela??o com os lan?amentos financeiros.

       if (:vguardaserdesp <> '') then
          begin
             vguardaserdesp = '';
             vsql = 'select list(ser.bdcodobrser) from ('||:vsqlserdesp||') ser where ser.bdtipo = 1';
             EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
          end

       vsql = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bddesconto ';
       vsql = vsql || 'from vct_base_servico ser ';
       vsql = vsql || 'where exists ';
       vsql = vsql || ' (';
       vsql = vsql || '    select bdcodobrser from vfin_esc_tlancbancario lan ';
       vsql = vsql || '    where (lan.bdcodobrser = ser.bdcodobrser) ';
       vsql = vsql || '    and lan.bdtiposervdesp = 0 ';
       vsql = vsql || '    and lan.bdvalorlanc > 0 ';

       IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';

       IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

       if (Upper(:prdemlancreembolso) = 'FALSE') then
          begin
            vsql = vsql || 'and not exists (';
            vsql = vsql || '   select rec.* from VFIN_ESC_TRECFATURASERVICO rec ';
            vsql = vsql || '   inner join VFIN_ESC_TORIGEMSERFAT orig on (orig.bdcodcli = rec.bdcodcli and orig.bdcodesc = rec.bdcodesc and orig.bdchavefatura = rec.bdchavefatura and orig.bdordemser = rec.bdordemser) ';
            vsql = vsql || '   inner join VFIN_ESC_TSERVICOFIXO serfix on (serfix.bdcodcli = orig.bdcodcli and serfix.bdcodesc = orig.bdcodesc and serfix.bdchaveserfix = orig.bdchaveserfix ';
            vsql = vsql || '   and serfix.bdordemserfix = orig.bdordemserfix) ';
            vsql = vsql || '   inner join VFIN_ESC_TVINC_PAG_SERVIC vinc on (vinc.bdcodcli = serfix.bdcodcli and vinc.bdcodesc = serfix.bdcodesc and vinc.bdchaveserfix = serfix.bdchaveserfix and ';
            vsql = vsql || '   vinc.bdordemserfix = serfix.bdordemserfix) ';
            vsql = vsql || '   where rec.bdcodesc = lan.bdcodesc and ';
            vsql = vsql || '   rec.bdcodcli = lan.bdcodcli and ';
            vsql = vsql || '   rec.bdchavefatura = lan.bdchavefatura and ';
            vsql = vsql || '   rec.bdordemser = lan.bdordemser and ';
            vsql = vsql || '   rec.bdordemrecser = lan.bdordemrecser ';
            vsql = vsql || ')';
          end

       vsql = vsql || ' )';

       IF (:vguardaserdesp <> '') THEN
          vsql = vsql || 'and ser.bdcodobrser in ('||:vguardaserdesp||') ';

     END
  ELSE
    BEGIN -- Despesas
      IF (prnivel = 0) THEN -- Ent?o s? possui t?tulos selecionadas
         BEGIN
           vsqlserdesp = 'select d.bdcoddesp, d.bdclassdesp, d.bddescdesp, d.bdtipodesp ';
           vsqlserdesp = vsqlserdesp || 'from (';
           vsqlserdesp = vsqlserdesp || '       select bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
           vsqlserdesp = vsqlserdesp || '       from vfin_base_tdespesa ';

           IF (:prcoddesp <> '') THEN
              vsqlserdesp = vsqlserdesp || 'where bdcoddesp in ('||:prcoddesp||') ';

           vsqlserdesp = vsqlserdesp || '      ) desp ';
           vsqlserdesp = vsqlserdesp || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';

           /* Se prnivel = 0 ent?o apenas a op??o "t?tulo" est? selecionada. Neste caso
           iremos trazer tamb?m as anal?ticas para que seja feito o c?lculo dos per?odos.
           Posteriormente apenas exibimos as t?tulos no relat?rio. */

           vsqlserdesp = vsqlserdesp || 'group by bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
           vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
         END
      ELSE
        IF (prnivel = 1) THEN -- Ent?o s? possui anal?ticas selecionadas
           BEGIN
             /* Se apenas a op??o "anal?ticas" est? selecionada, ent?o basta
             trazer as pr?prias anal?ticas selecionadas. */
             vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
             vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
             vsqlserdesp = vsqlserdesp || 'where desp.bdtipodesp = 1 ';

             IF (:prcoddesp <> '') THEN
                vsqlserdesp = vsqlserdesp || 'and desp.bdcoddesp in ('||:prcoddesp||') ';

             vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
           END
        ELSE -- Ent?o possui t?tulos e anal?ticas selecionadas, e obrigatoriamente as duas op??es "t?tulos" e "anal?ticas" est?o checadas.
          IF (prnivel = 2) THEN
             BEGIN

                if (prcoddesp = '') then
                   begin
                     vguardaserdesp = '';
                     vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                     vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                     vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
                   end
                else
                   begin
                       /* Se t?tulos e anal?ticas foram selecionadas, dever? trazer as anal?ticas das t?tulos
                       que est?o selecionadas e tamb?m dever? trazer as t?tulos das anal?ticas que foram selecionadas.*/
            
                       -- Primeiramente pegar as t?tulos que foram selecionadas
                       vsql = 'select list(desp.bdcoddesp) from vfin_base_tdespesa desp ';
                       vsql = vsql || 'where desp.bdtipodesp = 0 ';
        
                       IF (:prcoddesp <> '') THEN
                          vsql = vsql || 'and desp.bdcoddesp in ('||:prcoddesp||')';
        
                       EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
              
                       IF (vguardaserdesp IS NOT NULL) THEN
                          BEGIN
                            -- Em seguida, obter as anal?ticas destas t?tulos e guardar em vguardaservicos.
                            vsql = 'select d.bdcoddesp, d.bdclassdesp ';
                            vsql = vsql || 'from (';
                            vsql = vsql || '       select bdcoddesp, bdclassdesp, bddescdesp ';
                            vsql = vsql || '       from vfin_base_tdespesa ';
                            vsql = vsql || '       where bdcoddesp in('||:vguardaserdesp||') ';
                            vsql = vsql || '      ) desp ';
                            vsql = vsql || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';
                   
                            vguardaserdesp = '';
                         
                            FOR
                            EXECUTE STATEMENT :vsql
                            INTO
                            :vcodserdesp,
                            :vclassserdesp
                            DO
                            BEGIN
                              vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                            END
                          END
                       ELSE
                         vguardaserdesp = '';
        
                       -- Obtendo somente as anal?ticas selecionadas
                       vsql = 'select desp.bdcoddesp, desp.bdclassdesp ';
                       vsql = vsql || 'from (';
                       vsql = vsql || 'select bdcoddesp, bdclassdesp ';
                       vsql = vsql || 'from vfin_base_tdespesa ';
                       vsql = vsql || 'where bdtipodesp = 1';
        
                       IF (:prcoddesp <> '') THEN
                          vsql = vsql || 'and bdcoddesp in ('||:prcoddesp||') ';
        
                       vsql = vsql || ') desp ';
            
                       FOR
                       EXECUTE STATEMENT :vsql
                       INTO
                       :vcodserdesp,
                       :vclassserdesp
                       DO
                       BEGIN
                         vstop = 'FALSE';
                         vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                         vclassaux = :vclassserdesp;
                  
                         /* A implementa??o abaixo vai removendo sempre o ?ltimo n?vel da classifica??o
                         para obter todas as t?tulos que compoem a anal?tica, e vai guardando o c?digo
                         de cada t?tulo na vari?vel vguardaserdesp. */
                         WHILE (UPPER(:vstop) = 'FALSE') DO
                           BEGIN
                             SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
                  
                             IF (vposicaoponto > 0) THEN
                                BEGIN
                                  SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classifica??o
                                  SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a invers?o seria o ?ltimo ponto)
                                  SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                                  SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente
                                  SELECT COALESCE(bdcoddesp,0) FROM vfin_base_tdespesa WHERE bdclassdesp = :vclassaux INTO :vcodserdespaux;
            
                                  IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                     vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                                END
                             ELSE
                               BEGIN
                                 vstop = 'TRUE';
                               END
                           END
                       END
        
                       vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
                
                       -- Por fim, junta todos os servi?os relacionados em um sql.
                       vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                       vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                       vsqlserdesp = vsqlserdesp || 'where desp.bdcoddesp in ('||:vguardaserdesp||') ';
                       vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
                end
             END



      -- Depois de ter obtido todos os servi?os, trazer apenas os que possuem rela??o com os lan?amentos financeiros.
      if (vguardaserdesp <> '') then
         begin
            vguardaserdesp = '';
            vsql = 'select list(desp.bdcoddesp) from ('||:vsqlserdesp||') desp where desp.bdtipodesp = 1';
            EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
         end

      vsql = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, (null) bddesconto ';
      vsql = vsql || 'from vfin_base_tdespesa desp ';
      vsql = vsql || 'where exists ';
      vsql = vsql || ' (';

      if (Upper(:prdemlancreembolso) = 'FALSE') then
         begin
           vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lan ';
           vsql = vsql || 'left outer join vfin_esc_tvinc_pag_servic vinc on (vinc.bdcodesc = lan.bdcodesc and vinc.BDCHAVECTAPAG = lan.bdchavectapag ';
           vsql = vsql || 'and vinc.bdordemdesp = lan.bdordemdesp) ';
           vsql = vsql || 'where (lan.bdcoddesp = desp.bdcoddesp) ';
           vsql = vsql || 'and lan.bdtiposervdesp = 1 ';
           vsql = vsql || 'and lan.bdvalorlanc > 0 ';
           vsql = vsql || 'and vinc.bdcodesc is null  ';
         end
      else
        begin
          vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lan ';
          vsql = vsql || 'where (lan.bdcoddesp = desp.bdcoddesp) ';
          vsql = vsql || 'and lan.bdtiposervdesp = 1 ';
          vsql = vsql || 'and lan.bdvalorlanc > 0 ';
        end

      if ((:prcodesc <> '') and (:prcodesc is not null)) then
         vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';

      IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||')';


      vsql = vsql || ' )';

      IF (:vguardaserdesp <> '') THEN
         vsql = vsql || 'and desp.bdcoddesp in ('||:vguardaserdesp||') ';
    END

  /* Adicionar todas as anal?ticas em uma tabela tempor?ria com os valores de seus per?odos */
  FOR
  EXECUTE STATEMENT :vsql
  INTO
  :vcodserdesp,
  :vclassserdesp,
  :vdescserdesp,
  :vDesconto
  DO
  BEGIN
    vstop = 'FALSE';
    vperiodoinicial = '';
    vperiodofinal = '';
    vnumperiodo = 0;
  
    WHILE (UPPER(vstop) = 'FALSE') DO
      BEGIN
        vnumperiodo = :vnumperiodo +1;
  
        IF (:prtipodem = 0) THEN -- Demonstrativo total
           BEGIN
             vperiodoinicial = :prdatainicial;
             vperiodofinal = :prdatafinal;

             SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
           END
        ELSE
          IF (:prtipodem = 1) THEN -- Demonstrativo mensal
             BEGIN
               IF (:vperiodoinicial = '') THEN
                  BEGIN
                    vperiodoinicial = prdatainicial;
                  END
               ELSE
                 BEGIN
                   -- Acrescentando um m?s ? data
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 1) INTO :vperiodoinicial;
                   vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                 END

                 -- Obtendo o ?ltimo dia do m?s
                 SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodoinicial FROM 1 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodoinicial FROM 7 FOR 4) AS INTEGER)) INTO :vultdiames;
                 vperiodofinal = SUBSTRING(:vperiodoinicial FROM 1 FOR 3)||:vultdiames||SUBSTRING(:vperiodoinicial FROM 6 FOR 5);


                 -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                    END
                 ELSE
                 IF (:vnumperiodo = 7) THEN
                    BEGIN
                      vperiodo07 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo07;
                    END
                 ELSE
                 IF (:vnumperiodo = 8) THEN
                    BEGIN
                      vperiodo08 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo08;
                    END
                 ELSE
                 IF (:vnumperiodo = 9) THEN
                    BEGIN
                      vperiodo09 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo09;
                    END
                 ELSE
                 IF (:vnumperiodo = 10) THEN
                    BEGIN
                      vperiodo10 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo10;
                    END
                 ELSE
                 IF (:vnumperiodo = 11) THEN
                    BEGIN
                      vperiodo11 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo11;
                    END
                 ELSE
                 IF (:vnumperiodo = 12) THEN
                    BEGIN
                      vperiodo12 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo12;
                    END
             END
          ELSE
            IF (:prtipodem = 2) THEN -- Demonstrativo bimestral
               BEGIN
                 IF (:vperiodoinicial = '') THEN
                    BEGIN
                      vperiodoinicial = :prdatainicial;
                    END
                 ELSE
                   BEGIN
                     -- Por ser bimestral, dever? acrescentar dois meses ? data
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 2) INTO :vperiodoinicial;
                     vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                   END

                 /* Acrescentando um m?s ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                 Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 28/02/2017 */
                 SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 1) INTO :vperiodofinal;
                 SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                 vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
  
                 -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = '1? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = '2? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = '3? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = '4? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = '5? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = '6? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                    END
               END
            ELSE
              IF (:prtipodem = 3) THEN -- Demonstrativo trimestral
                 BEGIN
                   IF (:vperiodoinicial = '') THEN
                       BEGIN
                         vperiodoinicial = :prdatainicial;
                       END
                   ELSE
                     BEGIN
                       -- Por ser trimestral, dever? acrescentar tr?s meses ? data
                       SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 3) INTO :vperiodoinicial;
                       vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                     END

                   /* Acrescentando tr?s meses ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                   Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 31/03/2017 */
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 2) INTO :vperiodofinal;
                   SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                   vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
                   -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                   IF (:vnumperiodo = 1) THEN
                      BEGIN
                        vperiodo01 = '1? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                      END
                   ELSE
                   IF (:vnumperiodo = 2) THEN
                      BEGIN
                        vperiodo02 = '2? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                      END
                   ELSE
                   IF (:vnumperiodo = 3) THEN
                      BEGIN
                        vperiodo03 = '3? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                      END
                   ELSE
                   IF (:vnumperiodo = 4) THEN
                      BEGIN
                        vperiodo04 = '4? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                      END
                 END
              ELSE
                IF (:prtipodem = 4) THEN -- Demonstrativo semestral
                   BEGIN
                     IF (:vperiodoinicial = '') THEN
                       BEGIN
                         vperiodoinicial = :prdatainicial;
                       END
                     ELSE
                       BEGIN
                         -- Por ser semestral, dever? acrescentar seis meses ? data
                         SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 6) INTO :vperiodoinicial;
                         vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                       END

                     /* Acrescentando cinco meses ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                     Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 30/06/2017 */
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 5) INTO :vperiodofinal;
                     SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                     vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
  
                     -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                     IF (:vnumperiodo = 1) THEN
                        BEGIN
                          vperiodo01 = '1? semestre';
                          SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                        END
                     ELSE
                     IF (:vnumperiodo = 2) THEN
                        BEGIN
                          vperiodo02 = '2? semestre';
                          SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                        END
                   END
                ELSE
                  BEGIN
                    IF (:prtipodem = 5) THEN -- Desmonstrativo anual
                       BEGIN
                         IF (:vperiodoinicial = '') THEN
                             BEGIN
                               vperiodoinicial = :prdatainicial;
                             END
                         ELSE
                           BEGIN
                             -- Por ser anual, dever? acrescentar um ano ? data
                             SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 12) INTO :vperiodoinicial;
                             vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                           END
                         -- O ?ltimo dia do ano sempre ser? 31/12/ + o ano que foi incrementado no vperiodoinicial
                         vperiodofinal = '12/31/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
             
                         -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                         IF (:vnumperiodo = 1) THEN
                            BEGIN
                              vperiodo01 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                            END
                         ELSE
                         IF (:vnumperiodo = 2) THEN
                            BEGIN
                              vperiodo02 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                            END
                         ELSE
                         IF (:vnumperiodo = 3) THEN
                            BEGIN
                              vperiodo03 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                            END
                         ELSE
                         IF (:vnumperiodo = 4) THEN
                            BEGIN
                              vperiodo04 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                            END
                         ELSE
                         IF (:vnumperiodo = 5) THEN
                            BEGIN
                              vperiodo05 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                            END
                         ELSE
                         IF (:vnumperiodo = 6) THEN
                            BEGIN
                              vperiodo06 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                            END
                         ELSE
                         IF (:vnumperiodo = 7) THEN
                            BEGIN
                              vperiodo07 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo07;
                            END
                         ELSE
                         IF (:vnumperiodo = 8) THEN
                            BEGIN
                              vperiodo08 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo08;
                            END
                         ELSE
                         IF (:vnumperiodo = 9) THEN
                            BEGIN
                              vperiodo09 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo09;
                            END
                         ELSE
                         IF (:vnumperiodo = 10) THEN
                            BEGIN
                              vperiodo10 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo10;
                            END
                         ELSE
                         IF (:vnumperiodo = 11) THEN
                            BEGIN
                              vperiodo11 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo11;
                            END
                         ELSE
                         IF (:vnumperiodo = 12) THEN
                            BEGIN
                              vperiodo12 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo12;
                            END
                       END
                  END

        IF (:vperiodofinal = :prdatafinal) THEN
           vstop = 'TRUE';
      END

      vvlrtotperiodo = :vvlrperiodo01 + :vvlrperiodo02 + :vvlrperiodo03 + :vvlrperiodo04 + :vvlrperiodo05 + :vvlrperiodo06 + :vvlrperiodo07 +
                       :vvlrperiodo08 + :vvlrperiodo09 + :vvlrperiodo10 + :vvlrperiodo11 + :vvlrperiodo12;

      if (Upper(:vdesconto) = 'TRUE') then
         begin
           vvlrtotperiodo = - :vvlrtotperiodo;
           vvlrperiodo01 = - :vvlrperiodo01;
           vvlrperiodo02 = - :vvlrperiodo02;
           vvlrperiodo03 = - :vvlrperiodo03;
           vvlrperiodo04 = - :vvlrperiodo04;
           vvlrperiodo05 = - :vvlrperiodo05;
           vvlrperiodo06 = - :vvlrperiodo06;
           vvlrperiodo07 = - :vvlrperiodo07;
           vvlrperiodo08 = - :vvlrperiodo08;
           vvlrperiodo09 = - :vvlrperiodo09;
           vvlrperiodo10 = - :vvlrperiodo10;
           vvlrperiodo11 = - :vvlrperiodo11;
           vvlrperiodo12 = - :vvlrperiodo12;
         end

      INSERT INTO TMP_DEMRECDESP_ANALITICAS (BDCODOBRSER, BDCLASSIFICACAO, BDPERIODO01, BDVLRPERIODO01, BDPERIODO02, BDVLRPERIODO02, BDPERIODO03, BDVLRPERIODO03,
      BDPERIODO04, BDVLRPERIODO04, BDPERIODO05, BDVLRPERIODO05, BDPERIODO06, BDVLRPERIODO06, BDPERIODO07, BDVLRPERIODO07, BDPERIODO08, BDVLRPERIODO08,
      BDPERIODO09, BDVLRPERIODO09, BDPERIODO10, BDVLRPERIODO10, BDPERIODO11, BDVLRPERIODO11, BDPERIODO12, BDVLRPERIODO12, BDVLRTOTPERIODO)
      VALUES (:vcodserdesp, :vclassserdesp, :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
      :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08, :vperiodo09, :vvlrperiodo09,
      :vperiodo10, :vvlrperiodo10, :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12, :vvlrtotperiodo);

   END

   FOR
   EXECUTE STATEMENT :vsqlserdesp
   INTO
   :vcodserdesp,
   :vclassserdesp,
   :vdescserdesp,
   :vtiposerdesp
   DO
   BEGIN
     bdcodserdesp = :vcodserdesp;
     bdclassificacao = :vclassserdesp;
     bddescricao = :vdescserdesp;
     bdtipo = :vtiposerdesp;
     bdvlrtotperiodo = 0;

     SELECT bdperiodo01, SUM(bdvlrperiodo01) bdvlrperiodo01, bdperiodo02, SUM(bdvlrperiodo02) bdvlrperiodo02, bdperiodo03, SUM(bdvlrperiodo03) bdvlrperiodo03,
     bdperiodo04, SUM(bdvlrperiodo04) bdvlrperiodo04, bdperiodo05, SUM(bdvlrperiodo05) bdvlrperiodo05, bdperiodo06, SUM(bdvlrperiodo06) bdvlrperiodo06,
     bdperiodo07, SUM(bdvlrperiodo07) bdvlrperiodo07, bdperiodo08, SUM(bdvlrperiodo08) bdvlrperiodo08, bdperiodo09, SUM(bdvlrperiodo09) bdvlrperiodo09,
     bdperiodo10, SUM(bdvlrperiodo10) bdvlrperiodo10, bdperiodo11, SUM(bdvlrperiodo11) bdvlrperiodo11, bdperiodo12, SUM(bdvlrperiodo12) bdvlrperiodo12,
     SUM(bdvlrtotperiodo) bdvlrtotperiodo
     FROM TMP_DEMRECDESP_ANALITICAS
     WHERE bdclassificacao LIKE :vclassserdesp||'%'
     GROUP BY bdperiodo01, bdperiodo02, bdperiodo03, bdperiodo04, bdperiodo05, bdperiodo06, bdperiodo07,
     bdperiodo08, bdperiodo09, bdperiodo10, bdperiodo11, bdperiodo12
     INTO :bdperiodo01, :bdvlrperiodo01, :bdperiodo02, :bdvlrperiodo02, :bdperiodo03, :bdvlrperiodo03, :bdperiodo04, :bdvlrperiodo04,
     :bdperiodo05, :bdvlrperiodo05, :bdperiodo06, :bdvlrperiodo06, :bdperiodo07, :bdvlrperiodo07, :bdperiodo08, :bdvlrperiodo08,
     :bdperiodo09, :bdvlrperiodo09, :bdperiodo10, :bdvlrperiodo10, :bdperiodo11, :bdvlrperiodo11, :bdperiodo12, :bdvlrperiodo12,
     :bdvlrtotperiodo;

     -- Servi?os de desconto vem negativos
     IF (:bdvlrtotperiodo <> 0) THEN
        BEGIN
          SUSPEND;
        END
   END

   DELETE FROM TMP_DEMRECDESP_ANALITICAS;
END
^

/* Alter (SP_RETORNA_DIFERENCAS_VSUC_TLAN) */
ALTER PROCEDURE SP_RETORNA_DIFERENCAS_VSUC_TLAN(PRCODEMP VARCHAR(2048),
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRTRANSACAO INTEGER)
 RETURNS(PREMPRESA INTEGER,
PRDATA DATE,
PRDEBITO NUMERIC(15,6),
PRCREDITO NUMERIC(15,6),
PRDIFERENCA NUMERIC(15,6),
PRTOTAL NUMERIC(15,6))
 AS
DECLARE VARIABLE WCREDITO INTEGER;
DECLARE VARIABLE WDEBITO INTEGER;
DECLARE VARIABLE WVALORCRE NUMERIC(15,6);
DECLARE VARIABLE WVALORDEB NUMERIC(15,6);
DECLARE VARIABLE WVALORAUX NUMERIC(15,6);
DECLARE VARIABLE WDATAAUX DATE;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WSQL VARCHAR(2000);
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WEMPPRINC INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCAMPO INTEGER;
DECLARE VARIABLE WPOS_PERNAMATRIZ INTEGER;
DECLARE VARIABLE WPOS_MATRIZ INTEGER;
DECLARE VARIABLE WPOS_FILIAL INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
BEGIN
  wdataaux  = '12/31/1990';

  wvalorcre = 0;
  wvalordeb = 0;
  prTotal   = 0;

  wsql = 'select bdcodemp,bdDEBITO,bdCREDITO,bdDATA,bdVALOR,bdfilial,bdtipolancfilial from vsuc_empresas_tlan ';
  wsql = wsql||'where ';
  wsql = wsql||'((BDDEBITO is null) or (BDCREDITO is null)) '; --#alt:6504 - Apenas lan?amentos com uma perna - Bruno Borges
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  --#alt:4431. Transa??o
  IF (prtransacao > 0) THEN
    wsql = wsql||'and (bdtransacao = '||prtransacao||') ';
  wsql = wsql||'and (bddata between '''||:prdatainicial||''' and '''||:prdatafinal||''') ';
  --#alt:5837.wsql = wsql||'WHERE (bdCODEMP in ('||:prcodemp||')) ';
  wsql = wsql||'and ((bdCODEMP in ('||:prcodemp||')) or (bdfilial in ('||:prcodemp||'))) order by bdDATA asc';

  --Retorna a empresa principal
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos = 0) THEN
    wempprinc = prcodemp;
  ELSE
    wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wdebito,:wcredito,:wData,:wValorAux,:wfilial,:wtipolancfilial DO
     BEGIN
        prempresa = wcodemp;

        IF (wDataAux = '12/31/1990') THEN
           wdataaux = wData;

        IF (wDataAux <> wData) THEN -- gilberto - 10/01/2014
        --if ((wDataAux <> wData) or ((prempresa is not null) and (wcodemp <> prempresa))) then
           BEGIN
              IF (wvalorcre <> wvalordeb) THEN
                 BEGIN
                    prData = wDataAux;
                    prCredito = wvalorcre;
                    prDebito = wvalordeb;
                    prDiferenca = wvalorcre - wvalordeb;
                    prTotal = prTotal + (wvalorcre - wvalordeb);
                    SUSPEND;
                 END
              wdataaux = :wData;
              wvalorcre = 0;
              wvalordeb = 0;
              --prTotal = 0;-- gilberto - 10/01/2014
           END
        --prempresa = wcodemp;-- gilberto - 10/01/2014

        --alt:#6524 - implementado rotina "POS" aqui, por quest?o de desempenho, precisa apenas uma vez para as duas verifica??es
        IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
           BEGIN
             wpos_pernamatriz = POSITION(wempprinc, prcodemp);
             --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
             wpos_matriz = POSITION(wcodemp, prcodemp);
             --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
             wpos_filial = POSITION(wfilial, prcodemp);
          END
        wpermite = 0;


        --alt:#6524 - implementado rotina "VSUC_SP_PERMITECALCSALDOLANCMF" diretamente aqui, por quest?o de desempenho
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           wpermite = 1;
        ELSE
           BEGIN
             wcampo = 1;
             IF (((wempprinc = wcodemp) AND (wfilial = 0)) OR
                 --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
                 ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
                 --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                 ((wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                 --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
                 ((prmatrizfilialconsolidado = 1) AND (wempprinc <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                 --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
                 ((prmatrizfilialconsolidado = 1) AND (wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
               wpermite = 1;
           END
        ------------------------------------------------------------------------
        IF ((wpermite = 1) AND ((wdebito IS NOT NULL) OR (wdebito <> 0)))  THEN
           wvalordeb = wvalordeb + wValorAux;

        --alt:#6524 - implementado rotina "VSUC_SP_PERMITECALCSALDOLANCMF" diretamente aqui, por quest?o de desempenho
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(2,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           wpermite = 1;
        ELSE
           BEGIN
             wcampo = 2;
             IF (((wempprinc = wcodemp) AND (wfilial = 0)) OR
                 --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
                 ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
                 --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                 ((wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                 --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
                 ((prmatrizfilialconsolidado = 1) AND (wempprinc <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                 --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
                 ((prmatrizfilialconsolidado = 1) AND (wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
               wpermite = 1;             
           END
        ------------------------------------------------------------------------
        IF ((wpermite = 1) AND ((wcredito IS NOT NULL) OR (wcredito <> 0)))  THEN
           wvalorcre = wvalorcre + wValorAux;
     END

     IF (wvalorcre <> wvalordeb) THEN
        BEGIN
           prData = wdataaux;
           prCredito = wvalorcre;
           prDebito = wvalordeb;
           prDiferenca = wvalorcre - wvalordeb;
           prTotal = prTotal + (wvalorcre - wvalordeb);
           SUSPEND;
        END
END
^

/* empty dependent procedure body */
/* Clear: SP_RETORNA_EMPRESA_FILIAIS for: SP_RETORNA_EMPRESA_FILIAIS */
ALTER PROCEDURE SP_RETORNA_EMPRESA_FILIAIS(PRCODEMP INTEGER,
PRREFEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_RETORNA_EMPRESA_FILIAIS) */
ALTER PROCEDURE SP_RETORNA_EMPRESA_FILIAIS(PRCODEMP INTEGER,
PRREFEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER)
 AS
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
BEGIN
  /* retorna a empresa matriz ________________________________________________*/
  SELECT tempresas.bdcodemp, tempresas_ref.bdnomemp, tempresas.bdcnpjemp, tempresas.bdcodmatriz
  FROM tempresas
  LEFT OUTER JOIN tempresas_ref ON (tempresas_ref.bdcodemp = tempresas.bdcodemp)
  WHERE tempresas.bdcodemp = :prcodemp
  AND tempresas_ref.bdrefemp = (SELECT FIRST 1 temp.bdrefemp FROM tempresas_ref temp
                                WHERE temp.bdrefemp <= :prrefemp
                                AND temp.bdcodemp = :prcodemp
                                ORDER BY temp.bdcodemp DESC, temp.bdrefemp DESC)
  INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodmatriz;
  SUSPEND;

  /* retorna as filiais da empresa ___________________________________________*/
  FOR SELECT tempresas.bdcodemp, tempresas_ref.bdnomemp, tempresas.bdcnpjemp, tempresas.bdcodmatriz
      FROM tempresas
      LEFT OUTER JOIN tempresas_ref ON (tempresas_ref.bdcodemp = tempresas.bdcodemp)
      WHERE tempresas.bdcodmatriz = :prcodemp
      AND tempresas.bdcodemp <> tempresas.bdcodmatriz
      AND tempresas_ref.bdrefemp = (SELECT FIRST 1 temp.bdrefemp FROM tempresas_ref temp
                                    WHERE temp.bdrefemp <= :prrefemp
                                    AND temp.bdcodemp = tempresas.bdcodemp
                                    ORDER BY temp.bdrefemp DESC)
      ORDER BY tempresas.bdcodemp
      INTO :wcodemp, :wnomemp, :wcnpjemp, :wcodmatriz DO
  BEGIN
    /* verifica se a filial possui filial ____________________________________*/
    SELECT COUNT(tempresas.bdcodemp) FROM tempresas
           WHERE tempresas.bdcodmatriz = :wcodemp
           AND tempresas.bdcodemp <> tempresas.bdcodmatriz INTO :wcount;

    IF (wcount > 0) THEN
       BEGIN
         /* retorna as filiais das filiais ___________________________________*/
         FOR SELECT spemp.bdcodemp, spemp.bdnomemp, spemp.bdcnpjemp, spemp.bdcodmatriz FROM sp_retorna_empresa_filiais(:wcodemp, :prrefemp) spemp
             INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodmatriz DO
         SUSPEND;
       END
    ELSE
       BEGIN
         /* caso a filial n?o tenha filiais retorna o codigo da filial da
         empresa _____________________________________________________________*/
         bdcodemp = wcodemp;
         bdnomemp = wnomemp;
         bdcnpjemp = wcnpjemp;
         bdcodmatriz = wcodmatriz;
         SUSPEND;
       END
  END
END
^

/* empty dependent procedure body */
/* Clear: SP_REL_CONSULTA_CONFIGURAVEL2 for: SP_RETORNA_MESANO_EXTENSO */
ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL2 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDCODPLANO INTEGER,
BDCODQUADRO INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDLINHA INTEGER,
BDTITULOS VARCHAR(640))
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_RETORNA_MESANO_EXTENSO) */
ALTER PROCEDURE SP_RETORNA_MESANO_EXTENSO(PRMES VARCHAR(2),
PRANO VARCHAR(4),
PRSEPARADOR VARCHAR(1) = '/')
 RETURNS(BDANOMES VARCHAR(20))
 AS
DECLARE VARIABLE wmes INTEGER;
BEGIN
  wmes = CAST(prmes AS INTEGER);

  IF (wmes = 1) THEN
    bdanomes = 'Janeiro';
  ELSE IF (wmes = 2) THEN
    bdanomes = 'Fevereiro';
  ELSE IF (wmes = 3) THEN
    bdanomes = 'Mar?o';
  ELSE IF (wmes = 4) THEN
    bdanomes = 'Abril';
  ELSE IF (wmes = 5) THEN
    bdanomes = 'Maio';
  ELSE IF (wmes = 6) THEN
    bdanomes = 'Junho';
  ELSE IF (wmes = 7) THEN
    bdanomes = 'Julho';
  ELSE IF (wmes = 8) THEN
    bdanomes = 'Agosto';
  ELSE IF (wmes = 9) THEN
    bdanomes = 'Setembro';
  ELSE IF (wmes = 10) THEN
    bdanomes = 'Outubro';
  ELSE IF (wmes = 11) THEN
    bdanomes = 'Novembro';
  ELSE IF (wmes = 12) THEN
    bdanomes = 'Dezembro';

  bdanomes = :bdanomes||prseparador||prano;

  SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: SP_GET_CODPARTICIPANTEEXP for: SP_RETORNA_NUMEROS */
ALTER PROCEDURE SP_GET_CODPARTICIPANTEEXP(PRTIPOEXPCODPART INTEGER,
PRCODTER INTEGER,
PRCGCTER VARCHAR(18),
PRIETER VARCHAR(20),
PRCODIGOARQUIVO VARCHAR(60))
 RETURNS(BDRETORNO VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VALIDACHAVE_NFE for: SP_RETORNA_NUMEROS */
ALTER PROCEDURE SP_VALIDACHAVE_NFE(PRCHAVENFE VARCHAR(60))
 RETURNS(BDISVALID /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_RETORNA_NUMEROS) */
ALTER PROCEDURE SP_RETORNA_NUMEROS(PRSTR VARCHAR(1000),
PRTAMANHO INTEGER = 0)
 RETURNS(BDNUMERO VARCHAR(1000))
 AS
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCHAR VARCHAR(1);
DECLARE VARIABLE WPOSINICIALCORTE INTEGER;
BEGIN
  /*
    retorna somente os n?meros encontrados na string,
    dando op??o de fazer um corte(mantendo o final) na string resultado
    exemplo: '1234' com prtamanho = 2 fica: '34'
  */

  bdnumero = '';

  IF (:prstr IS NOT NULL) THEN
    BEGIN
      wpos = 1;

      WHILE (wpos <= CHAR_LENGTH(prstr)) DO
        BEGIN
          wchar = SUBSTRING(:prstr FROM :wpos FOR 1);

          IF (wchar IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')) THEN
             bdnumero = :bdnumero||:wchar;

          wpos = :wpos + 1;
        END

      /* faz um substring inverso (direta para esquerda) */
      IF ((prtamanho > 0) AND (CHAR_LENGTH(:bdnumero) > prtamanho))THEN
        BEGIN
          wposinicialcorte = CHAR_LENGTH(:bdnumero) - prtamanho + 1;
          bdnumero = SUBSTRING(:bdnumero FROM wposinicialcorte FOR prtamanho);
        END
    END

  IF (:bdnumero = '') THEN
     bdnumero = NULL;

  SUSPEND;
END
^

/* Alter (SP_RETORNA_REFERENCIAS) */
ALTER PROCEDURE SP_RETORNA_REFERENCIAS(PRREFINI INTEGER,
PRREFFIN INTEGER)
 RETURNS(BDREFERENCIA INTEGER)
 AS
DECLARE VARIABLE I    INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
BEGIN
  /* Retorna as refer?ncias entre a refer?ncia inicial e a refer?ncia final */
  IF ((PRREFINI <= PRREFFIN) AND
      (CHAR_LENGTH(TRIM(CAST(PRREFINI AS VARCHAR(6)))) = 6) AND -- REFERENCIA DEVE TER 6 CARACTERES
      (CHAR_LENGTH(TRIM(CAST(PRREFFIN AS VARCHAR(6)))) = 6)) THEN
    BEGIN
       WANO = CAST(SUBSTRING(CAST(PRREFINI AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
       WMES = CAST(SUBSTRING(CAST(PRREFINI AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
       I    = PRREFINI;

       WHILE (I <= PRREFFIN) DO
         BEGIN
           BDREFERENCIA = CAST(CAST(WANO AS VARCHAR(4))||LPAD(CAST(WMES AS VARCHAR(2)),2,'0') AS INTEGER);
  
           IF (WMES < 12) THEN
             WMES = WMES+1;
           ELSE
             BEGIN
               wMES = 1;
               WANO = WANO+1;
             END
  
           I = BDREFERENCIA;
           IF (I <= PRREFFIN) THEN
             SUSPEND;
         END
    END
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_BALANCETE_COMPA for: SP_RETORNA_SALDO_EMP */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE_COMPA(PRCODEMP VARCHAR(2048),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRTIPCOMP INTEGER,
PRQTDCOMP INTEGER,
PRCODTPCC VARCHAR(2048),
PRIGNZER SMALLINT,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCENTROS INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALANT NUMERIC(15,2),
BDSALATU_01 NUMERIC(15,2),
BDSALMOV_01 NUMERIC(15,2),
BDSALATU_02 NUMERIC(15,2),
BDSALMOV_02 NUMERIC(15,2),
BDSALATU_03 NUMERIC(15,2),
BDSALMOV_03 NUMERIC(15,2),
BDSALATU_04 NUMERIC(15,2),
BDSALMOV_04 NUMERIC(15,2),
BDSALATU_05 NUMERIC(15,2),
BDSALMOV_05 NUMERIC(15,2),
BDSALATU_06 NUMERIC(15,2),
BDSALMOV_06 NUMERIC(15,2),
BDSALATU_07 NUMERIC(15,2),
BDSALMOV_07 NUMERIC(15,2),
BDSALATU_08 NUMERIC(15,2),
BDSALMOV_08 NUMERIC(15,2),
BDSALATU_09 NUMERIC(15,2),
BDSALMOV_09 NUMERIC(15,2),
BDSALATU_10 NUMERIC(15,2),
BDSALMOV_10 NUMERIC(15,2),
BDSALATU_11 NUMERIC(15,2),
BDSALMOV_11 NUMERIC(15,2),
BDSALATU_12 NUMERIC(15,2),
BDSALMOV_12 NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_RAZAO_SALDO2 for: SP_RETORNA_SALDO_EMP */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO2(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(1024),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(80),
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(30),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(20),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_RETORNA_SALDO_EMP) */
ALTER PROCEDURE SP_RETORNA_SALDO_EMP(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(5000);
DECLARE VARIABLE wtemcc SMALLINT = 0;
DECLARE VARIABLE wtamanho INTEGER;
DECLARE VARIABLE wclassificacao VARCHAR(50);
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wdebito NUMERIC(15,2);
DECLARE VARIABLE wcredito NUMERIC(15,2);
DECLARE VARIABLE wlevel INTEGER;
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wvlr NUMERIC(15,2);
DECLARE VARIABLE wpermite INTEGER;
BEGIN
  codemp = prcodemp;
  SALDO_ANT_DEB = 0;
  SALDO_ANT_CRE = 0;
  saldo_anterior = 0;
  SALDO_DEB = 0;
  SALDO_CRE = 0;
  saldo_atual = 0;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and tpla.bdctalon like '''||wclassificacao||'%'' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROD = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_DEB do
     if (SALDO_DEB is null) then
        SALDO_DEB = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_DEB = SALDO_DEB + wvlr;
    END

--  exception ex_date;

  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROC = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_CRE do
     if (SALDO_CRE is null) then
        SALDO_CRE = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_CRE = SALDO_CRE + wvlr;
    END

  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';
/* #alt:6153 - gilberto - 09/08/2013 - retirado para sempre calcular zeramento no saldo anterior
  if (prignorazeramento = 1) then
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento
*/
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
     wsql = wsql||' and (TLAN.BDCODTERCEIROD = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_DEB do
     if (SALDO_ANT_DEB is null) then
        SALDO_ANT_DEB = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_ANT_DEB = SALDO_ANT_DEB + wvlr;
    END

  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';
/* #alt:6153 - gilberto - 09/08/2013 - retirado para sempre calcular zeramento no saldo anterior
  if (prignorazeramento = 1) then
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento
*/
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((BDCONCC is null) or (upper(bdconcc) = '|| '''FALSE'''||'))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROC = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_CRE do
     if (SALDO_ANT_CRE is null) then
        SALDO_ANT_CRE = 0; */
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_ANT_CRE = SALDO_ANT_CRE + wvlr;
    END

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;

  SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_RETORNA_SALDO_DIME for: SP_RETORNA_SALDO_EMP_X */
ALTER PROCEDURE SP_VEF_RETORNA_SALDO_DIME(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRREFEMP INTEGER,
PRANO INTEGER)
 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDQUADRO VARCHAR(5),
BDCODEXP INTEGER,
BDSALDO NUMERIC(15,2),
BDDETFILIAL VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_MOV_DIARIO for: SP_RETORNA_SALDO_EMP_X */
ALTER PROCEDURE VSUC_SP_RETORNA_MOV_DIARIO(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(DATA DATE,
DEB NUMERIC(15,2),
CRE NUMERIC(15,2),
SAL NUMERIC(15,2),
DEBANT NUMERIC(15,2),
CREANT NUMERIC(15,2),
SALANT NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_MOV_MENSAL for: SP_RETORNA_SALDO_EMP_X */
ALTER PROCEDURE VSUC_SP_RETORNA_MOV_MENSAL(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRCC VARCHAR(5000),
PRANOINICIAL INTEGER,
PRANOFINAL INTEGER,
PRREFEMP INTEGER,
PRPARTICIPANTE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDDEB01 NUMERIC(15,2),
BDDEB02 NUMERIC(15,2),
BDDEB03 NUMERIC(15,2),
BDDEB04 NUMERIC(15,2),
BDDEB05 NUMERIC(15,2),
BDDEB06 NUMERIC(15,2),
BDDEB07 NUMERIC(15,2),
BDDEB08 NUMERIC(15,2),
BDDEB09 NUMERIC(15,2),
BDDEB10 NUMERIC(15,2),
BDDEB11 NUMERIC(15,2),
BDDEB12 NUMERIC(15,2),
BDCRE01 NUMERIC(15,2),
BDCRE02 NUMERIC(15,2),
BDCRE03 NUMERIC(15,2),
BDCRE04 NUMERIC(15,2),
BDCRE05 NUMERIC(15,2),
BDCRE06 NUMERIC(15,2),
BDCRE07 NUMERIC(15,2),
BDCRE08 NUMERIC(15,2),
BDCRE09 NUMERIC(15,2),
BDCRE10 NUMERIC(15,2),
BDCRE11 NUMERIC(15,2),
BDCRE12 NUMERIC(15,2),
BDMOV01 NUMERIC(15,2),
BDMOV02 NUMERIC(15,2),
BDMOV03 NUMERIC(15,2),
BDMOV04 NUMERIC(15,2),
BDMOV05 NUMERIC(15,2),
BDMOV06 NUMERIC(15,2),
BDMOV07 NUMERIC(15,2),
BDMOV08 NUMERIC(15,2),
BDMOV09 NUMERIC(15,2),
BDMOV10 NUMERIC(15,2),
BDMOV11 NUMERIC(15,2),
BDMOV12 NUMERIC(15,2),
BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2),
BDSALTOTDEB NUMERIC(15,2),
BDSALTOTCRE NUMERIC(15,2),
BDSALTOTMOV NUMERIC(15,2),
BDSALTOTATU NUMERIC(15,2),
BDANO INTEGER,
BDDEBANT NUMERIC(15,2),
BDCREANT NUMERIC(15,2),
BDMOVANT NUMERIC(15,2),
BDSALANT NUMERIC(15,2),
BDGRPCTA INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_RAZAO_SALDO_X for: SP_RETORNA_SALDO_EMP_X */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO_X(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRDETALHARCC INTEGER,
PRLCC /* DM_MAXVARCHAR */ VARCHAR(32765),
PRLANCAMENTOSEMCC INTEGER,
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDCDOISLANCAMENTOS INTEGER,
PRCONTASSEMMOVIMENTO INTEGER,
PRIGNORAZERAMENTO INTEGER = 0,
PRIGNORASALDOANTERIOR INTEGER = 0,
PRDETALHARFILIAL INTEGER = 0)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(100),
BDCODCENTRO INTEGER,
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDNOME_CONTA_ORIGINAL VARCHAR(100),
BDCLASS_CONTA VARCHAR(40),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCGC_CONTA VARCHAR(18),
BDCLASS_CONTRA VARCHAR(40),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER,
BDTIPOLANCFILIAL INTEGER,
BDVLRCONCILIADO NUMERIC(15,2),
BDVLRACONCILIAR NUMERIC(15,2),
BDCHAVEONLINE VARCHAR(120),
BDTRANSACAO INTEGER,
BDTRANFECHADA /* DM_BOOLEAN */ VARCHAR(5),
BDTIPOLAN INTEGER,
BDSEQCTA VARCHAR(7),
BDCONCILIACAOPENDENTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_RETORNA_SALDO_EMP_X) */
ALTER PROCEDURE SP_RETORNA_SALDO_EMP_X(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRINDICE INTEGER,
PRIGNORAZERAMENTO SMALLINT,
PRCC VARCHAR(5000),
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0,
PRPARTICIPANTEFINAL INTEGER = 0,
PREMPREENDIMENTO INTEGER = 0,
PRUNIDIMOB INTEGER = 0,
PRAPENASCONTABILIZACAOSEL INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(18,2),
SALDO_ANT_CRE NUMERIC(18,2),
SALDO_DEB NUMERIC(18,2),
SALDO_CRE NUMERIC(18,2),
MOVIMENTO NUMERIC(18,2),
SALDO_ATUAL NUMERIC(18,2),
SALDO_ANTERIOR NUMERIC(18,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE WSQL DM_MAXVARCHAR;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WSALANT NUMERIC(15,2);
DECLARE VARIABLE WSALATU NUMERIC(15,2);
DECLARE VARIABLE WPOS_PERNAMATRIZ INTEGER;
DECLARE VARIABLE WPOS_MATRIZ INTEGER;
DECLARE VARIABLE WPOS_FILIAL INTEGER;
DECLARE VARIABLE WNIVEL INTEGER;
DECLARE VARIABLE WPARTE VARCHAR(2000);
DECLARE VARIABLE WGROUPBY VARCHAR(2000);
DECLARE VARIABLE WAPENASCONTABILIZACAOSELECIONADA VARCHAR(10);
BEGIN
  codemp = prcodemp;
  SALDO_ANT_DEB = 0;
  SALDO_ANT_CRE = 0;
  saldo_anterior = 0;
  SALDO_DEB = 0;
  SALDO_CRE = 0;
  saldo_atual = 0;

  IF (prapenascontabilizacaosel = 0) THEN
    wapenascontabilizacaoselecionada = '0,';
  ELSE
    wapenascontabilizacaoselecionada = '';

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- SALDO A D?BITO ____________________________________________________________
  wsql = 'Select tlan.bdcodemp, coalesce(tlan.bdfilial, 0),tlan.bdtipolancfilial,';
  /**************** ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS ****************/
  IF ((prcc IS NULL) OR (prcc = '')) THEN
    BEGIN
      IF (prIndice = 0) THEN
        wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlan.bdvalor else 0 end) as bdsalant, ';
      ELSE
        BEGIN
          wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlan.bdvalor';
          wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
       END

      wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
      IF (prignorazeramento = 1) THEN
         wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

      IF (prIndice = 0) THEN
        wsql = wsql||') then tlan.bdvalor else 0 end) as bdsalatu ';
      ELSE
        BEGIN
          wsql = wsql||') then tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                               (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END

      --#alt:23030. Forma incorreta de consultar os dados, deixa o processo lento e n?o retorna o valor correto. Ana - 20/03/2018
      --wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN, planos_tpla TPLA ';
      wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
      wsql = wsql||'inner join (select * from PLANOS_TPLA where BDCTALON like '''||wclassificacao||'%'') TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDDEBITO) ';
      wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';
      --#alt:23030. fim
    END
  /**************** ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS ****************/
  ELSE
    BEGIN
      IF (prIndice = 0) THEN
        wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlcc.bdvalor else 0 end) as bdsalant, ';
      ELSE
        BEGIN
          wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlcc.bdvalor';
          wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
       END

      wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
      IF (prignorazeramento = 1) THEN
         wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

      IF (prIndice = 0) THEN
        wsql = wsql||') then tlcc.bdvalor else 0 end) as bdsalatu ';
      ELSE
        BEGIN
          wsql = wsql||') then tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                               (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END

      --#alt:23030. Forma incorreta de consultar os dados, deixa o processo lento e n?o retorna o valor correto. Ana - 20/03/2018
      --wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC, planos_tpla TPLA ';
      wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
      wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
      wsql = wsql||'inner join (select * from PLANOS_TPLA where BDCTALON like '''||wclassificacao||'%'') TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDDEBITO) ';
      wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';
      --#alt:23030. fim
    END

  --#alt:23030. Ana - 21/03/2018
  /*wsql = wsql||' where TPLA.BDCTALON like ''' || wclassificacao || '%''';
  wsql = wsql||' and tpla.bdcodplapadrao=' || wcodplapadrao;
  wsql = wsql||' and (tpla.bdtipcta = 1)';*/

  wsql = wsql||' where TLAN.BDDATA <= '''||wdatfin||''' ';
  wsql = wsql||' and tlan.bdcodplapadrao = '||wcodplapadrao;

  IF (prcc CONTAINING ',') THEN
    wSQL = wSQL||' and tlcc.BDCODTPCC in ('||prcc||')';
  ELSE IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
    wSQL = wSQL||' and tlcc.BDCODTPCC = '||prcc;

  IF (prrelcta IS NOT NULL) THEN
    wsql = wsql||' and tpla.bdrelcta = '||prrelcta||' ';

  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||' and tlan.bdcontabilizacao in ('||wapenascontabilizacaoselecionada||prcontabilizacao||') ';

  --#alt:23030. Ana - 21/03/2018
  /*EXECUTE PROCEDURE CONTAR_CHAR(wclassificacao, '.') RETURNING_VALUES :wNivel;
  wsql = wsql||' and tpla.bdnivel >= ' || wNivel;

  wsql = wsql||' and TPLA.bdcodtpla = tlan.bddebito';*/

  if ((prparticipante > 0) and (prparticipante is not null)) then
     begin
       --#Alt:24142. Corrigido tratamento do participante inicial e final
       if ((prparticipantefinal = 0) or (prparticipantefinal is null)) then
          wsql = wsql||' and tlan.bdcodterceirod = '||prparticipante||' ';
       else
          wsql = wsql||' and tlan.bdcodterceirod >= '||prparticipante||' ';
     end

  --#Alt:24142. Inclu?do o tratamento para o participante final. S? exista o par?metro, mas n?o estava sendo utilizado.
  if ((prparticipantefinal > 0) and (prparticipantefinal is not null)) then
     begin
       if ((prparticipante = 0) or (prparticipante is null)) then
          wsql = wsql||' and tlan.bdcodterceirod = '||prparticipantefinal||' ';
       else
          wsql = wsql||' and tlan.bdcodterceirod <= '||prparticipantefinal||' ';
     end

  if ((prempreendimento > 0) and (prempreendimento is not null)) then
    wsql = wsql||' and TINCORP.BDCODEMPREENDIMENTO = '||prempreendimento||' ';

  if ((prunidimob > 0) and (prunidimob is not null)) then
    wsql = wsql||' and TINCORP.BDCODIGOUNIIMOB = '||prunidimob||' ';
  --#alt:23030. fim

  wParte = wsql;
  wgroupby = ' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';

  wsql = wparte;
  wsql = wsql||' and (tlan.bdcodemp = '||prcodemp||' and tlan.bdtipolancfilial <> 1) ';
  wsql = wsql||wgroupby;

  wsql = wsql || ' union all ';
  wsql = wsql || wparte;
  wsql = wsql || ' and (tlan.bdfilial = '||prcodemp||' and tlan.bdtipolancfilial = 1) ';
  wsql = wsql||wgroupby;

/* FIM RECONSTRU??O */

  FOR EXECUTE STATEMENT wSQL INTO :wcodemp, :wfilial, :wtipolancfilial, :wsalant, :wsalatu DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      wpos_pernamatriz = POSITION(prcodemp, wcodemp);
      wpos_matriz = POSITION(wcodemp,  prcodemp);
      wpos_filial = POSITION(wfilial,  prcodemp);
      IF (((prcodemp = wcodemp) AND (wfilial = 0)) OR
          --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
          ((prcodemp = wfilial) AND (1 = wtipolancfilial)) OR
          --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
          ((prcodemp = wcodemp) AND (wfilial <> 0) AND (1 <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
          --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
          ((prmatrizfilialconsolidado = 1) AND (prcodemp <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
          --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
          ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (1 = wtipolancfilial) AND (wpos_filial > 0))) THEN
         BEGIN
           saldo_ant_deb = saldo_ant_deb + wsalant;
           SALDO_DEB = SALDO_DEB + wsalatu;
         END
    END

  -- SALDO A CR?DITO ___________________________________________________________
  wsql = 'Select tlan.bdcodemp, coalesce(tlan.bdfilial, 0),tlan.bdtipolancfilial,';
  /**************** ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS ****************/
  IF ((prcc IS NULL) OR (prcc = '')) THEN
    BEGIN
      IF (prIndice = 0) THEN
        wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlan.bdvalor else 0 end) as bdsalant, ';
      ELSE
        BEGIN
          wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlan.bdvalor';
          wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
        END

      wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
      IF (prignorazeramento = 1) THEN
         wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

      IF (prIndice = 0) THEN
        wsql = wsql||') then tlan.bdvalor else 0 end) as bdsalatu ';
      ELSE
        BEGIN
          wsql = wsql||') then tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                               (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END

      --#alt:23030. Forma incorreta de consultar os dados, deixa o processo lento e n?o retorna o valor correto. Ana - 20/03/2018
      --wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN, planos_tpla TPLA ';
      wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
      wsql = wsql||'inner join (select * from PLANOS_TPLA where BDCTALON like '''||wclassificacao||'%'') TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDCREDITO) ';
      wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';
      --#alt:23030. fim
    END
  /**************** ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS ****************/
  ELSE
    BEGIN
      IF (prIndice = 0) THEN
        wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlcc.bdvalor else 0 end) as bdsalant, ';
      ELSE
        BEGIN
         wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlcc.bdvalor';
          wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
        END

      wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
      IF (prignorazeramento = 1) THEN
         wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

      IF (prIndice = 0) THEN
        wsql = wsql||') then tlcc.bdvalor else 0 end) as bdsalatu ';
      ELSE
        BEGIN
          wsql = wsql||') then tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                               (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END

      --#alt:23030. Forma incorreta de consultar os dados, deixa o processo lento e n?o retorna o valor correto. Ana - 20/03/2018
      --wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC, planos_tpla TPLA ';
      wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
      wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
      wsql = wsql||'inner join (select * from PLANOS_TPLA where BDCTALON like '''||wclassificacao||'%'') TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDCREDITO) ';
      wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';
      --#alt:23030. fim
    END

  --#alt:23030. Ana - 20/03/2018
  /*wsql = wsql||' where TPLA.BDCTALON like ''' || wclassificacao || '%''';
  wsql = wsql||' and tpla.bdcodplapadrao=' || wcodplapadrao;
  wsql = wsql||' and (tpla.bdtipcta = 1)';*/

  wsql = wsql||' where TLAN.BDDATA <= '''||wdatfin||''' ';
  wsql = wsql||' and tlan.bdcodplapadrao = '||wcodplapadrao;

  IF (prcc CONTAINING ',') THEN
    wSQL = wSQL||' and tlcc.BDCODTPCC in ('||prcc||')';
  ELSE IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
    wSQL = wSQL||' and tlcc.BDCODTPCC = '||prcc;

  IF (prrelcta IS NOT NULL) THEN
    wsql = wsql||' and tpla.bdrelcta = '||prrelcta||' ';

  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||' and tlan.bdcontabilizacao in ('||wapenascontabilizacaoselecionada||prcontabilizacao||') ';

  --#alt:23030. Ana - 20/03/2018
  /*EXECUTE PROCEDURE CONTAR_CHAR(wclassificacao, '.') RETURNING_VALUES :wNivel;
  wsql = wsql||' and tpla.bdnivel >= ' || wNivel;

  wsql = wsql||' and TPLA.bdcodtpla = tlan.bdcredito';*/

  if ((prparticipante > 0) and (prparticipante is not null)) then
     begin
       --#Alt:24142. Corrigido tratamento do participante inicial e final
       if ((prparticipantefinal = 0) or (prparticipantefinal is null)) then
          wsql = wsql||' and tlan.bdcodterceiroc = '||prparticipante||' ';
       else
          wsql = wsql||' and tlan.bdcodterceiroc >= '||prparticipante||' ';
     end

  --#Alt:24142. Inclu?do o tratamento para o participante final. S? exista o par?metro, mas n?o estava sendo utilizado.
  if ((prparticipantefinal > 0) and (prparticipantefinal is not null)) then
     begin
       if ((prparticipante = 0) or (prparticipante is null)) then
          wsql = wsql||' and tlan.bdcodterceiroc = '||prparticipantefinal||' ';
       else
          wsql = wsql||' and tlan.bdcodterceiroc <= '||prparticipantefinal||' ';
     end

  if ((prempreendimento > 0) and (prempreendimento is not null)) then
    wsql = wsql||' and TINCORP.BDCODEMPREENDIMENTO = '||prempreendimento||' ';

  if ((prunidimob > 0) and (prunidimob is not null)) then
    wsql = wsql||' and TINCORP.BDCODIGOUNIIMOB = '||prunidimob||' ';
  --#alt:23030. fim

  wParte = wsql;
  wgroupby = ' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';

  wsql = wparte;
  wsql = wsql||' and (tlan.bdcodemp = '||prcodemp||' and tlan.bdtipolancfilial <> 2) ';
  wsql = wsql||wgroupby;

  wsql = wsql || ' union all ';
  wsql = wsql || wparte;
  wsql = wsql || ' and (tlan.bdfilial = '||prcodemp||' and tlan.bdtipolancfilial = 2) ';
  wsql = wsql||wgroupby;

  FOR EXECUTE STATEMENT wSQL INTO :wcodemp, :wfilial, :wtipolancfilial, :wsalant, :wsalatu DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      wpos_pernamatriz = POSITION(prcodemp, wcodemp);
      wpos_matriz = POSITION(wcodemp,  prcodemp);
      wpos_filial = POSITION(wfilial,  prcodemp);
      IF (((prcodemp = wcodemp) AND (wfilial = 0)) OR
          --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
          ((prcodemp = wfilial) AND (2 = wtipolancfilial)) OR
          --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
          ((prcodemp = wcodemp) AND (wfilial <> 0) AND (2 <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
          --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
          ((prmatrizfilialconsolidado = 1) AND (prcodemp <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
          --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
          ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (2 = wtipolancfilial) AND (wpos_filial > 0))) THEN
         BEGIN
           saldo_ant_cre = saldo_ant_cre + wsalant;
           SALDO_cre = SALDO_cre + wsalatu;
         END
    END

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;

  -- MOVIMENTO _________________________________________________________________
  movimento = saldo_atual - saldo_anterior; --alt:9515 - Adicionado campo do movimento. Pedro


  SUSPEND;
END
^

/* Alter (SP_RETORNA_SALDO_MATRIZFILIAL) */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WCODEMPEFILIAL INTEGER;
DECLARE VARIABLE WSALDODEB NUMERIC(15,2);
DECLARE VARIABLE WSALDOCRE NUMERIC(15,2);
DECLARE VARIABLE WSALANTDEB NUMERIC(15,2);
DECLARE VARIABLE WSALANTCRE NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
BEGIN
  codemp = prcodemp;

  IF (prmatrizfiliais IS NULL) THEN
     prmatrizfiliais = prcodemp;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and tpla.bdctalon like '''||wclassificacao||'%'' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);



  -- retorna as empresas selecionadas
  wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||PRMATRIZFILIAIS||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  wsaldodeb = 0;
  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  wsaldocre = 0;
  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  wsalantdeb = 0;
  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  wsalantcre = 0;

  movimento = 0;

  FOR EXECUTE STATEMENT wsqlemp
              INTO :wcodempefilial DO
  BEGIN


  -- SALDO A D?BITO ____________________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsaldodeb do
  if (wsaldodeb is null) then
     wsaldodeb=0;*/
  wsaldodeb = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsaldodeb = wsaldodeb + wvlr;
    END
  saldo_deb = saldo_deb + wsaldodeb;

--  exception ex_date;

  -- SALDO A CR?DITO ___________________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN '; */
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsaldocre do
  if (wsaldocre is null) then
     wsaldocre=0;*/
  wsaldocre = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsaldocre = wsaldocre + wvlr;
    END
  saldo_cre = saldo_cre + wsaldocre;

  -- SALDO ANTERIOR A D?BITO _________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsalantdeb do
  if (wsalantdeb is null) then
     wsalantdeb=0;*/
  wsalantdeb = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsalantdeb = wsalantdeb + wvlr;
    END
  saldo_ant_deb = saldo_ant_deb + wsalantdeb;

  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';  */
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsalantcre do
  if (wsalantcre is null) then
     wsalantcre=0;*/
  wsalantcre = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsalantcre = wsalantcre + wvlr;
    END

  saldo_ant_cre = saldo_ant_cre + wsalantcre;

END /* matriz e filiais */

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;
  ELSE
    BEGIN
      movimento = saldo_atual - saldo_anterior;
    END

  SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: VLAL_SP_RETORNA_INT_CONTABLALUR for: SP_RETORNA_SALDO_MATRIZFILIAL_X */
ALTER PROCEDURE VLAL_SP_RETORNA_INT_CONTABLALUR(PRCODEMP VARCHAR(2048),
PRMATRIZFILIAL VARCHAR(2048),
PRCODCONTABLALUR INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRACUMULADO INTEGER,
PRDATALANC DATE,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRTIPOLANC INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRREFERENCIA INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA VARCHAR(7),
BDMESANO INTEGER,
BDDATA DATE,
BDCONTA INTEGER,
BDNOMLPA VARCHAR(60),
BDVALOR NUMERIC(15,2),
BDTIPOLANC INTEGER,
BDCODTPLA INTEGER,
BDCHAVELAN INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_RETORNA_SALDO_MATRIZFILIAL_X) */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL_X(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0,
PRCODTERCEIRO INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER,
CHAVELAN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WCODEMPEFILIAL INTEGER;
DECLARE VARIABLE WSALDODEB NUMERIC(15,2);
DECLARE VARIABLE WSALDOCRE NUMERIC(15,2);
DECLARE VARIABLE WSALANTDEB NUMERIC(15,2);
DECLARE VARIABLE WSALANTCRE NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WVLR_SALANT_DEB NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALATU_DEB NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALANT_CRE NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALATU_CRE NUMERIC(15,2);
DECLARE VARIABLE WCHAVELAN INTEGER;
DECLARE VARIABLE WDEBCRE INTEGER;
BEGIN
  codemp = prcodemp;
  IF (prmatrizfiliais IS NULL) THEN
     prmatrizfiliais = prcodemp;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||' and tpla.bdctalon starts with '''||wclassificacao||''' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- retorna as empresas selecionadas
  wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  --wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) '; --alt:13181 - N?o usa para nada este join. Pedro
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||PRMATRIZFILIAIS||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  wsaldodeb = 0;
  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  wsaldocre = 0;
  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  wsalantdeb = 0;
  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  wsalantcre = 0;
  movimento = 0;

  FOR EXECUTE STATEMENT wsqlemp
              INTO :wcodempefilial DO
  BEGIN

    --alt:11995 - 12/08/2015 - Somente ir? agruprar tudo se n?o estiver fazendo isso na integra??o do Cont?bil pro Lalur (na parte de gravar as chaves dos lan?amentos integrados). Pedro
    wSQL = '';
    IF ((PRINTCONTABILLALUR IS NULL) OR (PRINTCONTABILLALUR = 0))  THEN
      BEGIN
        wsql =        'select bddebcre, bdcodemp, bdfilial, bdtipolancfilial, null as BDCHAVE,';
        wsql = wsql|| '       sum(bdsalant_deb) as bdsalant_deb, sum(bdsalatu_deb) as bdsalatu_deb, ';
        wsql = wsql|| '       sum(bdsalant_cre) as bdsalant_cre, sum(bdsalatu_cre) as bdsalatu_cre  ';
    
        wsql = wsql|| ' from (';
      END
    --alt:11995 - Fim

    /*****D?bito***************************************************************************************************************************************************************************/

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| 'Select 1 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, TLAN.BDCHAVE, ';
    ELSE
      wsql = wsql|| 'Select 1 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, ';
    --alt:13181 - Fim

    --if ((prcc <> 0) and (not (prcc is null))) then
    --   SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP))
    --else
      --coalesce(sum(tlan.bdvalor),0) AS SOMA
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata < '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalant_deb, ';
    
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata >= '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalatu_deb, ';
        wsql = wsql|| '0 as bdsalant_cre, 0 as bdsalatu_cre ';
    
        wsql = wsql|| ' FROM VSUC_EMPRESAS_TLAN TLAN ';
    
    IF (wlevel > 1) THEN
       BEGIN
         wsql = wsql|| ' inner join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null)) ';
         IF (prrelcta IS NOT NULL) THEN
            wsql = wsql|| ' and (tpla.bdrelcta = '||prrelcta||')) ';
         ELSE
            wsql = wsql|| ' ) ';
       END
  
    wsql = wsql|| ' where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';

    --alt:11995 - 30/07/2015 - Quando for o processo de integra??o do cont?bil para o lalur n?o deve somar os lan?amentos j? integrados manualmente. Pedro
    IF (PRINTCONTABILLALUR = 1) THEN
       wsql = wsql||' and (not exists (select BDCHAVE from VLAL_VINCULO_CONTABIL_LALUR where BDCODEMPFILIAL = tlan.BDCODEMP and BDCHAVE = tlan.BDCHAVE))';
  
    IF (prcontabilizacao <> 99) THEN
       wsql = wsql|| ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

    IF (wlevel = 1) THEN
       wsql = wsql|| ' and (tlan.bddebito = '||prconta||') ';
    ELSE
       wsql = wsql|| ' and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

    --#Alt:19568. Inclu?do o filtro do participante
    IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
       wsql = wsql|| ' and (tlan.bdcodterceirod = '||prcodterceiro||') ';
    
    --alt:7728 - Estava comentado o ignorar zeramento, habilitei novamente porque estava gerando uma diferen?a de saldos. Pedro
    IF (prignorazeramento = 1) THEN
       wsql = wsql|| ' AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
    --alt:7728 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
       --  AND (TLCC.bdcodtpcc = 'prcc')
    
    IF (bdconciliados = 1) THEN
       wsql = wsql|| ' and (Upper(BDCONCD) = '''||'TRUE'||''') ';
    ELSE
    IF (bdconciliados = 2) THEN
       wsql = wsql|| ' and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null)) ';
  
    wsql = wsql|| ' and (tlan.bddata <= '''||wdatfin||''') ';

    --alt:11995 - Se estiver carregando as chaves de lan?amentos para a integra??o do Lalur, n?o pode carregar chaves de per?odos anteriores. Pedro
    IF (PRINTCONTABILLALUR = 1)  THEN
      wsql = wsql|| ' and (tlan.bddata >= '''||wdatini||''') ';

    --alt:9604 - Alterada regra do c?digo da empresa e c?digo da filial, pois antes ele n?o verificava o TipoLancFilial
    --e pegava registros que estavam lan?ado na filial ou na matriz que n?o deveriam trazer aqui. Pedro
    --wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
    wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL <> 1) or (bdfilial = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL = 1)) ';
  
    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, TLAN.BDCHAVE ';
    ELSE
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial ';
    --alt:13181 - Fim
    

    /******Cr?dito**************************************************************************************************************************************************************/
    wsql = wsql|| ' union all ';

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' Select 2 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, TLAN.BDCHAVE, 0 as bdsalant_deb, 0 as bdsalatu_deb, ';
    ELSE
      wsql = wsql|| 'Select 2 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, 0 as bdsalant_deb, 0 as bdsalatu_deb, ';
    --alt:13181 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
      --   SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP))
      --else
        --coalesce(sum(tlan.bdvalor),0) AS SOMA
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata < '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalant_cre, ';
    
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata >= '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalatu_cre ';
    
        wsql = wsql|| ' FROM VSUC_EMPRESAS_TLAN TLAN ';
    
    IF (wlevel > 1) THEN
       BEGIN
         wsql = wsql|| ' inner join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null)) ';
         IF (prrelcta IS NOT NULL) THEN
            wsql = wsql|| ' and (tpla.bdrelcta = '||prrelcta||')) ';
         ELSE
            wsql = wsql|| ' ) ';
       END
    
    wsql = wsql|| ' where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
    
    --alt:11995 - 30/07/2015 - Quando for o processo de integra??o do cont?bil para o lalur n?o deve somar os lan?amentos j? integrados manualmente. Pedro
    IF (printcontabillalur = 1) THEN
       wsql = wsql||' and (not exists (select BDCHAVE from VLAL_VINCULO_CONTABIL_LALUR where BDCODEMPFILIAL = tlan.BDCODEMP and BDCHAVE = tlan.BDCHAVE))';

    IF (prcontabilizacao <> 99) THEN
       wsql = wsql|| ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

    IF (wlevel = 1) THEN
       wsql = wsql|| ' and (tlan.bdcredito = '||prconta||') ';
    ELSE
       wsql = wsql|| ' and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

    --#Alt:19568. Inclu?do o filtro do participante
    IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
       wsql = wsql|| ' and (tlan.bdcodterceiroc = '||prcodterceiro||') ';
    
    --alt:7728 - Estava comentado o ignorar zeramento, habilitei novamente porque estava gerando uma diferen?a de saldos. Pedro
    IF (prignorazeramento = 1) THEN
       wsql = wsql|| ' AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
    --alt:7728 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
       --  AND (TLCC.bdcodtpcc = 'prcc')
    
    IF (bdconciliados = 1) THEN
       wsql = wsql|| ' and (Upper(BDCONCD) = '''||'TRUE'||''') ';
    ELSE
    IF (bdconciliados = 2) THEN
       wsql = wsql|| ' and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null)) ';
  
    wsql = wsql|| ' and (tlan.bddata <= '''||wdatfin||''') ';

    --alt:11995 - Se estiver carregando as chaves de lan?amentos para a integra??o do Lalur, n?o pode carregar chaves de per?odos anteriores. Pedro
    IF (PRINTCONTABILLALUR = 1)  THEN
      wsql = wsql|| ' and (tlan.bddata >= '''||wdatini||''') ';

    --alt:9604 - Alterada regra do c?digo da empresa e c?digo da filial, pois antes ele n?o verificava o TipoLancFilial
    --e pegava registros que estavam lan?ado na filial ou na matriz que n?o deveriam trazer aqui. Pedro
    --wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
    wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL <> 2) or (bdfilial = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL = 2)) ';
  

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, TLAN.BDCHAVE ';
    ELSE
       wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial ';
    --alt:13181 - Fim

  --alt:11995 - 12/08/2015 - Somente ir? agruprar tudo se n?o estiver fazendo isso na integra??o do Cont?bil pro Lalur (na parte de gravar as chaves dos lan?amentos integrados). Pedro
  IF ((PRINTCONTABILLALUR IS NULL) OR (PRINTCONTABILLALUR = 0))  THEN
    wsql = wsql|| ' ) group by bddebcre, bdcodemp, bdfilial, bdtipolancfilial ';

  wvlr_salant_deb = 0;
  wvlr_salatu_deb = 0;
  wvlr_salant_cre = 0;
  wvlr_salatu_cre = 0;

  wsalantdeb = 0;
  wsaldodeb = 0;
  wsalantcre = 0;
  wsaldocre = 0;

  FOR EXECUTE STATEMENT wSQL INTO :wdebcre, :wcodemp,:wfilial,:wtipolancfilial, :CHAVELAN, :wvlr_salant_deb, :wvlr_salatu_deb, :wvlr_salant_cre, :wvlr_salatu_cre DO
    BEGIN
      IF (wvlr_salant_deb IS NULL) THEN
         wvlr_salant_deb = 0;

      IF (wvlr_salatu_deb IS NULL) THEN
         wvlr_salatu_deb = 0;

      IF (wvlr_salant_cre IS NULL) THEN
         wvlr_salant_cre = 0;

      IF (wvlr_salatu_cre IS NULL) THEN
         wvlr_salatu_cre = 0;

      --alt:13903 - 29/03/2016 - N?o estava verificando a regra do "lan?ar a" quando era no cr?dito, estava fixo o d?bito. Pedro
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wdebcre,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          wsalantdeb = wsalantdeb + wvlr_salant_deb;
          wsaldodeb = wsaldodeb + wvlr_salatu_deb;
          wsalantcre = wsalantcre + wvlr_salant_cre;
          wsaldocre = wsaldocre + wvlr_salatu_cre;

          --alt:11995 - 12/08/2015 - Se estiver fazendo o processo de gravar as chaves integradas do Cont?bil pro Lalur deve retornar um lan?amento para cada registro. Pedro
          IF ((CHAVELAN > 0) AND (printcontabillalur = 1)) THEN
            BEGIN
              CODEMP = :wcodempefilial;
              SUSPEND;
            END
        END
    END

    saldo_deb = saldo_deb + wsaldodeb;
    saldo_ant_deb = saldo_ant_deb + wsalantdeb;
    saldo_cre = saldo_cre + wsaldocre;
    saldo_ant_cre = saldo_ant_cre + wsalantcre;

  END /* matriz e filiais */

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB - SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE - SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;
  ELSE
    BEGIN
      movimento = saldo_atual - saldo_anterior;
    END

  --alt:11995 - 12/08/2015 - S? retorna aqui se n?o estiver fazendo o processo de integra??o, para n?o duplicar registros. Pedro
  IF ((printcontabillalur = 0) OR (printcontabillalur IS NULL))  THEN
    SUSPEND;
END
^

/* Alter (SP_SETA_CADEMPRESA) */
ALTER PROCEDURE SP_SETA_CADEMPRESA(PRVALUE INTEGER)
 AS
BEGIN
  -- gilberto - 15/09/2014 - respons?vel por n?o deixar gerar tarefas autom?ticas no cadastro de empresas
  IF (prvalue IS NOT NULL AND prvalue <> 0) THEN
     rdb$set_context('USER_SESSION', 'W_CADEMPRESA', CAST(prvalue AS VARCHAR(6)));
  ELSE
     rdb$set_context('USER_SESSION', 'W_CADEMPRESA', NULL);
END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_0110 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_0110(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_1100_1500 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_1100_1500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_F60013001700 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_F60013001700(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M100 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M100_M500PAR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M200 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M200(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M210_M610AUX for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M220_M620 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M220_M620(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M230_M630 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M230_M630(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M350 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M350(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M400_M800PAR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M500 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURACAO_BLOCOM_M600 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M600(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_APURADOS_VALREF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURADOS_VALREF(PRCODEMP VARCHAR(6000),
PRCOLABORADOR VARCHAR(6000),
PRCOMPETENCIA INTEGER,
PRNRVIAS INTEGER)
 RETURNS(BDNRVIA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCONVREF INTEGER,
BDCOMPETENCIA INTEGER,
BDQUANTIDADE INTEGER,
BDTPAPURACAO INTEGER,
BDDTINICIAL DATE,
BDDTFINAL DATE,
BDDESCCONVREF VARCHAR(50),
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDNOMCOLUPPER /* DM_BDNOMCOL */ VARCHAR(70),
BDRGCOL VARCHAR(20),
BDCPFCOL VARCHAR(14),
BDVALUNI NUMERIC(18,6),
BDVALCUSTOEMP NUMERIC(18,6),
BDVALDESCONTO NUMERIC(18,6),
BDQTDCONVENIOREF INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_APURADOS_VALTRANS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_APURADOS_VALTRANS(PRCODEMP VARCHAR(25000),
PRCOLABORADOR VARCHAR(32700),
PRCOMPETENCIA INTEGER,
PRNRVIAS INTEGER)
 RETURNS(BDNRVIA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODITI INTEGER,
BDCOMPETENCIA INTEGER,
BDQUANTIDADE INTEGER,
BDTPAPURACAO INTEGER,
BDDTINICIAL DATE,
BDDTFINAL DATE,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDNOMCOLUPPER /* DM_BDNOMCOL */ VARCHAR(70),
BDRGCOL VARCHAR(20),
BDCPFCOL VARCHAR(14),
BDDESCITI VARCHAR(40),
BDLINHAITI VARCHAR(20),
BDVALUNI NUMERIC(18,6),
BDVALCUSTOEMP NUMERIC(18,6),
BDVALDESCONTO NUMERIC(18,6),
BDQTDITINERARIOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_ATU_CAMPOS_GERADOR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_ATU_CAMPOS_GERADOR AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_COMP_ACUMULADO_GPS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_COMP_ACUMULADO_GPS(PRCODEMP INTEGER,
PRAGRUPADO INTEGER,
PRCODTPCC INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOFOLHA INTEGER,
PRCHAVEDARF INTEGER = 0,
PRCOMPL13 SMALLINT = 1)
 RETURNS(BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULADO NUMERIC(15,6),
BDACUMULADOTERC NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONS_CALC_INTERMITENTE for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONS_CALC_INTERMITENTE(PRCODEMP INTEGER = null,
PRCODCOL INTEGER = null,
PRCODCONTRATO INTEGER = null,
PRDATAINICIAL DATE = null,
PRDATAFINAL DATE = null)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRGCOL VARCHAR(13),
BDCODCONTTI INTEGER,
BDDESCCONTRATOTI VARCHAR(2000),
BDDATACONVTI DATE,
BDHORACONVTI TIME,
BDDATAINISERVTI DATE,
BDDATAFIMSERVTI DATE,
BDDATAPAGTI DATE,
BDLIQUIDO NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDDATAPGTOFN DATE,
BDFGTSFN NUMERIC(18,6),
BDFGTS13FN NUMERIC(18,6),
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(18,6),
BDREFAUXVFN NUMERIC(18,6),
BDVALVFN NUMERIC(18,6),
BDVALIFN NUMERIC(18,6),
BDDESCVER VARCHAR(40),
BDTIPOCODVER INTEGER,
BDORDEMVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONS_FERIAS_PER_AQUIS_ESCALA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONS_FERIAS_PER_AQUIS_ESCALA(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PRPRIDIA DATE,
PRULTDIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDABONOFE NUMERIC(18,6),
BDQTDGOZOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDNOMEMP VARCHAR(100),
BDNOMCOL VARCHAR(70),
BDSALDOFINALSINDFE NUMERIC(18,6),
BDFERIADOSFE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTA_COL_POR_REF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTA_COL_POR_REF(PREMP INTEGER,
PRCOL INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDREFCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTA_EMP_POR_REF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTA_EMP_POR_REF(PREMP INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTA_TERCEIRO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTA_TERCEIRO(PRCODTER INTEGER,
PRREF INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER /* DM_BDENDERECO */ VARCHAR(60),
BDNUMTER VARCHAR(10),
BDCOMPTER /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDCEPTER VARCHAR(9),
BDBAITER VARCHAR(60),
BDDDDTER VARCHAR(3),
BDFONETER /* DM_BDTELEFONE */ VARCHAR(15),
BDFAXTER /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILTER /* DM_BDEMAIL */ VARCHAR(200),
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDORGAOPUBLICO VARCHAR(5),
BDCODTIPO INTEGER,
BDCODIBGE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTACLIENTES for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTACLIENTES(PRREFMICRO INTEGER,
PRCODCLI VARCHAR(10240),
PRCODSITCLI INTEGER)
 RETURNS(BDCODCLI INTEGER,
BDCODESC INTEGER,
BDCODPRESER INTEGER,
BDCODCLIMATRIZ INTEGER,
BDCNPJCLI VARCHAR(18),
BDDATAINIATIVCLI DATE,
BDDATAFIMATIVCLI DATE,
BDORGAOCLI VARCHAR(20),
BDNUMREGCLI VARCHAR(40),
BDNOMECARTORIO VARCHAR(100),
BDDATAREGCLI DATE,
BDLIVROREG VARCHAR(15),
BDFOLHAREG VARCHAR(15),
BDDOCAUXREG VARCHAR(18),
BDCODTIPOCLI INTEGER,
BDDATACADCLI DATE,
BDCODCID INTEGER,
BDCODCNAE INTEGER,
BDCODNATJUR INTEGER,
BDDESCPLASITFIN VARCHAR(50),
BDCODPLASITFIN INTEGER,
BDAPECLI /* DM_BDAPEMP */ VARCHAR(20),
BDNOMCLI /* DM_BDNOMEMP */ VARCHAR(100),
BDNOMREDUZCLI /* DM_BDNOMREDUZEMP */ VARCHAR(40),
BDCEPCLI VARCHAR(9),
BDLOGRCLI VARCHAR(15),
BDENDCLI /* DM_BDENDERECO */ VARCHAR(60),
BDNUMCLI INTEGER,
BDCOMPLCLI /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAICLI /* DM_BDBAIRRO */ VARCHAR(50),
BDDDDCLI INTEGER,
BDFONECLI /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDFAXCLI INTEGER,
BDFONEFAXCLI /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDCELCLI INTEGER,
BDCELCLI /* DM_BDTELEFONE */ VARCHAR(15),
BDCXPCLI /* DM_CXPOSTAL */ VARCHAR(15),
BDIECLI VARCHAR(20),
BDIMCLI VARCHAR(20),
BDEMAILCLI /* DM_BDEMAIL */ VARCHAR(200),
BDCAPITALSOC /* DM_NUMERIC_15_2 */ NUMERIC(15,2),
BDORGAOPUBLICO /* DM_BOOLEAN */ VARCHAR(5),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCCNAE VARCHAR(200),
BDDESCNAT VARCHAR(100),
BDNUMFUN INTEGER,
BDCODPLATRIB INTEGER,
BDINATIVO /* DM_BOOLEAN */ VARCHAR(5),
BDDESCPLATRIB VARCHAR(50),
BDCODIBGECID INTEGER,
BDCODFEDCID INTEGER,
BDCODSPEDPAIS INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTACLIENTES_SIS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTACLIENTES_SIS(PRREFMICRO INTEGER,
PRCODCLI INTEGER,
PRCODSITCLI INTEGER)
 RETURNS(BDCODCLI INTEGER,
BDCODESC INTEGER,
BDCODPRESER INTEGER,
BDCODCLIMATRIZ INTEGER,
BDCNPJCLI VARCHAR(18),
BDDATAINIATIVCLI DATE,
BDDATAFIMATIVCLI DATE,
BDORGAOCLI VARCHAR(20),
BDNUMREGCLI VARCHAR(40),
BDNOMECARTORIO VARCHAR(100),
BDDATAREGCLI DATE,
BDLIVROREG VARCHAR(15),
BDFOLHAREG VARCHAR(15),
BDDOCAUXREG VARCHAR(18),
BDCODTIPOCLI INTEGER,
BDDATACADCLI DATE,
BDCODCID INTEGER,
BDCODCNAE INTEGER,
BDCODNATJUR INTEGER,
BDAPECLI /* DM_BDAPEMP */ VARCHAR(20),
BDNOMCLI /* DM_BDNOMEMP */ VARCHAR(100),
BDNOMREDUZCLI /* DM_BDNOMREDUZEMP */ VARCHAR(40),
BDCEPCLI VARCHAR(9),
BDLOGRCLI VARCHAR(15),
BDENDCLI /* DM_BDENDERECO */ VARCHAR(60),
BDNUMCLI INTEGER,
BDCOMPLCLI /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAICLI /* DM_BDBAIRRO */ VARCHAR(50),
BDDDDCLI INTEGER,
BDFONECLI /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDFAXCLI INTEGER,
BDFONEFAXCLI /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDCELCLI INTEGER,
BDCELCLI /* DM_BDTELEFONE */ VARCHAR(15),
BDCXPCLI /* DM_CXPOSTAL */ VARCHAR(15),
BDIECLI VARCHAR(20),
BDIMCLI VARCHAR(20),
BDEMAILCLI /* DM_BDEMAIL */ VARCHAR(200),
BDCAPITALSOC /* DM_NUMERIC_15_2 */ NUMERIC(15,2),
BDORGAOPUBLICO /* DM_BOOLEAN */ VARCHAR(5),
BDDATAENTRADA DATE,
BDDATASAIDA DATE,
BDCODCONT INTEGER,
BDCONTATO VARCHAR(60),
BDPROFISCONTATO VARCHAR(60),
BDDATANASCCON DATE,
BDCPFCON VARCHAR(18),
BDCODCIDETI INTEGER,
BDNOMENDETI /* DM_BDNOMEMP */ VARCHAR(100),
BDLOGRETI VARCHAR(15),
BDENDERECOETI /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEROETI INTEGER,
BDCOMPLETI /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAIRROETI /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPETI VARCHAR(9),
BDCXPETI /* DM_CXPOSTAL */ VARCHAR(15),
BDNOMCIDETI VARCHAR(40),
BDSIGLAUFETI VARCHAR(2),
BDCODENQFED INTEGER,
BDCOMERCIO /* DM_BOOLEAN */ VARCHAR(5),
BDINDUSTRIA /* DM_BOOLEAN */ VARCHAR(5),
BDSERVICO /* DM_BOOLEAN */ VARCHAR(5),
BDANEXOIII /* DM_BOOLEAN */ VARCHAR(5),
BDANEXOIV /* DM_BOOLEAN */ VARCHAR(5),
BDANEXOV /* DM_BOOLEAN */ VARCHAR(5),
BDANEXOVI /* DM_BOOLEAN */ VARCHAR(5),
BDPERINSS /* DM_NUMERIC_7_4_ALIQ */ NUMERIC(7,4),
BDDEDINSSNF /* DM_BOOLEAN */ VARCHAR(5),
BDUSARPERISS INTEGER,
BDRETIR /* DM_BOOLEAN */ VARCHAR(5),
BDRETCSLL /* DM_BOOLEAN */ VARCHAR(5),
BDRETCOF /* DM_BOOLEAN */ VARCHAR(5),
BDRETPIS /* DM_BOOLEAN */ VARCHAR(5),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCSITCLI VARCHAR(100),
BDDESCCNAE VARCHAR(200),
BDDESCNAT VARCHAR(100),
BDNUMFUN INTEGER,
BDINATIVO /* DM_BOOLEAN */ VARCHAR(5),
BDCODPLATRIB INTEGER,
BDDESCPLATRIB VARCHAR(50),
BDCODIBGECID INTEGER,
BDCODFEDCID INTEGER,
BDCODSPEDPAIS INTEGER,
BDINCENTCULT /* DM_BOOLEAN */ VARCHAR(5),
BDCODIBGECIDETI INTEGER,
BDCODFEDCIDETI INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODSITESP INTEGER,
BDCODPLASITFIN INTEGER,
BDDESCPLASITFIN VARCHAR(50),
BDCODHIST INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTADESPESAS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTADESPESAS(PRREFDESP INTEGER,
PRCODDESP INTEGER)
 RETURNS(BDCODDESP INTEGER,
BDCLASSDESP /* DM_CLASSCONTAS */ VARCHAR(40),
BDDESCDESP VARCHAR(100),
BDSABDOMFER INTEGER,
BDDIAVENC INTEGER,
BDTIPODESP INTEGER,
BDVALORDESP /* DM_NUMERIC_15_2 */ NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTAEMPRESAS_SEARCH for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTAEMPRESAS_SEARCH(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDAPEEMP VARCHAR(20),
BDIEEMP VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTAEMPRESAS_SIS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTAEMPRESAS_SIS(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDDATAINIATIVEMP DATE,
BDORGAOEMP VARCHAR(8),
BDDATAREGEMP DATE,
BDDATACONSTEMP DATE,
BDDESCCARTEMP VARCHAR(40),
BDDATAFIMATIVEMP DATE,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCODCENTROS INTEGER,
BDCODCID INTEGER,
BDCODCONT INTEGER,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDNOMREDUZEMP /* DM_BDNOMREDUZEMP */ VARCHAR(40),
BDAPEEMP /* DM_BDAPEMP */ VARCHAR(20),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDFAXEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDCELULAREMP INTEGER,
BDCELULAREMP /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILEMP /* DM_BDEMAIL */ VARCHAR(200),
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDLOGREMP VARCHAR(15),
BDIEEMP VARCHAR(20),
BDIMEMP VARCHAR(20),
BDSITEMP VARCHAR(5),
BDDDDFAXEMP INTEGER,
BDNOMCID VARCHAR(40),
BDCODUF INTEGER,
BDNOMECONT VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCUF VARCHAR(40),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODCONFATIVO INTEGER,
BDSUFRAMA VARCHAR(9),
BDCODACESSOSN VARCHAR(12),
BDPERFILSPED INTEGER,
BDATIVIDADESPED INTEGER,
BDCODCONFIPI INTEGER,
BDCODCONFIRLP INTEGER,
BDCODCONFDIMESC INTEGER,
BDCODPORTEEMP INTEGER,
BDCODAPUCON INTEGER,
BDCODESCCONT INTEGER,
BDCODREGAPU INTEGER,
BDCONTPRODEC VARCHAR(5),
BDNRPARPRODEC INTEGER,
BDLANBCICMSVALCONT VARCHAR(5),
BDLANBCICMSISEOUT INTEGER,
BDLANCLISAISER VARCHAR(5),
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDMOVSER VARCHAR(5),
BDPERCISS NUMERIC(15,6),
BDREDPERCISS NUMERIC(15,6),
BDMOVIRRF VARCHAR(5),
BDALIQIRRF NUMERIC(15,6),
BDISENTOIRRF NUMERIC(15,6),
BDEMPINATIVA VARCHAR(5),
BDEMPDIFPAPEL VARCHAR(5),
BDEMPBARREST VARCHAR(5),
BDVERIFICARNOTASJALAN INTEGER,
BDCODPLANOONLINE INTEGER,
BDLRISSSN NUMERIC(15,6),
BDCOMERCIO VARCHAR(5),
BDINDUSTRIA VARCHAR(5),
BDSERVICO VARCHAR(5),
BDANEXOIII VARCHAR(5),
BDANEXOIV VARCHAR(5),
BDANEXOV VARCHAR(5),
BDCODENQFED INTEGER,
BDSUBSTRIB INTEGER,
BDCODCONFDACON INTEGER,
BDCODCONFICMSSPED INTEGER,
BDCODCONFCIAP INTEGER,
BDREDBCICMSENT NUMERIC(15,6),
BDREDBCICMSSAI NUMERIC(15,6),
BDCODCONFDASN INTEGER,
BDRETPARPIS VARCHAR(5),
BDRETPARCOFINS VARCHAR(5),
BDRETPARCSLL VARCHAR(5),
BDRETPARIRRF VARCHAR(5),
BDRETPARISSQN VARCHAR(5),
BDRETPARINSS VARCHAR(5),
BDRETPARFUNRURAL VARCHAR(5),
BDTIPOAPURACAO INTEGER,
BDSOMFREBASEICMS VARCHAR(5),
BDSOMFREVLRCONTAB VARCHAR(5),
BDCODPLATROCA INTEGER,
BDCODPLACFOP INTEGER,
BDCODCONFBLOCOP INTEGER,
BDCREDPRESUMIDO VARCHAR(5),
BDTERMOACEITE VARCHAR(5),
BDANTECIPAIMPOSTO VARCHAR(5),
BDTIPODECLARANTEDMED INTEGER,
BDREGISTROANSDMED INTEGER,
BDNUMEROCNESDMED INTEGER,
BDDTOBRIGSPEDCONT DATE,
BDTIPOAPURACAORET INTEGER,
BDTIPOAPURACAORETIR INTEGER,
BDDTOBRIGSPEDICMS DATE,
BDCODCONTEF INTEGER,
BDLIVRO VARCHAR(15),
BDFOLHA VARCHAR(15),
BDNOMECARTORIO VARCHAR(100),
BDLANCAPARCELAAUTO VARCHAR(5),
BDCODIGOPLA INTEGER,
BDINDATIV INTEGER,
BDTRANMANUAL VARCHAR(5),
BDIMPORTARVALORESICMSSN /* DM_BOOLEAN */ VARCHAR(5),
BDDIFALIQ VARCHAR(5),
BDDIFALIQBASEEM INTEGER,
BDANEXOVI /* DM_BOOLEAN */ VARCHAR(5),
BDCODPLATRIB INTEGER,
BDCODPLAPADRAOREF INTEGER,
BDINDNATPJ INTEGER,
BDCODIBGE INTEGER,
BDFORMATRIBUTACAO INTEGER,
BDSOMAPISCOFVLRCONT /* DM_BOOLEAN */ VARCHAR(5),
BDSOMAIIVLRCONT /* DM_BOOLEAN */ VARCHAR(5),
BDMANTERPARCELAS /* DM_BOOLEAN */ VARCHAR(5),
BDCODPLANOINCONS INTEGER,
BDABRIRRATEIO /* DM_BOOLEAN */ VARCHAR(5),
BDNAOPERMITERATEIOGRUPO /* DM_BOOLEAN */ VARCHAR(5),
BDINTEGRANET /* DM_BOOLEAN */ VARCHAR(5),
BDSOMAIPIPROD /* DM_BOOLEAN */ VARCHAR(5),
BDSOMAICMSVLRCONT /* DM_BOOLEAN */ VARCHAR(5),
BDCODPLAE115 INTEGER,
BDDATACADEMP DATE,
BDCODCLATRI INTEGER,
BDDATAOBRIGREINF DATE,
BDSOMASTPROD /* DM_BOOLEAN */ VARCHAR(5),
BDCALCANTICMS VARCHAR(5),
BDCONSIPIBC VARCHAR(5),
BDIMPICMSST VARCHAR(5),
BDANEXOIII_2018 VARCHAR(5),
BDANEXOIV_2018 VARCHAR(5),
BDANEXOV_2018 VARCHAR(5),
BDSTATUSEMP INTEGER,
BDQTDBACKUPEMP INTEGER,
BDIMPORTARISS VARCHAR(5),
BDINCORPORADORAS /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONSULTASERVICOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_CONSULTASERVICOS(PRREFSER INTEGER,
PRCODOBRSER INTEGER)
 RETURNS(BDCODOBRSER INTEGER,
BDCHAVE INTEGER,
BDCLASSIFICACAO VARCHAR(60),
BDDESCRICAO VARCHAR(100),
BDPERIODICIDADE INTEGER,
BDDIA INTEGER,
BDANTECIPAR VARCHAR(5),
BDVENCE INTEGER,
BDALERTA INTEGER,
BDCRIACAO DATE,
BDEXTINTO DATE,
BDSITEGOVERNO VARCHAR(255),
BDPREVHORAS VARCHAR(6),
BDTIPO SMALLINT,
BDPREVDIAS INTEGER,
BDCODSIS INTEGER,
BDMESVENCE INTEGER,
BDENTREGA INTEGER,
BDTEMPOESTIMADO INTEGER,
BDSABDOMFER INTEGER,
BDPERISS NUMERIC(15,4),
BDPERIRRF NUMERIC(15,4),
BDPERCSLL NUMERIC(15,4),
BDPERCOF NUMERIC(15,4),
BDPERPIS NUMERIC(15,4),
BDDEDISS VARCHAR(5),
BDDEDIRRF VARCHAR(5),
BDDEDCSLL VARCHAR(5),
BDDEDCOFINS VARCHAR(5),
BDDEDPIS VARCHAR(5),
BDTIPSERV INTEGER,
BDCALCINSS VARCHAR(5),
BDSOFREREAJ VARCHAR(5),
BDDESCONTO VARCHAR(5),
BDVALORPADRAO /* DM_NUMERIC_15_2 */ NUMERIC(15,2),
BDCODCOBSERV INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_EXP_SEFIP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_EXP_SEFIP(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRDATARECFGTS DATE,
PRDATARECINSS DATE,
PRTIPOFOLHA INTEGER,
PRMODALIDADE VARCHAR(1),
PRINDRECFGST VARCHAR(1),
PRINDRECINSS VARCHAR(1))
 RETURNS(BDARQ INTEGER,
BDREG VARCHAR(360),
BDORDEM VARCHAR(70),
BDINC VARCHAR(32000),
BDCONTADOR INTEGER,
BDCODREC INTEGER,
BDMODALIDADE VARCHAR(1))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOC_SAI_SPEDCONTR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(PRCODEMP INTEGER,
PRCODPLAPADRAOREF INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100))
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_FERIADO_EMPRESA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_FERIADO_EMPRESA(PRCODEMP INTEGER,
PRDATA DATE,
PRREFERENCIA INTEGER = 0,
PRSINDICATO INTEGER = 0)
 RETURNS(BDFERIADO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_FICHA_REGISTROS_SALARIOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_FICHA_REGISTROS_SALARIOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRREF INTEGER,
PRRETORNAVAZIO INTEGER,
PRTRAZERSALINI INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDSALINICOL NUMERIC(18,6),
BDDATACOL DATE,
BDSALBASECOL NUMERIC(18,6),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODTFUC INTEGER,
BDCODSHE INTEGER,
BDDESCSHE VARCHAR(50),
BDSALBASEANT NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_FUNCOES_PLANO_EMP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_FUNCOES_PLANO_EMP(PRCODEMP INTEGER,
PRCODPLAFUC INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODCBO INTEGER,
BDDESCCBO VARCHAR(150),
BDDESCTFUC VARCHAR(40),
BDCODCBOTSIN INTEGER,
BDDESCFUNCDET VARCHAR(100),
BDINATIVA VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_GERAR_INCON_TCADPRO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_GERAR_INCON_TCADPRO(PRSESSAO INTEGER,
PRCODEMP INTEGER,
PRCODPLANOINCO INTEGER,
PRREF INTEGER,
PRIDTERMINAL INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_IMPOSTO_EMPRESA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_IMPOSTO_EMPRESA(PRCODEMP INTEGER,
PRCODSIS INTEGER,
PRTIPORETENCAO INTEGER,
PRREF INTEGER,
PRQTD INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER,
BDCODSIS INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_NOME_TERCEIRO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_NOME_TERCEIRO(PRREF INTEGER,
PRTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDNOME VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_PBM for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_PBM(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDEMP INTEGER,
BDREF INTEGER,
BDOK INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_PERC_GORJETA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_PERC_GORJETA(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(2000),
PRREF INTEGER)
 RETURNS(BDREFCOL VARCHAR(10),
BDPERCGORJ NUMERIC(18,6),
BDNOMCOL VARCHAR(200),
BDCODCOL INTEGER,
BDCODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_REL_RESUMO_IMPOSTOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_REL_RESUMO_IMPOSTOS(PRCODEMP VARCHAR(10000),
PRCODIMP VARCHAR(10000),
PRCODSIS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRDTVCTOINI DATE,
PRDTVCTOFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(200),
BDCODREC INTEGER,
BDCODSIS INTEGER,
BDCODPERIODO INTEGER,
BDDESCPERIODO VARCHAR(40),
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDMESEXTENSO VARCHAR(20),
BDQUOTA INTEGER,
BDCODCOL INTEGER,
BDCODEMPCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDPERIODO DATE,
BDNUMREFDOC VARCHAR(20),
BDDATAVCTO DATE,
BDVALOR NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDJUROS NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDOBS BLOB,
BDORDEMCOMPL INTEGER,
BDBASEIMP NUMERIC(15,6),
BDALIQIMP NUMERIC(15,6),
BDVLRIMPORIGINAL NUMERIC(15,6),
BDVLRACUMULO NUMERIC(15,6),
BDVLRMULTAJUROS NUMERIC(15,6),
BDVLROUTENTIDADE NUMERIC(15,6),
BDTIPOIMPOSTO INTEGER,
BDCOMPENSACAO NUMERIC(15,6),
BDVLRACUOUTENT NUMERIC(15,6),
BDREFPAG INTEGER,
BDDTPGTO DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_TEMPRESAIMPOSTO_REF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_TEMPRESAIMPOSTO_REF(PRCODEMP VARCHAR(20000),
PRREFERENCIA INTEGER,
PRQUANTIDADE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_TREEVIEW_CONS_ANUAL_CONF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_TREEVIEW_CONS_ANUAL_CONF(PRSISTEMA INTEGER,
PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDANOSWS VARCHAR(4))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_TREEVIEW_CONS_CONF_ONLINE for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_TREEVIEW_CONS_CONF_ONLINE(PRPLANO INTEGER,
PRCLASSIFICACAO VARCHAR(100),
PRLENGTH INTEGER,
PRREF INTEGER,
PRCHAVE INTEGER,
PRAPENASNIVEL INTEGER,
PRFILTERCLASSIFICACAO /* DM_MAXVARCHAR */ VARCHAR(32765) = '',
PRFILTRERTREEVIEW VARCHAR(200) = '')
 RETURNS(BDFORMULA VARCHAR(80),
BDFORMULAITEM VARCHAR(80),
BDCONFIGTIT VARCHAR(5),
BDCLASSIFICACAO VARCHAR(100),
BDDESCRICAO VARCHAR(500),
BDAPECTADV VARCHAR(20),
BDAPECTACV VARCHAR(20),
BDAPECTADO VARCHAR(20),
BDAPECTACO VARCHAR(20),
BDDESCONTADV VARCHAR(100),
BDDESCONTACV VARCHAR(100),
BDDESCONTADO VARCHAR(100),
BDDESCONTACO VARCHAR(100),
BDCODHISTPROV INTEGER,
BDCODHISTPGTO INTEGER,
BDCODTIPOCONTA INTEGER,
BDCODNAT INTEGER,
BDCODVER INTEGER,
BDDESCREDVER VARCHAR(20),
BDAPELIDOTER VARCHAR(20),
BDNOMENAT VARCHAR(335),
BDAPEHISTPROV VARCHAR(20),
BDAPEHISTPGTO VARCHAR(20),
BDCONTADEBPROV INTEGER,
BDCONTACREDPROV INTEGER,
BDCONTADEBPGTO INTEGER,
BDCONTACREDPGTO INTEGER,
BDCHAVE INTEGER,
BDCHAVEVINC INTEGER,
BDCODPLANOONLINE INTEGER,
BDDESCIMP VARCHAR(100),
BDDESCOREC VARCHAR(100),
BDCODOREC INTEGER,
BDCODIMP INTEGER,
BDCODTCA INTEGER,
BDCODGRUPOCLA INTEGER,
BDDESCGRUPOCLA VARCHAR(200),
BDTIPONAT INTEGER,
BDCLASSVER VARCHAR(20),
BDTIPOVER INTEGER,
BDCODITEMONLINE INTEGER,
BDAPECOMHISTPROV VARCHAR(20),
BDAPECOMHISTPGTO VARCHAR(20),
BDCODCOMPHISTPROV INTEGER,
BDCODCOMPHISTPGTO INTEGER,
BDCOMHISTPROV VARCHAR(1000),
BDCOMHISTPGTO VARCHAR(1000),
BDCONFIGPROV VARCHAR(5),
BDCONFIGDEBPROV VARCHAR(5),
BDCONFIGCREDPROV VARCHAR(5),
BDCONFIGPAG VARCHAR(5),
BDCONFIGDEBPAG VARCHAR(5),
BDCONFIGCREDPAG VARCHAR(5),
BDCONFIGHISTPROV VARCHAR(5),
BDCONFIGHISTPAG VARCHAR(5),
BDNAOCONTAB VARCHAR(5),
BDCODREC INTEGER,
BDCONTABILIZA /* DM_BOOLEAN */ VARCHAR(5),
BDATIVA /* DM_BOOLEAN */ VARCHAR(5),
BDCODOBRSER INTEGER,
BDTIPOSER INTEGER,
BDSERDESCONTO /* DM_BOOLEAN */ VARCHAR(5),
BDCHAVECTABAN INTEGER,
BDCODCLI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_TREEVIEW_CONS_IMP_EMITIDOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_TREEVIEW_CONS_IMP_EMITIDOS(PRONLINE VARCHAR(10000),
PRCODEMP VARCHAR(10000),
PRCODIMP VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO INTEGER,
PRDTVCTOINI DATE,
PRDTVCTOFIM DATE,
PRPERIODO INTEGER,
PRFILTRO INTEGER)
 RETURNS(BDVLRPGTO /* DM_NUMERIC_15_2 */ NUMERIC(15,2),
BDCODMATRIZ INTEGER,
BDTIPOLANC INTEGER,
BDNRDOCPGTO VARCHAR(18),
BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(200),
BDCODPERIODO INTEGER,
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDQUOTA INTEGER,
BDCODTPCC INTEGER,
BDDATAVCTO DATE,
BDVALOR NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDJUROS NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDOBS BLOB SUB_TYPE 1,
BDORDEMCOMPL INTEGER,
BDBASEIMP NUMERIC(15,6),
BDALIQIMP NUMERIC(15,6),
BDVLRIMPORIGINAL NUMERIC(15,6),
BDVLRMULTAJUROS NUMERIC(15,6),
BDVLROUTENTIDADE NUMERIC(15,6),
BDDTPGTO DATE,
BDLIMITEISENCAO NUMERIC(15,6),
BDDOCARRECADACAO INTEGER,
BDFORMREL VARCHAR(1000),
BDCODREC INTEGER,
BDVLRRETENCAO NUMERIC(15,2),
BDDESCTIPOCALC VARCHAR(25),
BDFLAG VARCHAR(5),
BDVLRACUMULO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VAL_HE_RAIS_FF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VAL_HE_RAIS_FF(PREMP INTEGER,
PRCOL INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDHE NUMERIC(15,6),
BDCODVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_ENT_FORMULAS_DAPI for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_ENT_FORMULAS_DAPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDCODOPDAPI INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPAPCREDDAPI NUMERIC(15,2),
BDISENTASDAPI NUMERIC(15,2),
BDNTRIBDAPI NUMERIC(15,2),
BDPARBCCREDDAPI NUMERIC(15,2),
BDDIFERIDASTDAPI NUMERIC(15,2),
BDSUSPENSASDAPI NUMERIC(15,2),
BDSTDAPI NUMERIC(15,2),
BDOUTRASDAPI NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_EXPREG30_GIASP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_EXPREG30_GIASP(PRCODEMP VARCHAR(10000),
PRREFERENCIAINICIAL INTEGER,
PRREFERENCIAFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDCODEST INTEGER,
BDCODDIPAM VARCHAR(3),
BDVALOR NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_LIVROICMSMG for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_LIVROICMSMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDNUMCAMPO INTEGER,
BDDESCFORM VARCHAR(150),
BDCODQUADRO INTEGER,
BDCODTIPO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDSEQLIVRO VARCHAR(3),
BDTITULOQ VARCHAR(150),
BDDESCQ VARCHAR(150),
BDVALOR NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_REL_APURACAO_GIAMG for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_REL_APURACAO_GIAMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDNUMITEM VARCHAR(5),
BDAREACONS VARCHAR(10),
BDESCCENTRAL VARCHAR(5),
BDTITULO VARCHAR(60),
BDREGISTRO VARCHAR(60),
BDSUBTITULO VARCHAR(80),
BDNUMITEMORD VARCHAR(7))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_ANUAL_CON2 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ANUAL_CON2(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_BLOCOM for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOM(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRCLASSIFICACAO VARCHAR(11) = NULL,
PRCODQUADRO INTEGER = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDREFERENCIA INTEGER,
BDCODQUADRO INTEGER,
BDNUMCAMPO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,2),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_BLOCOP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCLASSIFICACAO VARCHAR(10),
PRGERAL INTEGER,
PREMPFIL INTEGER,
PRCODIGOAJUSTE VARCHAR(8),
PRREINF /* DM_BOOLEAN */ VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM /* DM_BDNOMEMP */ VARCHAR(100),
BDVALOR NUMERIC(15,2),
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODEMPFILIAL INTEGER,
BDORDENATVPREV INTEGER,
BDCODIGOATVPREV VARCHAR(8),
BDDESCPREV VARCHAR(550),
BDNOMEMPFIL VARCHAR(100),
BDCODTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_CALCATIVO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_CALCATIVO(PRCODEMP VARCHAR(10000),
PRCODBEM VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO VARCHAR(30))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDREFERENCIA INTEGER,
BDFATOR NUMERIC(15,6),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_DACON for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DACON(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRTIPO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(160),
BDDESCFORM VARCHAR(160),
BDVALOR NUMERIC(18,6),
BDVALOR2 NUMERIC(18,6),
BDVALOR3 NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODREC INTEGER,
BDTIPOCREDITO INTEGER,
BDTIPOCONFDACON INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_DIME for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DIME(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCODQUADRO INTEGER,
PRCODQUADROPRINC INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCODQUADROPRINC INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDNUMITEM INTEGER,
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_GIAES for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAES(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRTIPOAPU INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDTIPOAPU INTEGER,
BDCODNAT INTEGER,
BDAUXCFOP INTEGER,
BDORDEMTTNAT INTEGER,
BDCLASSNATGRUP VARCHAR(20),
BDDESCTTNAT VARCHAR(20),
BDTITULOGRUPO VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_GIAMG for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEMORDEM VARCHAR(5),
BDNUMITEM VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_GIAPR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAPR(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRCODNAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_GIARJ for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARJ(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRCODNAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_GIARO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARO(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDCODNAT INTEGER,
BDORDEMTTNAT INTEGER,
BDTITULOGRUPO VARCHAR(80))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_GIASP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIASP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(10),
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODTIPO INTEGER,
BDCODNAT INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_ICMSSPED for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ICMSSPED(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRUF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(150),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDCODTIPOVALAGRE INTEGER,
BDDESCRICAO VARCHAR(150),
BDCODTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_IMPOSTOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IMPOSTOS(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRSIGLAIMPOSTO VARCHAR(10))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,8),
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDCLASSIFICACAO VARCHAR(10))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_IPI for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONS_IRLP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IRLP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VEF_TREEVIEW_CONSUF_GIASP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONSUF_GIASP(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRNATENTSAI INTEGER,
PRPREFIXONAT INTEGER,
PRSIGLAUF VARCHAR(2))
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDSIGLAUF VARCHAR(2),
BDPREFIXONAT INTEGER,
BDDESCRICAO VARCHAR(100),
BDVALOR NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_CONVSAU_DIRF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_CONVSAU_DIRF(PREMP INTEGER,
PRCOL INTEGER,
PRREF INTEGER,
PRPLASAUDE INTEGER = 0)
 RETURNS(BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDREF INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODDPN INTEGER,
BDNOME /* DM_BDNOMCOL */ VARCHAR(70),
BDCPF VARCHAR(14),
BDVALORMENSALIDADE NUMERIC(18,2),
BDVALORCOPAR NUMERIC(18,2),
BDCODTIPOCONV INTEGER,
BDTIPOFAIXA INTEGER,
BDDESCRICAO VARCHAR(80),
BDCNPJ /* DM_CNPJ_CPF */ VARCHAR(18),
BDREGISTROANS INTEGER,
BDRAZAOSOCIAL VARCHAR(80),
BDPARENESCODPN INTEGER,
BDDATANASCDPN DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_DEC_REND_7_2 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_DEC_REND_7_2(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODDPN INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDCPF VARCHAR(14),
BDCNPJ VARCHAR(18),
BDRAZAOSOCIAL VARCHAR(80),
BDVALOR NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_EMP_MULTVINC_PGTO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_EMP_MULTVINC_PGTO(PREMPRESA VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_FECHAMENTO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_FECHAMENTO(PREMPRESAS VARCHAR(32000),
PRREF INTEGER = 0,
PRTIPOPER INTEGER = 1)
 RETURNS(BDCODEMP INTEGER,
BDFECHAMENTO INTEGER,
BDDATA DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_TREEVIEW_CONS_ADSALARIO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_ADSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDATAAD DATE,
BDREF INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_TREEVIEW_CONS_CALCAUT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCAUT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREFFN INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_TREEVIEW_CONS_CALCINT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCINT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRPORCONTRATO SMALLINT,
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREFFN INTEGER,
BDCODCONTTI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_TREEVIEW_CONS_CALCULO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREFFN INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_TREEVIEW_CONS_FOLAVUL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_FOLAVUL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDATAFA DATE,
BDREF INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_BASE_TVERBASEMP_CONS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_BASE_TVERBASEMP_CONS(PRCODEMP INTEGER,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODIGOVEREMP INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDTIPOCOLVEREMP INTEGER,
BDCLASSECOLVEREMP INTEGER,
BDCOMFGTS VARCHAR(5),
BDCODTCA INTEGER,
BDDESCTCA VARCHAR(50),
BDINTERMITENTE /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_INSS_13 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_13(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRANOTODO SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDVALORINSS13 NUMERIC(18,6),
BDBASEINSS13 NUMERIC(18,6),
BDSALFAM13 NUMERIC(18,6),
BDSALMATEMP13 NUMERIC(18,6),
BDBINSSMV13 NUMERIC(18,6),
BDCHAVE INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCODTOMADOR INTEGER,
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBRATAPO13 NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_INSS_FC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRREFPAG INTEGER,
PRGPSSEFIP SMALLINT = 0)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFCOMP INTEGER,
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBINSSMVFN NUMERIC(18,6),
BDBINSSMV13FN NUMERIC(18,6),
BDCODTIPOFC INTEGER,
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDBINSS13INDFN NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_INSS_FN for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FN(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRGPSSEFIP SMALLINT = 0,
PRFILIAIS VARCHAR(15000) = null,
PRCONTRATO INTEGER = 0)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBINSSMVFN NUMERIC(18,6),
BDBINSSMV13FN NUMERIC(18,6),
BDBINSS13INDFN NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDPERCRATCOL NUMERIC(18,6),
BDPERCDESCFPASCOL NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_INSS_FN_PREV_RESC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FN_PREV_RESC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRGPSSEFIP SMALLINT = 0,
PRFILIAIS VARCHAR(15000) = NULL)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDINSSFNPR NUMERIC(18,6),
BDINSSFEFOLFNPR NUMERIC(18,6),
BDINSS13FNPR NUMERIC(18,6),
BDBINSSFNPR NUMERIC(18,6),
BDBINSSFEFOLFNPR NUMERIC(18,6),
BDBINSS13FNPR NUMERIC(18,6),
BDBRATAPOFNPR NUMERIC(18,6),
BDBRATAPOFEFNPR NUMERIC(18,6),
BDBRATAPO13FNPR NUMERIC(18,6),
BDSALFAMFNPR NUMERIC(18,6),
BDSALMATEMPFNPR NUMERIC(18,6),
BDBINSS13INDFNPR NUMERIC(18,6),
BDBINSSAPFNPR NUMERIC(18,6),
BDBINSS13APFNPR NUMERIC(18,6),
BDINSSAPFNPR NUMERIC(18,6),
BDINSS13APFNPR NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDPERCRATCOL NUMERIC(18,6),
BDPERCDESCFPASCOL NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_INSS_FT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FT(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRGPSSEFIP SMALLINT = 0,
PRFILIAIS VARCHAR(15000) = null,
PRCONTRATO INTEGER = 0,
PRORDEM INTEGER = 0)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBINSSMVFN NUMERIC(18,6),
BDBINSSMV13FN NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13INDFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDPERCRATCOL NUMERIC(18,6),
BDPERCDESCFPASCOL NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_INSS_FT_PREV_RESC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FT_PREV_RESC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRGPSSEFIP SMALLINT = 0,
PRFILIAIS VARCHAR(15000) = NULL)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDINSSFTPR NUMERIC(18,6),
BDINSSFEFOLFTPR NUMERIC(18,6),
BDINSS13FTPR NUMERIC(18,6),
BDBINSSFTPR NUMERIC(18,6),
BDBINSSFEFOLFTPR NUMERIC(18,6),
BDBINSS13FTPR NUMERIC(18,6),
BDBRATAPOFTPR NUMERIC(18,6),
BDBRATAPOFEFTPR NUMERIC(18,6),
BDBRATAPO13FTPR NUMERIC(18,6),
BDSALFAMFTPR NUMERIC(18,6),
BDSALMATEMPFTPR NUMERIC(18,6),
BDBINSSAPFTPR NUMERIC(18,6),
BDBINSS13INDFTPR NUMERIC(18,6),
BDBINSS13APFTPR NUMERIC(18,6),
BDINSSAPFTPR NUMERIC(18,6),
BDINSS13APFTPR NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDPERCRATCOL NUMERIC(18,6),
BDPERCDESCFPASCOL NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_INSS_FTC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FTC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32000),
PRREF INTEGER,
PRREFPAG INTEGER,
PRGPSSEFIP SMALLINT = 0)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFCOMP INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBINSSMVFN NUMERIC(18,6),
BDBINSSMV13FN NUMERIC(18,6),
BDCODTIPOFC INTEGER,
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDBINSS13INDFN NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_13 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_13FC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_13FC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_AD for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_AD(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_C13 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_C13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_DARF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_DARF(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPORCC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFIR INTEGER,
BDREFIRFIR INTEGER,
BDTIPOCALCFIR INTEGER,
BDCCFIR INTEGER,
BDCODFERFIR INTEGER,
BDCODTCA INTEGER,
BDBASEIRFIR NUMERIC(18,6),
BDVALINSSFIR NUMERIC(18,6),
BDVALIRFIR NUMERIC(18,6),
BDVALDEPFIR NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDDATAFIR DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_FA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FA(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRSOMENTEPLR SMALLINT = 0,
PRSEMPLR SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDCODTCA INTEGER,
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_FC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPREVIARESC SMALLINT = 0,
PREXPORTACAO INTEGER = 0,
PRPORCC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
WGCLASS VARCHAR(1000),
WDESCVER2 VARCHAR(70),
WI INTEGER,
BDORDEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_FE for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FE(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PREXPORTACAO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDCODFE INTEGER,
BDINIPERAQUIS DATE,
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_FN for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FN(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPREVIARESC SMALLINT = 0,
PREXPORTACAO INTEGER = 0,
PRPORCC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_FN2 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FN2(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPREVIARESC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_INT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_INT(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPREVIARESC SMALLINT = 0,
PREXPORTACAO INTEGER = 0,
PRPORCC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER,
BDCODCONTTI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_IR_INT13 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_IR_INT13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER,
BDCODCONTTI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_PIS_13 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_PIS_C13 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_C13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_PIS_FC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_FC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DADOS_PIS_FN for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_FN(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_EMP_BASES_RESCISAO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_EMP_BASES_RESCISAO(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFAUXVFN NUMERIC(15,6),
BDREFVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDSALBASEFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDCNPJEMP VARCHAR(18),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDFAXEMP INTEGER,
BDFAXEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILEMP /* DM_BDEMAIL */ VARCHAR(200),
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDATAADMCOL DATE,
BDDATANASCCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL VARCHAR(10),
BDDSERIECTPSCOL VARCHAR(1),
BDDATAOPCAOFGTSCOL DATE,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAPAGRESCISAO DATE,
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCODPRES INTEGER,
BDSALDOFGTS NUMERIC(15,6),
BDDESCPRES VARCHAR(110))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_SEGDESEMPREGO3MESES for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_SEGDESEMPREGO3MESES(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREF INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDMAIORREMUNERACAO NUMERIC(18,6),
BDORIGEM SMALLINT)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_TCOL_VINC_REF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHF_TCOL_VINC_REF(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFCOL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDCODSINTRAB INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHM_FF_OP_ANO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHM_FF_OP_ANO(PREMP VARCHAR(32000) = '',
PRCOL VARCHAR(32000) = '',
PRANO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHM_VAL_PS_COL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHM_VAL_PS_COL(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDREF INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDVALORMENSALIDADE NUMERIC(15,6),
BDVALLORCOPAR NUMERIC(15,6),
BDCODTIPOCONV INTEGER,
BDCODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHM_VAL_PS_DEP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SP_VRHM_VAL_PS_DEP(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDREF INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDVALORMENSALIDADE NUMERIC(15,6),
BDVALLORCOPAR NUMERIC(15,6),
BDCODEMP INTEGER,
BDCODDPN INTEGER,
BDNOMDEP VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPCODIMPGPSCOMPLEMENTAR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPCODIMPGPSCOMPLEMENTAR(PRCODEMP VARCHAR(32000),
PRREF INTEGER,
PRREFPAG INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTIPOFC INTEGER,
BDCODIMP INTEGER,
BDCODMATRIZ INTEGER,
BDEMPIMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CALC_13SALARIO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CALC_13SALARIO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CALC_AD13SALARIO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CALC_AD13SALARIO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CALC_ADSAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CALC_ADSAL(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDDATAAD DATE,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CALC_AUTONOMO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CALC_AUTONOMO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER,
PRCODSERV INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CALC_COMP13SALARIO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CALC_COMP13SALARIO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CALC_FERIAS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CALC_FERIAS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODFE INTEGER,
PRINIPERAQUISFE DATE,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDREFFN INTEGER,
BDCODFE INTEGER,
BDINIPERAQUISFE DATE,
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDBASEIROUT NUMERIC(15,6),
BDVALORIROUT NUMERIC(15,6),
BDDEPIROUT NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CALC_FOLHACOMP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CALC_FOLHACOMP(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CONS_CALC_13SALARIO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CONS_CALC_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_CONS_CALC_AD13SALARIO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_CONS_CALC_AD13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDPERC NUMERIC(15,6),
BDVAL NUMERIC(15,6),
BDTIPOPROP INTEGER,
BDMESESPROP INTEGER,
BDBASEIR NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBASEFGTS NUMERIC(15,6),
BDDATABAIXA DATE,
BDREFBAIXA INTEGER,
BDPERCIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_TREEVIEW_CONS_13SAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_TREEVIEW_CONS_13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREF13 INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPRH_TREEVIEW_CONS_AD13SAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPRH_TREEVIEW_CONS_AD13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREFA13 INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SPVAL_ITINERARIO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE SPVAL_ITINERARIO(PRITI INTEGER,
PRREF INTEGER)
 RETURNS(BDITI INTEGER,
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_CONSULTA_VINCULOISS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_CONSULTA_VINCULOISS(PRCODCID INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDREFVINCISS INTEGER,
BDCODTIPOISS INTEGER,
BDDESTIPOISS VARCHAR(50),
BDCODTIPOISSEXP INTEGER,
BDDESTIPOISSEXP VARCHAR(50),
BDPERISS /* DM_NUMERIC_7_4_ALIQ */ NUMERIC(7,4),
BDVALORLIMISS /* DM_NUMERIC_15_2 */ NUMERIC(15,2),
BDCODTIPORPS INTEGER,
BDDESTIPORPS VARCHAR(50),
BDCODIBGE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_DADOS_ISS_EXP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_DADOS_ISS_EXP(PRWHEREISS VARCHAR(10000) = NULL,
PRWHERECID VARCHAR(10000) = NULL,
PRWHEREEMP VARCHAR(32000) = NULL,
PRREFINI INTEGER = 0,
PRREFFIN INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODCID INTEGER,
BDCODTIPOISSEXP INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_DIRF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_DIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDREFLAN INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6),
BDACREDEDUIRSERJAN NUMERIC(18,6),
BDACREDEDUIRSERFEV NUMERIC(18,6),
BDACREDEDUIRSERMAR NUMERIC(18,6),
BDACREDEDUIRSERABR NUMERIC(18,6),
BDACREDEDUIRSERMAIO NUMERIC(18,6),
BDACREDEDUIRSERJUN NUMERIC(18,6),
BDACREDEDUIRSERJUL NUMERIC(18,6),
BDACREDEDUIRSERAGO NUMERIC(18,6),
BDACREDEDUIRSERSET NUMERIC(18,6),
BDACREDEDUIRSEROUT NUMERIC(18,6),
BDACREDEDUIRSERNOV NUMERIC(18,6),
BDACREDEDUIRSERDEZ NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_DIRF_RTIRF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_DIRF_RTIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_DIRF_RTRT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_DIRF_RTRT(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIME for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIME(PRCODEMP VARCHAR(10000),
PRREFERENCIAINICIAL INTEGER,
PRREFERENCIAFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCCAMPO VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODNAT INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDSIGLAUF VARCHAR(2),
BDVLRCONT NUMERIC(15,6),
BDVLRBC NUMERIC(15,6),
BDVLRIMPOSTO NUMERIC(15,6),
BDVLRISENTRIB NUMERIC(15,6),
BDVLROUTRAS NUMERIC(15,6),
BDVLRICMSSTPE NUMERIC(15,6),
BDVLRICMSSTOP NUMERIC(15,6),
BDVLRCONTCONT NUMERIC(15,6),
BDVLRBCCONT NUMERIC(15,6),
BDVLRICMSST NUMERIC(15,6),
BDNUMITEM INTEGER,
BDCODTIPO INTEGER,
BDBASEST NUMERIC(15,6),
BDICMSRETST NUMERIC(15,6),
BDDIFALIQENT NUMERIC(15,6),
BDALIMPREP VARCHAR(5),
BDCODEXP48 VARCHAR(3))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG1_18 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_18(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDFAXEMP INTEGER,
BDFAXEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILEMP /* DM_BDEMAIL */ VARCHAR(200),
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC /* DM_BDEMAIL */ VARCHAR(200),
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDFAXCONT INTEGER,
BDFAXCONT /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILCONT /* DM_BDEMAIL */ VARCHAR(200),
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER,
BDVLRRECBRU32_CSLL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG1_3 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_3(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDFAXEMP INTEGER,
BDFAXEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILEMP /* DM_BDEMAIL */ VARCHAR(200),
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC /* DM_BDEMAIL */ VARCHAR(200),
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDFAXCONT INTEGER,
BDFAXCONT /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILCONT /* DM_BDEMAIL */ VARCHAR(200),
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG20 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG20(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDEXISTEMOV INTEGER,
BDPERIODO INTEGER,
BDMES INTEGER,
BDVLRSALDOCREANT NUMERIC(15,6),
BDVLRDEBITO NUMERIC(15,6),
BDVLRCREDITO NUMERIC(15,6),
BDVLRSALDO NUMERIC(15,6),
BDCREDORDEVEDOR INTEGER,
BDSEQUENCIAL INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG21 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG21(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRINSUMOSNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVVENDASNACIONAL NUMERIC(15,6),
BDVLROUTRASENTNACIONAL NUMERIC(15,6),
BDVLRINSUMOSEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRDEVVENDASEXTERIOR NUMERIC(15,6),
BDVLROUTRASENTEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG22 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG22(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRPRODNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVCOMPRASNACIONAL NUMERIC(15,6),
BDVLROUTRASSAINACIONAL NUMERIC(15,6),
BDVLRPRODEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPEXTERIOR NUMERIC(15,6),
BDVLRDEVCOMPRASEXTERIOR NUMERIC(15,6),
BDVLROUTRASSAIEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG23 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG23(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG24 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG24(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG25 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG25(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG26 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG26(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_DIPJ_REG60_61A for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG60_61A(PREMPRESAS VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRCODPAISBRASIL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODFED INTEGER,
BDTIPOPESSOA INTEGER,
BDCGCCEISOC VARCHAR(18),
BDCODSOC INTEGER,
BDNOMSOC VARCHAR(200),
BDEXPQUALISOC INTEGER,
BDCAPTOTCOTA NUMERIC(15,6),
BDCAPVOLCOTA NUMERIC(15,6),
BDCPFRESPLEGALSOC VARCHAR(14),
BDEXPQUALIRESPSOC INTEGER,
BDREMTRACOTA NUMERIC(15,6),
BDRENISECOTA NUMERIC(15,6),
BDRENTRICOTA NUMERIC(15,6),
BDDEMRENCOTA NUMERIC(15,6),
BDIRFONTCOTA NUMERIC(15,6),
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_GIASP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_GIASP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCFORM VARCHAR(150),
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDVLRCONT NUMERIC(18,6),
BDBASEICMS NUMERIC(18,6),
BDVLRICMS NUMERIC(18,6),
BDISENTASICMS NUMERIC(18,6),
BDOUTRASICMS NUMERIC(18,6),
BDVLRST NUMERIC(18,6),
BDIMPSUBSTITUTO NUMERIC(18,6),
BDIMPSUBSTITUIDO NUMERIC(18,6),
BDOUTROSIMPOSTOS NUMERIC(18,6),
BDUF_R14 VARCHAR(2),
BDVALOR_CONTABIL_1_R14 NUMERIC(18,6),
BDBASECALCULO_1_R14 NUMERIC(18,6),
BDVALOR_CONTABIL_2_R14 NUMERIC(18,6),
BDBASECALCULO_2_R14 NUMERIC(18,6),
BDIMPOSTO_R14 NUMERIC(18,6),
BDOUTRAS_R14 NUMERIC(18,6),
BDICMSCOBRADOST_R14 NUMERIC(18,6),
BDPETROLEOENERGIA_R14 NUMERIC(18,6),
BDOUTROS_PRODUTOS_R14 NUMERIC(18,6),
BDCODIGO_R20 INTEGER,
BDOPERACAO_R20 INTEGER,
BDFUNLEGAL_R20 VARCHAR(150),
BDDESCRICAO_R20 VARCHAR(250),
BDINSCESTREM_R25 VARCHAR(15),
BDCODAUTORIZACAO_R28 VARCHAR(14),
BDVLRCONT1 NUMERIC(18,6),
BDBASEICMS1 NUMERIC(18,6),
BDVLRCONT2 NUMERIC(18,6),
BDBASEICMS2 NUMERIC(18,6),
BDNRDOC INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_GISSONLINE for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_GISSONLINE(PREMPRESAS VARCHAR(10000),
PRTIPOLANC SMALLINT,
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCIDEMP INTEGER,
BDNUMDOCINI VARCHAR(15),
BDNUMDOCFIN VARCHAR(15),
BDSERIE VARCHAR(6),
BDDATAEMISSAO DATE,
BDVLRCONTAB NUMERIC(15,6),
BDCODMUNATVM VARCHAR(20),
BDCODLOCEXP VARCHAR(1),
BDCODTPNFEXP VARCHAR(2),
BDCODOBRA VARCHAR(10),
BDCONSTCIVIL VARCHAR(5),
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDNOMETER VARCHAR(100),
BDCEPTER VARCHAR(9),
BDLOGRTER /* DM_LOGRADOURO */ VARCHAR(15),
BDENDTER /* DM_BDENDERECO */ VARCHAR(60),
BDNUMTER VARCHAR(10),
BDCOMPTER /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAITER VARCHAR(60),
BDCODCIDTER INTEGER,
BDIMTER VARCHAR(16),
BDIETER VARCHAR(20),
BDSIGLAUFTER VARCHAR(2),
BDNOMCIDTER VARCHAR(40),
BDCODENQFEDTER INTEGER,
BDTIPOREG VARCHAR(1),
BDTIPLAN VARCHAR(1),
BDCODSITNF INTEGER,
BDBCISSSER NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_SPEDCONTRIBUICAO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_SPEDCONTRIBUICAO(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIN DATE)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODBEM INTEGER,
NAT_BC_CRED VARCHAR(2),
IDENT_BEM_IMOB VARCHAR(2),
IND_ORIG_CRED INTEGER,
IND_UTIL_BEM_IMOB INTEGER,
MES_OPER_AQUIS VARCHAR(6),
VL_OPER_AQUIS NUMERIC(18,2),
VL_OPER_DEP NUMERIC(18,2),
PARC_OPER_NAO_BC_CRED NUMERIC(18,2),
VL_BC_CRED NUMERIC(18,2),
IND_NR_PARC INTEGER,
CST_PIS VARCHAR(2),
VL_BC_PIS NUMERIC(18,2),
ALIQ_PIS NUMERIC(18,4),
VL_PIS NUMERIC(18,2),
CST_COFINS VARCHAR(2),
VL_BC_COFINS NUMERIC(18,2),
ALIQ_COFINS NUMERIC(18,4),
VL_COFINS NUMERIC(18,2),
COD_CTA VARCHAR(255),
COD_PLAPADRAO INTEGER,
ANO INTEGER,
COD_CCUS VARCHAR(1000),
DESC_BEM_IMOB VARCHAR(300),
BDDATABAIXA DATE,
BDDATORIAQUIBEM DATE,
COD_CTA_REF VARCHAR(60),
COD_PLAPADRAOREF INTEGER,
NUMPARC INTEGER,
BDCODCCSPED INTEGER,
BDDEPDIARIA VARCHAR(5),
BDNUMDIAS INTEGER,
BDDEPDIADATA INTEGER,
BDDEPMESBAIXABEM VARCHAR(5),
BDCALCPATRIMONIO VARCHAR(5),
BDCTALON VARCHAR(40))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_TERCEIRO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_TERCEIRO(PREMPRESA VARCHAR(2048),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER /* DM_LOGRADOURO */ VARCHAR(15),
BDENDTER /* DM_BDENDERECO */ VARCHAR(60),
BDNUMTER VARCHAR(10),
BDCOMPTER /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDCEPTER VARCHAR(9),
BDBAITER /* DM_BDBAIRRO */ VARCHAR(50),
BDDDDTER VARCHAR(3),
BDFONETER /* DM_BDTELEFONE */ VARCHAR(15),
BDFAXTER /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILTER /* DM_BDEMAIL */ VARCHAR(200),
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_TNATOP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_TNATOP(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_EXP_TPRODUTOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_EXP_TPRODUTOS(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_LANCAMENTOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_LANCAMENTOS(PRREFMICRO INTEGER,
PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDPERCISS NUMERIC(15,6),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODPLANOONLINE INTEGER,
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDLANBCICMSISEOUT INTEGER,
BDALIQINSS NUMERIC(7,4))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_RETORNA_DIME_Q47 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_RETORNA_DIME_Q47(PRCODEMP VARCHAR(2048),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSIMPLIFICADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDVALOR NUMERIC(15,2),
BDCODCIDTOT INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_RETORNA_DIME_Q48 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_RETORNA_DIME_Q48(PRCODEMP VARCHAR(2048),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSIMPLIFICADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODCIDTOT INTEGER,
BDALIMPREP VARCHAR(5),
BDCODEXP VARCHAR(3),
BDCODATIVQ48 VARCHAR(3),
BDVALOR NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_RETORNA_DIME_VENC_PRODEC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_RETORNA_DIME_VENC_PRODEC(PRCODEMP INTEGER,
PRREF INTEGER)
 RETURNS(BDDATAVENC DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_RETORNA_TOTAIS_ENT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_RETORNA_TOTAIS_ENT(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDTOTALLANC INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRCSOCIAL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_RETORNA_TOTAIS_SAI for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_RETORNA_TOTAIS_SAI(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDTOTALLANC INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRCSOCIAL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_RETORNA_TOTAIS_SER for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_RETORNA_TOTAIS_SER(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDTOTALLANC INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBCISSSER NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRISSSER NUMERIC(15,6),
BDISENTASISSSER NUMERIC(15,6),
BDOUTRASISSSER NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDBCIRSER NUMERIC(15,6),
BDVLRIRSER NUMERIC(15,6),
BDACREDEDUIRSER NUMERIC(15,6),
BDVLRCSOCIAL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SPED_LAN_ENT_PRO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SPED_LAN_ENT_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDAPEUNIMEDFAT VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SPED_LAN_SAI_PRO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SPED_LAN_SAI_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDCODCLAENETEL INTEGER,
BDINDREC INTEGER,
BDCODCLAENETELGAS INTEGER,
BDINDRECGAS INTEGER,
BDCODSELOIPI INTEGER,
BDQTDSELOIPI INTEGER,
BDCODCLASSEIPI VARCHAR(5),
BDVLRUNIDADE NUMERIC(15,6),
BDQTDUNIDADE NUMERIC(15,6),
BDAPEUNIMEDFAT VARCHAR(5),
BDCODSAIDA VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_431 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_431(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDMODELOAUX VARCHAR(15),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDVLRFRETEC100 NUMERIC(15,6),
BDVLRSEGUROC100 NUMERIC(15,6),
BDVLROUTDESPC100 NUMERIC(15,6),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDVLRIR NUMERIC(15,2),
BDINSSRET NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDORDEMPRO INTEGER,
BDTIPOREG VARCHAR(10),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
BDBINSSRET NUMERIC(15,2),
BDRETVAZIO VARCHAR(1),
BDVLRCONTAB2 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_4310_TREDZ for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_4310_TREDZ(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAREDZ DATE,
BDCODPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDALIQICMS NUMERIC(15,2),
BDCAMPO8 NUMERIC(15,2),
BDVLRTOTPRO NUMERIC(15,2),
BDALIQPIS NUMERIC(15,4),
BDVLRPIS NUMERIC(15,2),
BDALIQCOFINS NUMERIC(15,4),
BDVLRCOFINS NUMERIC(15,2),
BDNCMPROD INTEGER,
BDTIPOREG VARCHAR(10))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_432 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_432(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5),
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(3),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCSTPIS VARCHAR(3),
BDCSTCOF VARCHAR(3),
BDVLRUNITARIO NUMERIC(15,4),
BDVLRCOFINSEXP NUMERIC(15,2),
BDVLRCOFINSTRIBINT NUMERIC(15,2),
BDVLRCOFINSNTRIBINT NUMERIC(15,2),
BDVLRPISEXP NUMERIC(15,2),
BDVLRPISTRIBINT NUMERIC(15,2),
BDVLRPISNTRIBINT NUMERIC(15,2),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_433 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_433(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIAPRO NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
BDVLRIR NUMERIC(15,2),
BDINSSRET NUMERIC(15,2),
BDVLRPISRET NUMERIC(15,2),
BDVLRCOFINSRET NUMERIC(15,2),
BDVLRCSLLRET NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_434 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_434(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(5),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDCAMPO10 NUMERIC(15,2),
BDCAMPO11 NUMERIC(15,2),
BDCAMPO12 NUMERIC(15,2),
BDCAMPO17 NUMERIC(15,2),
BDCAMPO18 NUMERIC(15,2),
BDCAMPO19 NUMERIC(15,2),
BDVLRUNITARIO NUMERIC(15,4),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_491 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDDATACADTER DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDIMTER VARCHAR(16),
BDNOMETER VARCHAR(100),
BDLOGRTER /* DM_LOGRADOURO */ VARCHAR(15),
BDENDTER /* DM_BDENDERECO */ VARCHAR(60),
BDENDEXPTER /* DM_BDENDERECO */ VARCHAR(60),
BDNUMTER VARCHAR(10),
BDCOMPTER /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAITER VARCHAR(60),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCEPTER VARCHAR(9),
BDDESCPAIS VARCHAR(60),
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDCODCGCTER VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_494 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_495 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRPROD VARCHAR(10000))
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_EXP_491 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_EXP_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_EXP_494 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_EXP_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_EXP_495 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_EXP_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_EXP_CAD for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_EXP_CAD(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_SERVICOS_ITENS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_SERVICOS_ITENS(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODSERVICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDCODCID INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(6),
BDSERIE VARCHAR(5),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDORDEM INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDCODOBS INTEGER,
BDIDCST INTEGER,
BDCONDPGTO INTEGER,
BDCONDPGTOAUX VARCHAR(1),
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDCODCSTPIS VARCHAR(2),
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDCODCSTCOF VARCHAR(2),
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDCAMPO07_4106 NUMERIC(15,2),
BDCAMPO14_4106 NUMERIC(15,2),
BDVLRCONTAB_4106 NUMERIC(15,3),
BDCAMPO10_4106 NUMERIC(15,2),
BDCAMPO17_4106 NUMERIC(15,2),
BDDESCPROD VARCHAR(45),
BDPRODSERVICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_SVA_SERVICOS_MOV for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_SVA_SERVICOS_MOV(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDIDCST INTEGER,
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VEF_SP_TREEVIEW_CONS_ANUAL_CONF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VEF_SP_TREEVIEW_CONS_ANUAL_CONF(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODPLANO INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDCODMATRIZ INTEGER,
BDREGAUX INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VFIN_SP_CONSFORNECEDORES for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VFIN_SP_CONSFORNECEDORES(PRCODFOR INTEGER,
PRREF INTEGER,
PRWHEREFOR VARCHAR(20000))
 RETURNS(BDCODFOR INTEGER,
BDCNPJFOR VARCHAR(18),
BDREFFOR INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDNOMEFOR /* DM_BDNOMEMP */ VARCHAR(100),
BDAPEFOR /* DM_BDAPEMP */ VARCHAR(20),
BDCEPFOR VARCHAR(9),
BDLOGRFOR /* DM_LOGRADOURO */ VARCHAR(15),
BDENDFOR /* DM_BDENDERECO */ VARCHAR(60),
BDNUMENDFOR /* DM_BDENDERECO_NR */ VARCHAR(10),
BDBAIFOR /* DM_BDBAIRRO */ VARCHAR(50),
BDCOMPLENDFOR /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDIEFOR VARCHAR(20),
BDIMFOR VARCHAR(20),
BDDDDFONEFOR INTEGER,
BDFONEFOR /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDFAXFOR INTEGER,
BDFAXFOR /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILFOR /* DM_BDEMAIL */ VARCHAR(200),
BDDATACADFOR DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_CAD_TERC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_CAD_TERC(PRCODCOL VARCHAR(32700),
PRCODCLA VARCHAR(1000),
PRREF INTEGER,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOLCON_DIA SMALLINT)
 RETURNS(BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDLOGRCOL VARCHAR(15),
BDENDCOL /* DM_BDENDERECO */ VARCHAR(60),
BDNUMCOL VARCHAR(10),
BDCOMPLCOL /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAICOL /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL /* DM_BDTELEFONE */ VARCHAR(15),
BDCELCOL /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILCOL /* DM_BDEMAIL */ VARCHAR(200),
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL /* DM_ORGAOEMISSOR */ VARCHAR(20),
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODCBO INTEGER,
BDCODCBOTSIN INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_COLCON for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_COLCON(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSIN VARCHAR(1000),
PRCODCLA VARCHAR(1000),
PRCODFUC VARCHAR(1000),
PRREF INTEGER,
PRULTDIA DATE,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOL_DOC SMALLINT,
PRCOL_HIST SMALLINT,
PRCOL_PARENT SMALLINT,
PRCOL_FIS SMALLINT,
PRCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOL_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOL_ADM SMALLINT,
PRCOL_CALC SMALLINT,
PRCOL_HISTF SMALLINT,
PRCON_VINC SMALLINT,
PRCOLCON_DIA SMALLINT,
PRFILTRARESC SMALLINT,
PRFILTRATRANS SMALLINT,
PRFILTRASIT SMALLINT,
PRFILTRAFERIAS SMALLINT,
PRFILTRA13SALARIO SMALLINT,
PRFILTRAFOLHANORMAL SMALLINT,
PRREFFOLHANORMAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDLOGRCOL VARCHAR(15),
BDENDCOL /* DM_BDENDERECO */ VARCHAR(60),
BDNUMCOL INTEGER,
BDCOMPLCOL /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAICOL /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL /* DM_BDTELEFONE */ VARCHAR(15),
BDCELCOL /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILCOL /* DM_BDEMAIL */ VARCHAR(200),
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCONTRCOL INTEGER,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL /* DM_ORGAOEMISSOR */ VARCHAR(20),
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB SUB_TYPE 1 SEGMENT SIZE 5000,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(18,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_CONS_COL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_CONS_COL(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
WFILTRO VARCHAR(500),
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODCLA INTEGER,
BDDATAADMCOL DATE,
BDGRUPOCLA INTEGER,
BDTIPOCOL INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_CONS_COL_NOVO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_CONS_COL_NOVO(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
WFILTRO VARCHAR(500),
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODCLA INTEGER,
BDDATAADMCOL DATE,
BDGRUPOCLA INTEGER,
BDTIPOCOL INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER,
BDCODPRES INTEGER,
BDDESCPRES VARCHAR(110),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDSTATUSQC INTEGER,
BDSTATUS_ES INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_CONS_COLCON for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_CONS_COLCON(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDTIPOCOL INTEGER,
BDCODCLA INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_CONS_FERIAS_PER_AQUIS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_CONS_FERIAS_PER_AQUIS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDGOZOFE NUMERIC(18,6),
BDQTDABONOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDSALDOFINALSINDFE NUMERIC(18,6),
BDCALCA13FE VARCHAR(5),
BDTIPOA13FE INTEGER,
BDPERCA13FE NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_CONS_VERBAS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_CONS_VERBAS(WREFERENCIA INTEGER,
WVERBAS VARCHAR(32700),
WTAMANHOCLASSE INTEGER)
 RETURNS(BDCODVER INTEGER,
BDCLAVER VARCHAR(20),
BDAPEVER VARCHAR(20),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDORDEMVER INTEGER,
BDINATIVAVER VARCHAR(5),
BDSITVER INTEGER,
BDTIPOVER INTEGER,
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDIRVER INTEGER,
BDFGTSVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDFORMINTVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDREFVER INTEGER,
BDFORMREFAUXVER VARCHAR(5000),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDRENDISENTOIRVER VARCHAR(5),
BDSITMATVER VARCHAR(5),
BDSITDOEVER VARCHAR(5),
BDSITACITRABVER VARCHAR(5),
BDSITMILITARVER VARCHAR(5),
BDSITMATEMPVER VARCHAR(5),
BDSITACITRAB15VER VARCHAR(5),
BDSITDOETRABVER VARCHAR(5),
BDSITLICVENCVER VARCHAR(5),
BDSITDOE15VER VARCHAR(5),
BDSITSINDICALVER VARCHAR(5),
BDSITAPOINVVER VARCHAR(5),
BDSITOUTRASVER VARCHAR(5),
BDPAGAESTOUROVER /* DM_BOOLEAN */ VARCHAR(5),
BDGARANTIAMINVER /* DM_BOOLEAN */ VARCHAR(5),
BDINDRESC /* DM_BOOLEAN */ VARCHAR(5),
BDNAOCONVHORASVER /* DM_BOOLEAN */ VARCHAR(5),
BDBASEDSRHNVER /* DM_BOOLEAN */ VARCHAR(5),
BDBASEDSROUVER /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_CONSULTA_SITUACAO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_CONSULTA_SITUACAO(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCODSIT INTEGER,
BDDESCSIT VARCHAR(70),
BDDATAINISEFIP DATE,
BDDATAINISIT DATE,
BDDATAFIMSIT DATE,
BDDIASSIT INTEGER,
BDNBENEFICIOSIT VARCHAR(20),
BDDATAPERICIASIT DATE,
BDDATAPARTOSIT DATE,
BDDATAESTAB DATE,
BDCODDOE INTEGER,
BDDESCDOE VARCHAR(200),
BDTIPOACID VARCHAR(50),
BDCODMED INTEGER,
BDNOMMED VARCHAR(60),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDOBSERVACAO VARCHAR(255),
BDGRUPOSIT INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_EMPRESAS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_EMPRESAS(PREMP VARCHAR(10000),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCID INTEGER,
BDCODUF INTEGER,
BDCODPLAFUC INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCENTROS INTEGER,
BDPAGEMP INTEGER,
BDFECHAMESEMP INTEGER,
BDFECHAVTEMP INTEGER,
BDARREMP INTEGER,
BDTIPOARREMP INTEGER,
BDTIPOFEREMP INTEGER,
BDSOMSALFEREMP VARCHAR(5),
BDTIPOAD13EMP INTEGER,
BDSOMSALAD13EMP VARCHAR(5),
BDPERCADSALEMP NUMERIC(15,6),
BDREFHOREMP VARCHAR(5),
BDLICREMFEREMP VARCHAR(5),
BDESTOUROEMP VARCHAR(5),
BDESTOURORESEMP VARCHAR(5),
BDFALFEREMP VARCHAR(5),
BDFALHORFEREMP VARCHAR(5),
BDDEPIRRESCEMP VARCHAR(5),
BDCODGPS INTEGER,
BDCODTERC INTEGER,
BDCODFPAS INTEGER,
BDCNAERATEMP NUMERIC(15,6),
BDEMPEMP NUMERIC(15,6),
BDAUTEMP NUMERIC(15,6),
BDFUNEMP NUMERIC(15,6),
BDCODSINPAT INTEGER,
BDCAPSOCEMP NUMERIC(15,6),
BDETIQEMP VARCHAR(5),
BDTAXSEREMP NUMERIC(15,6),
BDREFCAGEDEMP INTEGER,
BDPROPADMEMP INTEGER,
BDPROPRESEMP INTEGER,
BDPROPFEREMP INTEGER,
BDPROPSITEMP INTEGER,
BDCALCMEDIASTEMP INTEGER,
BDNATESTEMP INTEGER,
BDDATABASEEMP INTEGER,
BDPATEMP VARCHAR(5),
BDNROPROPEMP INTEGER,
BDSERPROPRIOPATEMP INTEGER,
BDPATREFCONVENIOEMP INTEGER,
BDPATCESTAALIMENTOEMP INTEGER,
BDPATADMCOZINHAEMP INTEGER,
BDPATREFTRANSPEMP INTEGER,
BDPATALICONVENIOEMP INTEGER,
BDSINDICALIZEMP VARCHAR(5),
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDIDENTEMP VARCHAR(14),
BDCATSEFIPEMP INTEGER,
BDISENFILEMP NUMERIC(15,6),
BDCETRTALIZAEMP INTEGER,
BDCODIR INTEGER,
BDCODINSS INTEGER,
BDCODMEN INTEGER,
BDCALCFCNAFNEMP VARCHAR(5),
BDCALCC13NAFNEMP VARCHAR(5),
BDTIPOCONTAB INTEGER,
BDTIPOEMIGUIAS INTEGER,
BDFAP NUMERIC(15,6),
BDTAXACNAEEMP NUMERIC(15,6),
BDPERTERC NUMERIC(15,6),
BDPERCPIS NUMERIC(15,6),
BDLIMINARAVPREVEMP INTEGER,
BDSIMPLESGPS INTEGER,
BDMESDSREMP INTEGER,
BDCODPLACONVSAU INTEGER,
BDARREDONDAFN /* DM_BOOLEAN */ VARCHAR(5),
BDARREDONDAFC /* DM_BOOLEAN */ VARCHAR(5),
BDARREDONDAFE /* DM_BOOLEAN */ VARCHAR(5),
BDARREDONDAA13 /* DM_BOOLEAN */ VARCHAR(5),
BDARREDONDA13 /* DM_BOOLEAN */ VARCHAR(5),
BDARREDONDAC13 /* DM_BOOLEAN */ VARCHAR(5),
BDARREDONDAAD /* DM_BOOLEAN */ VARCHAR(5),
BDARREDONDAAU /* DM_BOOLEAN */ VARCHAR(5),
BDARREDONDAFA /* DM_BOOLEAN */ VARCHAR(5),
BDPAGEMPCONTR INTEGER,
BDDESCFALHORASDIAS /* DM_BOOLEAN */ VARCHAR(5),
BDPERCLIMIDESCPAR NUMERIC(15,6),
BDCALCC13FNNEGEMP /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_GRRF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_GRRF(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRDATAPAGTO DATE,
PRPRIDIA DATE,
PRULTDIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODPRES INTEGER,
BDREFRESCISAO INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDSALDOFGTS NUMERIC(15,6),
BDDATAHOM DATE,
BDDATAPAGGRFC DATE,
BDDATADISSIDIO DATE,
BDAVPREPRES INTEGER,
BDCODSEFMFG VARCHAR(5),
BDCODSAQUE INTEGER,
BDBFGTS NUMERIC(15,6),
BDBFGTSMESANT NUMERIC(15,6),
BDVALINDEN NUMERIC(15,6),
BDCNPJEMP VARCHAR(18),
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDLOGREMP VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDCODCNAE INTEGER,
BDCODCONT INTEGER,
BDSIMPLESGPS INTEGER,
BDCODFPAS INTEGER,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDATAADMCOL DATE,
BDSEXOCOL INTEGER,
BDGRAUINSTCOL INTEGER,
BDDATANASCCOL DATE,
BDCONTRCOL INTEGER,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDCATEGORIACOL INTEGER,
BDOCORRENCIACOL INTEGER,
BDDATAOPCAOFGTSCOL DATE,
BDHORASSEMANAISCOL NUMERIC(15,6),
BDCODCBO VARCHAR(4),
BDTAMCNPJ INTEGER,
BDNOMREDUZEMP /* DM_BDNOMREDUZEMP */ VARCHAR(40),
BDFGTSSEMIND NUMERIC(15,6),
BDSITEMP /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_LISTAADM_RESC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_LISTAADM_RESC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMESINI INTEGER,
PRANOMESFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDATAADM DATE,
BDDATARESCISAO DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_LISTAADM_RESC_TOT_EMP for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_LISTAADM_RESC_TOT_EMP(PRCODEMP VARCHAR(10000),
PRANOMESANT INTEGER,
PRANOMESATU INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCAMPOC INTEGER,
BDCAMPOD INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_REL_RECIBO_FOLHA_NORMAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_REL_RECIBO_FOLHA_NORMAL(PRCODEMP INTEGER,
PRREF INTEGER,
PRCODCLA VARCHAR(10000),
PRCODTPCC VARCHAR(20000) = NULL,
PRDATAINI DATE = NULL,
PRDATAFIM DATE = NULL,
PRSITCOL SMALLINT = 1)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFVFN_SUM NUMERIC(15,6),
BDREFVFN_MAX NUMERIC(15,6),
BDREFAUXVFN_SUM NUMERIC(15,6),
BDREFAUXVFN_MAX NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDDATAFN INTEGER,
BDSALBASE NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDCNPJEMP VARCHAR(18),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDORDEMVER INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDPISCOL VARCHAR(14),
BDCPFCOL VARCHAR(14),
BDRG VARCHAR(13),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDTIPOREFVER INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDMODOPAGTOCOL INTEGER,
BDCLAVER VARCHAR(20),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_RELATORIO_CAT2 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_RELATORIO_CAT2(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRCHAVE INTEGER,
PRULTIMODIA DATE,
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCHAVE INTEGER,
BDCODCID INTEGER,
BDDATAACIDENTE DATE,
BDDATAEMISSAO DATE,
BDDATAULTIMODIA DATE,
BDDATAOBITO DATE,
BDEMITENTE INTEGER,
BDNRCAT VARCHAR(25),
BDTIPOAFAST INTEGER,
BDREGPOLICIAL VARCHAR(5),
BDAFASTAMENTO VARCHAR(5),
BDHORAACIDENTE TIME,
BDTIPOCAT INTEGER,
BDLOCALACIDENTE INTEGER,
BDESPLOCALACIDENTE VARCHAR(40),
BDOBJETOCAUSADORACID VARCHAR(10000),
BDDESCACIDENTE BLOB SUB_TYPE 1 SEGMENT SIZE 210,
BDPARTESATINGIDAS VARCHAR(10000),
BDAREAACIDENTE INTEGER,
BDHOUVEOBITO VARCHAR(5),
BDREMUNMENSAL INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDCODCNAE INTEGER,
BDNUMEMP INTEGER,
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDLOGREMP VARCHAR(15),
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDCNPJEMP VARCHAR(18),
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDDATANASCCOL DATE,
BDSEXOCOL INTEGER,
BDESTCIVCOL INTEGER,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDRGCOL VARCHAR(13),
BDDATAEMIRGCOL DATE,
BDORGEMIRGCOL VARCHAR(8),
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL /* DM_BDENDERECO */ VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL /* DM_BDTELEFONE */ VARCHAR(15),
BDFILIACAOPREV INTEGER,
BDAPOSENTADO INTEGER,
BDNOMCIDACID VARCHAR(40),
BDUFACID VARCHAR(2),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDNOMECIDCOL VARCHAR(40),
BDUFCOL VARCHAR(2),
BDUFCTPS VARCHAR(2),
BDDESCCBO VARCHAR(100),
BDCODCBO INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDUFRG VARCHAR(2),
BDDDDCELCOL INTEGER,
BDCELCOL /* DM_BDTELEFONE */ VARCHAR(15),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDDTAPOSENT DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_SERV_TERC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_SERV_TERC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRSERV VARCHAR(1000),
PRCODCLA VARCHAR(1000),
PRREF INTEGER,
PRINICIO DATE,
PRFIM DATE,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOLCON_DIA SMALLINT)
 RETURNS(BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDHORASERV TIME,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDLOGRCOL VARCHAR(15),
BDENDCOL /* DM_BDENDERECO */ VARCHAR(60),
BDNUMCOL VARCHAR(10),
BDCOMPLCOL /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAICOL /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL /* DM_BDTELEFONE */ VARCHAR(15),
BDCELCOL /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILCOL /* DM_BDEMAIL */ VARCHAR(200),
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL /* DM_ORGAOEMISSOR */ VARCHAR(20),
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODCBO INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255),
BDCONTRCOL INTEGER,
BDPERTRANSPINSSTER NUMERIC(15,6),
BDPERTRANSPIRTER NUMERIC(15,6),
BDACORDOINSSTERC /* DM_BOOLEAN */ VARCHAR(5),
BDPERCIRTERC NUMERIC(18,6),
BDPIRTERC /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_SERV_TERC_MANUAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRH_SP_SERV_TERC_MANUAL(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRSERV INTEGER,
PRDATA DATE,
PRREF INTEGER,
PRDATAPAG DATE,
PRHORA VARCHAR(10),
PRVALOR NUMERIC(15,2))
 RETURNS(BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDHORASERV TIME,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDLOGRCOL /* DM_LOGRADOURO */ VARCHAR(15),
BDENDCOL /* DM_BDENDERECO */ VARCHAR(60),
BDNUMCOL VARCHAR(10),
BDCOMPLCOL /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAICOL /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL /* DM_BDTELEFONE */ VARCHAR(15),
BDCELCOL /* DM_BDTELEFONE */ VARCHAR(15),
BDEMAILCOL /* DM_BDEMAIL */ VARCHAR(200),
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL /* DM_ORGAOEMISSOR */ VARCHAR(20),
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODCBO INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255),
BDCONTRCOL INTEGER,
BDPERTRANSPINSSTER NUMERIC(15,6),
BDPERTRANSPIRTER NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_ARREDONDAMENTOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_ARREDONDAMENTOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREFARRE INTEGER,
BDVALARRE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_CALC_AUTONOMO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_CALC_AUTONOMO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRSERVICO INTEGER,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = NULL,
PRCODTPCC VARCHAR(10000) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(5000),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBINSSCALC NUMERIC(15,6),
BDBIRCALC NUMERIC(15,6),
BDDATAPGTO DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_CALC_FOLHANORMAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = null,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(800),
BDFORMREFVER VARCHAR(800),
BDFORMVALVER VARCHAR(800),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFEFOL NUMERIC(15,6),
BDFGTSFEFOL NUMERIC(15,6),
BDDATAPGTO DATE,
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDCODCONTTI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_CALC_GPS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_CALC_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_CONS_CALC_AUTONOMOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_CONS_CALC_AUTONOMOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_CONS_CALC_FOLHAINT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHAINT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCODCONTTI INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_CONS_CALC_FOLHANORMAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_CONS_CALC_FOLHANORMALPR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMALPR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6),
BDDATARESCISAOPREV DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_CONS_IR_TERCEIROS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_CONS_IR_TERCEIROS(PRCODEMP VARCHAR(10000),
PRCODTER VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODTER INTEGER,
BDNOMTER VARCHAR(100),
BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDREF VARCHAR(6),
BDBASEIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDVALORDEP NUMERIC(15,6),
BDBASEINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,6),
BDCPFTER VARCHAR(14),
BDCODRECOF VARCHAR(4),
BDBASEIRTOT NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_DADOS_CALC_GPS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_DADOS_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENAGPS INTEGER)
 RETURNS(BDTIPO INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_DADOS_IND_CALC_GPS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_DADOS_IND_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENASGPS INTEGER)
 RETURNS(BDCODCENTRO INTEGER,
BDTIPO INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_ESTOUROS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_ESTOUROS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREFEST INTEGER,
BDVALEST NUMERIC(15,6),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_FICHA_REG_COLABORADOR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_FICHA_REG_COLABORADOR(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRMODELO INTEGER,
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE,
PROBS INTEGER,
PRSITCOL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDCIDADEEMP VARCHAR(40),
BDUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDFONEEMP /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDNOMCOLORDEM /* DM_BDNOMCOL */ VARCHAR(70),
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCOL DATE,
BDCORCOL INTEGER,
BDSEXOCOL INTEGER,
BDPAISCOL VARCHAR(40),
BDNACIONALIDADE VARCHAR(30),
BDDATACHEBRASILCOL DATE,
BDCIDADENASCCOL VARCHAR(40),
BDUFNASCCOL VARCHAR(2),
BDTIPOSANGUECOL INTEGER,
BDCPFCOL VARCHAR(14),
BDRGCOL VARCHAR(13),
BDDATAEMIREGCOL DATE,
BDORGEMIRGCOL /* DM_ORGAOEMISSOR */ VARCHAR(20),
BDCNHCOL VARCHAR(11),
BDCATCNHCOL VARCHAR(2),
BDVENCNHCOL DATE,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDRESERVISTACOL VARCHAR(20),
BDTITELEICOL VARCHAR(20),
BDGRAUINSTCOL INTEGER,
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDESTCIVCOL INTEGER,
BDLOGRCOL /* DM_LOGRADOURO */ VARCHAR(15),
BDENDCOL /* DM_BDENDERECO */ VARCHAR(60),
BDNUMCOL INTEGER,
BDCOMPLCOL /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAICOL /* DM_BDBAIRRO */ VARCHAR(50),
BDCIDADECOL VARCHAR(40),
BDUFCOL VARCHAR(2),
BDCEPCOL VARCHAR(9),
BDFONECOL /* DM_BDTELEFONE */ VARCHAR(15),
BDDDDCOL INTEGER,
BDEMAILCOL /* DM_BDEMAIL */ VARCHAR(200),
BDCELCOL /* DM_BDTELEFONE */ VARCHAR(15),
BDDATAADMCOL DATE,
BDDATACADCOL DATE,
BDSALINICOL NUMERIC(15,2),
BDFORMAPAGTOCOL INTEGER,
BDPERCINSALUBCOL NUMERIC(15,6),
BDPERCPERCULCOL NUMERIC(15,2),
BDCATEGORIACOL INTEGER,
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDDEFCOL /* DM_BOOLEAN */ VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDREAB /* DM_BOOLEAN */ VARCHAR(5),
BDTIPOCOL INTEGER,
BDCTAFGTSCOL VARCHAR(20),
BDDATAOPCAOFGTSCOL DATE,
BDCTADEPCOL VARCHAR(20),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDCODCBO INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDDATAPAGGRFC DATE,
BDCODPRES INTEGER,
BDDESCPRES VARCHAR(110),
BDFOTOCOL BLOB,
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDUFCTPS VARCHAR(2),
BDDESCCATEGORIA VARCHAR(300),
BDNOMBAN VARCHAR(60),
BDCODBAN INTEGER,
BDNOMAG VARCHAR(40),
BDCODAG INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDOBSCOL BLOB SUB_TYPE 1 SEGMENT SIZE 5000,
BDDDDCELCOL INTEGER,
BDSIGLAUFRG VARCHAR(2),
BDDIANASC VARCHAR(2),
BDMESNASC VARCHAR(2),
BDANONASC VARCHAR(10),
BDCONTRCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC /* DM_BDNOMEMP */ VARCHAR(100),
BDNOMCIDTPCC VARCHAR(40),
BDUFTPCC VARCHAR(2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_FICHAFGTS2 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_FICHAFGTS2(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODIND INTEGER,
BDBFGTS NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDBFGTSFC NUMERIC(18,6),
BDFGTSFC NUMERIC(18,6),
BDBASEFGTSA13 NUMERIC(18,6),
BDFGTSA13 NUMERIC(18,6),
BDBASEFGTS13 NUMERIC(18,6),
BDFGTS13 NUMERIC(18,6),
BDBASEFGTSC13 NUMERIC(18,6),
BDFGTSC13 NUMERIC(18,6),
BDINDICEJAM NUMERIC(18,6),
BDSALDOANTFGTS NUMERIC(18,6),
BDVALORJAM NUMERIC(18,6),
BDSALDOFGTS NUMERIC(18,6),
BDSOMAFGTS NUMERIC(18,6),
BDPERCINDCOMP NUMERIC(18,6),
BDVALORINDCOMP NUMERIC(18,6),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_FICHAINSS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_FICHAINSS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREF INTEGER,
BDBINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDINSSC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_FICHAIR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_FICHAIR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRTIPOCALC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREF VARCHAR(10),
BDTIPOCALC INTEGER,
BDBRUTO NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDVALIR NUMERIC(15,6),
BDVALINSS NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_FICHAIR_ANUAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_FICHAIR_ANUAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOBASE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCPFCOL VARCHAR(14),
BDDATAADMCOL DATE,
BDDATARESCISAO DATE,
BDREF VARCHAR(10),
BDRENDTRIB NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDALUGUEIS NUMERIC(15,6),
BDPRIVPRIVADA NUMERIC(15,6),
BDDESPMEDICAS NUMERIC(15,6),
BDPENSAOALIM NUMERIC(15,6),
BDPENSAOJUDICIAL NUMERIC(15,6),
BDAJUDACUSTO NUMERIC(15,6),
BDLUCROPJ NUMERIC(15,6),
BDAVISOPREV NUMERIC(15,6),
BDRENDTRIB13 NUMERIC(15,6),
BDDEP13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDPENSAOALIM13 NUMERIC(15,6),
BDDATA DATE,
BDGRUPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_FICHARAIS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_FICHARAIS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_FICHARAIS_NOVO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_FICHARAIS_NOVO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_GPS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUTERCEIROS NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACUM VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALNOTAS NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_GPS_CONTRATANTE for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_GPS_CONTRATANTE(PREMP INTEGER,
PRREF INTEGER,
PRTERC INTEGER,
PRTPCC INTEGER,
PRNRNF VARCHAR(15))
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_GPS_FUNRURAL for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_GPS_FUNRURAL(PREMP INTEGER,
PRREF INTEGER,
PRNRNF VARCHAR(15),
PRTIPOEMISSAO INTEGER,
PRCODIMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDVALOR NUMERIC(15,6),
BDVALTERC NUMERIC(15,6),
BDVALORACU NUMERIC(15,6),
BDVALACUTERC NUMERIC(15,6),
BDDESCNOTAS VARCHAR(5000),
BDBASECALC NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_GRCSCOLABORADOR for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_GRCSCOLABORADOR(PREMPRESA VARCHAR(9999),
PRCOLABORADOR VARCHAR(9999),
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODSIND INTEGER,
BDCODCNAE INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND /* DM_BDBAIRRO */ VARCHAR(50),
BDCOMPLSIND /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDNUMSIND INTEGER,
BDENTSIND VARCHAR(40),
BDDESCSIND VARCHAR(60),
BDLOGRSIND /* DM_LOGRADOURO */ VARCHAR(15),
BDENDSIND /* DM_BDENDERECO */ VARCHAR(60),
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDCNPJ VARCHAR(20),
BDBAI /* DM_BDBAIRRO */ VARCHAR(50),
BDCEP VARCHAR(9),
BDCOMPL /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDNUM INTEGER,
BDLOGR /* DM_LOGRADOURO */ VARCHAR(15),
BDEND VARCHAR(80),
BDNOM /* DM_BDNOMEMP */ VARCHAR(100),
BDCAPSOC NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_GRCSEMPRESA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_GRCSEMPRESA(PRSINDICATO INTEGER,
PRREFEMP INTEGER,
PRCODEMP VARCHAR(10000),
PRULTIMODIA DATE)
 RETURNS(BDCODCNAE INTEGER,
BDVALORDOC NUMERIC(15,2),
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDBAI /* DM_BDBAIRRO */ VARCHAR(50),
BDCEP VARCHAR(9),
BDCOMPL /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDNUM INTEGER,
BDEND /* DM_BDENDERECO */ VARCHAR(60),
BDCNPJ VARCHAR(18),
BDNOM /* DM_BDNOMEMP */ VARCHAR(100),
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND /* DM_BDBAIRRO */ VARCHAR(50),
BDCOMPLSIND /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDNUMSIND INTEGER,
BDENTSIND VARCHAR(20),
BDDESCSIND VARCHAR(60),
BDENDSIND /* DM_BDENDERECO */ VARCHAR(60),
BDCAPSOC NUMERIC(15,2),
BDTIPOEMP CHAR,
BDTIPOCOL CHAR,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDSALBASE NUMERIC(15,2),
BDTOTCOLAPU INTEGER,
BDTOTCOLEMP INTEGER,
BDTOTREMU NUMERIC(15,2),
BDLOGRSIND /* DM_LOGRADOURO */ VARCHAR(15),
BDLOGR /* DM_LOGRADOURO */ VARCHAR(15))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_OUTRASINF_CALC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_OUTRASINF_CALC_ATIVOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_ATIVOS(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_OUTRASINF_CALC_AUT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_AUT(PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PREMPRESA INTEGER = 0)
 RETURNS(BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,2),
BDVALORPREVPRIVNCOL NUMERIC(15,2),
BDVALORPREVPRIV13COL NUMERIC(15,2),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,2),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,2),
BDPERCDESCFPASCOL NUMERIC(15,2),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,2),
BDHORASSEMANAISCOL NUMERIC(15,2),
BDHORASDIARIASCOL NUMERIC(15,2),
BDPERCINSALUBCOL NUMERIC(15,2),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,2),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,2),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_QUADROHORARIOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_QUADROHORARIOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRDIASEMANA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCIDADE VARCHAR(40),
BDUF VARCHAR(2),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDPISCOL VARCHAR(14),
BDCODQH INTEGER,
BDDESQH /* DM_BDDESCQH */ VARCHAR(80),
BDDIA INTEGER,
BDHORAENT TIME,
BDHORASAI TIME)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_RECIBO_FERIAS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_RECIBO_FERIAS(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRDATAGOZOINI DATE,
PRDATAGOZOFIM DATE,
PRPERIODOAQUISITIVO DATE,
PRCODIGOFERIAS INTEGER,
PRTIPOCODVER INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE,
PRCOLETIVAS INTEGER,
PRAVISO INTEGER = 0,
PRIDADE21 INTEGER = 2100,
PRNOVORECIBO SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDNOMCIDEMP VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCHAVE INTEGER,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDSIGLAUFCTPS VARCHAR(2),
BDDESCTFUC VARCHAR(40),
BDDATAADMCOL DATE,
BDINIPERAQUISFE DATE,
BDFIMPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERGOZOFE DATE,
BDFALTASFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDQTDABONOFE NUMERIC(18,6),
BDDATAPAGFE DATE,
BDCODVER INTEGER,
BDTIPOCODVER INTEGER,
BDORDEMVER INTEGER,
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDREFVFE NUMERIC(15,6),
BDVALVFE NUMERIC(15,6),
BDTIPOREFVER INTEGER,
BDREFPAGABOFE INTEGER,
BDINISWS DATE,
BDFIMSWS DATE,
BDVALLIQUIDO NUMERIC(15,6),
BDCALCA13FE VARCHAR(5),
BDSALINI NUMERIC(15,6),
BDDIASLICFE NUMERIC(18,6),
BDDATAAVISO DATE,
BDCLASSVER VARCHAR(20),
BDREFAUXVER NUMERIC(15,6),
BDCOLETIVAS VARCHAR(5),
BDDEPIR INTEGER,
BDDIASFERFE NUMERIC(18,6),
BDLOGOEMP BLOB SEGMENT SIZE 32720,
BDREFHOREMP /* DM_BOOLEAN */ VARCHAR(5),
BDCPFCOL VARCHAR(14),
BDDATARELABONO DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_REL_DECLARA_RENDIMENTOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_REL_DECLARA_RENDIMENTOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCPFCOL VARCHAR(14),
BDTOTALRENDIMENTOS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDVAL13 NUMERIC(15,6),
BDVALPENALI NUMERIC(15,6),
BDVALIND NUMERIC(15,6),
BDVALDIR NUMERIC(15,6),
BDVALDME NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_REL_LIQUIDO_FOLHA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_REL_LIQUIDO_FOLHA(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRULTDIAMES DATE,
PRTABELA VARCHAR(300),
PRDATANULL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCPFCOL VARCHAR(14),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDCODAGBAN VARCHAR(5),
BDCODAGBANDV VARCHAR(2),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDDATAADMCOL DATE,
BDDESCTFUC VARCHAR(40),
BDREF INTEGER,
SALBASE NUMERIC(15,6),
PROVE NUMERIC(15,6),
DESCO NUMERIC(15,6),
LIQ NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_REL_PREVIA_RESC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCPFCOL VARCHAR(14),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDCAMPO29 NUMERIC(15,2),
BDCAMPO30 NUMERIC(15,2),
BDCAMPO30REF INTEGER,
BDCAMPO31 NUMERIC(15,2),
BDCAMPO31REF INTEGER,
BDCAMPO32 NUMERIC(15,2),
BDCAMPO32REF INTEGER,
BDCAMPO33 NUMERIC(15,2),
BDCAMPO33REF INTEGER,
BDCAMPO34 NUMERIC(15,2),
BDCAMPO34REF INTEGER,
BDCAMPO35 NUMERIC(15,2),
BDCAMPO35REF INTEGER,
BDCAMPO36 NUMERIC(15,2),
BDCAMPO36REF INTEGER,
BDCAMPO37 NUMERIC(15,2),
BDCAMPO38 NUMERIC(15,2),
BDCAMPO39 NUMERIC(15,2),
BDCAMPO40 NUMERIC(15,2),
BDCAMPO40REF INTEGER,
BDCAMPO41 NUMERIC(15,2),
BDCAMPO42 NUMERIC(15,2),
BDCAMPO43 NUMERIC(15,2),
BDCAMPO44 NUMERIC(15,2),
BDCAMPO45 NUMERIC(15,2),
BDCAMPO46BRUTO NUMERIC(15,2),
BDCAMPO47 NUMERIC(15,2),
BDCAMPO48 NUMERIC(15,2),
BDCAMPO49 NUMERIC(15,2),
BDCAMPO50 NUMERIC(15,2),
BDCAMPO51 NUMERIC(15,2),
BDCAMPO52 NUMERIC(15,2),
BDCAMPO53 NUMERIC(15,2),
BDCAMPO54TOTDED NUMERIC(15,2),
BDCAMPO55LIQREC NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_REL_PREVIA_RESC2 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCPFCOL VARCHAR(14),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDORDEMVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_REL_RECIBO_RESCISAO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_REL_RECIBO_RESCISAO(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFOLHA INTEGER,
PRDATAINI INTEGER,
PRDATAFIM INTEGER)
 RETURNS(BDMAIORREMUNERACAOANT NUMERIC(18,6),
BDCODTIPOCONTRATO INTEGER,
BDDESCTIPOCONTRATO VARCHAR(150),
BDCODSINTRAB INTEGER,
BDCODCEDENTETRAB VARCHAR(20),
BDCNPJSINTRAB VARCHAR(18),
BDDESCSINTRAB VARCHAR(60),
BDPERTRCTRESC NUMERIC(15,6),
BDPERFGTSRESC NUMERIC(15,6),
BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCPFCOL VARCHAR(14),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL /* DM_DIGSERIECTPS */ VARCHAR(1),
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDVINCEMPCOL INTEGER,
BDSIGLAUFCTPS VARCHAR(2),
BDSIGLAHNET VARCHAR(3),
BDDESCHNET VARCHAR(200),
BDDESCCATEGORIA VARCHAR(300),
BDSALBASE NUMERIC(18,6),
BDDATAOPCAOFGTS DATE,
BDTIPOCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_REL_RECIBO_RESCISAO2 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_REL_RECIBO_RESCISAO2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER,
PRTIPOFOLHA INTEGER,
PRDTPGTO INTEGER,
PRDTPGTOFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCPFCOL VARCHAR(14),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL /* DM_DIGSERIECTPS */ VARCHAR(1),
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDREFRESCISAO INTEGER,
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(18,6),
BDREFAUXV NUMERIC(18,6),
BDHEVER NUMERIC(18,6),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDORDEMVER INTEGER,
BDCLAVER VARCHAR(20),
BDPERCINSALUBCOL NUMERIC(18,6),
BDPERCPERICULCOL NUMERIC(18,6),
BDPERCNOTURNOCOL NUMERIC(18,6),
BDHORASDIARIASCOL NUMERIC(18,6),
BDSIGLAUFCTPS VARCHAR(2),
BDTIPOREFVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDCLAVERAUX VARCHAR(20),
BDDESCVERAUX VARCHAR(70),
BDPROVENTOOUTROS NUMERIC(18,6),
BDDESCONTOOUTROS NUMERIC(18,6),
BDTIPOCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_RETORNAEMPRESA_GPS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_RETORNAEMPRESA_GPS(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDSIMPLESGPS INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_SALARIOS_CONTRIB for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_SALARIOS_CONTRIB(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRBANCO INTEGER,
PRAGENCIA INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDLOGREMP /* DM_LOGRADOURO */ VARCHAR(15),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDNOMCIDEMP VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAINSS DATE,
BDREFINSS INTEGER,
BDBASEINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,2),
BDCODEMPAUX INTEGER,
BDCODCOLAUX INTEGER,
BDDATAINSSAUX DATE,
BDVALORINSSAUX NUMERIC(15,6),
BDBASEINSSAUX NUMERIC(15,6),
BDREFINSSAUX INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TODAS_GPS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_TODAS_GPS(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(22000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TOTAL_COL_ATIVOS for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_TOTAL_COL_ATIVOS(PRCODEMP INTEGER,
PRREF INTEGER,
PRDATAADMISSAO DATE)
 RETURNS(TTATIVOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TPREPFB_CC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_TPREPFB_CC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6),
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TPREPFN_CC_REF for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_TPREPFN_CC_REF(PRREF INTEGER,
PREMPRESA VARCHAR(32700),
PRCOLABORADOR VARCHAR(32700),
PRTEMPO INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRFERIAS SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6),
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140),
BDTEMPO INTEGER,
BDTEMPOFN INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TVERBAFC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_TVERBAFC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(25000),
PRREFINICOMP INTEGER,
PRREFFIMCOMP INTEGER,
PRREFINIPAG INTEGER,
PRREFFIMPAG INTEGER,
PRAGRUPATOMADOR INTEGER,
PRSEPARARCALC INTEGER = 0,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = NULL)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFCOMP INTEGER,
BDREFVFC NUMERIC(15,6),
BDREFAUXVFC NUMERIC(15,6),
BDVALVFC NUMERIC(15,6),
BDIGNREFVFC VARCHAR(5),
BDIGNREFAVFC VARCHAR(5),
BDIGNVALVFC VARCHAR(5),
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDREFFC INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TVERBAFN for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_TVERBAFN(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = null,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(2788) = null)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(15,6),
BDREFAUXVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNREFAVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCODCONTTI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_UNION_VERBAS_SIM_NAO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF BLOB,
BDFORMVAL BLOB,
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_UNION_VERBAS_SIM_NAO_2 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO_2(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_VERBAS_FN_FC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_VERBAS_FN_FC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRCLASSVERBAS VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_VERBAS_FOL_NORMAL_AUT for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_VERBAS_FOL_NORMAL_AUT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRFILTRO VARCHAR(2000),
PRCODTPCC VARCHAR(10000),
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = null)
 RETURNS(BDCODPLAFUC INTEGER,
BDCODSINTRAB INTEGER,
BDCODCLA INTEGER,
BDDESCENQFED VARCHAR(10),
BDTEMGRRF INTEGER,
BDBSALFAM NUMERIC(18,6),
BDDATARESCISAO DATE,
BDDESCRICAOMOTRES VARCHAR(300),
BDTIPOMOV INTEGER,
BDTIPO_COL INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPEMP VARCHAR(9),
BDCNPJEMP VARCHAR(18),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDATAADMCOL DATE,
BDPERCRATCOL NUMERIC(18,6),
BDDESCTFUC VARCHAR(150),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCODENQFED INTEGER,
BDSIMPLESGPS INTEGER,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDCODCBO INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREFFN INTEGER,
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(80),
BDREFV NUMERIC(18,6),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDSALBASE NUMERIC(18,6),
BDBINSS NUMERIC(18,6),
BDBFGTS NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDBIRRF NUMERIC(18,6),
BDBRAIS NUMERIC(18,6),
BDDESCREDVER VARCHAR(80),
BDIRRF NUMERIC(18,6),
BDGRUPOCLA INTEGER,
BDBINSS13 NUMERIC(18,6),
BDBFGTS13 NUMERIC(18,6),
BDBIRRF13 NUMERIC(18,6),
BDVFGTS13 NUMERIC(18,6),
BDBINSSFEFOL NUMERIC(18,6),
BDVINSSFEFOL NUMERIC(18,6),
BDBFGTSFEFOL NUMERIC(18,6),
BDVFGTSFEFOL NUMERIC(18,6),
BDDESCCC VARCHAR(80),
BDPISVER VARCHAR(5),
BDCLAVER VARCHAR(20),
BDBFGTSMESANT NUMERIC(18,6),
BDFGTSMESANT NUMERIC(18,6),
BDBFGTSMES NUMERIC(18,6),
BDFGTSMES NUMERIC(18,6),
BDSALDO NUMERIC(18,6),
BDFGTS40 NUMERIC(18,6),
BDFGTS10 NUMERIC(18,6),
BDTOTALGRRF NUMERIC(18,6),
BDORDEMVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDTIPOCODVER INTEGER,
BDCODTFUC INTEGER,
BDTIPOREFVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDVALMVINSSTER NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDDATAPGTO DATE,
BDCCATVCONCOM /* DM_BOOLEAN */ VARCHAR(5),
BDBFGTSMESPOST NUMERIC(18,6),
BDFGTSMESPOST NUMERIC(18,6),
BDINSSFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDMVINSSTER NUMERIC(18,6),
BDHORASMENSAISCOL NUMERIC(18,6),
BDFGTSIND NUMERIC(18,6),
BDDATAGRRF DATE,
BDBASEINSSMV NUMERIC(18,6),
BDBASEIRRFMV NUMERIC(18,6),
BDVALORINSSMV NUMERIC(18,6),
BDVALORIRRFMV NUMERIC(18,6),
BDPERCMULTA40 NUMERIC(15,2),
BDPERCMULTA10 NUMERIC(15,2),
BDCODCONTTI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_VERBAS_FOLHA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_VERBAS_FOLHA(PREMPRESA VARCHAR(30000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMPRESSAO INTEGER,
PRTIPOFOLHA INTEGER,
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRAGRUPARSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDESCTFUC VARCHAR(40),
BDDATAADMCOL DATE,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDSERIECTPSCOL /* DM_SERIECTPS */ VARCHAR(11),
BDDSERIECTPSCOL VARCHAR(1),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDLOGRSINTRAB VARCHAR(15),
BDENDSINTRAB VARCHAR(40),
BDBAISINTRAB VARCHAR(20),
BDNROSINTRAB INTEGER,
BDCOMPLSINTRAB VARCHAR(20),
BDNOMCIDSINTRAB VARCHAR(40),
BDSIGLAUFSINTRAB VARCHAR(2),
BDCODVER INTEGER,
BDREFVER INTEGER,
BDDESCVER VARCHAR(40),
BDREFV NUMERIC(15,6),
BDVALV NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_VERBAS_PREV_RESC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_VERBAS_PREV_RESC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER)
 RETURNS(BDCODPLAFUC INTEGER,
BDCODSINTRAB INTEGER,
BDCODCLA INTEGER,
BDDESCENQFED VARCHAR(10),
BDTEMGRRF INTEGER,
BDBSALFAM NUMERIC(18,6),
BDDATARESCISAO DATE,
BDDESCRICAOMOTRES VARCHAR(300),
BDTIPOMOV INTEGER,
BDTIPO_COL INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDENDEMP /* DM_BDENDERECO */ VARCHAR(60),
BDNUMEMP INTEGER,
BDBAIEMP /* DM_BDBAIRRO */ VARCHAR(50),
BDCEPEMP VARCHAR(9),
BDCNPJEMP VARCHAR(18),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCOMPLEMP /* DM_BDCOMPENDERECO */ VARCHAR(60),
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDATAADMCOL DATE,
BDPERCRATCOL NUMERIC(18,6),
BDDESCTFUC VARCHAR(80),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCODENQFED INTEGER,
BDSIMPLESGPS INTEGER,
BDCTPSCOL /* DM_BDCTPS */ VARCHAR(11),
BDCODCBO INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREFFN INTEGER,
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(80),
BDREFV NUMERIC(18,6),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDSALBASE NUMERIC(18,6),
BDBINSS NUMERIC(18,6),
BDBFGTS NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDBIRRF NUMERIC(18,6),
BDBRAIS NUMERIC(18,6),
BDDESCREDVER VARCHAR(80),
BDIRRF NUMERIC(18,6),
BDGRUPOCLA INTEGER,
BDBINSS13 NUMERIC(18,6),
BDBFGTS13 NUMERIC(18,6),
BDBIRRF13 NUMERIC(18,6),
BDVFGTS13 NUMERIC(18,6),
BDBINSSFEFOL NUMERIC(18,6),
BDVINSSFEFOL NUMERIC(18,6),
BDBFGTSFEFOL NUMERIC(18,6),
BDVFGTSFEFOL NUMERIC(18,6),
BDDESCCC VARCHAR(80),
BDPISVER VARCHAR(5),
BDCLAVER VARCHAR(20),
BDBFGTSMESANT NUMERIC(18,6),
BDFGTSMESANT NUMERIC(18,6),
BDBFGTSMES NUMERIC(18,6),
BDFGTSMES NUMERIC(18,6),
BDSALDO NUMERIC(18,6),
BDFGTS40 NUMERIC(18,6),
BDFGTS10 NUMERIC(18,6),
BDTOTALGRRF NUMERIC(18,6),
BDORDEMVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDTIPOCODVER INTEGER,
BDTIPOREFVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATAPGTO DATE,
BDBFGTSMESPOST NUMERIC(18,6),
BDFGTSMESPOST NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDINSSFNPR NUMERIC(18,6),
BDINSS13FNPR NUMERIC(18,6),
BDCCATVCONCOM /* DM_BOOLEAN */ VARCHAR(5),
BDREFAUXV NUMERIC(18,6),
BDFGTSIND NUMERIC(18,6),
BDDATAGRRF DATE,
BDPERCMULTA40 NUMERIC(15,2),
BDPERCMULTA10 NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_VERBAS_SIM_COL_CALC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_VERBAS_SIM_COL_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_VERBAS_SIM_PRES_CALC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SP_VERBAS_SIM_PRES_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODPRES INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SPF_BC_PROLAB_COLAB for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SPF_BC_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SPF_PROLAB_COLAB for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SPF_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SPF_RATAPO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SPF_RATAPO(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SPF_SALFAM for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SPF_SALFAM(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SPF_SALMATERNIDADE for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VRHF_SPF_SALMATERNIDADE(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_EXPORTA_SPED_I300 for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VSUC_SP_EXPORTA_SPED_I300(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDDATA DATE,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDDEBITO NUMERIC(15,2),
BDCREDITO NUMERIC(15,2),
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_DIARIO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VSUC_SP_RETORNA_DIARIO(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRMODELO INTEGER,
PRFILIAIS VARCHAR(1024),
PRLCC VARCHAR(1024),
PRDETALHARCTAPARTICIPANTE INTEGER,
PRREFEMP INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRCLASSI_CREDITO VARCHAR(40),
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRCLASSI_DEBITO VARCHAR(40),
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(400),
PREMPRESA INTEGER,
PRNOMEEMPRESA /* DM_BDNOMEMP */ VARCHAR(100),
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDETALHE VARCHAR(130),
PREMPRESAFILIAL INTEGER,
PRCHAVEONLINE VARCHAR(120),
PRTRANSACAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_RELESTATIST_GRA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATIST_GRA(PRCODEMP VARCHAR(2048),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES VARCHAR(8),
BDMESVALOR INTEGER,
BDCOLOR VARCHAR(10))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_RELESTATISTGRA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTGRA(PRCODEMP VARCHAR(2048),
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_RELESTATISTICA for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTICA(PRCODEMP VARCHAR(2048),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_SALDO for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRFORM VARCHAR(10),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
SALDO_MOVIMENTO NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_TOTAIS_LANC for: SP_SETA_COMPETENCIA */
ALTER PROCEDURE VSUC_SP_RETORNA_TOTAIS_LANC(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0,
PRLANCSEMTRANS INTEGER = 1,
PRDATAS VARCHAR(1024) = '')
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDQTDLINHA INTEGER,
BDVALLINHA NUMERIC(15,2),
BDQTDDEB INTEGER,
BDVALDEB NUMERIC(15,2),
BDQTDCRE INTEGER,
BDVALCRE NUMERIC(15,2),
BDQTDGERAL INTEGER,
BDVALGERAL NUMERIC(15,2),
BDDIF NUMERIC(15,2),
BDCODEMPFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_SETA_COMPETENCIA) */
ALTER PROCEDURE SP_SETA_COMPETENCIA(PRANOMES INTEGER,
PRDATAPRIDIAMES DATE = NULL,
PRDATAULTDIAMES DATE = NULL)
 AS
DECLARE VARIABLE WREF VARCHAR(6);
BEGIN
  /*
    Seta 3 vari?veis de contexto, na se??o do usu?rio.
    Essas vari?veis devem conter a compet?ncia atual.
    Essas vari?veis s?o utilizadas como uma forma de passagem de par?metro para view's.

    Para ler o conteudo da vari?vel de contexto utilize a seguinte sintaxe:
      select rdb$get_context('USER_SESSION', 'W_ANOMES')
      from rdb$database
  */

  IF (PRANOMES IS NOT NULL) THEN
     BEGIN
       IF (PRANOMES = 0) THEN
          BEGIN
            -- Gilberto - 20/10/2014 - N?o h? necessidade de executar um sql nesse caso, alterei porque dava erro na execu??o do script "Procedures_and_views_and_trigger"
            --select SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) from 6 for 2) from RDB$DATABASE into :wref;
            wRef = SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2);
          END
       ELSE
          wref = CAST(PRANOMES AS VARCHAR(6));

       rdb$set_context('USER_SESSION', 'W_ANOMES', wref);
     END
--  else
--     rdb$set_context('USER_SESSION', 'W_ANOMES', null);

  IF (PRDATAPRIDIAMES IS NOT NULL) THEN
     rdb$set_context('USER_SESSION', 'W_PRIDIAMES', CAST(PRDATAPRIDIAMES AS VARCHAR(10)));
--  else
--     rdb$set_context('USER_SESSION', 'W_PRIDIAMES', null);

  IF (PRDATAULTDIAMES IS NOT NULL) THEN
     rdb$set_context('USER_SESSION', 'W_ULTDIAMES', CAST(PRDATAULTDIAMES AS VARCHAR(10)));
--  else
--     rdb$set_context('USER_SESSION', 'W_ULTDIAMES', null);

END
^

/* Alter (SP_SOMENTE_ATIVOS) */
ALTER PROCEDURE SP_SOMENTE_ATIVOS(PRDATAINI DATE,
PRDATAFIM DATE,
PRCODEMP INTEGER = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';

  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';

  -- Admiss?es
  wsql = wsql||'where ';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||'COLCON.BDCODEMP = '||prcodemp||' and ';

  wsql = wsql||'COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataini||'''))';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END
^

/* Alter (SP_SOMENTE_ATIVOS_CAGED) */
ALTER PROCEDURE SP_SOMENTE_ATIVOS_CAGED(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WDATAADM01 date;
BEGIN
  wdataadm01 = CAST((SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 8)||'01') AS DATE);

  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';

  wsql = wsql||'left outer join vw_vrh_emp_tcolcon_vinc vinc on vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol ';
  wsql = wsql||'left outer join vrh_base_tclasse classe on classe.bdcodcla = vinc.bdcodcla ';
  wsql = wsql||'left outer join vrh_emp_trescisao RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql||'left outer join vrh_emp_ttranscol TRF on (TRF.BDCODEMPDEST = COLCON.BDCODEMP and TRF.BDCODCOLDEST = COLCON.BDCODCOL) ';

  -- Somente colaboradores
  wsql = wsql||'where COLCON.BDCONTRCOL <> 1 and classe.bdgrupocla <> 5 and ';

  -- Admiss?es
  wsql = wsql||'COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescis?es
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >='''||prdataini||''')) ';

  -- Transfer?ncias
  wsql = wsql||' and ((TRF.BDDATATRF is null) or (TRF.BDDATATRF <= '''||prdatafim||''')) ';

  wsql = wsql||' and COLCON.BDDATAADMCOL <> '''||:wdataadm01||'''';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END
^

/* Alter (SP_SOMENTE_ATIVOS_RAIS) */
ALTER PROCEDURE SP_SOMENTE_ATIVOS_RAIS(PRDATAINI DATE,
PRDATAFIM DATE,
PRCODEMP INTEGER = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql||'left outer join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = RESC.BDCODPRES) ';

  wsql = wsql||'where ';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||'COLCON.BDCODEMP = '||prcodemp||' and ';

  -- Admiss?es
  wsql = wsql||'COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescis?es e Transfer?ncias
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or '||
         '(case when COALESCE(PRES.BDAVPREPRES,0) in (0,1) and RESC.BDPROJECAOAVISO is not null then RESC.BDPROJECAOAVISO else RESC.BDDATARESCISAO end >= '''||prdataini||''')) ';


  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END
^

/* Alter (SP_TEMPRESAIMPOSTO_REF) */
ALTER PROCEDURE SP_TEMPRESAIMPOSTO_REF(PRCODEMP VARCHAR(20000),
PRREFERENCIA INTEGER,
PRQUANTIDADE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER)
 AS
DECLARE VARIABLE WPRIDIA DATE;
DECLARE VARIABLE WULTDIA DATE;
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select ';

  EXECUTE PROCEDURE sp_seta_competencia(:prreferencia,NULL,NULL);

  IF (prquantidade IS NOT NULL AND prquantidade <> 0) THEN
     wsql = wsql||'first '||prquantidade||' ';

  wsql = wsql|| 'BDCODEMP, '||
                'BDREFEMP, '||
                'BDREFFIMIMP, '||
                'BDCODIMP, '||
                'BDDESCIMP, '||
                'BDDATACRIACAO, '||
                'BDDATAEXTINTO, '||
                'BDCOMPETENCIA, '||
                'BDDOCARRECADACAO, '||
                'BDPERAPURACAO, '||
                'BDDIAVENCTO, '||
                'BDANTECIPA, '||
                'BDMESVENCTO, '||
                'BDJUROSDIA, '||
                'BDVLRJUROS, '||
                'BDJUROSDIAMES, '||
                'BDMULTADIA, '||
                'BDVLRMULTA, '||
                'BDMULTADIAMES, '||
                'BDVLRMAXMULTA, '||
                'COALESCE(BDALIQIMPOSTO, 0.0) BDALIQIMPOSTO, '||
                'BDLIMITEISENCAO, '||
                'BDTIPORETENCAO, '||
                'BDCODREC, '||
                'BDCODIND, '||
                'BDRETBCCALCULOIMP, '||
                'BDDESCREC, '||
                'BDTIPOIMPOSTO ';
  wsql = wsql||'from VW_TEMPRESAIMPOSTOREF ';


  wwhere = '';

  IF (prreferencia IS NOT NULL AND prreferencia <> 0) THEN
     BEGIN
       wpridia = CAST((SUBSTRING(prreferencia FROM 5 FOR 2)||'-01-'||SUBSTRING(prreferencia FROM 1 FOR 4)) AS DATE);
       wultdia = wpridia - EXTRACT(DAY FROM wpridia) + 32 - EXTRACT(DAY FROM wpridia - EXTRACT(DAY FROM wpridia) + 32);

       wwhere = wwhere||'BDREFEMP <= '||prreferencia||' ';

       wwhere = wwhere||' and (';

       wwhere = wwhere||'(BDDATACRIACAO is null) or (BDDATACRIACAO <= '''||wpridia||''') and ';
       wwhere = wwhere||'(BDDATAEXTINTO is null) or (BDDATAEXTINTO > '''||wultdia||''')';

       wwhere = wwhere||') ';
     END

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodemp;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

--  wsql = wsql||' group by BDCODEMP, BDCODIMP, BDDESCIMP, BDDATACRIACAO, BDDATAEXTINTO, BDCOMPETENCIA, BDDOCARRECADACAO, BDPERAPURACAO, BDDIAVENCTO, '||
--                         'BDANTECIPA, BDMESVENCTO, BDJUROSDIA, BDVLRJUROS, BDJUROSDIAMES, BDMULTADIA, BDVLRMULTA, BDMULTADIAMES, BDVLRMAXMULTA, '||
--                         'BDALIQIMPOSTO, BDLIMITEISENCAO, BDTIPORETENCAO, BDCODREC, BDCODIND, BDRETBCCALCULOIMP, BDDESCREC, BDTIPOIMPOSTO ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFEMP,
    :BDREFFIMIMP,
    :BDCODIMP,
    :BDDESCIMP,
    :BDDATACRIACAO,
    :BDDATAEXTINTO,
    :BDCOMPETENCIA,
    :BDDOCARRECADACAO,
    :BDPERAPURACAO,
    :BDDIAVENCTO,
    :BDANTECIPA,
    :BDMESVENCTO,
    :BDJUROSDIA,
    :BDVLRJUROS,
    :BDJUROSDIAMES,
    :BDMULTADIA,
    :BDVLRMULTA,
    :BDMULTADIAMES,
    :BDVLRMAXMULTA,
    :BDALIQIMPOSTO,
    :BDLIMITEISENCAO,
    :BDTIPORETENCAO,
    :BDCODREC,
    :BDCODIND,
    :BDRETBCCALCULOIMP,
    :BDDESCREC,
    :BDTIPOIMPOSTO
  DO
  SUSPEND;
END
^

/* Alter (SP_TERCEIRO) */
ALTER PROCEDURE SP_TERCEIRO(PRCODTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER DM_BDENDERECO,
BDNUMTER VARCHAR(10),
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3))
 AS
BEGIN
  IF (prcodter IS NOT NULL) THEN
     BEGIN
       SELECT FIRST 1 bdcodter, bdcodplapadrao, bdcodtpla, bdcgcter,
                      bdrefemp, bdapelidoter, bdnometer, bdlogrter, bdendter,
                      bdnumter, bdcompter, bdcepter, bdbaiter, bddddter, bdfoneter,
                      bdfaxter, bdemailter, bdieter, bddatacadter, bdimter, bdpruralter,
                      bdenqsimplesfedter, bdinscsuframater, bdcodgps, bdcodcid,
                      bdcodpais, bddescpais, bddddfaxter
       FROM vw_tterceiro WHERE bdcodter = :prcodter
       INTO :BDCODTER, :BDCODPLAPADRAO, :BDCODTPLA, :BDCGCTER,
            :BDREFEMP, :BDAPELIDOTER, :BDNOMETER, :BDLOGRTER, :BDENDTER,
            :BDNUMTER, :BDCOMPTER, :BDCEPTER, :BDBAITER, :BDDDDTER, :BDFONETER,
            :BDFAXTER, :BDEMAILTER, :BDIETER, :BDDATACADTER, :BDIMTER, :BDPRURALTER,
            :BDENQSIMPLESFEDTER, :BDINSCSUFRAMATER, :BDCODGPS, :BDCODCID,
            :BDCODPAIS, :BDDESCPAIS, :BDDDDFAXTER;
       SUSPEND;
     END
END
^

/* Alter (SP_TFERIADOS) */
ALTER PROCEDURE SP_TFERIADOS(PRANOMESI INTEGER,
PRANOMESF INTEGER)
 RETURNS(BDDATAFER DATE,
BDDESCFER VARCHAR(50),
BDCODCID INTEGER,
BDCODUF INTEGER,
BDREFFER INTEGER,
BDCODSINTRAB INTEGER,
BDDATAFERI DATE,
BDCODFERI INTEGER)
 AS
DECLARE VARIABLE WANOI INTEGER;
DECLARE VARIABLE WANOF INTEGER;
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WMESDIA VARCHAR(4);
BEGIN
  wanoi = CAST((SUBSTRING(pranomesi FROM 1 FOR 4)) AS INTEGER);
  wanof = CAST((SUBSTRING(pranomesf FROM 1 FOR 4)) AS INTEGER);

  WHILE (wanoi <= wanof) DO
    BEGIN                                                                                         -- Data vari?vel
      wsql = 'select BDCODUF, BDCODCID, BDDESCFERI, BDMESDIAFERI, BDCODSINTRAB, BDCODFERI from TFERIADOSNOVO where BDTIPOFERI <> 1';
      FOR EXECUTE STATEMENT wsql INTO :bdcoduf, :bdcodcid, :bddescfer, :wmesdia, :bdcodsintrab, :bdcodferi DO
        BEGIN
          IF (CAST((wanoi||SUBSTRING(wmesdia FROM 3 FOR 2)) AS INTEGER) >= pranomesi AND CAST((wanoi||SUBSTRING(wmesdia FROM 3 FOR 2)) AS INTEGER) <= pranomesf) THEN
             BEGIN
               bddatafer  = CAST((SUBSTRING(wmesdia FROM 3 FOR 2)||'-'||SUBSTRING(wmesdia FROM 1 FOR 2)||'-'||wanoi) AS DATE);
               bddataferi = CAST((SUBSTRING(wmesdia FROM 3 FOR 2)||'-'||SUBSTRING(wmesdia FROM 1 FOR 2)||'-'||wanoi) AS DATE);
               bdreffer = CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER);
               SUSPEND;
             END
        END

      wsql = 'select BDCODUF, BDCODCID, BDDESCFERI, BDDATAFERI, BDCODSINTRAB, BDCODFERI from TFERIADOSNOVO where BDTIPOFERI = 1 and BDDATAFERI >= '''||'01-01-'||wanoi||''' and BDDATAFERI <= '''||'12-31-'||wanoI||'''';
      FOR EXECUTE STATEMENT wsql INTO :bdcoduf, :bdcodcid, :bddescfer, :bddatafer, :bdcodsintrab, :bdcodferi DO
        BEGIN
          wmesdia = SUBSTRING(CAST(bddatafer AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(bddatafer AS VARCHAR(10)) FROM 9 FOR 2);
          IF (CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER) >= pranomesi AND CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER) <= pranomesf) THEN
             BEGIN
               bddataferi = bddatafer;
               bdreffer = CAST((SUBSTRING((CAST(bddatafer AS VARCHAR(10))) FROM 1 FOR 4)||SUBSTRING((CAST(bddatafer AS VARCHAR(10))) FROM 6 FOR 2)) AS INTEGER);
               SUSPEND;
             END
        END
      wanoi = wanoi + 1;
    END

END
^

/* Alter (SP_TIRATODOSSINAIS) */
ALTER PROCEDURE SP_TIRATODOSSINAIS(STR VARCHAR(32000))
 RETURNS(RESULT VARCHAR(32000))
 AS
BEGIN
  RESULT = STR;
  RESULT = REPLACE(RESULT, '/', '');
  RESULT = REPLACE(RESULT, '(', '');
  RESULT = REPLACE(RESULT, ')', '');
  RESULT = REPLACE(RESULT, '-', '');
  RESULT = REPLACE(RESULT, '_', '');
  RESULT = REPLACE(RESULT, '.', '');
  RESULT = REPLACE(RESULT, ',', '');
  RESULT = REPLACE(RESULT, '\', '');
  RESULT = REPLACE(RESULT, '$', '');
  RESULT = REPLACE(RESULT, '*', '');
  RESULT = REPLACE(RESULT, ':', '');
  RESULT = REPLACE(RESULT, '"', '');
  RESULT = REPLACE(RESULT, '?', '');
  RESULT = REPLACE(RESULT, '?', '');

  SUSPEND;
END
^

/* Alter (SP_TREEVIEW_CONF_DEPARA_ONLINE) */
ALTER PROCEDURE SP_TREEVIEW_CONF_DEPARA_ONLINE(PRPLANO_DE INTEGER,
PRPLANO_PARA INTEGER,
PRCODINT INTEGER,
PRPLANOCONTASANT INTEGER,
PRPLANOCONTASATU INTEGER,
PRPLANOHISTANT INTEGER,
PRPLANOHISTATU INTEGER,
PRCLASSIFICACAO VARCHAR(100),
PRLENGTH INTEGER,
PRREF INTEGER,
PRCHAVE INTEGER,
PRAPENASNIVEL INTEGER,
PRFILTERCLASSIFICACAO DM_MAXVARCHAR = '',
PRCONFAUT INTEGER = 0)
 RETURNS(BDFORMULA VARCHAR(80),
BDFORMULAITEM VARCHAR(80),
BDCONFIGTIT DM_BOOLEAN,
BDCLASSIFICACAO VARCHAR(100),
BDDESCRICAO VARCHAR(500),
BDAPECTADV VARCHAR(20),
BDAPECTACV VARCHAR(20),
BDAPECTADO VARCHAR(20),
BDAPECTACO VARCHAR(20),
BDDESCONTADV VARCHAR(100),
BDDESCONTACV VARCHAR(100),
BDDESCONTADO VARCHAR(100),
BDDESCONTACO VARCHAR(100),
BDCODHISTPROV INTEGER,
BDCODHISTPGTO INTEGER,
BDCODTIPOCONTA INTEGER,
BDCODNAT INTEGER,
BDCODVER INTEGER,
BDDESCREDVER VARCHAR(20),
BDAPELIDOTER VARCHAR(20),
BDNOMENAT VARCHAR(335),
BDAPEHISTPROV VARCHAR(20),
BDAPEHISTPGTO VARCHAR(20),
BDCONTADEBPROV INTEGER,
BDCONTACREDPROV INTEGER,
BDCONTADEBPGTO INTEGER,
BDCONTACREDPGTO INTEGER,
BDCHAVE INTEGER,
BDCHAVEVINC INTEGER,
BDCODPLANOONLINE INTEGER,
BDDESCIMP VARCHAR(100),
BDDESCOREC VARCHAR(100),
BDCODOREC INTEGER,
BDCODIMP INTEGER,
BDCODTCA INTEGER,
BDCODGRUPOCLA INTEGER,
BDDESCGRUPOCLA VARCHAR(200),
BDTIPONAT INTEGER,
BDCLASSVER VARCHAR(20),
BDTIPOVER INTEGER,
BDCODITEMONLINE INTEGER,
BDAPECOMHISTPROV VARCHAR(20),
BDAPECOMHISTPGTO VARCHAR(20),
BDCODCOMPHISTPROV INTEGER,
BDCODCOMPHISTPGTO INTEGER,
BDCOMHISTPROV VARCHAR(1000),
BDCOMHISTPGTO VARCHAR(1000),
BDCONFIGPROV DM_BOOLEAN,
BDCONFIGDEBPROV DM_BOOLEAN,
BDCONFIGCREDPROV DM_BOOLEAN,
BDCONFIGPAG DM_BOOLEAN,
BDCONFIGDEBPAG DM_BOOLEAN,
BDCONFIGCREDPAG DM_BOOLEAN,
BDCONFIGHISTPROV DM_BOOLEAN,
BDCONFIGHISTPAG DM_BOOLEAN,
BDNAOCONTAB DM_BOOLEAN,
BDCODREC INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(42),
BDCODTPHIST INTEGER,
BDAPELIDOHIST VARCHAR(20),
BDCHAVE_PARA INTEGER,
BDCODMASTER INTEGER,
BDPODEEDITAR DM_BOOLEAN,
BDCLASSIFICACAOORI VARCHAR(100),
BDCODOBRSER INTEGER,
BDCHAVECTABAN INTEGER,
BDCODCLI INTEGER)
 AS
DECLARE VARIABLE WSQL DM_MAXVARCHAR;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(100);
DECLARE VARIABLE WCODTPLAANT INTEGER;
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WNOMCTAANT VARCHAR(100);
DECLARE VARIABLE WTIPCTAANT INTEGER;
DECLARE VARIABLE WCODTPLAATU INTEGER;
DECLARE VARIABLE WCTALONATU VARCHAR(40);
DECLARE VARIABLE WNOMCTAATU VARCHAR(100);
DECLARE VARIABLE WCODTPHIANT INTEGER;
DECLARE VARIABLE WAPELIDOANT VARCHAR(20);
DECLARE VARIABLE WHISTANT VARCHAR(100);
DECLARE VARIABLE WCODTPHIATU INTEGER;
DECLARE VARIABLE WAPELIDOATU VARCHAR(20);
DECLARE VARIABLE WHISTATU VARCHAR(100);
DECLARE VARIABLE WCODPLANOONLINE_PARA INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WQTDAUX INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WCHAVE_PARA INTEGER;
DECLARE VARIABLE WCODHISTPROV INTEGER;
DECLARE VARIABLE WCODHISTPGTO INTEGER;
DECLARE VARIABLE WCONTADEBPROV INTEGER;
DECLARE VARIABLE WCONTACREDPROV INTEGER;
DECLARE VARIABLE WCONTADEBPGTO INTEGER;
DECLARE VARIABLE WCONTACREDPGTO INTEGER;
DECLARE VARIABLE WCODCOMPHISTPROV INTEGER;
DECLARE VARIABLE WCODCOMPHISTPGTO INTEGER;
DECLARE VARIABLE WCOMHISTPROV VARCHAR(1000);
DECLARE VARIABLE WCOMHISTPGTO VARCHAR(1000);
DECLARE VARIABLE WDE INTEGER;
DECLARE VARIABLE WATE INTEGER;
BEGIN
  /*prconfaut - > 0 - False | 1 - True
  Quando for para configura??o autom?tica preciso trazer tudo de uma vez. E ele
  s? traz os que n?o tenham nada configurado*/
  wde  = 1;
  wate = 1;
  IF (prconfaut = 1) THEN
    BEGIN
      wate = 4; -- 1 - Grupo principal | 2 - Plano de contas | 3 - Hist?rico | 4 - Online
      -- limpa tabela tempor?ria da configura??o autom?tica
      DELETE FROM VINT_BASE_TINTCONFAUT WHERE bdcodplanoonline_de IS NOT NULL;
    END

  bdcodplanoonline = prplano_de;
  WHILE  (wde <= wate)  DO
    BEGIN
      IF (prconfaut = 1) THEN
        BEGIN
          IF (wde = 1) THEN
            prclassificacao = '';
          ELSE
          IF (wde = 2) THEN
            prclassificacao = '01';
          ELSE
          IF (wde = 3) THEN
            prclassificacao = '02';
          ELSE
            prclassificacao = '03';
        END

      IF (((prclassificacao IS NULL) OR (prclassificacao = '')) AND ((prapenasnivel = 0) OR (prapenasnivel IS NULL) OR (prconfaut = 1))) THEN
        BEGIN
          bdclassificacao    = '01';
          bdclassificacaoori = NULL;
          bddescricao        = 'Plano de contas';
          bdpodeeditar       = 'FALSE';
          SUSPEND;
          bdclassificacao    = '02';
          bdclassificacaoori = NULL;
          bddescricao        = 'Hist?rico';
          bdpodeeditar       = 'FALSE';
          SUSPEND;
          bdclassificacao    = '03';
          bdclassificacaoori = NULL;
          bddescricao        = 'Online';
          bdpodeeditar       = 'FALSE';
          SUSPEND;
        END
      ELSE
      IF (SUBSTRING(prclassificacao FROM 1 FOR 2) = '01') THEN --Plano de contas
        BEGIN
          wclassificacao = TRIM((SUBSTRING(prclassificacao FROM 4 FOR (CHAR_LENGTH(prclassificacao)))));
    
          wqtd = 0;
          IF (prapenasnivel = 0) THEN
            BEGIN
              wcount = 1;
              WHILE (wcount <= CHAR_LENGTH(prclassificacao)) DO
                BEGIN
                  IF (SUBSTRING(prclassificacao FROM wcount FOR 1) = '.') THEN
                    wqtd = wqtd + 1;
                  wcount = wcount + 1;
                END
            END
    
          wsql = 'Select tAnt.bdCODTPLA,tAnt.bdCTALON,tAnt.bdNOMCTA,tAnt.bdTIPCTA, ';
          wsql = wsql||'tInt.bdCODTPLAATU,tAtu.bdCTALON,tAtu.bdNOMCTA from planos_tpla tAnt ';
          wsql = wsql||'left join vint_base_tintcontas tInt on (tInt.bdcodint = '||:prcodint||' and tInt.bdcodplapadraoant = '||:prplanocontasant||' and tInt.bdcodtplaant = tAnt.bdcodtpla) ';
          wsql = wsql||'left join planos_tpla tAtu on (tAtu.bdcodplapadrao = tInt.bdcodplapadraoatu and tAtu.bdcodtpla = tInt.bdcodtplaatu) ';
          wsql = wsql||'where ';
    
          IF (prapenasnivel = 0) THEN
            wsql = wsql||'(tAnt.bdtipcta <> 1) and ';
    
          IF (wclassificacao <> '') THEN
            BEGIN
              wsql = wsql||'(substring(tAnt.bdctalon from 1 for '||CHAR_LENGTH(TRIM(wclassificacao))||') = '||''''||TRIM(wclassificacao)||''') and ';
              wsql = wsql||'(tant.bdctalon <> '||''''||TRIM(wclassificacao)||''') and ';
            END
    
    
          wsql = wsql||'(tAnt.bdcodplapadrao = '||:prplanocontasant||') order by tAnt.bdCTALON';
    
          FOR EXECUTE STATEMENT wsql
              INTO :wcodtplaant,:wctalonant,:wnomctaant,:wtipctaant,:wcodtplaatu,:wctalonatu,:wnomctaatu DO
            BEGIN
              wqtdaux = 0;
              IF (prapenasnivel = 0) THEN
                BEGIN
                  wcount = 1;
                  WHILE (wcount <= CHAR_LENGTH(wctalonant)) DO
                    BEGIN
                      IF (SUBSTRING(wctalonant FROM wcount FOR 1) = '.') THEN
                        wqtdaux = wqtdaux + 1;
                      wcount = wcount + 1;
                    END
                END
    
              IF (wqtd = wqtdaux) THEN
                BEGIN
                  bdclassificacao    = '01.'||wctalonant;
                  bdclassificacaoori = wctalonant;
                  bdcodmaster        = wcodtplaant;
                  bdcodcta           = wcodtplaant;
                  bdctalon           = wctalonant;
                  bddescricao        = wnomctaant;
                  bdpodeeditar       = 'FALSE';
                  IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wcodtplaatu,0) = 0) AND (wtipctaant = 1))) THEN
                    SUSPEND;
        
                  IF (wtipctaant = 1) THEN -- Anal?ticas
                    BEGIN
                      bdclassificacao    = '01.'||wctalonant||'.Z';
                      bdclassificacaoori = wctalonant;
                      bdcodmaster        = wcodtplaant;
                      bdpodeeditar       = 'TRUE';
                      bdcodcta           = NULL;
                      bdctalon           = '';
                      bddescricao        = '';
                      IF (COALESCE(wcodtplaatu,0) > 0) THEN
                        BEGIN
                          bdcodcta        = wcodtplaatu;
                          bdctalon        = wctalonatu;
                          bddescricao     = wnomctaatu;
                        END

                      IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wcodtplaatu,0) = 0))) THEN
                        SUSPEND;
                    END
                END
            END
        END
      ELSE
      IF ((SUBSTRING(prclassificacao FROM 1 FOR 2) = '02') AND (prapenasnivel = 1)) THEN --Hist?rico
        BEGIN
          wsql = 'Select tAnt.bdCODTPHI,tAnt.bdAPELIDO,tAnt.bdNOME,tInt.bdCODTPHIATU, ';
          wsql = wsql||'tAtu.bdAPELIDO,tAtu.bdNOME from hist_tphi tAnt ';
          wsql = wsql||'left join vint_base_tinthist tInt on (tInt.bdcodint = '||:prcodint||' and tInt.bdcodhistant = '||:prplanohistant||' and tInt.bdcodtphiant = tAnt.bdcodtphi) ';
          wsql = wsql||'left join hist_tphi tAtu on (tAtu.bdcodhist = tInt.bdcodhistatu and tAtu.bdcodtphi = tInt.bdcodtphiatu) ';
          wsql = wsql||'where ';
          wsql = wsql||'(tAnt.bdcodhist = '||:prplanohistant||') order by tAnt.bdcodtphi';
    
          FOR EXECUTE STATEMENT wsql
              INTO :wcodtphiant,:wapelidoant,:whistant,:wcodtphiatu,:wapelidoatu,:whistatu DO
            BEGIN
              bdclassificacao    = '02.'||LPAD(wcodtphiant||'.A', 15, '0');
              bdclassificacaoori = wcodtphiant;
              bdcodmaster        = wcodtphiant;
              bdcodtphist        = wcodtphiant;
              bdapelidohist      = wapelidoant;
              bddescricao        = whistant;
              bdpodeeditar       = 'FALSE';
              IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wcodtphiatu,0) = 0))) THEN
                SUSPEND;

              bdclassificacao    = '02.'||LPAD(wcodtphiant||'.Z', 15, '0');
              bdclassificacaoori = wcodtphiant;
              bdcodmaster        = wcodtphiant;
              bdpodeeditar       = 'TRUE';
              bdcodtphist        = NULL;
              bdapelidohist      = '';
              bddescricao        = '';
              IF (COALESCE(wcodtphiatu,0) > 0) THEN
                BEGIN
                  bdcodtphist   = wcodtphiatu;
                  bdapelidohist = wapelidoatu;
                  bddescricao   = whistatu;
                END

              IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wcodtphiatu,0) = 0))) THEN
                SUSPEND;
            END
        END
      ELSE
      IF (SUBSTRING(prclassificacao FROM 1 FOR 2) = '03') THEN --Online
        BEGIN
          wclassificacao = TRIM((SUBSTRING(prclassificacao FROM 4 FOR (CHAR_LENGTH(prclassificacao)))));
          wqtd           = 0;
    
          wsql = 'Select tAnt.bdFORMULA,tAnt.bdFORMULAITEM,tAnt.bdCONFIGTIT,tAnt.bdCLASSIFICACAO,tAnt.bdDESCRICAO,tAnt.bdAPECTADV,tAnt.bdAPECTACV,';
          wsql = wsql||'tAnt.bdAPECTADO,tAnt.bdAPECTACO,tAnt.bdDESCONTADV,tAnt.bdDESCONTACV,tAnt.bdDESCONTADO,tAnt.bdDESCONTACO,tAnt.bdCODHISTPROV,';
          wsql = wsql||'tAnt.bdCODHISTPGTO,tAnt.bdCODTIPOCONTA,tAnt.bdCODNAT,tAnt.bdCODVER,tAnt.bdDESCREDVER,tAnt.bdAPELIDOTER,tAnt.bdNOMENAT,';
          wsql = wsql||'tAnt.bdAPEHISTPROV,tAnt.bdAPEHISTPGTO,tAnt.bdCONTADEBPROV,tAnt.bdCONTACREDPROV,tAnt.bdCONTADEBPGTO,tAnt.bdCONTACREDPGTO,';
          wsql = wsql||'tAnt.bdCHAVE,tAnt.bdCHAVEVINC,tAnt.bdCODPLANOONLINE,tAnt.bdDESCIMP,tAnt.bdDESCOREC,tAnt.bdCODOREC,tAnt.bdCODIMP,';
          wsql = wsql||'tAnt.bdCODTCA,tAnt.bdCODGRUPOCLA,tAnt.bdDESCGRUPOCLA,tAnt.bdTIPONAT,tAnt.bdCLASSVER,tAnt.bdTIPOVER,tAnt.bdCODITEMONLINE,';
          wsql = wsql||'tAnt.bdAPECOMHISTPROV,tAnt.bdAPECOMHISTPGTO,tAnt.bdCODCOMPHISTPROV,tAnt.bdCODCOMPHISTPGTO,tAnt.bdCOMHISTPROV,tAnt.bdCOMHISTPGTO,';
          wsql = wsql||'tAnt.bdCONFIGPROV,tAnt.bdCONFIGDEBPROV,tAnt.bdCONFIGCREDPROV,tAnt.bdCONFIGPAG,tAnt.bdCONFIGDEBPAG,tAnt.bdCONFIGCREDPAG,';
          wsql = wsql||'tAnt.bdCONFIGHISTPROV,tAnt.bdCONFIGHISTPAG,tAnt.bdNAOCONTAB,tAnt.bdCODREC,tint.bdCODPLANOONLINE_PARA,tint.bdCHAVE_PARA,';
          wsql = wsql||'tConf.bdcodhistprov,tConf.bdcodhistpgto,tConf.bdcontadebprov,tConf.bdcontacredprov,tConf.bdcontadebpgto,tConf.bdcontacredpgto,';
          wsql = wsql||'tConf.bdcodcomphistprov,tConf.bdcodcomphistpgto,tChistP.bdcomplemento bdcomhistprov,tChistO.bdcomplemento bdcomhistpgto,';
          wsql = wsql||'tAnt.bdcodobrser,tAnt.bdchavectaban,tAnt.bdcodcli ';
          wsql = wsql||'from SP_TREEVIEW_CONS_CONF_ONLINE('||:prplano_de||','''||:wclassificacao||''',';
    
          IF (prlength > 0) THEN
            wsql = wsql||:prlength;
          ELSE
            wsql = wsql||'null';
          wsql = wsql||',';
          wsql = wsql||:prref||',';
    
          IF (prchave IS NOT NULL) THEN
            wsql = wsql||:prchave;
          ELSE
            wsql = wsql||'null';
          wsql = wsql||',';
          wsql = wsql||:prapenasnivel;
    
          IF ((TRIM(prfilterclassificacao) <> '') AND (TRIM(prfilterclassificacao) IS NOT NULL)) THEN
            wsql = wsql||','''||:prfilterclassificacao||'''';
          wsql = wsql||') tAnt ';
          wsql = wsql||'left join vint_base_tintconfcontasonline tInt on (tInt.bdcodint = '||:prcodint||' and tInt.bdcodplanoonline_de = '||:prplano_de||' and tInt.bdchave_de = tAnt.bdchave) ';
          wsql = wsql||'left join tconf_contas_online tConf on (tConf.bdcodplanoonline = '||:prplano_para||' and tConf.bdchave = tint.bdCHAVE_PARA and tint.bdCHAVE_PARA > 0) ';
          wsql = wsql||'left outer join tcomplemento_hist tChistP on (tChistP.bdcodcomphist = tConf.BDCODCOMPHISTPROV ) ';
          wsql = wsql||'left outer join tcomplemento_hist tChistO on (tChistO.bdcodcomphist = tConf.BDCODCOMPHISTPGTO ) ';
          wsql = wsql||'order by tAnt.bdclassificacao,tAnt.bdchave ';
          FOR EXECUTE STATEMENT wsql
              INTO :bdformula,:bdformulaitem,:bdconfigtit,:wclassificacao,:bddescricao,:bdapectadv,:bdapectacv,
                   :bdapectado,:bdapectaco,:bddescontadv,:bddescontacv,:bddescontado,:bddescontaco,:bdcodhistprov,
                   :bdcodhistpgto,:bdcodtipoconta,:bdcodnat,:bdcodver,:bddescredver,:bdapelidoter,:bdnomenat,
                   :bdapehistprov,:bdapehistpgto,:bdcontadebprov,:bdcontacredprov,:bdcontadebpgto,:bdcontacredpgto,
                   :bdchave,:bdchavevinc,:bdcodplanoonline,:bddescimp,:bddescorec,:bdcodorec,:bdcodimp,
                   :bdcodtca,:bdcodgrupocla,:bddescgrupocla,:bdtiponat,:bdclassver,:bdtipover,:bdcoditemonline,
                   :bdapecomhistprov,:bdapecomhistpgto,:bdcodcomphistprov,:bdcodcomphistpgto,:bdcomhistprov,:bdcomhistpgto,
                   :bdconfigprov,:bdconfigdebprov,:bdconfigcredprov,:bdconfigpag,:bdconfigdebpag,:bdconfigcredpag,
                   :bdconfighistprov,:bdconfighistpag,:bdnaocontab,:bdcodrec,:wcodplanoonline_para,:wchave_para,
                   :wcodhistprov,:wcodhistpgto,:wcontadebprov,:wcontacredprov,:wcontadebpgto,:wcontacredpgto,
                   :wcodcomphistprov,:wcodcomphistpgto,:wcomhistprov,:wcomhistpgto,:bdcodobrser,:bdchavectaban,:bdcodcli DO
            BEGIN
              bdclassificacao    = '03.'||wclassificacao;
              bdclassificacaoori = wclassificacao;
              bdcodmaster        = bdchave;
              bdpodeeditar       = 'FALSE';
              bdchave_para       = NULL;
    
              --Registro que sejam filhos, ou seja, que tenham um v?nculo
              IF (bdchavevinc > 0) THEN
                BEGIN
                  wqtd            = wqtd + 1;
                  bdclassificacao = bdclassificacao||'.Z'||LPAD(wqtd, 15, '0');
                  wqtd            = wqtd + 1;
                END

              IF (COALESCE(prconfaut,0) = 0) THEN
                SUSPEND;
    
              IF ((UPPER(bdconfigtit) = 'TRUE') OR
                  ((UPPER(bdconfigtit) = 'FALSE') AND (bdcoditemonline > 0) AND
                   ((COALESCE(bdconfigprov,'FALSE') <> 'FALSE') OR (COALESCE(bdconfigpag,'FALSE') <> 'FALSE')))) THEN -- Podem ser configuradas
                BEGIN
                  IF ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wchave_para,0) = 0)) THEN
                    SUSPEND;

                  bdcodhistprov     = NULL;
                  bdcodhistpgto     = NULL;
                  bdcontadebprov    = NULL;
                  bdcontacredprov   = NULL;
                  bdcontadebpgto    = NULL;
                  bdcontacredpgto   = NULL;
                  bdcodcomphistprov = NULL;
                  bdcodcomphistpgto = NULL;
                  bdcomhistprov     = NULL;
                  bdcomhistpgto     = NULL;
    
                  bdclassificacao    = '03.'||wclassificacao||'.Z';
                  bdclassificacaoori = wclassificacao;
                  bdcodmaster        = bdchave;
                  bdpodeeditar       = 'TRUE';
                  bdchave            = NULL;
                  bdchave_para       = NULL;
    
                  --Registro que sejam filhos, ou seja, que tenham um v?nculo
                  IF (bdchavevinc > 0) THEN
                    bdclassificacao = bdclassificacao||LPAD(wqtd, 15, '0');
    
                  IF (COALESCE(wchave_para,0) > 0) THEN
                    BEGIN
                      bdchave           = wchave_para;
                      bdchave_para      = wchave_para;
                      bdcodhistprov     = wcodhistprov;
                      bdcodhistpgto     = wcodhistpgto;
                      bdcontadebprov    = wcontadebprov;
                      bdcontacredprov   = wcontacredprov;
                      bdcontadebpgto    = wcontadebpgto;
                      bdcontacredpgto   = wcontacredpgto;
                      bdcodcomphistprov = wcodcomphistprov;
                      bdcodcomphistpgto = wcodcomphistpgto;
                      bdcomhistprov     = wcomhistprov;
                      bdcomhistpgto     = wcomhistpgto;
                    END

                  IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wchave_para,0) = 0))) THEN
                    SUSPEND;
                END
            END
        END

      wde = wde + 1;
    END
END
^

/* Alter (SP_TREEVIEW_CONS_ANUAL_CONF) */
ALTER PROCEDURE SP_TREEVIEW_CONS_ANUAL_CONF(PRSISTEMA INTEGER,
PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDANOSWS VARCHAR(4))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WQUADROANT INTEGER;
DECLARE VARIABLE WQUADROATU INTEGER;
DECLARE VARIABLE WDESQUADROANT VARCHAR(80);
DECLARE VARIABLE WORDEMANT INTEGER;
DECLARE VARIABLE WDESCORDEMANT VARCHAR(80);
DECLARE VARIABLE WANO CHAR(10);
DECLARE VARIABLE WANOSWS CHAR(2);
DECLARE VARIABLE WPRIMEIROQUADRO INTEGER;
DECLARE VARIABLE WTOTALQUADRO NUMERIC(15,6);
DECLARE VARIABLE WJANQUADRO NUMERIC(15,6);
DECLARE VARIABLE WFEVQUADRO NUMERIC(15,6);
DECLARE VARIABLE WMARQUADRO NUMERIC(15,6);
DECLARE VARIABLE WABRQUADRO NUMERIC(15,6);
DECLARE VARIABLE WMAIQUADRO NUMERIC(15,6);
DECLARE VARIABLE WJUNQUADRO NUMERIC(15,6);
DECLARE VARIABLE WJULQUADRO NUMERIC(15,6);
DECLARE VARIABLE WAGOQUADRO NUMERIC(15,6);
DECLARE VARIABLE WSETQUADRO NUMERIC(15,6);
DECLARE VARIABLE WOUTQUADRO NUMERIC(15,6);
DECLARE VARIABLE WNOVQUADRO NUMERIC(15,6);
DECLARE VARIABLE WDEZQUADRO NUMERIC(15,6);
BEGIN
  /* giovanni */

  /* Procedure Text */

  /* SP Padrao para montar a treeview DA Consulta anual configuravel */
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wano    = SUBSTRING(prref FROM 1 FOR 4);
  wanosws = SUBSTRING(prref FROM 3 FOR 2);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || 'T.BDREF, ';
  wsql = wsql || 'T.BDCODQPLACONSCONF, ';
  wsql = wsql || 'QUADRO.BDDESCRICAO, ';
  wsql = wsql || 'T.BDORDEM, ';
  wsql = wsql || 'T.BDDESCRICAO,';
  wsql = wsql || 'T.BDVALOR';

  -- Baseado na tabela TSistema
  IF (prsistema = 4) THEN -- Cont?bil
    wsql = wsql || ' from VSUC_REL_CONS_ANUAL_CONF T';
  ELSE
    wsql = wsql || ' from VEF_REL_CONS_ANUAL_CONF T';

  /* tirado a spconsultaempresas_sis muito lenta... */
  --  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas on (empresas.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join TPLANOCONSCONF_Q QUADRO on (QUADRO.BDCODQPLACONSCONF = t.BDCODQPLACONSCONF AND QUADRO.BDCODPLACONSCONF = T.BDCODPLACONSCONF) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
    wwhere = ' where '||:PRCODEMP;

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDCODQPLACONSCONF  = '||:prcodquadro;
    END

  IF (wwhere <> '') THEN
    wwhere = wwhere||' and ';
  ELSE
    wwhere = wwhere||' where ';

  -- Baseado na tabela TSistema
  IF (prsistema = 4) THEN -- Cont?bil
    wwhere = wwhere||' QUADRO.bdcodsis = 4 ';
  ELSE
    wwhere = wwhere||' QUADRO.bdcodsis = 3 '; -- Escrita

  -- wsql = wsql||wwhere || ' order by bdcodemp, bdref desc, BDCODQPLACONSCONF, bdordem' ;
  wsql = wsql||wwhere || ' order by bdcodemp, BDCODQPLACONSCONF, bdordem, bdref  ' ;

  wquadroant      = 0;
  wordemant       = 0;
  wdesquadroant   = '';
  wdescordemant   = '';
  wPrimeiroQuadro = 1;

  -- Baseado na tabela TSistema
  --#6408, comentado o if: precisa inicializar as variaveis pois ? feito soma incremental (null + valor = null)
  --if (prsistema = 4) then -- Cont?bil
  --  begin
      BDJAN   = 0;
      BDFEV   = 0;
      BDMAR   = 0;
      BDABR   = 0;
      BDMAI   = 0;
      BDJUN   = 0;
      BDJUL   = 0;
      BDAGO   = 0;
      BDSET   = 0;
      BDOUT   = 0;
      BDNOV   = 0;
      BDDEZ   = 0;
      BDVALOR = 0;
      BDTOTAL = 0;

      WTOTALQUADRO = 0;
      WJANQUADRO   = 0;
      WFEVQUADRO   = 0;
      WMARQUADRO   = 0;
      WABRQUADRO   = 0;
      WMAIQUADRO   = 0;
      WJUNQUADRO   = 0;
      WJULQUADRO   = 0;
      WAGOQUADRO   = 0;
      WSETQUADRO   = 0;
      WOUTQUADRO   = 0;
      WNOVQUADRO   = 0;
      WDEZQUADRO   = 0;
    --end

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdref,
    bdcodquadro,
    bddescquadro,
    bdordem,
    bddescricao,
    bdvalor
  DO
  BEGIN
    IF (((wordemant = bdordem) OR (wordemant = 0)) AND ((wquadroant = bdcodquadro) OR (wquadroant = 0))) THEN   /* totaliza o quadro e a ordem atual */ -- (((wquadroant = bdcodquadro) or (wquadroant = 0))
      BEGIN
        wquadroant    = bdcodquadro;
        wdesquadroant = bddescquadro;
        wordemant     = bdordem;
        wdescordemant = bddescricao;

        IF (bdtotal <> 0) THEN
          bdtotal = bdtotal + bdvalor;
        ELSE
          bdtotal = bdvalor;

        wtotalquadro = wtotalquadro + bdvalor;

        -- Baseado na tabela TSistema
        IF (prSistema <> 4) THEN -- Cont?bil
          BEGIN
            IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
              bdjan = bdjan + bdvalor; --#6408: bdjan = bdvalor, modificado para soma incremental para todos os meses desse if
            ELSE
            IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
              bdfev = bdfev + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
              bdmar = bdmar + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
              bdabr = bdabr + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
              bdmai = bdmai + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
              bdjun = bdjun + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
              bdjul = bdjul + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
              bdago = bdago + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
              bdset = bdset + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
              bdout = bdout + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
              bdnov = bdnov + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
              bddez = bddez + bdvalor;
          END
        ELSE
          BEGIN
            IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
              BEGIN
                bdjan      = bdjan + bdvalor;
                wjanquadro = wjanquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
              BEGIN
                bdfev      = bdfev + bdvalor;
                wfevquadro = wfevquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
              BEGIN
                bdmar      = bdmar + bdvalor;
                wmarquadro = wmarquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
              BEGIN
                bdabr      = bdabr + bdvalor;
                wabrquadro = wabrquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
              BEGIN
                bdmai      = bdmai + bdvalor;
                wmaiquadro = wmaiquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
              BEGIN
                bdjun      = bdjun + bdvalor;
                wjunquadro = wjunquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
              BEGIN
                bdjul      = bdjul + bdvalor;
                wjulquadro = wjulquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
              BEGIN
                bdago      = bdago + bdvalor;
                wagoquadro = wagoquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
              BEGIN
                bdset      = bdset + bdvalor;
                wsetquadro = wsetquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
              BEGIN
                bdout      = bdout + bdvalor;
                woutquadro = woutquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
              BEGIN
                bdnov      = bdnov + bdvalor;
                wnovquadro = wnovquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
              BEGIN
                bddez      = bddez + bdvalor;
                wdezquadro = wdezquadro + bdvalor;
              END
          END
      END
    ELSE
      BEGIN
        IF ((prSistema <> 4) AND (((prdetalhaquadro = 1) AND (wquadroant <> bdcodquadro)) OR (wprimeiroquadro = 1))) THEN  /* quebra por quadro */
--        if  ((wprimeiroquadro = 1) and (prdetalhaquadro = 1)) then  /* quebra por quadro */
          BEGIN
            wprimeiroquadro = 0;
            bdordem         = NULL;
            bddescricao     = bddescquadro;
            bdanosws        = wanosws;
            SUSPEND;
          END

        bdordem      = wordemant;
        wquadroatu   = bdcodquadro;
        bdcodquadro  = wquadroant;
        bddescquadro = wdesquadroant;
        bddescricao  = wdescordemant;
        bdanosws     = wanosws;
        SUSPEND;

        IF ((prSistema = 4) AND (prdetalhaquadro = 1) AND (wquadroant <> wquadroatu)) THEN  /* quebra por quadro */
          BEGIN
            wprimeiroquadro = 0;
            bdordem         = NULL;
            bddescricao     = bddescquadro;
            BDJAN           = WJANQUADRO;
            BDFEV           = WFEVQUADRO;
            BDMAR           = WMARQUADRO;
            BDABR           = WABRQUADRO;
            BDMAI           = WMAIQUADRO;
            BDJUN           = WJUNQUADRO;
            BDJUL           = WJULQUADRO;
            BDAGO           = WAGOQUADRO;
            BDSET           = WSETQUADRO;
            BDOUT           = WOUTQUADRO;
            BDNOV           = WNOVQUADRO;
            BDDEZ           = WDEZQUADRO;
            BDTOTAL         = WTOTALQUADRO;
            SUSPEND;
            WTOTALQUADRO    = 0;
            WJANQUADRO      = 0;
            WFEVQUADRO      = 0;
            WMARQUADRO      = 0;
            WABRQUADRO      = 0;
            WMAIQUADRO      = 0;
            WJUNQUADRO      = 0;
            WJULQUADRO      = 0;
            WAGOQUADRO      = 0;
            WSETQUADRO      = 0;
            WOUTQUADRO      = 0;
            WNOVQUADRO      = 0;
            WDEZQUADRO      = 0;
          END

        wquadroant = 0;
        wordemant  = 0;
        bdtotal    = 0;

        IF (bdtotal <> 0) THEN
          bdtotal = bdtotal + bdvalor;
        ELSE
          bdtotal = bdvalor;

        wtotalquadro = wtotalquadro + bdvalor;

        IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
          BEGIN
            bdjan      = bdvalor;
            wjanquadro = wjanquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
          BEGIN
            bdfev      = bdvalor;
            wfevquadro = wfevquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
          BEGIN
            bdmar      = bdvalor;
            wmarquadro = wmarquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
          BEGIN
            bdabr      = bdvalor;
            wabrquadro = wabrquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
          BEGIN
            bdmai      = bdvalor;
            wmaiquadro = wmaiquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
          BEGIN
            bdjun      = bdvalor;
            wjunquadro = wjunquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
          BEGIN
            bdjul      = bdvalor;
            wjulquadro = wjulquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
          BEGIN
            bdago      = bdvalor;
            wagoquadro = wagoquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
          BEGIN
            bdset      = bdvalor;
            wsetquadro = wsetquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
          BEGIN
            bdout      = bdvalor;
            woutquadro = woutquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
          BEGIN
            bdnov      = bdvalor;
            wnovquadro = wnovquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
          BEGIN
            bddez      = bdvalor;
            wdezquadro = wdezquadro + bdvalor;
          END

        wdesquadroant = '';
        wdescordemant = '';
/*          BDFEV = 0;
          BDMAR = 0;
          BDABR = 0;
          BDMAI = 0;
          BDJUN = 0;
          BDJUL = 0;
          BDAGO = 0;
          BDSET = 0;
          BDOUT = 0;
          BDNOV = 0;
          BDDEZ = 0;*/
      END
  END

  IF ((prsistema <> 4) AND (wprimeiroquadro = 1)) THEN  /* quebra por quadro */
    BEGIN
      wprimeiroquadro = 0;
      bdordem         = NULL;
      bddescricao     = bddescquadro;
      bdanosws        = wanosws;
      SUSPEND;
    END

  bdordem      = wordemant;
  bdcodquadro  = wquadroant;
  bddescquadro = wdesquadroant;
  bddescricao  = wdescordemant;
  bdanosws     = wanosws;
  SUSPEND;

  IF ((prsistema = 4) /*and (wprimeiroquadro = 1)*/) THEN  /* quebra por quadro */
    BEGIN
      wprimeiroquadro = 0;
      bdordem         = NULL;
      bddescricao     = bddescquadro;
      BDJAN           = WJANQUADRO;
      BDFEV           = WFEVQUADRO;
      BDMAR           = WMARQUADRO;
      BDABR           = WABRQUADRO;
      BDMAI           = WMAIQUADRO;
      BDJUN           = WJUNQUADRO;
      BDJUL           = WJULQUADRO;
      BDAGO           = WAGOQUADRO;
      BDSET           = WSETQUADRO;
      BDOUT           = WOUTQUADRO;
      BDNOV           = WNOVQUADRO;
      BDDEZ           = WDEZQUADRO;
      BDTOTAL         = WTOTALQUADRO;
      SUSPEND;
    END
END
^

/* Alter (SP_TREEVIEW_CONS_CONF_ONLINE) */
ALTER PROCEDURE SP_TREEVIEW_CONS_CONF_ONLINE(PRPLANO INTEGER,
PRCLASSIFICACAO VARCHAR(100),
PRLENGTH INTEGER,
PRREF INTEGER,
PRCHAVE INTEGER,
PRAPENASNIVEL INTEGER,
PRFILTERCLASSIFICACAO DM_MAXVARCHAR = '',
PRFILTRERTREEVIEW VARCHAR(200) = '')
 RETURNS(BDFORMULA VARCHAR(80),
BDFORMULAITEM VARCHAR(80),
BDCONFIGTIT VARCHAR(5),
BDCLASSIFICACAO VARCHAR(100),
BDDESCRICAO VARCHAR(500),
BDAPECTADV VARCHAR(20),
BDAPECTACV VARCHAR(20),
BDAPECTADO VARCHAR(20),
BDAPECTACO VARCHAR(20),
BDDESCONTADV VARCHAR(100),
BDDESCONTACV VARCHAR(100),
BDDESCONTADO VARCHAR(100),
BDDESCONTACO VARCHAR(100),
BDCODHISTPROV INTEGER,
BDCODHISTPGTO INTEGER,
BDCODTIPOCONTA INTEGER,
BDCODNAT INTEGER,
BDCODVER INTEGER,
BDDESCREDVER VARCHAR(20),
BDAPELIDOTER VARCHAR(20),
BDNOMENAT VARCHAR(335),
BDAPEHISTPROV VARCHAR(20),
BDAPEHISTPGTO VARCHAR(20),
BDCONTADEBPROV INTEGER,
BDCONTACREDPROV INTEGER,
BDCONTADEBPGTO INTEGER,
BDCONTACREDPGTO INTEGER,
BDCHAVE INTEGER,
BDCHAVEVINC INTEGER,
BDCODPLANOONLINE INTEGER,
BDDESCIMP VARCHAR(100),
BDDESCOREC VARCHAR(100),
BDCODOREC INTEGER,
BDCODIMP INTEGER,
BDCODTCA INTEGER,
BDCODGRUPOCLA INTEGER,
BDDESCGRUPOCLA VARCHAR(200),
BDTIPONAT INTEGER,
BDCLASSVER VARCHAR(20),
BDTIPOVER INTEGER,
BDCODITEMONLINE INTEGER,
BDAPECOMHISTPROV VARCHAR(20),
BDAPECOMHISTPGTO VARCHAR(20),
BDCODCOMPHISTPROV INTEGER,
BDCODCOMPHISTPGTO INTEGER,
BDCOMHISTPROV VARCHAR(1000),
BDCOMHISTPGTO VARCHAR(1000),
BDCONFIGPROV VARCHAR(5),
BDCONFIGDEBPROV VARCHAR(5),
BDCONFIGCREDPROV VARCHAR(5),
BDCONFIGPAG VARCHAR(5),
BDCONFIGDEBPAG VARCHAR(5),
BDCONFIGCREDPAG VARCHAR(5),
BDCONFIGHISTPROV VARCHAR(5),
BDCONFIGHISTPAG VARCHAR(5),
BDNAOCONTAB VARCHAR(5),
BDCODREC INTEGER,
BDCONTABILIZA DM_BOOLEAN,
BDATIVA DM_BOOLEAN,
BDCODOBRSER INTEGER,
BDTIPOSER INTEGER,
BDSERDESCONTO DM_BOOLEAN,
BDCHAVECTABAN INTEGER,
BDCODCLI INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WDESCITEM VARCHAR(200);
DECLARE VARIABLE WDESCVERBA VARCHAR(200);
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE WCODCONFDIMESC INTEGER;
DECLARE VARIABLE WCODCONFGIASP INTEGER;
DECLARE VARIABLE WCODCONFGIAMG INTEGER;
DECLARE VARIABLE WCODCONFIPI INTEGER;
DECLARE VARIABLE WCODCONFCIAP INTEGER;
DECLARE VARIABLE WCODCONFDACON INTEGER;
DECLARE VARIABLE WCODDEMDOC INTEGER;
DECLARE VARIABLE WCODCONFIRLP INTEGER;
DECLARE VARIABLE WDESCIPI VARCHAR(80);
DECLARE VARIABLE WDESCCIAP VARCHAR(80);
DECLARE VARIABLE WDESCDACON VARCHAR(80);
DECLARE VARIABLE WDESCIRLP VARCHAR(80);
DECLARE VARIABLE WBDCONFIGPROV VARCHAR(5);
DECLARE VARIABLE WBDCONFIGDEBPROV VARCHAR(5);
DECLARE VARIABLE WBDCONFIGCREDPROV VARCHAR(5);
DECLARE VARIABLE WBDCONFIGPAG VARCHAR(5);
DECLARE VARIABLE WBDCONFIGDEBPAG VARCHAR(5);
DECLARE VARIABLE WBDCONFIGCREDPAG VARCHAR(5);
DECLARE VARIABLE WBDCONFIGHISTPROV VARCHAR(5);
DECLARE VARIABLE WBDCONFIGHISTPAG VARCHAR(5);
DECLARE VARIABLE WDESCDEMDOC VARCHAR(250);
DECLARE VARIABLE WSIS INTEGER;
DECLARE VARIABLE WCODCONFGIAES INTEGER;
DECLARE VARIABLE WCODCONFGIARO INTEGER;
DECLARE VARIABLE WCODCONFGIAPR INTEGER;
DECLARE VARIABLE WCODCONFGIARJ INTEGER;
DECLARE VARIABLE WSTR VARCHAR(200);
DECLARE VARIABLE WOR VARCHAR(4);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WTIPOOPERIMOB INTEGER;
DECLARE VARIABLE WDESCOPERIMOB VARCHAR(80);
DECLARE VARIABLE WDESCSERFIN VARCHAR(100);
DECLARE VARIABLE WDESCCHAVECTABAN VARCHAR(200);
DECLARE VARIABLE WNOMCLI DM_BDNOMEMP;
DECLARE VARIABLE WCODCONFBLOCOM INTEGER;
DECLARE VARIABLE WDESCBLOCOM VARCHAR(80);
DECLARE VARIABLE WCODCONFBLOCOMAUX INTEGER;
DECLARE VARIABLE WDESCBLOCOMAUX VARCHAR(150);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREF,NULL,NULL);
--  suspend;
  wsql = 'select contas.BDCODPLANOONLINE, '||
                'contas.bdcodtipoconta, '||
                'contas.BDCHAVE,'||
                'contas.BDCHAVEVINC,'||
                'contas.bdclassificacao,'||
                'tipoconta.bddescricao, '||
                'tipoconta.bdconfigtit,'||
                'contas.BDFORMULA, '||
                'tipoconta.bdFORMULA, '||
                'PLADV.bdapecta bdapectaDV,'||
                'PLACV.bdapecta bdapectaCV,'||
                'PLADO.bdapecta bdapectaDO,'||
                'PLACO.bdapecta bdapectaCO, '||

                'PLADV.BDNOMCTA bdDESCCONTADV,'||
                'PLACV.BDNOMCTA bdDESCCONTACV,'||
                'PLADO.BDNOMCTA bdDESCCONTADO,'||
                'PLACO.BDNOMCTA bdDESCCONTACO, '||

                'contas.BDCODHISTPROV ,'||
                'contas.BDCODHISTPGTO, '||
                'contas.bdcodnat, '||
                'contas.bdcodver, '||
                'ver.BDDESCREDVER, '||
                'null bdapelidoter, '|| --ter.
                'nat.bdnomenat, '||
                'histp.bdapelido bdapehistprov, '||
                'histo.bdapelido bdapehistpgto, '||
                'contas.bdcontadebprov,'||
                'contas.bdcontacredprov,'||
                'contas.bdcontadebpgto,'||
                'contas.bdcontacredpgto,'||
                'contas.bdcodimp,'||
                'contas.bdcodtca,'||
                'IMP.BDDESCIMP,'||
                'contas.bdcodorec, '||
                'OREC.BDDESCOREC,'||
                'cla.BDCODGRUPOCLA, '||
                'cla.BDDESCRICAO,'||
                'nat.BDTIPONAT, '||
                'ver.BDCLAVER, '||
                'verref.BDTIPOCODVER,'||
                'contas.BDCODITEMONLINE,'||
                'itemconf.BDDESCRICAO,'||
                'ver.BDDESCVER,'||
                'uf.bdsiglauf,'||
                'contas.bdcodconfdimesc,'||
                'contas.bdcodconfSP,'||
                'contas.bdcodconfGIAMG,'||
                'contas.bdcodconfGIAES,'||
                'contas.bdcodconfGIARO,'||
                'contas.bdcodconfipi,'||
                'contas.BDCODCONFCIAP,'||
                'contas.bdcodconfDACON,'||
                'contas.bdcodconfirlp,'||

                'IPI.BDDESCIPI,'||
                'CIAP.BDDESCCIAP,'||
                'DACON.BDDESCDACON,'||
                'IRLP.BDDESCIRLP,'||
                'CHISTP.BDAPELIDO BDAPECOMHISTPROV,'||
                'CHISTO.BDAPELIDO BDAPECOMHISTPGTO,'||
                'CONTAS.BDCODCOMPHISTPROV,'||
                'CONTAS.BDCODCOMPHISTPGTO,'||
                'CHISTP.BDCOMPLEMENTO BDCOMHISTPROV,'||
                'CHISTO.BDCOMPLEMENTO BDCOMHISTPGTO,'||

                'tipoconta.BDCONFIGPROV,'||
                'tipoconta.BDCONFIGDEBPROV  ,'||
                'tipoconta.BDCONFIGCREDPROV,'||
                'tipoconta.BDCONFIGPAG,'||
                'tipoconta.BDCONFIGDEBPAG,'||
                'tipoconta.BDCONFIGCREDPAG,'||

                'itemconf.BDCONFIGPROV,'||
                'itemconf.BDCONFIGDEBPROV  ,'||
                'itemconf.BDCONFIGCREDPROV,'||
                'itemconf.BDCONFIGPAG,'||
                'itemconf.BDCONFIGDEBPAG,'||
                'itemconf.BDCONFIGCREDPAG,'||

                'tipoconta.BDCONFIGHISTPROV,'||
                'tipoconta.BDCONFIGHISTPAG,'||
                'itemconf.BDCONFIGHISTPROV,'||
                'itemconf.BDCONFIGHISTPAG,'||
                'DEMDOC.BDCODTIPODOC ,'||
                'contas.BDNAOCONTAB,'||
                'DEMDOC.BDDESCRICAO BDDESCDEMDOC,imp.bdcodsis, '||
                'contas.BDCODREC, '||
                'contas.BDCODCONFGIAPR, '||
                'contas.BDCODCONFGIARJ, '||
                'COALESCE(nat.BDCONTABILIZA, IIF(demdoc.BDNAOCONTABILIZA = ''TRUE'',''FALSE'',NULL) ) as BDCONTABILIZA, '|| -- Alt.: 13623 - Caso o tipo do documento n?o contabilize, deve bloquear a altera??o das contas, caso contr?rio retorno "null" para caso venha outra configura??o, ? s? inserir no Coalesce...
                'F200.bdtipooperimob, '||
                'F200.bddescricao, '||
                'contas.BDATIVA, '|| --alt:13055 - 04/04/2016 - Adicionado campo. Pedro
                'contas.bdCODOBRSER, '||
                'ser.BDDESCRICAO, '||
                'ser.BDTIPO, '||
                'ser.BDDESCONTO, '|| --Adilson Hasckel - sol. 14282
                'ctaban.BDCHAVECTABAN, '||
                'ctaban.BDDESCCTABAN, '|| --Adilson Hasckel - sol. 14543
                'cli.BDCODCLI, '||
                'cli.BDNOMCLI, '||
                'contas.BDCODCONFBLOCOM, BlocoM.BDDESCCONF as BDDESCBLOCOM, '|| -- Alt.: 22861 - Configura??o do Bloco M
                'CAST(CASE '|| -- Alt.: 23804 - Contas detalhes da contabiliza??o do Bloco M
                '       WHEN (contas.BDFORMULA like ''BLOCOMCREDDESC%(%)'') then SUBSTRING(contas.bdCLASSIFICACAO from CHAR_LENGTH(contas.bdCLASSIFICACAO)-7 for 8) '||
                '       WHEN (contas.BDFORMULA like ''BLOCOMDEBITO%(%)'') then SUBSTRING(contas.bdCLASSIFICACAO from CHAR_LENGTH(contas.bdCLASSIFICACAO)-7 for 8) '||
                '     ELSE NULL '||
                '     END as INTEGER) as BDCODCONFBLOCOMAUX, '||
                'CASE '|| -- Alt.: 23804 - Contas detalhes da contabiliza??o do Bloco M
                '  WHEN (contas.BDFORMULA LIKE ''BLOCOMCREDDESC%(%)'') THEN t437.bdDESCRICAO '||
                '  WHEN (contas.BDFORMULA LIKE ''BLOCOMDEBITO%(%)'') THEN t435.bdDESCRICAO '||
                'ELSE NULL END as BDDESCBLOCOMAUX ';

--  if ((prplano is not null) and (prplano <> 0))  then
--      wsql = wsql || ' from (select * from TCONF_CONTAS_ONLINE where bdcodplanoonline = '||prPlano||') contas ';
--  else
      wsql = wsql || ' from TCONF_CONTAS_ONLINE contas ';
  wsql = wsql || ' left outer join ttipocontaonline tipoconta on (contas.bdcodtipoconta = tipoconta.bdcodtipoconta)';
  wsql = wsql || ' left outer join planos_tpla PLADV on (PLADV.bdcodplapadrao = contas.bdcodplapadrao AND PLADV.bdcodtpla = CONTAS.bdcontadebprov) ';
  wsql = wsql || ' left outer join planos_tpla PLACV on (PLACV.bdcodplapadrao = contas.bdcodplapadrao AND PLACV.bdcodtpla = CONTAS.bdcontacredprov) ';
  wsql = wsql || ' left outer join planos_tpla PLADO on (PLADO.bdcodplapadrao = contas.bdcodplapadrao AND PLADO.bdcodtpla = CONTAS.bdcontadebpgto) ';
  wsql = wsql || ' left outer join planos_tpla PLACO on (PLACO.bdcodplapadrao = contas.bdcodplapadrao AND PLACO.bdcodtpla = CONTAS.bdcontacredpgto) ';
  wsql = wsql || ' left outer join hist_tphi histP on (histP.bdcodhist = contas.bdcodtphi and histP.bdcodtphi = contas.bdcodhistprov) ';
  wsql = wsql || ' left outer join hist_tphi histO on (histO.bdcodhist = contas.bdcodtphi and histO.bdcodtphi = contas.bdcodhistpgto) ';

  wsql = wsql || ' left outer join TCOMPLEMENTO_HIST ChistP on (ChistP.bdcodcomphist = contas.BDCODCOMPHISTPROV ) ';
  wsql = wsql || ' left outer join TCOMPLEMENTO_HIST ChistO on (ChistO.bdcodcomphist = contas.BDCODCOMPHISTPGTO ) ';

--  wsql = wsql || ' left outer join TIMPOSTO IMP on (IMP.bdcodimp = contas.bdCODIMP and IMP.bdcodsis = 3) ';
  wsql = wsql || ' left outer join TIMPOSTO IMP on (IMP.bdcodimp = contas.bdCODIMP and IMP.bdcodsis in (3,7)) ';--gilberto - 11/05/2014 - ALT#:1044

  wsql = wsql || ' left outer join Tuf uf on (uf.bdcoduf = contas.bdCODuf) ';
  wsql = wsql || ' left outer join tgrupoclassecol cla on (contas.BDCODGRUPOCLA = cla.BDCODGRUPOCLA)';
--  wsql = wsql || ' left outer join vw_tterceiro ter on (contas.bdcodter = ter.bdcodter and contas.bdcodtipter = ter.bdcodtipter)';
  wsql = wsql || ' left outer join vrh_base_tverbas ver on (contas.bdcodver = ver.bdcodver)';
  wsql = wsql || ' left outer join VW_VERBAS_REF_ATUAL verref on (contas.bdcodver = verref.bdcodver)';
  wsql = wsql || ' left outer join vef_base_tnatop nat on (contas.bdcodnat = nat.bdcodnat)';
  wsql = wsql || ' left outer join vef_base_tcadorec OREC on (OREC.bdcodorec = contas.bdcodorec) ';
  wsql = wsql || ' left outer join TITEMCONFIGONLINE itemconf on (itemconf.bdcoditemonline = contas.bdcoditemonline) ';
/* APURACAO DE IMPOSTOS*/
  wsql = wsql || ' left outer join vef_base_tconfipi IPI on (contas.bdcodconfipi = IPI.bdcodconfipi)';
  wsql = wsql || ' left outer join VEF_BASE_TCONFCIAP CIAP on (CIAP.BDCODCONFCIAP = contas.BDCODCONFCIAP)';
  wsql = wsql || ' left outer join vef_base_tconfDACON DACON on (contas.bdcodconfDACON = DACON.bdcodconfDACON)';
  wsql = wsql || ' left outer join vef_base_tconfirlp IRLP on (contas.bdcodconfIRLP = IRLP.bdcodconfirlp)';

/* DEMAIS DOCUMENTOS*/
  --wsql = wsql || ' left outer join VEF_BASE_TAB_BC_CRED DEMDOC on (contas.BDNAT_BC_CRED = DEMDOC.BDNAT_BC_CRED)';
  --alterado para utilizar a tabela de tipo de documento
  wsql = wsql || ' left outer join vef_base_tcadtipodemdoc DEMDOC on (contas.BDCODTIPODOC = DEMDOC.bdcodtipodoc)';
  
  /*Opera??es imobili?rias*/
  wsql = wsql || ' left outer join vef_base_ttabtipoopf200 f200 on(contas.bdtipooperimob = f200.bdtipooperimob)';

  /*servi?os do financeiro*/
  wsql = wsql || ' left outer join VCT_BASE_SERVICO ser on (contas.bdCODOBRSER = ser.bdCODOBRSER) ';

  /*contas banc?rias do financeiro*/
  wsql = wsql || ' left outer join VFIN_ESC_TCONTASBAN ctaban on (contas.bdCHAVECTABAN = ctaban.bdCHAVECTABAN) ';

  /*cliente do financeiro*/
  wSql = wSql || ' left outer join VW_VFIN_CLIENTES_REF cli on (contas.bdcodcli = cli.bdcodcli) ';
  /* Bloco M */
  wSql = wSql || ' left outer join VEF_BASE_TCONFBLOCOM BlocoM on (BlocoM.BDCODCONF = contas.BDCODCONFBLOCOM) '; -- Alt.: 22861
  -- Alt.: 23804 - Contas detalhes da contabiliza??o do Bloco M
  wSql = wSql || ' left outer join VEF_BASE_TNATBCPISCOFINS t437 on (t437.bdREGEXP = CAST(IIF((contas.BDFORMULA like ''BLOCOMCREDDESC%(%)''), SUBSTRING(contas.bdCLASSIFICACAO from CHAR_LENGTH(contas.bdCLASSIFICACAO)-7 for 8), ''0'') as INTEGER)) ';
  wSql = wSql || ' left outer join VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.bdCODCSOCIALEXP = CAST(IIF((contas.BDFORMULA like ''BLOCOMDEBITO%(%)''), SUBSTRING(contas.bdCLASSIFICACAO from CHAR_LENGTH(contas.bdCLASSIFICACAO)-7 for 8), ''0'') as INTEGER)) ';

--  wsql = wsql || ' left outer join centros_tpcc tpcc on (tpcc.bdcodcentro = contas.bdcodcentro and tpcc.bdcodtpcc = contas.bdcodtpcc) ';

  wwhere = ' where ';
  IF (prPlano IS NOT NULL) THEN
     BEGIN
       wsql = wsql||wwhere||'contas.bdcodplanoonline = '||prPlano;
       wwhere = ' and ';
     END

  IF ((prclassificacao <> '') AND (prclassificacao IS NOT NULL)) THEN
     BEGIN
       wsql = wsql||wwhere||'char_length(contas.bdclassificacao) >= '||CHAR_LENGTH(prclassificacao);

       IF (prApenasNivel = 2) THEN
          wsql = wsql||' and contas.bdclassificacao = '||''''||prclassificacao||'''';
       ELSE
          wsql = wsql||' and substring(contas.bdclassificacao from 1 for '||CHAR_LENGTH(prclassificacao)||') = '||''''||prclassificacao||'''';

       --IF (prCLASSIFICACAO <>  '03.002.000000010') THEN -- Alt.: 23804 - Contas detalhes da contabiliza??o do Bloco M, n?o vai trazer todas as analiticas.
       --  wsql = wsql||' and contas.BDFORMULA not like ''%.%'' ';

       wwhere = ' and ';
     END

  IF (prApenasNivel IS NULL) THEN
     prApenasNivel = 1;

  IF ((prlength > 0) AND (prlength IS NOT NULL)) THEN
     BEGIN
       IF (prApenasNivel = 0) THEN
          wsql = wsql||wwhere||' char_length(contas.bdclassificacao) = '||prlength;
       ELSE
          wsql = wsql||wwhere||' char_length(contas.bdclassificacao) >= '||prlength;
       wwhere = ' and ';
     END

  IF ((prchave <> 0) AND (prchave IS NOT NULL)) THEN
     BEGIN
       IF (prapenasnivel = 3) THEN
         wsql = wsql||wwhere||' ((contas.bdchavevinc = '||prchave||') or (contas.bdchave = '||prchave||'))';
       ELSE
         wsql = wsql||wwhere||' contas.bdchavevinc = '||prchave;
       wwhere = ' and ';
     END
  ELSE
    IF ((prchave <> 0) OR (prchave IS NULL))  THEN
      BEGIN
       wsql = wsql||wwhere||' contas.bdchavevinc is null ';
        wwhere = ' and ';
      END

  --Alt.:5789, N?o levar mais as classifica??es de "outras receitas".
  wsql = wsql||wwhere||' (NOT UPPER(CONTAS.BDCLASSIFICACAO) STARTING WITH UPPER(''03.001.000000004'')) ';

  --Alt.:6461. Quando for configura??o do plano de troca de/para busco apenas os itens necess?rios, ou seja,
  --os que foram passado por par?metro
  IF ((prfilterclassificacao IS NOT NULL) AND (prfilterclassificacao <> ''))  THEN
    BEGIN
      wor  = '';
      wsql = wsql||' and (';
      WHILE (TRIM(prfilterclassificacao) <> '') DO
        BEGIN
          wpos = POSITION(',', prfilterclassificacao);
          IF (wpos > 0) THEN
            BEGIN
              wstr = SUBSTRING(prfilterclassificacao FROM 1 FOR wpos-1);
              prfilterclassificacao = SUBSTRING(prfilterclassificacao FROM wpos+1 FOR CHAR_LENGTH(prfilterclassificacao));
            END
          ELSE
            BEGIN
              wstr                  = prfilterclassificacao;
              prfilterclassificacao = '';
            END

          IF (POSITION('#', wstr) > 0) THEN
            BEGIN
              wstr = SUBSTRING(wstr FROM 2 FOR CHAR_LENGTH(wstr));
              wsql = wsql||wor||' (Upper(contas.bdclassificacao) = Upper('''||wstr||'''))';
            END
          ELSE
            wsql = wsql||wor||' (Upper(contas.bdclassificacao) starting with Upper('''||wstr||'''))';

          wor  = ' or ';
        END
      wsql = wsql||') ';
    END

  IF ((prfiltrertreeview <> '') AND (prfiltrertreeview IS NOT NULL)) THEN
     BEGIN
       wsql = wsql||' and ('''||prfiltrertreeview||''' starting with contas.bdclassificacao) ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    bdcodplanoonline,
    bdcodtipoconta,
    bdchave,
    bdchavevinc,
    bdclassificacao,
    bddescricao,
    bdconfigtit,
    bdformula,
    BDFORMULAITEM,
    bdapectadv,
    bdapectacv,
    bdapectado,
    bdapectaco,

    BDDESCONTAdv,
    BDDESCONTAcv,
    BDDESCONTAdo,
    BDDESCONTAco,

    bdcodhistprov,
    bdcodhistpgto,
    bdcodnat,
    bdcodver,
    bddescredver,
    bdapelidoter,
    bdnomenat,
    bdapehistprov,
    bdapehistpgto,
    bdcontadebprov,
    bdcontacredprov,
    bdcontadebpgto,
    bdcontacredpgto,
    bdcodimp,
    bdcodtca,
    bddescimp,
    bdcodorec,
    bddescorec,
    bdcodgrupocla,
    bddescgrupocla,
    bdtiponat,
    bdclassver,
    bdtipover,
    bdcoditemonline,
    wdescitem,
    wdescverba,
    wsiglauf,
    wcodconfdimesc,
    wcodconfGIASP,
    wcodconfGIAMG,
    wcodconfGIAES,
    wcodconfGIARO,
    wcodconfipi,
    wCODCONFCIAP,
    wcodconfDACON,
    wcodconfirlp,
    WDESCIPI,
    WDESCCIAP,
    WDESCDACON,
    WDESCIRLP,
    BDAPECOMHISTPROV,
    BDAPECOMHISTPGTO,
    BDCODCOMPHISTPROV,
    BDCODCOMPHISTPGTO,
    BDCOMHISTPROV,
    BDCOMHISTPGTO,

    BDCONFIGPROV,
    BDCONFIGDEBPROV,
    BDCONFIGCREDPROV,
    BDCONFIGPAG,
    BDCONFIGDEBPAG,
    BDCONFIGCREDPAG,

    WBDCONFIGPROV,
    WBDCONFIGDEBPROV,
    WBDCONFIGCREDPROV,
    WBDCONFIGPAG,
    WBDCONFIGDEBPAG,
    WBDCONFIGCREDPAG,

    BDCONFIGHISTPROV,
    BDCONFIGHISTPAG,
    WBDCONFIGHISTPROV,
    WBDCONFIGHISTPAG,
    WCODDEMDOC,
    BDNAOCONTAB,
    WDESCDEMDOC,
    wsis,
    bdcodrec,
    wcodconfgiapr,
    wCODCONFGIARJ,
    BDCONTABILIZA,
    wtipooperimob,
    wdescoperimob,
    BDATIVA,
    bdcodobrser,
    wdescserfin,
    bdtiposer,
    bdserdesconto,
    bdchavectaban,
    wDescChaveCtaBan,
    bdcodcli, 
    wNomcli,
    WCODCONFBLOCOM,
    WDESCBLOCOM,
    wCODCONFBLOCOMAUX,
    wDESCBLOCOMAUX
    DO
   BEGIN
     IF ((bdcodnat IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        BEGIN
          bddescricao = SUBSTRING(bdcodnat FROM 1 FOR 1)||'.'||SUBSTRING(bdcodnat FROM 2 FOR 3)||'-'||SUBSTRING(bdcodnat FROM 5 FOR 3)||' - '||bdnomenat;
        END

     IF ((WCODDEMDOC IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = WCODDEMDOC ||'-'|| WDESCDEMDOC;

     IF ((wcodconfipi IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = wcodconfipi ||'-'|| wdescipi;

     IF ((wCODCONFCIAP IS NOT NULL) AND (BDCODITEMONLINE IS NULL)) THEN
        bdDESCRICAO = wCODCONFCIAP ||'-'|| wDESCCIAP;

     IF ((wcodconfDACON IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = wcodconfDACON ||'-'|| wdescDACON;

     IF ((wcodconfirlp IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = wcodconfirlp ||'-'|| wdescirlp;

     IF ((wtipooperimob IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = wtipooperimob ||'-'|| wdescoperimob;  

     IF ((wCodConfBlocoM IS NOT NULL) AND (bdCodItemOnline IS NULL)) THEN
        bdDESCRICAO = wCodConfBlocoM ||'-'|| WDESCBLOCOM;

     IF (wsiglauf IS NOT NULL) THEN
        bddescricao = wsiglauf;

     IF ((wcodconfdimesc IS NOT NULL) OR (wcodconfgiasp IS NOT NULL) OR (wcodconfgiamg IS NOT NULL) OR (wcodconfgiaes IS NOT NULL)
        OR (wcodconfgiaro IS NOT NULL) OR (wcodconfgiapr IS NOT NULL) OR (wCODCONFGIARJ IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        BEGIN
          IF (wsiglauf = 'ES') THEN
             BEGIN
               SELECT conf.bddescconf FROM vef_estados_tconfgiaes conf WHERE conf.bdcodconf = :wcodconfgiaes INTO bddescricao;
               bddescricao = wcodconfgiaes ||'-'|| bddescricao;
             END
          ELSE
          IF (wsiglauf = 'SC') THEN
            BEGIN
              SELECT conf.bddescconf FROM VEF_ESTADOS_TCONFDIMESC conf WHERE conf.bdcodconfdimesc = :wcodconfdimesc INTO bddescricao;
              bddescricao = wcodconfdimesc ||'-'|| bddescricao;
            END
          ELSE
          IF (wsiglauf = 'SP') THEN
            BEGIN
              SELECT conf.bddescconf FROM vef_estados_tconfgiasp conf WHERE conf.bdcodconf = :wcodconfgiasp INTO bddescricao;
              bddescricao = wcodconfgiasp ||'-'|| bddescricao;
            END
          ELSE
          IF (wsiglauf = 'MG') THEN
            BEGIN
              SELECT conf.bddescconf FROM vef_estados_tconfgiamg conf WHERE conf.bdcodconf = :wcodconfgiamg INTO bddescricao;
              bddescricao = wcodconfgiamg ||'-'|| bddescricao;
            END
          ELSE
          IF (wsiglauf = 'RO') THEN
             BEGIN
               SELECT conf.bddescconf FROM vef_estados_tconfgiaro conf WHERE conf.bdcodconf = :wcodconfgiaro INTO bddescricao;
               bddescricao = wcodconfgiaro ||'-'|| bddescricao;
             END
          ELSE
          IF (wsiglauf = 'PR') THEN
             BEGIN
               SELECT confpr.bddescconf FROM vef_estados_tconfgiapr confpr WHERE confpr.bdcodconf = :wcodconfgiapr INTO bddescricao;
               bddescricao = wcodconfgiapr ||'-'|| bddescricao;
             END
          ELSE
          IF (wSiglaUF = 'RJ') THEN
             BEGIN
               SELECT confrj.BDDESCCONF FROM VEF_ESTADOS_TCONFGIARJ confrj WHERE confrj.BDCODCONF = :wCODCONFGIARJ INTO BDDESCRICAO;
               BDDESCRICAO = wCODCONFGIARJ ||'-'|| BDDESCRICAO;
             END
        END

     IF (bdapelidoter IS NOT NULL) THEN
        bddescricao = bdapelidoter;

     IF (bddescorec IS NOT NULL) THEN
        bddescricao = bddescorec;

     IF (bddescimp IS NOT NULL) THEN
        bddescricao = bdcodimp ||' - '|| bddescimp;

     IF (wdescitem IS NOT NULL) THEN
        bddescricao = wdescitem;

     IF (bddescgrupocla IS NOT NULL) THEN
        bddescricao = bddescgrupocla;
     ELSE
     IF (bdcodtca IS NOT NULL) THEN
        BEGIN
          SELECT X.BDDESCTCA FROM vrh_base_ttipocalcavul X WHERE x.bdcodtca = :bdcodtca INTO :bddescricao;
        END

     IF ((bdcodrec IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        BEGIN
           SELECT X.bddescrec FROM tcodrec X WHERE x.bdcodrec = :bdcodrec INTO :bddescricao;

           bddescricao = bdcodrec||' - '||bddescricao;
        END

     IF (wdescverba IS NOT NULL) THEN
--        bddescricao = bdclassver||' - '||wdescverba;
        bddescricao = bdcodver||' - '||wdescverba;

     IF (wdescserfin IS NOT NULL) THEN
        bddescricao =  bdcodobrser||' - '||wdescserfin;

     IF (wdescchavectaban IS NOT NULL) THEN
        bddescricao = bdchavectaban||' - '||wdescchavectaban;

     IF (wnomcli IS NOT NULL) THEN
        bddescricao = bdcodcli||' - '||wnomcli;

     IF ((wCODCONFBLOCOMAUX IS NOT NULL) AND (wDESCBLOCOMAUX IS NOT NULL)) THEN
        bdDESCRICAO = LPAD(wCODCONFBLOCOMAUX, 2, '0') ||'-'|| wDESCBLOCOMAUX;

     IF (bdcoditemonline IS NOT NULL) THEN
        BEGIN
          BDCONFIGPROV = WBDCONFIGPROV;
          BDCONFIGDEBPROV  = WBDCONFIGDEBPROV;
          BDCONFIGCREDPROV = WBDCONFIGCREDPROV;
          BDCONFIGPAG = WBDCONFIGPAG;
          BDCONFIGDEBPAG = WBDCONFIGDEBPAG;
          BDCONFIGCREDPAG = WBDCONFIGCREDPAG;
          BDCONFIGHISTPROV = WBDCONFIGHISTPROV;
          BDCONFIGHISTPAG = WBDCONFIGHISTPAG;
        END

    IF (BDCODOBRSER > 0 AND BDSERDESCONTO = UPPER('TRUE')) THEN
        BEGIN
          BDCONFIGDEBPROV  = 'TRUE';
          BDCONFIGCREDPROV = 'FALSE';
          BDCONFIGDEBPAG   = 'TRUE';
        END

--     if ((bdcodimp is null) or (wsis = 3) and (bdcodimp is not null)) then
     IF ((bdcodimp IS NULL) OR (wsis IN (3,7)) AND (bdcodimp IS NOT NULL)) THEN --gilberto - 11/05/2014 - ALT#:1044
     SUSPEND;
   END
END
^

/* Alter (SP_TREEVIEW_CONS_GIA_FORMULA) */
ALTER PROCEDURE SP_TREEVIEW_CONS_GIA_FORMULA(PRPLANO INTEGER,
PRCLASSQUADRO VARCHAR(10),
PRGRUPO INTEGER,
PRUF VARCHAR(2))
 RETURNS(BDCODPLANO INTEGER,
BDDESCPLANO VARCHAR(100),
BDNUMITEM VARCHAR(5),
BDDESCFORM VARCHAR(100),
BDFORMULA VARCHAR(10000),
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(100),
BDCLASSIFICACAO VARCHAR(11),
BDCODITEMONLINE INTEGER,
BDDESCRICAO VARCHAR(300))
 AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WCAMPOCODCONF VARCHAR(10);
DECLARE VARIABLE WCAMPOQUADRO VARCHAR(10);
DECLARE VARIABLE WCAMPOTABELA VARCHAR(10);
DECLARE VARIABLE WCAMPOTABELAFOR VARCHAR(10);
DECLARE VARIABLE WCAMPODESCFORM VARCHAR(10);
DECLARE VARIABLE WCODQ INTEGER;
DECLARE VARIABLE WITEM VARCHAR(5); --integer
DECLARE VARIABLE WDESC VARCHAR(100);
DECLARE VARIABLE WCLAS VARCHAR(11);
DECLARE VARIABLE WFORM VARCHAR(10000);
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WDESCQT VARCHAR(100);
DECLARE VARIABLE WCLASQT VARCHAR(10);
DECLARE VARIABLE WCLASQTANT VARCHAR(10);
DECLARE VARIABLE WCODITEMONLINE INTEGER;
DECLARE VARIABLE WDESCRICAOITEM VARCHAR(300);
BEGIN
  IF (prUf = 'SC') THEN
    BEGIN
      wcampocodconf = 'DIMESC';
      wcampoquadro  = 'QDIME';
      wcampotabela  = 'dimesc';
      wcampotabelafor = 'DIME';
      wcampodescform = 'DIME';
    END
  ELSE
    BEGIN
      wcampocodconf = '';
      wcampoquadro  = 'QUADRO';
      wcampotabela  = 'GIA'||pruf;
      wcampotabelafor = 'GIA'||pruf;
      wcampodescform = '';
    END

  IF (prgrupo = 1) THEN
     BEGIN
       wSql = 'select conf.bdcodconf'||:wcampocodconf||' BDCODPLANO, ';
       wSql = wSql || 'conf.bddescconf BDDESCPLANO ';
     END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
       wSql = 'select qd.bdclassificacao, ';
       wSql = wSql || ' QD.BDDESC'||wcampoquadro||' BDDESCQUADRO ';
     END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wSql = 'select conff.BDNUMITEM, conff.BDDESCFORM'||wcampodescform||' BDDESCFORM, conff.BDFORMULA'||wcampodescform||' BDFORMULA, ';
       wSql = wSql || ' QD.BDDESC'||wcampoquadro||' BDDESCQUADRO ,CONFF.BDCOD'||wcampoquadro||' BDCODQUADRO ,QD.BDCLASSIFICACAO, conff.BDCODITEMONLINE, i.bddescricao ';
     END

  wwhere = '';

  IF (prgrupo = 2) THEN
    BEGIN
--      wsql = wsql || ' qd.bddesc'||wcampoquadro||',qd.bdclassificacao from VEF_ESTADOS_TCONF'||wcampotabelafor||'Q qd where bdclassificacao = substring('||:bdclassificacao||' from 1 for '||waux||')';
      wsql = wsql || ' from VEF_ESTADOS_TCONF'||wcampotabelafor||'Q qd  ';
    END
  ELSE
    BEGIN
      wsql = wsql || ' from VEF_ESTADOS_TCONF'||wcampotabelafor||'FORM conff ';
      wsql = wsql || ' left outer join  vef_estados_tconf'||wcampotabela||' conf on( conf.bdcodconf'||:wcampocodconf||' = conff.bdcodconf'||:wcampocodconf|| ')';
      wsql = wsql || ' left outer join VEF_ESTADOS_TCONF'||wcampotabelafor||'Q QD on(conff.bdcod'||wcampoquadro||' = qd.bdcod'||wcampoquadro||')';

      wsql = wsql || ' left outer join titemconfigonline i on(i.bdcoditemonline = conff.bdcoditemonline)';



      IF (prPlano IS NOT NULL) THEN
         wwhere = wWhere||' conff.bdcodconf'||:wcampocodconf||' = '||prPlano||' ';
    
      IF ((PRCLASSQUADRO IS NOT NULL) AND (PRCLASSQUADRO <> '')) THEN
         BEGIN
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
            waux = CHARACTER_LENGTH(TRIM(prclassquadro));
            IF (prUf = 'MG') THEN
               BEGIN
                  waux = waux + 1;
                  wWhere = wwhere||' substring(QD.BDCLASSIFICACAO from 1 for '||waux||') = '''||PRCLASSQUADRO||'.'' ';--Caso quadro fosse VI, retornava VII e tamb?m VIII
                  waux = waux - 1;
               END
            ELSE
               wWhere = wwhere||' substring(QD.BDCLASSIFICACAO from 1 for '||waux||') = '||PRCLASSQUADRO||' ';
         END
    
    
      IF (wwhere <> '') THEN
          wwhere = 'where '||wwhere||' ';
    
    END
  IF (prgrupo = 1) THEN
     BEGIN
       wgroupby = ' group by conf.bdcodconf'||:wcampocodconf||', conf.bddescconf ';
       worderby = ' order by conf.bdcodconf'||:wcampocodconf||' ';
      END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
       wgroupby = '';
       worderby = ' order by qd.bdclassificacao ';
--       wgroupby = ' group by CONFF.BDCOD'||wcampoquadro||' , QD.BDDESC'||wcampoquadro||'  ';
--       worderby = ' order by CONFF.BDCOD'||wcampoquadro||' ';
      END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wgroupby = '';
--       worderby = ' order by  conff.BDCOD'||wcampoquadro||', conff.BDNUMITEM ';
       worderby = ' order by qd.bdclassificacao, conff.BDNUMITEM '; 
      END

  wsql = wsql||wwhere||wgroupby||worderby;

  IF (prgrupo = 1) THEN
     BEGIN
        FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODPLANO,
            :BDDESCPLANO
          DO
          SUSPEND;
    END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
        FOR EXECUTE STATEMENT wsql
          INTO
            :bdclassificacao,
            :BDDESCQUADRO
          DO
          BEGIN
            SELECT FIRST 1 tpos.pos FROM pos('.',:bdclassificacao) tpos INTO :waux;
            IF (waux = 0) THEN
              BEGIN
                SUSPEND;
              END
          END
    END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wCodQ = 0;
       wclasqtANT = '';
        FOR EXECUTE STATEMENT wsql
          INTO
            :BDNUMITEM,
            :BDDESCFORM,
            :BDFORMULA,
            :BDDESCQUADRO,
            :BDCODQUADRO,
            :bdclassificacao,
            :BDCODITEMONLINE,
            :BDDESCRICAO
          DO
          BEGIN
            wItem = BDNUMITEM;
            wDesc = BDDESCFORM;
            wForm = BDFORMULA;
            wclas = bdclassificacao;

            IF (wCodQ <> BDCODQUADRO) THEN
              BEGIN
                SELECT FIRST 1 tpos.pos FROM pos('.',:bdclassificacao) tpos INTO :waux;
                IF (waux > 0) THEN
                  BEGIN
                    WAUX = WAUX -1;
--                    wdescqt = '';
                    wsql = 'select qd.bddesc'||wcampoquadro||',qd.bdclassificacao from VEF_ESTADOS_TCONF'||wcampotabelafor||'Q qd where bdclassificacao = substring('||''''||:bdclassificacao||''''||' from 1 for '||waux||')';
                    EXECUTE STATEMENT wsql INTO :wdescqt,wclasqt;
                    IF (wclasqtANT <> wclasqt) THEN
                      BEGIN
                        wclasqtANT = wclasqt;
                        bddescform = wclasqt || ' - ' || wdescqt;
                        bdnumitem = NULL;
                        bdformula = NULL;
                        WCODITEMONLINE = BDCODITEMONLINE;
                        WDESCRICAOITEM = BDDESCRICAO;

                        BDCODITEMONLINE = NULL;
                        BDDESCRICAO = NULL;
                        bdclassificacao = wclasqt;
                        SUSPEND;
                        BDCODITEMONLINE = WCODITEMONLINE;
                        BDDESCRICAO = WDESCRICAOITEM;
                      END
                  END

                bdclassificacao = wclas;
                wcodq = BDCODQUADRO;
                bddescform = bdclassificacao || ' - ' || BDDESCQUADRO;
                bdnumitem = NULL;
                bdformula = NULL;
                WCODITEMONLINE = BDCODITEMONLINE;
                WDESCRICAOITEM = BDDESCRICAO;
                BDCODITEMONLINE = NULL;
                BDDESCRICAO = NULL;
                SUSPEND;
                BDCODITEMONLINE = WCODITEMONLINE;
                BDDESCRICAO = WDESCRICAOITEM;
              END

            BDNUMITEM  = wItem;
            BDDESCFORM = wDesc;
            BDFORMULA  = wForm;
--            bdclassificacao = wclas;

            SUSPEND;
          END
    END

END
^

/* Alter (SP_TREEVIEW_CONS_IMP_EMITIDOS) */
ALTER PROCEDURE SP_TREEVIEW_CONS_IMP_EMITIDOS(PRONLINE VARCHAR(10000),
PRCODEMP VARCHAR(10000),
PRCODIMP VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO INTEGER,
PRDTVCTOINI DATE,
PRDTVCTOFIM DATE,
PRPERIODO INTEGER,
PRFILTRO INTEGER)
 RETURNS(BDVLRPGTO DM_NUMERIC_15_2,
BDCODMATRIZ INTEGER,
BDTIPOLANC INTEGER,
BDNRDOCPGTO VARCHAR(18),
BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(200),
BDCODPERIODO INTEGER,
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDQUOTA INTEGER,
BDCODTPCC INTEGER,
BDDATAVCTO DATE,
BDVALOR NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDJUROS NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDOBS BLOB SUB_TYPE 1,
BDORDEMCOMPL INTEGER,
BDBASEIMP NUMERIC(15,6),
BDALIQIMP NUMERIC(15,6),
BDVLRIMPORIGINAL NUMERIC(15,6),
BDVLRMULTAJUROS NUMERIC(15,6),
BDVLROUTENTIDADE NUMERIC(15,6),
BDDTPGTO DATE,
BDLIMITEISENCAO NUMERIC(15,6),
BDDOCARRECADACAO INTEGER,
BDFORMREL VARCHAR(1000),
BDCODREC INTEGER,
BDVLRRETENCAO NUMERIC(15,2),
BDDESCTIPOCALC VARCHAR(25),
BDFLAG VARCHAR(5),
BDVLRACUMULO NUMERIC(15,6))
 AS
declare variable WGROUPBY varchar(10000);
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(10000);
declare variable WORDERBY varchar(5000);
declare variable WEXISTS varchar(1000);
declare variable WTIPOIMPDOC integer;
declare variable WCODDOCARREC integer;
declare variable WTIPOIMPOSTO integer;
declare variable WTIPOCALC integer;
declare variable WVLRPGTO numeric(15,6);
declare variable WTOTAL numeric(15,6);
declare variable WVALOR numeric(15,6);
declare variable WVLRMULTAJUROS numeric(15,6);
begin
  execute procedure SP_SETA_COMPETENCIA(PRREFATUAL, null, null);

  /*agrupar por empresa*/
  if (PRGRUPO = 1) then
  begin
    WSQL = 'select DARF.BDCODEMP, ';
    WSQL = WSQL || 'emp.BDNOMEMP ';
  end
  else


  /*agrupar por REFERÊNCIA*/
  if (PRGRUPO = 2) then
  begin
    WSQL = 'select DARF.BDREFERENCIA ';
  end
  else


  /*agrupar por IMPOSTO*/
  if (PRGRUPO = 3) then
  begin
    WSQL = 'select DARF.BDCODIMP,IMP.BDDESCIMP ';
  end
  else
  begin
    WSQL = 'select DARF.BDCODEMP, ';
    WSQL = WSQL || 'EMP.BDNOMEMP, ';
    WSQL = WSQL || 'EMP.BDCNPJEMP, ';
    WSQL = WSQL || 'DARF.BDCODIMP, ';
    WSQL = WSQL || 'DARF.BDCODTPCC, ';
    WSQL = WSQL || 'IMP.BDDESCIMP, ';
    WSQL = WSQL || 'DARF.BDCODPERIODO, ';
    WSQL = WSQL || 'DARF.BDREFERENCIA, ';
    WSQL = WSQL || 'DARF.BDQUOTA, ';
    WSQL = WSQL || 'DARF.BDDATAVCTO , ';
    --        wSql = wSql || 'PGTO.bddatapgto , ';
    WSQL = WSQL || 'DARF.BDBASEIMP , ';
    WSQL = WSQL || 'DARF.BDALIQIMP , ';
    WSQL = WSQL || 'DARF.BDVLRIMPORIGINAL , ';
    WSQL = WSQL || 'DARF.BDVALOR , ';
    WSQL = WSQL || 'DARF.BDMULTA , ';
    WSQL = WSQL || 'DARF.BDJUROS , ';
    WSQL = WSQL || 'DARF.BDTOTAL , ';
    WSQL = WSQL || 'DARF.BDOBS , ';
    WSQL = WSQL || 'DARF.BDORDEMCOMPL , ';
    WSQL = WSQL || 'DARF.BDVLRMULTAJUROS , ';
    WSQL = WSQL || 'DARF.BDVLROUTENTIDADE, ';
    WSQL = WSQL || 'DARF.BDORDEM, ';
    WSQL = WSQL || 'DARF.BDCHAVEDARF, ';
    WSQL = WSQL || 'IMP.BDLIMITEISENCAO, ';
    WSQL = WSQL || 'IMP.BDDOCARRECADACAO, ';
    WSQL = WSQL || 'DocArr.BDFORMREL, ';
    WSQL = WSQL || 'DARF.BDCODREC, ';
    WSQL = WSQL || 'DARF.BDVLRRETENCAO, ';
    WSQL = WSQL || 'IMP.BDTIPOIMPDOC, ';
    WSQL = WSQL || 'DocArr.BDCODDOCARREC, ';
    WSQL = WSQL || 'DARF.BDTIPOIMPOSTO, ';
    WSQL = WSQL || 'DARF.BDTIPOCALC, ';
    WSQL = WSQL || 'DARF.BDVLRACUMULO, ';
    WSQL = WSQL || 'emp.BDCODMATRIZ ';

    --left outer join sp _consultaempresas(201010, DARF.bdcodemp, null) emp on (emp.bdcodemp = DARF.bdcodemp )
    --LEFT OUTER JOIN timposto IMP ON (IMP.BDCODIMP = DARF.bdcodimp)
    --left outer join tdarfgerpgto PGTO on (PGTO.bdcodemp = DARF.bdcodemp and PGTO.BDCODIMP = DARF.BDCODIMP AND PGTO.bdcodperiodo = DARF.bdcodperiodo AND PGTO.bdreferencia = DARF.bdreferencia AND PGTO.bdordem = DARF.bdordem AND PGTO.bdquota = DARF.bdquota)
    --LEFT OUTER join TTIPOSPERIODO PER on (PER.bdcodperiodo = DARF.bdcodperiodo)
    --where DARF.BDREFERENCIA >= 201001  and DARF.BDREFERENCIA <= 201012
    --AND DARF.bdcodperiodo = 7
    --AND DARF.bddatavcto BETWEEN '03/01/2010' AND '03/31/2010'
    --AND PGTO.bddatapgto BETWEEN '03/01/2010' AND '03/31/2010'
    --order by DARF.bdcodemp, DARF.BDCODIMP, DARF.bdreferencia

  end

  WSQL = WSQL || 'from tdarfpadrao DARF , timposto IMP , VW_EMPRESAS_REF_ATUAL emp, TDOCARRECADACAO DocArr ';

  --  wsql = wsql||'left outer join SP_CONSULTAEMPRESAS('|| prrefatual || ', DARF.bdcodemp, null) emp on (emp.bdcodemp = DARF.bdcodemp ) ' ;
  --  wsql = wsql||'LEFT OUTER JOIN timposto IMP ON (IMP.BDCODIMP = DARF.bdcodimp) ' ;
  --  wsql = wsql||'left outer join tdarfgerpgto PGTO on (PGTO.bdcodemp = DARF.bdcodemp and PGTO.BDCODIMP = DARF.BDCODIMP AND PGTO.bdcodperiodo = DARF.bdcodperiodo AND PGTO.bdreferencia = DARF.bdreferencia AND PGTO.bdordem = DARF.bdordem AND PGTO.bdquota = DARF.bdquota) ' ;

  --  if (prgrupo is not null) then
  --     wsql = wSql||'left outer join tdarfgerpgto PGTO on (PGTO.bdcodemp = emp.bdcodemp and PGTO.BDCODIMP = DARF.BDCODIMP) ';

  WWHERE = '';

  if (PRCODEMP is not null) then
    WWHERE = WWHERE || PRCODEMP || ' ';

  if ((PRONLINE is not null)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
    WWHERE = WWHERE || PRONLINE || ' ';
  end

  if ((PRCODIMP is not null) or (PRCODIMP > 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
    WWHERE = WWHERE || PRCODIMP || ' ';
  end

  if ((PRREFINI is not null) and
      (PRREFINI > 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
       /*Elizeu - 01/08/2013 - sol 4886 - imposto semanal*/
    if (PRPERIODO <> 1) then
    begin
      WWHERE = WWHERE || 'DARF.BDREFERENCIA >= ' || PRREFINI || ' ';
    end
    else
    begin
      WWHERE = WWHERE || ' cast(substring(cast(DARF.BDREFERENCIA as varchar(8)) from 1 for 6) as integer) >= ' || PRREFINI || ' ';
    end
  end

  if ((PRREFFIN is not null) and
      (PRREFFIN > 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';

       /*Elizeu - 01/08/2013 - sol 4886 - imposto semanal*/
    if (PRPERIODO <> 1) then
    begin
      WWHERE = WWHERE || 'DARF.BDREFERENCIA <= ' || PRREFFIN || ' ';
    end
    else
    begin
      WWHERE = WWHERE || ' cast(substring(cast(DARF.BDREFERENCIA as varchar(8)) from 1 for 6) as integer) <= ' || PRREFFIN || ' ';
    end
  end

  if ((PRPERIODO is not null) and
      (PRPERIODO > 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';

    WWHERE = WWHERE || 'DARF.bdcodperiodo = ' || PRPERIODO || ' ';
  end

  if (PRDTVCTOINI is not null) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';

    WWHERE = WWHERE || 'DARF.bddatavcto >= ' || '''' || PRDTVCTOINI || '''';
  end

  if (PRDTVCTOFIM is not null) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';

    WWHERE = WWHERE || 'DARF.bddatavcto <= ' || '''' || PRDTVCTOFIM || '''';
  end
  /*
  if (prdtpgtoini is not null) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'PGTO.bddatapgto >= '||''''||prdtpgtoini||'''';
     end

  if (prdtpgtofim is not null) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'PGTO.bddatapgto <= '||''''||prdtpgtofim||'''';
     end
*/
  WEXISTS = '';

  if ((PRFILTRO is not null) and
      (PRFILTRO <> 0) and
      (PRFILTRO <> 1234)) then
  begin
    WEXISTS = ' exists ( ' || ' select baixa.bdcodemp,baixa.bdchavedarf ' || ' from tdarfpadrao baixa ' || ' left outer join (select pgto.bdcodemp,pgto.bdchavedarf,max(pgto.bddatapgto) bddatapgto ,sum(pgto.bdvlrpgto) bdvlrpgto from tdarfgerpgto pgto ' || '                  group by pgto.bdcodemp,pgto.bdchavedarf ) pgto on (PGTO.bdcodemp = baixa.bdcodemp and PGTO.BDCHAVEDARF = baixa.bdchavedarf) ' || ' where (';

       /* prFiltro
         1 = sem baixa
         2 = baixa parcial
         3 = baixa integral
         4 = Acumulada
         12 = sem baixa/baixa parcial
         13 = sem baixa/baixa integral
         14 = sem baixa/acumula
         23 = baixa parcial/baixa integral
         24 = baixa parcial/acumulada
         34 = baixa integral/acumulada
         123 = sem baixa/baixa parcia/baixa total
         124 = sem baixa/baixa parcia/acumulada
         134 = sem baixa/baixa total/acumulada
         234 = baixa parcia/baixa total/acumulada
         1234 = todos (n?o faz o filtro)

         1,2,3,4,12,13,14,23,24,34,123,124,134,234,1234
       */
    if (PRFILTRO in (1, 12, 13, 14, 123, 124, 134)) then
    begin
      WEXISTS = WEXISTS || ' (pgto.bdvlrpgto is null) ';
    end

    if (PRFILTRO in (2, 12, 24, 123, 124, 234)) then
    begin
      if ((PRFILTRO > 2) and
          (PRFILTRO <> 24) and
          (PRFILTRO <> 234)) then
        WEXISTS = WEXISTS || ' or ';
      WEXISTS = WEXISTS || ' ((pgto.bdvlrpgto < coalesce(baixa.BDTOTAL,coalesce(baixa.BDVALOR,0)+coalesce(baixa.BDVLRMULTAJUROS,0))) and (pgto.bdvlrpgto is not null))';
    end

    if (PRFILTRO in (3, 13, 34, 123, 134, 234)) then
    begin
      if ((PRFILTRO > 3) and
          (PRFILTRO <> 34)) then
        WEXISTS = WEXISTS || ' or ';
      WEXISTS = WEXISTS || ' (pgto.bdvlrpgto >= coalesce(baixa.BDTOTAL,coalesce(baixa.BDVALOR,0)+coalesce(baixa.BDVLRMULTAJUROS,0)))';
    end

    if (PRFILTRO = 23) then
    begin
      WEXISTS = WEXISTS || ' (pgto.bdvlrpgto is not null) ';
    end

    if (PRFILTRO in (4, 14, 24, 34, 124, 134, 234)) then
    begin
      if (PRFILTRO > 4) then
        WEXISTS = WEXISTS || ' or ';
      WEXISTS = WEXISTS || ' (IMP.BDLIMITEISENCAO > coalesce(baixa.BDTOTAL,coalesce(baixa.BDVALOR,0)+coalesce(baixa.BDVLRMULTAJUROS,0)))';
    end

    WEXISTS = WEXISTS || ' ) ';/* fim where sql filtro */

    if (PRFILTRO not in (4, 14, 24, 34, 124, 134, 234)) then
    begin
      WEXISTS = WEXISTS || ' and ';
      WEXISTS = WEXISTS || ' (IMP.BDLIMITEISENCAO < coalesce(baixa.BDTOTAL,coalesce(baixa.BDVALOR,0)+coalesce(baixa.BDVLRMULTAJUROS,0)))';
    end

    WEXISTS = WEXISTS || ' and  baixa.bdcodemp = darf.bdcodemp and baixa.bdchavedarf = darf.bdchavedarf) ';
  end

  if (WWHERE <> '') then
    WWHERE = 'where ' || WWHERE || ' ';

  WWHERE = WWHERE || ' and (imp.bdcodimp = darf.bdcodimp) and (emp.bdcodemp = darf.bdcodemp) and (imp.BDDOCARRECADACAO = DocArr.BDCODDOCARREC) ';

  if (WEXISTS <> '') then
    WWHERE = WWHERE || ' and ' || WEXISTS;

  if (PRGRUPO = 1) then
  begin
    WGROUPBY = 'group by DARF.bdcodemp, EMP.bdnomemp ';
    WORDERBY = 'order by DARF.bdcodemp ';
  end
  else
  if (PRGRUPO = 2) then
  begin
    WGROUPBY = 'group by DARF.BDREFERENCIA ';
    WORDERBY = 'order by DARF.BDREFERENCIA ';
  end
  else
  if (PRGRUPO = 3) then
  begin
    WGROUPBY = 'group by DARF.BDCODIMP,IMP.BDDESCIMP ';
    WORDERBY = 'order by DARF.BDCODIMP,IMP.BDDESCIMP ';
  end
  else
  begin
    WGROUPBY = '';
    WORDERBY = 'order by DARF.BDCODIMP, DARF.bdreferencia, DARF.BDORDEM, DARF.BDCODPERIODO';
  end

  WSQL = WSQL || WWHERE || WGROUPBY || WORDERBY;

  if (PRGRUPO = 1) then
  begin
    for execute statement WSQL
            into :BDCODEMP, :BDNOMEMP
    do
      suspend;
  end
  else
  if (PRGRUPO = 2) then
  begin
    for execute statement WSQL
            into :BDREFERENCIA

    do
      suspend;
  end
  else
  if (PRGRUPO = 3) then
  begin
    for execute statement WSQL
            into :BDCODIMP, :BDDESCIMP
    do
      suspend;
  end
  else
  begin
    for execute statement WSQL
            into :BDCODEMP, :BDNOMEMP, :BDCNPJEMP, :BDCODIMP, :BDCODTPCC, :BDDESCIMP, :BDCODPERIODO, :BDREFERENCIA,
            :BDQUOTA, :BDDATAVCTO,
            --              :bddatapgto ,
            :BDBASEIMP, :BDALIQIMP, :BDVLRIMPORIGINAL, :BDVALOR, :BDMULTA, :BDJUROS, :BDTOTAL, :BDOBS, :BDORDEMCOMPL,
            :BDVLRMULTAJUROS, :BDVLROUTENTIDADE, :BDORDEM, :BDCHAVEDARF, :BDLIMITEISENCAO, :BDDOCARRECADACAO,
            :BDFORMREL, :BDCODREC, :BDVLRRETENCAO, :WTIPOIMPDOC, :WCODDOCARREC, :WTIPOIMPOSTO, :WTIPOCALC,
            :BDVLRACUMULO, :BDCODMATRIZ
    do
    begin
      if (coalesce(WCODDOCARREC, 0) not in (1, 2) and
          BDTOTAL <= BDLIMITEISENCAO) then
        /* Darf's */
                BDVLRACUMULO = BDTOTAL;

      BDDESCTIPOCALC = null;
      select max(PGTO.BDDATAPGTO), sum(PGTO.BDVLRPGTO), max(PGTO.BDNRODOC)
      from TDARFGERPGTO PGTO
      where (PGTO.BDCODEMP = :BDCODEMP and
            PGTO.BDCHAVEDARF = :BDCHAVEDARF)
      into :BDDTPGTO, :BDVLRPGTO, :BDNRDOCPGTO;

      select first 1 BDCODTIPOLANC
      from TDARFGERPGTO PGTO
      where (PGTO.BDCODEMP = :BDCODEMP and
            PGTO.BDCHAVEDARF = :BDCHAVEDARF)
      order by PGTO.BDDATAPGTO desc
      into :BDTIPOLANC;

              /* Setar a flag se for uma baixa parcial - In?cio */
      WVLRPGTO = 0;
      WTOTAL = 0;
      WVALOR = 0;
      WVLRMULTAJUROS = 0;
      select coalesce(PGTO.BDVLRPGTO, 0), coalesce(BAIXA.BDTOTAL, 0), coalesce(BAIXA.BDVALOR, 0),
             coalesce(BAIXA.BDVLRMULTAJUROS, 0)
      /* Alt:22559 - Everton
         Alterado o trecho abaixo para ao inv?s de pegar direto da tabela TDARFPADRAO inteira,
         fazer um select apenas com os registros dela correspondentes ao for execute statement atual.
         Desta forma, evita leitura de registros n?o indexados, o que deixava o processo lento.
      */
      --FROM tdarfpadrao baixa
      from (select DARFP.BDCODEMP, DARFP.BDCHAVEDARF, DARFP.BDTOTAL, DARFP.BDVALOR, DARFP.BDVLRMULTAJUROS
            from TDARFPADRAO DARFP
            where DARFP.BDCODEMP = :BDCODEMP and
                  DARFP.BDCHAVEDARF = :BDCHAVEDARF) BAIXA
      left outer join(select PGTO.BDCODEMP, PGTO.BDCHAVEDARF, max(PGTO.BDDATAPGTO) BDDATAPGTO,
                             sum(PGTO.BDVLRPGTO) BDVLRPGTO
                      from TDARFGERPGTO PGTO
                      where (PGTO.BDVLRPGTO is not null) and
                            (PGTO.BDCODEMP = :BDCODEMP) and
                            (PGTO.BDCHAVEDARF = :BDCHAVEDARF)
                      group by PGTO.BDCODEMP, PGTO.BDCHAVEDARF) PGTO on (PGTO.BDCODEMP = BAIXA.BDCODEMP and PGTO.BDCHAVEDARF = BAIXA.BDCHAVEDARF)
      where (PGTO.BDVLRPGTO < coalesce(BAIXA.BDTOTAL, coalesce(BAIXA.BDVALOR, 0) + coalesce(BAIXA.BDVLRMULTAJUROS, 0)))

      into WVLRPGTO, WTOTAL, WVALOR, WVLRMULTAJUROS;

              BDFLAG = 'FALSE';
      if (WVLRPGTO > 0) then
      begin
        if ((WTOTAL > 0) and
            (WVLRPGTO < WTOTAL)) then
                    BDFLAG = 'TRUE';
        else
        if (WVLRPGTO < WVALOR + WVLRMULTAJUROS) then
                    BDFLAG = 'TRUE';
      end
              /* Setar a flag se for uma baixa parcial - Fim */

      --                                  tdaDARF, tdaGPS
      if (WCODDOCARREC = 12) then
      begin --         tcRHGPS_Calculo, tcRHGPS_Carne, tcRHGPS_Complementar
        if (WTIPOIMPOSTO = 0) then
                       BDDESCTIPOCALC = 'Folha normal';
        else
        if (WTIPOIMPOSTO = 1) then
                       BDDESCTIPOCALC = 'Folha complementar';
        else
        if (WTIPOIMPOSTO = 2) then
                       BDDESCTIPOCALC = '13? Sal?rio';
        else
        if (WTIPOIMPOSTO = 3) then
                       BDDESCTIPOCALC = 'Complemento 13? sal?rio';
        else
                       BDDESCTIPOCALC = 'N?o informado';
      end
      else
      if (WCODDOCARREC = 1) then
      begin --    tcRHDarf_IRRF_Por_Calc, tcRHDarf_PIS_Por_Calc
        if (WTIPOCALC = 0) then
                       BDDESCTIPOCALC = 'Todos';
        else
        if (WTIPOCALC = 1) then
                       BDDESCTIPOCALC = 'Folha normal';
        else
        if (WTIPOCALC = 2) then
                       BDDESCTIPOCALC = 'Adiantamento salarial';
        else
        if (WTIPOCALC = 3) then
                       BDDESCTIPOCALC = 'Adiantamento 13? sal?rio';
        else
        if (WTIPOCALC = 4) then
                       BDDESCTIPOCALC = '13 Sal?rio';
        else
        if (WTIPOCALC = 5) then
                       BDDESCTIPOCALC = 'Complemento 13? sal?rio';
        else
        if (WTIPOCALC = 6) then
                       BDDESCTIPOCALC = 'F?rias';
        else
        if (WTIPOCALC = 7) then
                       BDDESCTIPOCALC = 'Folha avulsa';
        else
        if (WTIPOCALC = 8) then
                       BDDESCTIPOCALC = 'Folha complementar';
        else
        if (WTIPOCALC = 9) then
                       BDDESCTIPOCALC = 'Rescis?o';
        else
        if (WTIPOCALC = 10) then
                       BDDESCTIPOCALC = 'M?dias';
        else
                       BDDESCTIPOCALC = 'N?o informado';
      end
      else


      --                                tdaGRCS_contribui??o_sindical, tdaGRCS_mensalidade_sindical, tdaGRCS_contribui??o_confederativa, tdaGRCS_taxa_assistencial, tdaGRCS_revers?o_sal?rial
      if (WCODDOCARREC in (14, 15, 16, 17, 18)) then
      begin
        if (WTIPOIMPDOC in (0, 14, 15, 16, 17, 18)) then
        begin
          if (WTIPOCALC = 0) then
                           BDDESCTIPOCALC = 'Todos';
          else
          if (WTIPOCALC = 1) then
                           BDDESCTIPOCALC = 'Folha normal';
          else
          if (WTIPOCALC = 2) then
                           BDDESCTIPOCALC = 'Adiantamento salarial';
          else
          if (WTIPOCALC = 3) then
                           BDDESCTIPOCALC = 'Adiantamento 13? sal?rio';
          else
          if (WTIPOCALC = 4) then
                           BDDESCTIPOCALC = '13 Sal?rio';
          else
          if (WTIPOCALC = 5) then
                           BDDESCTIPOCALC = 'Complemento 13? sal?rio';
          else
          if (WTIPOCALC = 6) then
                           BDDESCTIPOCALC = 'F?rias';
          else
          if (WTIPOCALC = 7) then
                           BDDESCTIPOCALC = 'Folha avulsa';
          else
          if (WTIPOCALC = 8) then
                           BDDESCTIPOCALC = 'Folha complementar';
          else
          if (WTIPOCALC = 9) then
                           BDDESCTIPOCALC = 'Rescis?o';
          else
          if (WTIPOCALC = 10) then
                           BDDESCTIPOCALC = 'M?dias';
          else
                           BDDESCTIPOCALC = 'N?o informado';
        end
      end
      else
      if (WCODDOCARREC = 19) then
      begin
        if (WTIPOCALC = 1) then
                       BDDESCTIPOCALC = 'Complementar';
        else
                       BDDESCTIPOCALC = 'Original';
      end

      suspend;
    end
  end
end
^

/* Alter (SP_UPDATE_INSUMOS_TEMP) */
ALTER PROCEDURE SP_UPDATE_INSUMOS_TEMP(PRSESSAO INTEGER)
 AS
BEGIN
  /*Desvincula todos os produtos*/
  UPDATE TMP_TCADPRO_INSUMOS_TEMP T SET T.BDCODPROINSUMO = NULL, T.BDDESCPROD = NULL WHERE T.BDSESSAO = :PRSESSAO;
    
  /*1 - Busca os produtos na tabela TEMP, cont?m os registros que est?o sendo importados*/
  UPDATE TMP_TCADPRO_INSUMOS_TEMP T
  SET T.BDCODPROINSUMO = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODSAIDA = T.BDCODSAIDAPROD),
      T.BDDESCPROD = (
                      SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                      FROM TMP_TCADPRO_TEMP P
                      WHERE P.BDSESSAO = :PRSESSAO
                      AND P.BDCODSAIDA = T.BDCODSAIDAPROD
                     )
  WHERE T.BDSESSAO = :PRSESSAO;
    
  /*2 - Busca os produtos na tabela TMP, cont?m todos os registros de produto do banco*/
  UPDATE TMP_TCADPRO_INSUMOS_TEMP T
  SET T.BDCODPROINSUMO = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDAPROD),
      T.BDDESCPROD = (
                      SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                      FROM TMP_TCADPRO P
                      WHERE P.BDCODEMP = T.BDCODEMP
                      AND P.BDCODSAIDA = T.BDCODSAIDAPROD
                     )
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODPROINSUMO IS NULL;
    
  /*Apenas joga o altcodprod para o bdcodprod*/
--  UPDATE TMP_TCADPRO_INSUMOS_TEMP T SET T.BDCODPROINSUMO = T.BDALTCODPROD
--  WHERE T.BDSESSAO = :PRSESSAO
--  AND T.BDALTCODPROD IS NOT NULL;
END
^

/* Alter (SP_UPDATE_K220) */
ALTER PROCEDURE SP_UPDATE_K220(PRID_TERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOK220 INTEGER;
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_TCADPRO_TEMP' INTO :wSessaoPro;
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_VEF_EMP_TMOVESTK220_TEMP' INTO :wSessaoK220;

  /*Desvincula todos os produtos*/
  UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP T SET T.BDCODPRODDEST = NULL, T.BDDESCPRODDEST = NULL WHERE T.BDSESSAO = :wSessaoK220;
    
  /*1 - Busca os produtos na tabela TEMP, cont?m os registros que est?o sendo importados*/
  UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP T
  SET T.BDALTCODPRODDEST = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :wSessaoPro AND P.BDCODSAIDA = T.BDCODSAIDADEST),
      T.BDDESCPRODDEST = (
                          SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                          FROM TMP_TCADPRO_TEMP P
                          WHERE P.BDSESSAO = :wSessaoPro
                          AND P.BDCODSAIDA = T.BDCODSAIDADEST
                         )
  WHERE T.BDSESSAO = :wSessaoK220
  AND ((T.BDCODSAIDADEST IS NOT NULL) AND (T.BDCODSAIDADEST <> ''));
    
  /*2 - Busca os produtos na tabela TMP, cont?m todos os registros de produto do banco*/
  UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP T
  SET T.BDALTCODPRODDEST = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDADEST),
      T.BDDESCPRODDEST = (
                          SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                          FROM TMP_TCADPRO P
                          WHERE P.BDCODEMP = T.BDCODEMP
                          AND P.BDCODSAIDA = T.BDCODSAIDADEST
                         )
  WHERE T.BDSESSAO = :wSessaoK220
  AND T.BDALTCODPRODDEST IS NULL
  AND ((T.BDCODSAIDADEST IS NOT NULL) AND (T.BDCODSAIDADEST <> ''));

  /*Apenas joga o altcodprod para o bdcodprod*/
  UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP T SET T.BDCODPRODDEST = T.BDALTCODPRODDEST
  WHERE T.BDSESSAO = :wSessaoK220
  AND T.BDALTCODPRODDEST IS NOT NULL;
END
^

/* Alter (SP_UPDATE_K235K255) */
ALTER PROCEDURE SP_UPDATE_K235K255(PRID_TERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
DECLARE VARIABLE WSESSAOK235K255 INTEGER;
BEGIN
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_TCADPRO_TEMP' INTO :wSessaoPro;
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_VEF_EMP_TMOVINK235K255_TEMP' INTO :wSessaoK235K255;

  /*Desvincula todos os produtos*/
  UPDATE TMP_VEF_EMP_TMOVINK235K255_TEMP T SET T.BDCODPRODSUB = NULL, T.BDDESCPRODSUB = NULL WHERE T.BDSESSAO = :wSessaoK235K255;
    
  /*1 - Busca os produtos na tabela TEMP, cont?m os registros que est?o sendo importados*/
  UPDATE TMP_VEF_EMP_TMOVINK235K255_TEMP T
  SET T.BDALTCODPRODSUB = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :wSessaoPro AND P.BDCODSAIDA = T.BDCODSAIDASUB),
      T.BDDESCPRODSUB = (
                         SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                         FROM TMP_TCADPRO_TEMP P
                         WHERE P.BDSESSAO = :wSessaoPro
                         AND P.BDCODSAIDA = T.BDCODSAIDASUB
                        )
  WHERE T.BDSESSAO = :wSessaoK235K255
  AND ((T.BDCODSAIDASUB IS NOT NULL) AND (T.BDCODSAIDASUB <> ''));
    
  /*2 - Busca os produtos na tabela TMP, cont?m todos os registros de produto do banco*/
  UPDATE TMP_VEF_EMP_TMOVINK235K255_TEMP T
  SET T.BDALTCODPRODSUB = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDASUB),
      T.BDDESCPRODSUB = (
                         SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                         FROM TMP_TCADPRO P
                         WHERE P.BDCODEMP = T.BDCODEMP
                         AND P.BDCODSAIDA = T.BDCODSAIDASUB
                        )
  WHERE T.BDSESSAO = :wSessaoK235K255
  AND T.BDALTCODPRODSUB IS NULL
  AND ((T.BDCODSAIDASUB IS NOT NULL) AND (T.BDCODSAIDASUB <> ''));

  /*Apenas joga o altcodprod para o bdcodprod*/
  UPDATE TMP_VEF_EMP_TMOVINK235K255_TEMP T SET T.BDCODPRODSUB = T.BDALTCODPRODSUB
  WHERE T.BDSESSAO = :wSessaoK235K255
  AND T.BDALTCODPRODSUB IS NOT NULL;
END
^

/* Alter (SP_UPDATE_K275) */
ALTER PROCEDURE SP_UPDATE_K275(PRID_TERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
DECLARE VARIABLE WSESSAO INTEGER;
BEGIN
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_TCADPRO_TEMP' INTO :wSessaoPro;
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_VEF_EMP_TMOVK275_TEMP' INTO :wSessao;

  /*Desvincula todos os produtos*/
  UPDATE TMP_VEF_EMP_TMOVK275_TEMP T SET T.BDCODPRODSUB = NULL, T.BDDESCPRODSUB = NULL WHERE T.BDSESSAO = :wSessao;
    
  /*1 - Busca os produtos na tabela TEMP, cont?m os registros que est?o sendo importados*/
  UPDATE TMP_VEF_EMP_TMOVK275_TEMP T
  SET T.BDALTCODPRODSUB = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :wSessaoPro AND P.BDCODSAIDA = T.BDCODSAIDASUB),
      T.BDDESCPRODSUB = (
                         SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                         FROM TMP_TCADPRO_TEMP P
                         WHERE P.BDSESSAO = :wSessaoPro
                         AND P.BDCODSAIDA = T.BDCODSAIDASUB
                        )
  WHERE T.BDSESSAO = :wSessao
  AND ((T.BDCODSAIDASUB IS NOT NULL) AND (T.BDCODSAIDASUB <> ''));
    
  /*2 - Busca os produtos na tabela TMP, cont?m todos os registros de produto do banco*/
  UPDATE TMP_VEF_EMP_TMOVK275_TEMP T
  SET T.BDALTCODPRODSUB = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDASUB),
      T.BDDESCPRODSUB = (
                         SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                         FROM TMP_TCADPRO P
                         WHERE P.BDCODEMP = T.BDCODEMP
                         AND P.BDCODSAIDA = T.BDCODSAIDASUB
                        )
  WHERE T.BDSESSAO = :wSessao
  AND T.BDALTCODPRODSUB IS NULL
  AND ((T.BDCODSAIDASUB IS NOT NULL) AND (T.BDCODSAIDASUB <> ''));

  /*Apenas joga o altcodprod para o bdcodprod*/
  UPDATE TMP_VEF_EMP_TMOVK275_TEMP T SET T.BDCODPRODSUB = T.BDALTCODPRODSUB
  WHERE T.BDSESSAO = :wSessao
  AND T.BDALTCODPRODSUB IS NOT NULL;
END
^

/* Alter (SP_VAL_GPS_PROV_13) */
ALTER PROCEDURE SP_VAL_GPS_PROV_13(PRREFERENCIA INTEGER,
PRCODEMP VARCHAR(30000),
PRCODCOL VARCHAR(30000))
 RETURNS(BDREFERENCIA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDTIPOIMPOSTO INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(15,6),
BDTERCFN NUMERIC(15,6),
BDRATFN NUMERIC(15,6),
BDRATAPOFN NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDTERC13 NUMERIC(15,6),
BDRAT13 NUMERIC(15,6),
BDRATAPO13 NUMERIC(15,6),
BDINSS13IND NUMERIC(15,6),
BDTERC13IND NUMERIC(15,6),
BDRAT13IND NUMERIC(15,6),
BDRATAPO13IND NUMERIC(15,6),
BDINSSC13 NUMERIC(15,6),
BDTERCC13 NUMERIC(15,6),
BDRATC13 NUMERIC(15,6),
BDRATAPOC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(3000);
BEGIN
  /* Procedure Text */
  wsql = 'select y.bdreferencia,x.bdcodemp,x.bdcodcol,x.bdcodter,y.bdtipoimposto,x.bdcodcentro,x.bdcodtpcc,'||
       /*FOLHA*/
         'coalesce(x.bdvalfunemp13fn,0) +'||
         'coalesce(x.bdvalfunemp13fc,0) +'||
         'coalesce(x.bdvalproemp13fc,0) +'||
         'coalesce(x.bdvalproemp13fn,0) +'||
         'coalesce(x.bdvalautemp13fn,0) +'||
         'coalesce(x.bdvalautemp13fc,0) INSSFN,'||
         'coalesce(x.bdvalfpasemp13fn,0) +'||
         'coalesce(x.bdvalfpasemp13fc,0) TERCFN,'||
         'coalesce(x.bdvalRATemp13fn,0) +'||
         'coalesce(x.bdvalRATemp13fc,0) RATFN,'||
         'coalesce(x.bdvalRATAPOemp13fn,0) +'||
         'coalesce(x.bdvalRATAPOemp13fc,0) RATAPOFN,'||
       /*13*/
         'coalesce(x.bdvalfunemp13,0) +'||
         'coalesce(x.bdvalproemp13,0) +'||
         'coalesce(x.bdvalautemp13,0) INSS13,'||
         'coalesce(x.bdvalfpasemp13,0) TERC13,'||
         'coalesce(x.bdvalRATemp13,0) RAT13,'||
         'coalesce(x.bdvalRATAPOemp13,0) RATAPO13,'||
       /* Complemento 13*/
         'coalesce(x.bdvalfunempc13,0) +'||
         'coalesce(x.bdvalproempc13,0) +'||
         'coalesce(x.bdvalautempc13,0) INSSc13,'||
         'coalesce(x.bdvalfpasempc13,0) TERCc13,'||
         'coalesce(x.bdvalRATempc13,0) RATc13,'||
         'coalesce(x.bdvalRATAPOempc13,0) RATAPOc13,'||
       /*13? Indenizado*/
         'coalesce(x.bdvalfunemp13indfn,0) +'||
         'coalesce(x.bdvalproemp13indfn,0) +'||
         'coalesce(x.bdvalautemp13indfn,0) +'||
         'coalesce(x.bdvalautemp13fc,0) INSS13INDFN,'||
         'coalesce(x.bdvalfpasemp13indfn,0) TERC13INDFN,'||
         'coalesce(x.bdvalRATemp13indfn,0) RAT13INDFN,'||
         'coalesce(x.bdvalRATAPOemp13indfn,0) RATAPO13INDFN'||
         ' from vrhf_emp_gps_ind x'||
         ' left outer join tdarfpadrao y on (x.bdcodemp = y.bdcodemp and x.BDCHAVEDARF = y.BDCHAVEDARF)';


  IF (prreferencia IS NULL) THEN
     prreferencia = 0;

  wsql = wsql||' where y.bdreferencia <= '||prreferencia;

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       wsql = wsql||' and '||prcodcol;
     END

  wsql = wsql||' and x.bdcodter is null ';
  wsql = wsql||' order by x.bdcodemp,x.bdcodcol,x.bdcodtpcc,y.bdreferencia';

  FOR EXECUTE STATEMENT wsql INTO
   :bdreferencia,
   :bdcodemp ,
   :bdcodcol ,
   :bdcodter ,
   :bdtipoimposto ,
   :bdcodcentro ,
   :bdcodtpcc,
   :bdinssfn,
   :bdtercfn,
   :bdratfn,
   :bdratapofn,
   :bdinss13,
   :bdterc13,
   :bdrat13,
   :bdratapo13,
   :bdinssc13,
   :bdtercc13,
   :bdratc13,
   :bdratapoc13,
   :bdinss13IND,
   :bdterc13IND,
   :bdrat13IND,
   :bdratapo13IND
  DO
  BEGIN
    SUSPEND;
  END
--  suspend;
END
^

/* Alter (SP_VAL_HE_RAIS_FF) */
ALTER PROCEDURE SP_VAL_HE_RAIS_FF(PREMP INTEGER,
PRCOL INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDHE NUMERIC(15,6),
BDCODVER INTEGER)
 AS
DECLARE VARIABLE WBOOL VARCHAR(5);
DECLARE VARIABLE WHE NUMERIC(15,6);
DECLARE VARIABLE WINT INTEGER;
BEGIN
  /* Procedure Text */
--  suspend;

  FOR SELECT bdcodemp,bdcodcol, bdreffhe, bdvreffhe, bdcodver FROM VW_VRHF_EMP_TFICHAHE WHERE bdcodemp = :premp AND bdcodcol = :prcol AND
       CAST(SUBSTRING(CAST(bdreffhe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER) = :prano
  INTO bdcodemp,bdcodcol,bdref, bdhe, bdcodver DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);

      SELECT bdrefhoremp FROM VW_VRHF_BASE_TEMPCALC WHERE bdcodemp = :premp INTO wbool;

      IF (wBool = 'TRUE') THEN
         BEGIN
           whe = bdhe;
           wint = CAST(whe - 0.5 AS INTEGER);

           whe = whe - wint;

           IF ((whe > 0) AND (bdhe > 0)) THEN
              BEGIN
                whe = (whe / 60 * 100) + wint;
                bdhe = whe;
              END
         END

      SUSPEND;
    END
END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_VAL_RAIS_FF for: SP_VAL_RAIS_FF */
ALTER PROCEDURE SP_VRH_VAL_RAIS_FF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_VAL_RAIS_FF) */
ALTER PROCEDURE SP_VAL_RAIS_FF(PREMP INTEGER = 0,
PRCOL INTEGER = 0,
PRANO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQLAUX VARCHAR(32000);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WREFRESC INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(15,6);
DECLARE VARIABLE WCLASS VARCHAR(300);
DECLARE VARIABLE WCLASS2 VARCHAR(300);
DECLARE VARIABLE WCLASS3 VARCHAR(300);
DECLARE VARIABLE WCLASS4 VARCHAR(300);
DECLARE VARIABLE WCLASS1 VARCHAR(10);
DECLARE VARIABLE WBASRAIS VARCHAR(5);
DECLARE VARIABLE WTIPOCOD INTEGER;
DECLARE VARIABLE WVALAUX NUMERIC(15,6);
DECLARE VARIABLE WJAN INTEGER;
DECLARE VARIABLE WFEV INTEGER;
DECLARE VARIABLE WMAR INTEGER;
DECLARE VARIABLE WABR INTEGER;
DECLARE VARIABLE WMAI INTEGER;
DECLARE VARIABLE WJUN INTEGER;
DECLARE VARIABLE WJUL INTEGER;
DECLARE VARIABLE WAGO INTEGER;
DECLARE VARIABLE WSET INTEGER;
DECLARE VARIABLE WOUT INTEGER;
DECLARE VARIABLE WNOV INTEGER;
DECLARE VARIABLE WDEZ INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WEXISTE INTEGER;
DECLARE VARIABLE WRESCORIGINAL INTEGER;
BEGIN
  /* Procedure Text */
--  wsql = 'select fol.bdreffn, fol.bdvalv, ver.bdclaver from VW_VRHF_CONS_CALC_FOLHA_VERBAS fol '||
--         ' left outer join vrh_base_tverbas ver on (ver.bdcodver = fol.bdcodver) '||


  bdorigem = 0;
  IF (prano >= 2014) THEN
     BEGIN
       wsql = 'select RAIS.BDREFFN, RAIS.BDVALV, VER.BDCLAVER, VERREF.BDRAISVER, VERREF.BDTIPOCODVER, RAIS.BDREFRESCISAO, RAIS.BDREFRESCORIGINAL '||
              'from (select FOL.BDREFFN, FOL.BDVALVFN BDVALV,  '||
                           '0 BDREFRESCISAO, 0 BDREFRESCORIGINAL, FOL.BDCODVER '||
                    'from (select 1 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFFN, BDREFFN BDREFFILTRO, BDREFVFN, BDREFAUXVFN, '||
                                 'BDVALVFN, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFN COLCON '||
                          'union all '||
                          'select 1 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                 'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                                 'CC.BDDATAENTRADA, CC.BDCODCENTRO, CC.BDCODTPCC '||
                          'from VRHF_EMP_TVERBATOMADOR COLCON '||
                          'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                          'union all '||
                          'select 2 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFFN, BDREFFN, BDREFVFC, BDREFAUXVFC, BDVALVFC, '||
                                 'cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFC FC '||
                          'union all '||
                          'select 2 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                 'COLCON.BDREFTOMADOR, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.BDVALVFC, CC.BDDATAENTRADA, '||
                                 'CC.BDCODCENTRO, CC.BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
                          'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                          'union all '||
                          'select 3 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFA13, BDREFA13 BDREFFILTRO, BDREFVA13, BDREFAUXVA13, '||
                                 'BDVALVA13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAA13 FC '||
                          'union all '||
                          'select 4 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREF13, BDREF13 BDREFFILTRO, BDREFV13, BDREFAUXV13, '||
                                 'BDVALV13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBA13 FC '||
                          'union all '||
                          'select 4 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFC13, BDREFC13 BDREFFILTRO, BDREFVC13, BDREFAUXVC13, '||
                                 'BDVALVC13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAC13 FC) FOL '||
                    'where (FOL.BDCODEMP = '||premp||') and '||
                          '(substring(FOL.BDREFFILTRO from 1 for 4) = '''||prano||''') and '||
                          'FOL.BDCODCOL = '||prcol||' '||
                    'union all '||
                    'select FOL.BDREFFN, FOL.BDVALVFN BDVALV, '||
                           'case '||
                             'when PRES.BDINIPRES = 1 and RES.BDPROJECAOAVISO is not null then RES.BDREFPROJECAOAVISO '||
                             'else RES.BDREFRESCISAO '||
                           'end BDREFRESCISAO, '||
                           'RES.BDREFRESCISAO BDREFRESCORIGINAL, FOL.BDCODVER '||
                    'from VRH_EMP_TRESCISAO RES '||
                    'join(select 1 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFFN, BDREFFN BDREFFILTRO, BDREFVFN, BDREFAUXVFN, '||
                                'BDVALVFN, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC '||
                         'from VRHF_EMP_TVERBAFN COLCON '||
                         'union all '||
                         'select 1 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                                'CC.BDDATAENTRADA, CC.BDCODCENTRO, CC.BDCODTPCC '||
                         'from VRHF_EMP_TVERBATOMADOR COLCON '||
                         'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                         'union all '||
                         'select 2 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFFN, BDREFFN BDREFFILTRO, BDREFVFC, BDREFAUXVFC, '||
                                'BDVALVFC, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC '||
                         'from VRHF_EMP_TVERBAFC FC '||
                         'union all '||
                         'select 2 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.BDVALVFC, CC.BDDATAENTRADA, '||
                                'CC.BDCODCENTRO, CC.BDCODTPCC '||
                         'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
                         'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                         'union all '||
                         'select 3 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFA13, BDREFA13 BDREFFILTRO, BDREFVA13, BDREFAUXVA13, '||
                                'BDVALVA13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC '||
                         'from VRHF_EMP_TVERBAA13 FC '||
                         'union all '||
                         'select 4 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREF13, BDREF13 BDREFFILTRO, BDREFV13, BDREFAUXV13, '||
                                'BDVALV13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC '||
                         'from VRHF_EMP_TVERBA13 FC '||
                         'union all '||
                         'select 4 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFC13, BDREFC13 BDREFFILTRO, BDREFVC13, BDREFAUXVC13, '||
                                'BDVALVC13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC '||
                         'from VRHF_EMP_TVERBAC13 FC) FOL on (FOL.BDCODEMP = RES.BDCODEMP and FOL.BDCODCOL = RES.BDCODCOL and FOL.BDREFFN = RES.BDREFRESCISAO) '||
                    'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = RES.BDCODPRES) '||
                    'where (FOL.BDCODEMP = '||premp||') and '||
                          '((substring(RES.BDREFRESCISAO from 1 for 4) = '''||prano||''') or (substring(RES.BDREFPROJECAOAVISO from 1 for 4) = '''||prano||''')) and '||
                          '(substring(RES.BDREFRESCISAO from 1 for 4) > '''||'2013'||''') and '||
                          'FOL.BDCODCOL = '||prcol||') RAIS '||

              'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = RAIS.BDCODVER) '||
              'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = RAIS.BDCODVER) '||
              ' where VERREF.BDTIPOCODVER <= 1 '||
              'order by RAIS.BDREFFN, RAIS.BDREFRESCISAO, RAIS.BDCODVER ';
     END
  ELSE
     BEGIN
       wsql = ' select fol.bdreffn,  fol.bdvalvfn BDVALV, ver.bdclaver,  '||
                 ' verref.bdraisver, verref.bdtipocodver, res.bdrefrescisao, 0 bdrefrescoriginal from '||
                 ' ( '||
     --            // Folha normal
                 ' select  BDCODEMP, BDCODCOL,  bdcodver,  bdreffn,  bdrefvfn,  bdrefauxvfn,  bdvalvfn, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC  from vrhf_emp_tverbafn COLCON '||
                 ' UNION all '||
     --              // Folha normal tomador
                 ' select COLCON.BDCODEMP, COLCON.BDCODCOL,  COLCON.BDCODVER,  COLCON.BDREFTOMADOR,  COLCON.BDREFVFT,  COLCON.BDREFAUXVFT,  COLCON.BDVALVFT, cc.bddataentrada, cc.bdcodcentro, cc.bdcodtpcc '||
                 ' from vrhf_emp_tverbatomador COLCON '||
                 ' join VRHF_EMP_TPREPFN cc on (COLCON.bdcodemp = cc.bdcodemp and  COLCON.bdcodcol = cc.bdcodcol and COLCON.bdordem = cc.bdordem) '||
     --              // Folha Complementar
                 ' union all '||
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdreffn,  bdrefvfc,  bdrefauxvfc,  bdvalvfc, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC  from vrhf_emp_tverbafc fc '||
                 ' UNION all '||
     --              // Folha Complementar tomador
                 ' select COLCON.BDCODEMP, COLCON.BDCODCOL,  COLCON.BDCODVER,  COLCON.BDREFTOMADOR,  COLCON.BDREFVFc,  COLCON.BDREFAUXVFc,  COLCON.BDVALVFc, cc.bddataentrada, cc.bdcodcentro, cc.bdcodtpcc '||
                 ' from vrhf_emp_tverbafctomador COLCON '||
                 ' join VRHF_EMP_TPREPFN cc on (COLCON.bdcodemp = cc.bdcodemp and  COLCON.bdcodcol = cc.bdcodcol and COLCON.bdordem = cc.bdordem) '||
     --              // Adiantamento 13? salario
                 ' union all '||
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdrefa13,  bdrefva13,  bdrefauxva13,  bdvalva13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC '||
                 ' from vrhf_emp_tverbaa13 fc '||
     --              // 13? sal?rio
                 ' union all '||
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdref13,  bdrefv13,  bdrefauxv13,  bdvalv13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC '||
                 ' from vrhf_emp_tverba13 fc '||
     --              // Complemento 13? sal?rio
                 ' union all '||
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdrefc13,  bdrefvc13,  bdrefauxvc13,  bdvalvc13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC '||
                 ' from vrhf_emp_tverbac13 fc '||
                 ' ) fol '||
                 ' join vrh_base_tverbas ver on (ver.bdcodver = fol.bdcodver) '||
                 ' join vw_vrh_base_tverbas_ref verref on (verref.bdcodver = fol.bdcodver) '||
                 ' left outer join vrh_emp_trescisao res on (fol.bdcodemp = res.bdcodemp and fol.bdcodcol = res.bdcodcol) '||
     
     
              ' where verref.bdtipocodver <= 1 and (fol.bdcodemp = '||premp||')  and (cast (substring(fol.bdreffn from 1 for 4) as integer) = '||prano||') AND FOL.bdcodcol = '||prcol||
              ' order by bdreffn, fol.bdcodver ';
     END

  bdcodcol = prcol;
  bdcodemp = premp;
  bdref = 0;

  wjan = 0;
  wfev = 0;
  wmar = 0;
  wabr = 0;
  wmai = 0;
  wjun = 0;
  wjul = 0;
  wago = 0;
  wset = 0;
  wout = 0;
  wnov = 0;
  wdez = 0;

  WEXISTE = 0;

  FOR EXECUTE STATEMENT wsql INTO wref,wvalor,wclass,wbasrais,wtipocod,wrefresc,:wrescoriginal DO
    BEGIN
      WEXISTE = 1;

      IF (bdref <> wref) THEN
         BEGIN
           IF (bdref <> 0) THEN
              BEGIN
                IF (prano >= 2014) THEN
                   BEGIN
                     IF (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4)) AND wref = wrescoriginal) THEN
                        bdref = wrefresc;
                   END

                SUSPEND;
              END

           IF (prano >= 2014) THEN
              BEGIN
                IF (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4)) AND wref = wrescoriginal) THEN
                   wmes = CAST(SUBSTRING(CAST(wrefresc AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);
                ELSE
                   wmes = CAST(SUBSTRING(CAST(wref AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);
              END
           ELSE
              wmes = CAST(SUBSTRING(CAST(wref AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);

           IF (wmes = 1) THEN
              wjan = 1;
           IF (wmes = 2) THEN
              wfev = 1;
           IF (wmes = 3) THEN
              wmar = 1;
           IF (wmes = 4) THEN
              wabr = 1;
           IF (wmes = 5) THEN
              wmai = 1;
           IF (wmes = 6) THEN
              wjun = 1;
           IF (wmes = 7) THEN
              wjul = 1;
           IF (wmes = 8) THEN
              wago = 1;
           IF (wmes = 9) THEN
              wset = 1;
           IF (wmes = 10) THEN
              wout = 1;
           IF (wmes = 11) THEN
              wnov = 1;
           IF (wmes = 12) THEN
              wdez = 1;

           bdref = wref;

           BDMULTA = 0;

           IF (prano >= 2014) THEN
              BEGIN
                IF ((wref = wrescoriginal) AND (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4)))) THEN
                   BEGIN
                     SELECT bdfgts40 FROM vrhf_emp_val_grrf(:premp,:prcol,:wrescoriginal,:wrescoriginal, 0) INTO bdmulta;
                   END
              END
           ELSE
              BEGIN
                IF (wref = wrefresc) THEN
                   BEGIN
                     SELECT bdfgts40 FROM vrhf_emp_val_grrf(:premp,:prcol,:wref,:wref, 0) INTO bdmulta;
                   END
              END

           /* Zera todos valores */
           BDAVPREV = 0;
           BDFERIND = 0;
           BDGRATIF = 0;
           BDSINDICAL = 0;
           BDASSISTENCIAL = 0;
           BDCONFEDERATIVA = 0;
           bdbase13 = 0;
           bdbasea13 = 0;
           bdbasec13 = 0;
           bdbasefn = 0;
           bdmensalidade = 0;
         END

      wclass1 = SUBSTRING(wclass FROM 1 FOR 1);
      wclass2 = SUBSTRING(wclass FROM 1 FOR 5);
      wclass3 = SUBSTRING(wclass FROM 1 FOR 7);
      wclass4 = SUBSTRING(wclass FROM 1 FOR 9);

      IF (wbasrais = 'TRUE') THEN
         BEGIN
           wvalaux = wvalor;
           IF (wtipocod = 1) THEN
              wvalaux = wvalaux * -1;


           IF (wclass1 = '4') THEN
              BEGIN
                IF (prano >= 2014) THEN
                   BEGIN
                     IF (wrefresc = 0) THEN
                        bdbasea13 = bdbasea13 + wvalaux;
                   END
                ELSE
                   bdbasea13 = bdbasea13 + wvalaux;
              END
--           // Verba de 13?
           ELSE IF ((wclass1 = '5') OR (wclass2 = '7.060') OR
                   (wclass2 = '7.050') OR (wclass2 = '7.061')) THEN
              BEGIN
                IF (prano >= 2014) THEN
                   BEGIN
                     IF (wrefresc = 0) THEN
                        bdbase13 = bdbase13 + wvalaux;
                   END
                ELSE
                   bdbase13 = bdbase13 + wvalaux;
              END
--           // Verba de Complemento 13?
           ELSE IF ((wclass1 = '6')) THEN
              BEGIN
                IF (prano >= 2014) THEN
                   BEGIN
                     IF (wrefresc = 0) THEN
                        bdbasec13 = bdbasec13 + wvalaux;
                   END
                ELSE
                   bdbasec13 = bdbasec13 + wvalaux;
              END
--           // Demais Verbas participa da folha normal
           ELSE
              BEGIN
                IF ((wclass3 <> '7.001.3') AND (wclass2 <> '7.010') AND (wclass2 <> '7.030') AND (wclass2 <> '7.032') AND (wclass2 <> '7.012') AND
                    (wclass2 <> '7.031') AND (wclass2 <> '7.033') AND (wclass2 <> '7.020') AND (wclass2 <> '7.021')) THEN
                   BEGIN
                     IF (prano >= 2014) THEN
                        BEGIN
                          IF (wrefresc = 0) THEN
                             bdbasefn = bdbasefn + wvalaux;
                        END
                     ELSE
                        bdbasefn = bdbasefn + wvalaux;
                   END
              END
         END

      -- aviso pr?vio indenizado // 7.001.3
      IF (prano >= 2014) THEN
         BEGIN
           IF (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4)) AND wclass3 = '7.001.3') THEN
              bdavprev = bdavprev + wvalor;
         END
      ELSE
         BEGIN
           IF (wclass3 = '7.001.3') THEN
              bdavprev = bdavprev + wvalor;
         END


      -- f?rias indenizadas // 7.020 - 7.021

      IF (prano >= 2014) THEN
         BEGIN
           IF (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4))) THEN
              BEGIN
                IF (((wclass2 = '7.010') OR (wclass2 = '7.012')) OR
                   ((wclass2 = '7.030') OR (wclass2 = '7.031')) OR
                   ((wclass2 = '7.032') OR (wclass2 = '7.033'))) THEN
                   bdferind = bdferind + wvalor;
              END
         END
      ELSE
         BEGIN
           IF (((wclass2 = '7.010') OR (wclass2 = '7.012')) OR
              ((wclass2 = '7.030') OR (wclass2 = '7.031')) OR
              ((wclass2 = '7.032') OR (wclass2 = '7.033'))) THEN
              bdferind = bdferind + wvalor;
         END

      -- gratifica??es // 0.003.0.0
      IF (prano >= 2014) THEN
         BEGIN
           IF (wref = wrefresc) THEN
              BEGIN
                IF (wclass4 = '0.003.0.0') THEN
                   bdgratif = bdgratif + wvalor;
              END
         END
      ELSE
         BEGIN
           IF (wref = wrefresc) THEN
              BEGIN
                IF (wclass4 = '0.003.0.0') THEN
                   bdgratif = bdgratif + wvalor;
              END
         END

      -- multa rescis?ria // 7.001.1.0 ? a multa de FGTS
--      if (wclass4 = '7.001.1.0') then
--         bdmulta = bdmulta + wvalor;

      -- contribui??o sindical // 0.004.0.1 - 0.004.0.0
      IF (prano >= 2014) THEN
         BEGIN
           IF ((wclass4 = '0.004.0.1') OR (wclass4 = '0.004.0.0') OR (wclass4 = '0.710.0.1') OR (wclass4 = '0.710.0.0') OR
               (wclass4 = '4.047.0.1') OR (wclass4 = '4.047.0.0') OR (wclass4 = '5.070.0.1') OR (wclass4 = '5.070.0.0') OR
               (wclass4 = '6.070.0.1') OR (wclass4 = '6.070.0.0')) THEN
              BEGIN
                IF ((wrefresc = 0) OR (wrefresc = wrescoriginal) OR (SUBSTRING(wrefresc FROM 1 FOR 4) <> CAST(prano AS VARCHAR(4)))) THEN
                   bdsindical = bdsindical + wvalor;
              END
         END
      ELSE
         BEGIN
           IF ((wclass4 = '0.004.0.1') OR (wclass4 = '0.004.0.0') OR (wclass4 = '0.710.0.1') OR (wclass4 = '0.710.0.0') OR
               (wclass4 = '4.047.0.1') OR (wclass4 = '4.047.0.0') OR (wclass4 = '5.070.0.1') OR (wclass4 = '5.070.0.0') OR
               (wclass4 = '6.070.0.1') OR (wclass4 = '6.070.0.0')) THEN
              bdsindical = bdsindical + wvalor;
         END

      IF (prano >= 2014) THEN
         BEGIN
           -- contribui??o assistencial // 0.004.0.3
           IF ((wclass4 = '0.004.0.3') OR (wclass4 = '0.710.0.3') OR (wclass4 = '4.047.0.3') OR (wclass4 = '5.070.0.3') OR (wclass4 = '6.070.0.3')) THEN
              BEGIN
                IF ((wrefresc = 0) OR (wrefresc = wrescoriginal) OR (SUBSTRING(wrefresc FROM 1 FOR 4) <> CAST(prano AS VARCHAR(4)))) THEN
                   bdassistencial = bdassistencial + wvalor;
              END
     
           -- contribui??o confederativa // 0.004.0.2
           IF ((wclass4 = '0.004.0.2') OR (wclass4 = '0.710.0.2') OR (wclass4 = '4.047.0.2') OR (wclass4 = '5.070.0.2') OR (wclass4 = '6.070.0.2')) THEN
              BEGIN
                IF ((wrefresc = 0) OR (wrefresc = wrescoriginal) OR (SUBSTRING(wrefresc FROM 1 FOR 4) <> CAST(prano AS VARCHAR(4)))) THEN
                   bdconfederativa = bdconfederativa + wvalor;
              END
     
           -- Mensalidade sindical
           IF ((wclass4 = '0.004.0.0') OR (wclass4 = '0.710.0.0') OR (wclass4 = '4.047.0.0') OR (wclass4 = '5.070.0.0') OR (wclass4 = '6.070.0.0')) THEN
              BEGIN
                IF ((wrefresc = 0) OR (wrefresc = wrescoriginal) OR (SUBSTRING(wrefresc FROM 1 FOR 4) <> CAST(prano AS VARCHAR(4)))) THEN
                   bdmensalidade = bdmensalidade + wvalor;
              END
         END
      ELSE
         BEGIN
           -- contribui??o assistencial // 0.004.0.3
           IF ((wclass4 = '0.004.0.3') OR (wclass4 = '0.710.0.3') OR (wclass4 = '4.047.0.3') OR (wclass4 = '5.070.0.3') OR (wclass4 = '6.070.0.3')) THEN
              bdassistencial = bdassistencial + wvalor;
     
           -- contribui??o confederativa // 0.004.0.2
           IF ((wclass4 = '0.004.0.2') OR (wclass4 = '0.710.0.2') OR (wclass4 = '4.047.0.2') OR (wclass4 = '5.070.0.2') OR (wclass4 = '6.070.0.2')) THEN
              bdconfederativa = bdconfederativa + wvalor;
     
           -- Mensalidade sindical
           IF ((wclass4 = '0.004.0.0') OR (wclass4 = '0.710.0.0') OR (wclass4 = '4.047.0.0') OR (wclass4 = '5.070.0.0') OR (wclass4 = '6.070.0.0')) THEN
              bdmensalidade = bdmensalidade + wvalor;
         END
    END

  IF (wexiste = 1) THEN
     SUSPEND;

  bdmensalidade = 0;
  -- busca valores da ficha financeira para meses que n?o tem informa??es
  wsqlaux = 'select a.bdreffrais,coalesce(a.bdrendfrais,0), coalesce(a.bda13frais,0), coalesce(a.bd13frais,0), coalesce(a.bdferiasrescisaofrais,0), '||
              ' coalesce(a.bdmultarescfrais,0), coalesce(a.bdcontrsindfrais,0), coalesce(a.bdcontassistfrais,0), '||
              ' coalesce(a.bdcontconffrais,0), coalesce(a.bdavisopreviofrais,0), coalesce(a.bdc13frais,0), '||
              ' coalesce(a.bdgratificacaofrais,0), coalesce(BDCONTAASS1FRAIS,0) from vrhf_emp_tficharais a '||
              ' where a.bdcodemp = '||:premp||' and a.bdcodcol = '||:prcol||
              ' and a.bdreffrais = '||:prano;
  bdorigem = 1;
  IF (wjan = 0) THEN
     BEGIN
       wsql = wsqlaux||'01';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wfev = 0) THEN
     BEGIN
       wsql = wsqlaux||'02';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wmar = 0) THEN
     BEGIN
       wsql = wsqlaux||'03';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wabr = 0) THEN
     BEGIN
       wsql = wsqlaux||'04';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wmai = 0) THEN
     BEGIN
       wsql = wsqlaux||'05';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wjun = 0) THEN
     BEGIN
       wsql = wsqlaux||'06';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wjul = 0) THEN
     BEGIN
       wsql = wsqlaux||'07';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wago = 0) THEN
     BEGIN
       wsql = wsqlaux||'08';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wset = 0) THEN
     BEGIN
       wsql = wsqlaux||'09';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wout = 0) THEN
     BEGIN
       wsql = wsqlaux||'10';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wnov = 0) THEN
     BEGIN
       wsql = wsqlaux||'11';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wdez = 0) THEN
     BEGIN
       wsql = wsqlaux||'12';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END
END
^

/* Alter (SP_VALIDA_CNPJ) */
ALTER PROCEDURE SP_VALIDA_CNPJ(PRCNPJ VARCHAR(18))
 RETURNS(BDISVALID VARCHAR(5))
 AS
DECLARE VARIABLE FSOMA INTEGER;
DECLARE VARIABLE FRESULT VARCHAR(5);
DECLARE VARIABLE FCNPJ CHAR(13);
DECLARE VARIABLE FDIGITO CHAR(2);
DECLARE VARIABLE FMULT CHAR(13);
DECLARE VARIABLE FI INTEGER;
DECLARE VARIABLE FDigCnpj INTEGER;
DECLARE VARIABLE FDigMult INTEGER;
DECLARE VARIABLE FResto INTEGER;
DECLARE VARIABLE FFirstDig INTEGER;
DECLARE VARIABLE FSecDig INTEGER;
DECLARE VARIABLE FDigCalc CHAR(2);
BEGIN
  FMULT = '543298765432';
  BDISVALID = 'TRUE';

  /*Retira pontos, barras...*/
  SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(:PRCNPJ) INTO :PRCNPJ;

  /*Se todos os digitos forem iguais ? valido*/
  SELECT BDRESULT FROM SP_DIGITOS_IGUAIS(:PRCNPJ) INTO :FRESULT;
  IF (:FRESULT = 'TRUE') THEN
    BEGIN
      BDISVALID = 'TRUE';
      SUSPEND;
      EXIT;
    END

  FDIGITO = SUBSTRING(:PRCNPJ FROM 13 FOR 2);
  FCNPJ   = SUBSTRING(:PRCNPJ FROM 1 FOR 12);

  /*Verifica se tem letras no CNPJ*/
  SELECT BDRESULT FROM SONUMEROS(:PRCNPJ) INTO :FRESULT;

  IF (:FRESULT = '0') THEN
    BDISVALID = 'FALSE';
  ELSE
  IF (CHAR_LENGTH(:FCNPJ) < 12) THEN
    BDISVALID = 'FALSE';

  FSOMA = 0;
  FI = 1;
  WHILE (:FI <= 12) DO
    BEGIN
      FDigCnpj = CAST(SUBSTRING(:FCNPJ FROM FI FOR 1) AS INTEGER);
      FDigMult = CAST(SUBSTRING(:FMult FROM FI FOR 1) AS INTEGER);
      FSoma    = FSoma + (FDigCnpj * FDigMult);
      FI = :FI + 1;
    END

  FResto = :FSoma - ((:FSoma/11) * 11);

  FFirstDig = 11 - :FResto;

  IF ((:FResto = 1) OR (:FResto = 0)) THEN
    FFirstDig = 0;

  FDigCalc = CAST(:FFirstDig AS CHAR(1));

  FCNPJ = TRIM(FCNPJ) || FDigCalc;

  FMult = '6543298765432';

  IF (CHAR_LENGTH(:FCNPJ) < 13) THEN
    BEGIN
      BDISVALID = 'FALSE';
      SUSPEND;
      EXIT;
    END

  FSoma = 0;
  FI = 1;
  WHILE (FI <= 13) DO
    BEGIN
      FDigCnpj = CAST(SUBSTRING(:FCNPJ FROM :FI FOR 1) AS INTEGER);
      FDigMult = CAST(SUBSTRING(:FMult FROM :FI FOR 1) AS INTEGER);
      FSoma    = :FSoma + (:FDigCnpj * FDigMult);
      FI = :FI + 1;
    END

  FResto = :FSoma - ((:FSoma/11) * 11);
  FSecDig= 11 - FResto;
  IF ((:FResto = 1) OR (:FResto = 0)) THEN
    FSecDig = 0;

  FDigCalc = TRIM(:FDigCalc) || :FSecDig;
  IF (:FDigito <> :FDigCalc) THEN
    BDISVALID = 'FALSE';

  SUSPEND;
END
^

/* Alter (SP_VALIDA_CONTA_ONLINE_TEMP) */
ALTER PROCEDURE SP_VALIDA_CONTA_ONLINE_TEMP(PRCODPLANOONLINE INTEGER,
PRSESSAO INTEGER,
PRENQFED INTEGER,
PRCODCONFIRLP INTEGER)
 AS
DECLARE VARIABLE WCLASSIFIBUSCA VARCHAR(100);
DECLARE VARIABLE WCHAVECONF INTEGER;
DECLARE VARIABLE WACHOUCONTA VARCHAR(5);
DECLARE VARIABLE WCONTADEBPROV INTEGER;
DECLARE VARIABLE WVLRCOFINS NUMERIC(15,2);
DECLARE VARIABLE WVLRIPI NUMERIC(15,2);
DECLARE VARIABLE WVLRPIS NUMERIC(15,2);
DECLARE VARIABLE WVLRICMS NUMERIC(15,2);
DECLARE VARIABLE WVLRCONTAB NUMERIC(15,2);
DECLARE VARIABLE WVLRST NUMERIC(15,2);
DECLARE VARIABLE WCONTACREDPROV INTEGER;
DECLARE VARIABLE WTIPOCONTA INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCLASS VARCHAR(100);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WCODITEMONLINE INTEGER;
DECLARE VARIABLE WCOMPLEMENTO BLOB SUB_TYPE 1 SEGMENT SIZE 1000;
DECLARE VARIABLE WCODTPHI INTEGER;
BEGIN
  /*Remover esse delete, a tabela ? tempor?ria*/
  DELETE FROM TMP_TCFOP_TMOV;

  /*Agrupa os lan?amentos por CFOP e condi??o de pagamento(Vista, prazo e outras) e grava na tabela tempor?ria*/
  /*INSERT INTO TMP_TCFOP_TMOV(BDCONDPGTO, BDCODNAT)*/
  FOR SELECT CASE
               WHEN COALESCE(M.BDCONDPGTO, 0) = 0 THEN 50
               WHEN COALESCE(M.BDCONDPGTO, 0) = 1 THEN 51
               WHEN COALESCE(M.BDCONDPGTO, 0) = 2 THEN 406
             END BDCONDPGTO, I.BDCODNAT,
             SUM(COALESCE(I.BDVLRCONTAB, 0)) BDVLRCONTAB,  SUM(COALESCE(I.BDVLRICMS, 0)) BDVLRICMS,
             SUM(COALESCE(I.BDVLRIPI, 0)) BDVLRIPI,        SUM(COALESCE(I.BDVLRPIS, 0)) BDVLRPIS,
             SUM(COALESCE(I.BDVLRCOFINS, 0)) BDVLRCOFINS,  SUM(COALESCE(I.BDVLRST, 0)) BDVLRST
      FROM TMP_VEF_EMP_TMOVSAI_TEMP M
      JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDSESSAO = M.BDSESSAO)
      WHERE M.BDSESSAO = :PRSESSAO
      GROUP BY M.BDCONDPGTO, I.BDCODNAT
      INTO :wTipoConta, :wCodNat, :wVlrContab, :wVlrIcms, :wVlrIpi, :wVlrPis, :wVlrCofins, :wVlrSt
  DO
    BEGIN
      IF (:wVlrContab > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdcodnat, bdcondpgto, bdcoditemonline) VALUES(:wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 111 /*A vista*/
                                                                                                             WHEN :wTipoConta = 51  THEN 117 /*Prazo*/
                                                                                                             WHEN :wTipoConta = 406 THEN 170 /*Outras*/
                                                                                                        END);

      IF (:wVlrIcms > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdcodnat, bdcondpgto, bdcoditemonline) VALUES(:wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 112
                                                                                                             WHEN :wTipoConta = 51  THEN 118
                                                                                                             WHEN :wTipoConta = 406 THEN 171
                                                                                                        END);

      IF (:wVlrSt > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdcodnat, bdcondpgto, bdcoditemonline) VALUES(:wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 113
                                                                                                             WHEN :wTipoConta = 51  THEN 119
                                                                                                             WHEN :wTipoConta = 406 THEN 172
                                                                                                        END);

      IF (:wVlrIpi > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdcodnat, bdcondpgto, bdcoditemonline) VALUES(:wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 114
                                                                                                             WHEN :wTipoConta = 51  THEN 120
                                                                                                             WHEN :wTipoConta = 406 THEN 173
                                                                                                        END);

      IF (:wVlrPis > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdcodnat, bdcondpgto, bdcoditemonline) VALUES(:wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 115
                                                                                                             WHEN :wTipoConta = 51  THEN 121
                                                                                                             WHEN :wTipoConta = 406 THEN 174
                                                                                                        END);

      IF (:wVlrCofins > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdcodnat, bdcondpgto, bdcoditemonline) VALUES(:wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 116
                                                                                                             WHEN :wTipoConta = 51  THEN 122
                                                                                                             WHEN :wTipoConta = 406 THEN 175
                                                                                                        END);

      wVlrContab = 0;
      wVlrCofins = 0;
      wVlrIcms   = 0;
      wVlrIpi    = 0;
      wVlrPis    = 0;
      wVlrSt     = 0;
    END

  /*Insere na tabela todas as reten??es que v?o ser usadas na importa??o*/
  INSERT INTO TMP_TCFOP_TMOV(bdcoditemonline, bdcodrec)
  SELECT CASE WHEN MOV.BDVLRPIS > 0     THEN 89
              WHEN MOV.BDVLRCOFINS  > 0 THEN 90
              WHEN MOV.BDVLRCSOCIAL > 0 THEN 91
              WHEN MOV.BDVLRIR      > 0 THEN 92
              WHEN MOV.BDINSSRET    > 0 THEN 93
              WHEN MOV.BDISSRET     > 0 THEN 94
         END BDCODITEMONLINE, MOV.BDCODREC
  FROM (
        SELECT R.BDCODRECPIS BDCODREC, 'PIS' BDTIPO, SUM(COALESCE(R.BDVLRPIS, 0)) BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDINSSRET, 0 BDISSRET
        FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
        WHERE R.BDSESSAO = :PRSESSAO
        GROUP BY R.BDCODEMP, R.BDSESSAO, R.BDCODRECPIS
          UNION ALL
        SELECT R.BDCODRECCOFINS BDCODREC, 'COFINS' BDTIPO, 0 BDVLRPIS, SUM(COALESCE(R.BDVLRCOFINS, 0)) BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDINSSRET, 0 BDISSRET
        FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
        WHERE R.BDSESSAO = :PRSESSAO
        GROUP BY R.BDCODEMP, R.BDSESSAO, R.BDCODRECCOFINS
          UNION ALL
        SELECT R.BDCODRECCSOCIAL BDCODREC, 'CSOCIAL' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, SUM(COALESCE(R.BDVLRCSOCIAL, 0)), 0 BDVLRIR, 0 BDINSSRET, 0 BDISSRET
        FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
        WHERE R.BDSESSAO = :PRSESSAO
        GROUP BY R.BDCODEMP, R.BDSESSAO, R.BDCODRECCSOCIAL
          UNION ALL
        SELECT R.BDCODRECIR BDCODREC, 'IR' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, SUM(COALESCE(R.BDVLRIR, 0)) BDVLRIR, 0 BDINSSRET, 0 BDISSRET
        FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
        WHERE R.BDSESSAO = :PRSESSAO
        GROUP BY R.BDCODEMP, R.BDSESSAO, R.BDCODRECIR
          UNION ALL
        SELECT R.BDCODRECINSS BDCODREC, 'INSS' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, SUM(COALESCE(R.BDINSSRET, 0)) BDINSSRET, 0 BDISSRET
        FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
        WHERE R.BDSESSAO = :PRSESSAO
        GROUP BY R.BDCODEMP, R.BDSESSAO, R.BDCODRECINSS
          UNION ALL
        SELECT R.BDCODRECISS BDCODREC, 'ISS' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDINSSRET, SUM(COALESCE(R.BDISSRET, 0)) BDISSRET
        FROM TMP_VEF_EMP_TMOVSAIRET_TEMP R
        WHERE R.BDSESSAO = :PRSESSAO
        GROUP BY R.BDCODEMP, R.BDSESSAO, R.BDCODRECISS
       ) MOV
  WHERE ((MOV.BDVLRPIS > 0) OR (BDVLRCOFINS > 0) OR (BDVLRCSOCIAL > 0) OR (BDVLRIR > 0) OR (BDINSSRET > 0) OR (BDISSRET > 0));

  /*Remover esse delete, a tabela ? tempor?ria*/
  DELETE FROM TCONTAS_ONLINE_TEMP;

  /*Pega as contas dos lan?amentos(CFOPS e condi??es de pagamento) que tem na tabela temporaria*/
  INSERT INTO TCONTAS_ONLINE_TEMP(bdchave, bdcodtipoconta, bdcodnat, bdclassificacao, bdcontadebprov, bdcontacredprov, bdcoditemonline, bdcodplapadrao, BDFORMULA, BDCLASS_TITULO, BDCHAVECONF, BDCLASSCODNAT, BDCOMPLEMENTO, BDCODTPHI)
  SELECT C.BDCHAVE, C.BDCODTIPOCONTA, C.BDCODNAT, C.BDCLASSIFICACAO, C.BDCONTADEBPROV, C.BDCONTACREDPROV, C.BDCODITEMONLINE, C.BDCODPLAPADRAO, C.BDFORMULA, C.BDCLASSIFICACAO, C.BDCHAVE, NAT.BDCLASSIFICACAO, H.BDCOMPLEMENTO, C.BDCODTPHI
  FROM TCONF_CONTAS_ONLINE C
  JOIN TMP_TCFOP_TMOV CF ON(CF.BDCODNAT = C.BDCODNAT AND CF.BDCONDPGTO = C.BDCODTIPOCONTA AND CF.BDCODITEMONLINE = C.BDCODITEMONLINE)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = C.BDCODCOMPHISTPROV)
  LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = C.BDCODNAT)
  WHERE C.BDCODPLANOONLINE = :PRCODPLANOONLINE
  AND C.BDCHAVEVINC IS NULL -- Alt.: 18904 - Para n?o carregar as contas por rateio e evitar "multiple rows"...
  AND NAT.BDCODNAT IS NOT NULL;

  /*Insere as contas que tem c?digo de receita na tabela tempor?ria de contas*/
  INSERT INTO TCONTAS_ONLINE_TEMP (BDCHAVE, BDCONTADEBPROV, BDCLASSIFICACAO, BDCODITEMONLINE, BDCODPLAPADRAO, BDFORMULA, BDCLASS_TITULO, BDCHAVECONF, BDCODREC, BDCOMPLEMENTO, BDCODTPHI)
  SELECT O.BDCHAVE, O.BDCONTADEBPROV, O.BDCLASSIFICACAO, CF.BDCODITEMONLINE, O.BDCODPLAPADRAO, O.BDFORMULA, O.BDCLASSIFICACAO, O.BDCHAVE, CF.BDCODREC, H.BDCOMPLEMENTO, O.BDCODTPHI
  FROM TCONF_CONTAS_ONLINE O
  JOIN (
        SELECT CM.BDCODITEMONLINE, CM.BDCODREC
        FROM TMP_TCFOP_TMOV CM
        WHERE CM.BDCODNAT IS NULL
        AND CM.BDCONDPGTO IS NULL
        AND CM.BDCODREC IS NOT NULL
       ) CF ON(CF.BDCODREC = O.BDCODREC AND CF.BDCODITEMONLINE = O.BDCODITEMONLINE)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = O.BDCODCOMPHISTPROV)
  WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE;

  /*Insere as contas que n?o tem c?digo de receita(Se n?o tiveram conta de d?bito para provis?o j? s?o inconsistentes)*/
  INSERT INTO TCONTAS_ONLINE_TEMP (BDCHAVE, BDCONTADEBPROV, BDCLASSIFICACAO, BDCODITEMONLINE, BDCODPLAPADRAO, BDFORMULA, BDCLASS_TITULO, BDCHAVECONF, BDCODREC, BDCOMPLEMENTO, BDCODTPHI)
  SELECT O.BDCHAVE, O.BDCONTADEBPROV, O.BDCLASSIFICACAO, CF.BDCODITEMONLINE, O.BDCODPLAPADRAO, O.BDFORMULA, O.BDCLASSIFICACAO, O.BDCHAVE, CF.BDCODREC, H.BDCOMPLEMENTO, O.BDCODTPHI
  FROM TCONF_CONTAS_ONLINE O
  JOIN (
        SELECT CM.BDCODITEMONLINE, CM.BDCODREC
        FROM TMP_TCFOP_TMOV CM
        WHERE CM.BDCODNAT IS NULL
        AND CM.BDCONDPGTO IS NULL
        AND CM.BDCODREC = 0 /*0 ? o valor default do campo na tabela de reten??es*/
       ) CF ON(CF.BDCODITEMONLINE = O.BDCODITEMONLINE)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = O.BDCODCOMPHISTPROV)
  WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE
  AND O.BDCODREC IS NULL;

  /*Pega as chaves que est?o sem conta de cred ou deb da provis?o e procura nos outros niveis da cfop
  EX: 5.305.001, 5.305.000, 5.300.000, 5.000.000*/
  wACHOUCONTA   = 'FALSE';
  wCONTADEBPROV = NULL;
  wCONTACREDPROV= NULL;
  wChaveConf    = NULL;
  wClassifiBusca= NULL;
  FOR SELECT C.BDCLASSCODNAT, C.BDCODTIPOCONTA, C.BDCODITEMONLINE, C.BDCHAVE
      FROM TCONTAS_ONLINE_TEMP C
      WHERE ((C.BDCONTADEBPROV IS NULL) OR (C.BDCONTACREDPROV IS NULL))
      AND C.BDCODNAT IS NOT NULL
      AND C.BDCODTIPOCONTA IS NOT NULL
      INTO :wClass, :wTIPOCONTA, :wCodItemOnline, :wCHAVE
  DO
    BEGIN
      wACHOUCONTA = 'FALSE';
      WHILE (:wACHOUCONTA = 'FALSE') DO
        BEGIN
          IF (CHAR_LENGTH(:wClass) = 9) THEN
            wClass = SUBSTRING(:wClass FROM 1 FOR (CHAR_LENGTH(:wClass)-4)); /*Ex: CFOP 5.300.303 fica 5.300*/
          ELSE
          IF (CHAR_LENGTH(:wClass) = 5) THEN
            wClass = SUBSTRING(:wClass FROM 1 FOR (CHAR_LENGTH(:wClass)-4)); /*Ex: CFOP 5.300 fica 5*/
          ELSE
            wAchouConta = 'TRUE';

          IF (:wAchouConta = 'FALSE') THEN
            BEGIN
              SELECT C.BDCONTACREDPROV, C.BDCONTADEBPROV, C.BDCHAVE, C.BDCLASSIFICACAO, H.BDCOMPLEMENTO, C.BDCODTPHI
              FROM TCONF_CONTAS_ONLINE C
              LEFT OUTER JOIN VEF_BASE_TNATOP NT ON(NT.BDCLASSIFICACAO = :wCLASS)
              LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = C.BDCODCOMPHISTPROV)
              WHERE C.BDCODTIPOCONTA = :wTIPOCONTA
              AND C.BDCODNAT = NT.BDCODNAT
              AND C.BDCODITEMONLINE = :wCodItemOnline
              AND C.BDCODPLANOONLINE = :PRCODPLANOONLINE
              INTO :wCONTACREDPROV, :wCONTADEBPROV, :wCHAVECONF, :wClassifiBusca, :wComplemento, :wCodTpHi;
            END

          IF ((((:wCONTACREDPROV IS NULL) OR (:wCONTADEBPROV IS NULL))) AND (:wAchouConta <> 'TRUE')) THEN
            wACHOUCONTA = 'FALSE';
          ELSE
            BEGIN
              IF ((:wCONTADEBPROV IS NOT NULL) AND (:wCONTACREDPROV IS NOT NULL)) THEN
                UPDATE TCONTAS_ONLINE_TEMP SET BDCONTADEBPROV = :wCONTADEBPROV, BDCONTACREDPROV = :wCONTACREDPROV,
                                               BDCHAVECONF = :wChaveConf, BDCLASS_TITULO = :wClassifiBusca, BDCOMPLEMENTO = :wComplemento, BDCODTPHI = :wCodTpHi
                WHERE BDCHAVE = :wCHAVE;

              wACHOUCONTA = 'TRUE';
            END
        END
      wChave = 0;
    END

  wCodItemOnline = NULL;
  wChave         = NULL;
  FOR SELECT CT.bdchave, CT.BDCODITEMONLINE
      FROM TCONTAS_ONLINE_TEMP CT
      JOIN TMP_TCFOP_TMOV O ON(O.BDCODITEMONLINE = CT.BDCODITEMONLINE AND O.BDCODREC IS NOT NULL)
      WHERE CT.BDCONTADEBPROV IS NULL
      INTO :wChave, :wCodItemOnline
  DO
    BEGIN
      wChaveConf     = NULL;
      wContaDebProv  = NULL;
      wClassifiBusca = NULL;
      SELECT CO.BDCONTADEBPROV, CO.BDCLASSIFICACAO, CO.BDCHAVE, H.BDCOMPLEMENTO, CO.BDCODTPHI
      FROM TCONF_CONTAS_ONLINE CO
      LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = CO.BDCODCOMPHISTPROV)
      WHERE CO.BDCODITEMONLINE = :wCodItemOnline
      AND CO.BDCODPLANOONLINE  = :PRCODPLANOONLINE
      AND CO.BDCODREC IS NULL
      INTO :wContaDebProv, :wClassifiBusca, :wChaveConf, :wComplemento, :wCodTpHi;

      IF (:wContaDebProv IS NOT NULL) THEN
        UPDATE TCONTAS_ONLINE_TEMP SET BDCONTADEBPROV = :wContaDebProv, BDCHAVECONF = :wChaveConf, BDCLASS_TITULO = :wClassifiBusca, BDCOMPLEMENTO = :wComplemento, BDCODTPHI = :wCodTpHi
        WHERE BDCHAVE = :wChave;

      wCodItemOnline = NULL;
      wChave         = NULL;
    END

  /*Busca a conta do desconto, caso tenha desconto em algum lan?amento
  SELECT SUM(COALESCE(T.BDDESCONTO, 0)) BDDESCONTO
  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  GROUP BY T.BDCODEMP, T.BDSESSAO
  INTO :wDesconto;*/

  INSERT INTO TCONTAS_ONLINE_TEMP(bdchave, bdcodtipoconta, bdcodnat, bdclassificacao, bdcontadebprov, bdcontacredprov, bdcoditemonline, bdcodplapadrao, BDFORMULA, BDCLASS_TITULO, BDCHAVECONF, BDCLASSCODNAT, BDCOMPLEMENTO, BDCODTPHI)
  SELECT C.BDCHAVE, C.BDCODTIPOCONTA, C.BDCODNAT, C.BDCLASSIFICACAO, C.BDCONTADEBPROV, C.BDCONTACREDPROV, C.BDCODITEMONLINE, C.BDCODPLAPADRAO, C.BDFORMULA,
         C.BDCLASSIFICACAO, C.BDCHAVE, NULL BDCLASSCODNAT, H.BDCOMPLEMENTO, C.BDCODTPHI
  FROM TCONF_CONTAS_ONLINE C
  LEFT OUTER JOIN TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = C.BDCODCOMPHISTPROV)
  WHERE C.BDCODPLANOONLINE = :PRCODPLANOONLINE
  AND C.BDCODITEMONLINE = 88 /*Desconto de sa?da*/
  AND C.BDCONTADEBPROV IS NOT NULL;  

   /*Insere as inconsistencias nos lan?amentos que est?o sem conta de cred e/ou deb da provis?o*/
   EXECUTE PROCEDURE SP_INSERT_INCONSISTENCIAS_CONTA(:PRSESSAO, :PRCODPLANOONLINE, :PRENQFED, :PRCODCONFIRLP);
END
^

/* Alter (SP_VALIDA_EXPORTACAO_SPED) */
ALTER PROCEDURE SP_VALIDA_EXPORTACAO_SPED(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRBLOCO CHAR(4))
 AS
DECLARE VARIABLE WENTRADA INTEGER;
DECLARE VARIABLE WSAIDA INTEGER;
DECLARE VARIABLE WSQL VARCHAR(200);
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WQTDMAX INTEGER;
BEGIN
  wEntrada = 0;
  wSaida   = 1;
  PRBLOCO  = UPPER(:PRBLOCO);

  wSQL =          'SELECT COUNT(S.BDORDEMINCO) BDQTD ';
  wSQL = :wSQL || 'FROM TEXPORTACAO_SPED_INCO S ';
  wSQL = :wSQL || 'WHERE S.BDID = '''||:PRARQUIVO||''' ';
  wSQL = :wSQL || 'GROUP BY S.BDID';

  SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_LIM_INCO_EXPORTACAO') FROM RDB$DATABASE INTO :wQtdMax;
  SETORDEMSEQUENCIAL(0);  

  IF (:PRBLOCO = 'C100') THEN
    BEGIN
  /*****************************************************************************
   *                                   C113                                    *
   ****************************************************************************/
    
   IF (:PRDTINI > '12/31/2016') THEN
     BEGIN
       /*1 - Chave NFE inv?lida!*/
       INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
       SELECT :PRARQUIVO, C113.BDCHAVE, 1, :wEntrada, 'C113' /*Entrada*/
       FROM (
             SELECT MOVINF.BDCHAVE, MOVINF.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE(C113.BDCHAVENFE)) BDISVALID
             FROM (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                   FROM (
                         SELECT M.BDCODEMP, M.BDCHAVE
                         FROM VEF_EMP_TMOVENT M
                         WHERE M.BDCODEMP = :PRCODEMP
                         AND M.BDMODELO IN (1, 4, 55, 100)
                         AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                        ) MOV
                   JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  ) MOVINF                                                                                                                                            /*Modelos: 55, 57*/
             JOIN VEF_EMP_TMOVENTDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC AND C113.BDCODDOCFIS IN(30, 31))
            ) C113
       WHERE C113.BDISVALID = 'FALSE'
       UNION ALL
       SELECT :PRARQUIVO, C113.BDCHAVE, 1, :wSaida, 'C113' /*Sa?da*/
       FROM (
             SELECT MOVINF.BDCHAVE, MOVINF.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE(C113.BDCHAVENFE)) BDISVALID
             FROM (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                   FROM (
                         SELECT M.BDCODEMP, M.BDCHAVE
                         FROM VEF_EMP_TMOVSAI M
                         WHERE M.BDCODEMP = :PRCODEMP
                         AND M.BDMODELO IN (1, 4, 55, 100)
                         AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        ) MOV
                   JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  ) MOVINF                                                                                                                                            /*Modelos: 55, 57*/
             JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC AND C113.BDCODDOCFIS IN(30, 31))
            ) C113
       WHERE C113.BDISVALID = 'FALSE';
     END
      
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/
  /*2 - Produto sem vinculo com a empresa!*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODPROD, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, PRO.BDORDEMPRO, VINC.BDCODPROD, 2, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
       ) ENT
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')))
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, PRO.BDORDEMPRO, VINC.BDCODPROD, 2, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
       ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*3 - O valor total do desconto declarado no Registro C100 n?o confere com o somat?rio dos valores dos descontos declarados nos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, 3, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDORDEM
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) ENT
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
        GROUP BY ENT.BDCODEMP, ENT.BDCHAVE
       ) PRO
  JOIN VEF_EMP_TMOVENT LAN ON(LAN.BDCODEMP = PRO.BDCODEMP AND LAN.BDCHAVE = PRO.BDCHAVE)
  WHERE LAN.BDDESCONTONOTA <> PRO.BDVLRDESC
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, 3, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDORDEM
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) SAI
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
        GROUP BY SAI.BDCODEMP, SAI.BDCHAVE
       ) PRO
  JOIN VEF_EMP_TMOVSAI LAN ON(LAN.BDCODEMP = PRO.BDCODEMP AND LAN.BDCHAVE = PRO.BDCHAVE)
  WHERE LAN.BDDESCONTONOTA <> PRO.BDVLRDESC;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*4 - O valor declarado no campo Valor do PIS, no Registro C100, deve corresponder ? soma dos valores declarados no mesmo campo dos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 4, :wEntrada, 'C170' /*Entrada*/
  FROM (
        --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTPIS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPISPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTPIS <> PRO.BDVLRPISPROD
  UNION ALL
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 4, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTPIS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPISPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTPIS <> PRO.BDVLRPISPROD;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*5 - O valor declarado no campo Valor do Cofins, no Registro C100, deve corresponder ? soma dos valores declarados no mesmo campo dos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 5, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTCOFINS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINSPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTCOFINS <> PRO.BDVLRCOFINSPROD
  UNION ALL
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 5, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTCOFINS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINSPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTCOFINS <> PRO.BDVLRCOFINSPROD;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*6 - Quando o campo ALIQ_ICMS (Al?quota do ICMS) for preenchido com um valor maior que zero no Registro C170, os valores dos campos VL_BC_ICMS e VL_ICMS tamb?m devem ser maiores que zero.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 6, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 ((PRO.BDALIQICMS > 0) AND ((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) AND ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 6, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 ((PRO.BDALIQICMS > 0) AND ((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) AND ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*7 - O campo VL_BC_IPI (Valor da base de c?lculo do IPI) e/ou VL_IPI (Valor do IPI) est?(?o) inconsistente(s) no Registro C170. Observar: Os campos VL_BC_IPI e VL_IPI n?o devem ser maior que 0 (zero) quando a CST-IPI for diferente de: 00 e/ou 50.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 7, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI NOT IN(1, 8) AND ((PRO.BDBCIPI > 0) OR (PRO.BDVLRIPI > 0)))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 7, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI NOT IN(1, 8) AND ((PRO.BDBCIPI > 0) OR (PRO.BDVLRIPI > 0)));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*8 - Registro C170 se os dois ?ltimos d?gitos do C?digo da Situa??o Tribut?ria (CST_ICMS) forem diferentes de: 30, 40, 41,50 e/ou 60.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 8, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTICMS = 1 AND (((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) OR
                                                           ((PRO.BDALIQICMS IS NULL) OR (PRO.BDALIQICMS = 0)) OR
                                                           ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 8, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTICMS = 1 AND (((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) OR
                                                           ((PRO.BDALIQICMS IS NULL) OR (PRO.BDALIQICMS = 0)) OR
                                                           ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*9 - O campo Base de IPI/aliquota/valor do IPI deve ser maior que 0 (zero) se o Campo CST_IPI estiver preenchido com CST?s representativos de receitas tributadas ou opera??es com direito a cr?dito: 00 (Entrada) e/ou 50 (Sa?das).*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 9, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI IN (1, 8) AND (((PRO.BDBCIPI IS NULL) OR (PRO.BDBCIPI = 0)) OR
                                                                ((PRO.BDALIQIPI IS NULL) OR (PRO.BDALIQIPI = 0)) OR
                                                                ((PRO.BDVLRIPI IS NULL) OR (PRO.BDVLRIPI = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 9, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI IN (1, 8) AND (((PRO.BDBCIPI IS NULL) OR (PRO.BDBCIPI = 0)) OR
                                                                ((PRO.BDALIQIPI IS NULL) OR (PRO.BDALIQIPI = 0)) OR
                                                                ((PRO.BDVLRIPI IS NULL) OR (PRO.BDVLRIPI = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*10 - Itens declarados com CFOP de ativo imobilizado devem ser declarados com o tipo do item igual a 08.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 10, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 9
  AND C170.BDCODNAT IN(1406, 1551, 2406, 2551)
  UNION ALL
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 10, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 9
  AND C170.BDCODNAT IN(1406, 1551, 2406, 2551);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*11 - Itens declarados com CFOP de uso e consumo devem ser declarados com o tipo do item igual a 07.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 11, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 8
  AND C170.BDCODNAT IN(1407, 1556, 2407, 2556, 1653, 2653)
  UNION ALL
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 11, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 8
  AND C170.BDCODNAT IN(1407, 1556, 2407, 2556, 1653, 2653);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*12 - Deve ser informado se o C?digo da Situa??o Tribut?ria referente ao IPI (CST_IPI) for igual a: 01,02,03,04,05
    13 - Deve ser informado se o C?digo da Situa??o Tribut?ria referente ao IPI (CST_IPI) for igual a: 51,52,53,54,55*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 12, :wEntrada, 'C110' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND PRO.BDCODCSTIPI IN(2, 3, 4, 5, 6))
  LEFT OUTER JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 13, :wSaida, 'C110' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND PRO.BDCODCSTIPI IN(9, 10, 11, 12, 13))
  LEFT OUTER JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  WHERE INF.BDCHAVE IS NULL; /*N?o existe informa??o complementar para este lan?amento*/
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*14 - Normalmente deve ser informado se os dois ?ltimos d?gitos do C?digo da Situa??o Tribut?ria referente ao ICMS (CST_ICMS) forem iguais a:
         20, 30, 40, 41, 50, 51 e/ou 70. Consulte a legisla??o do seu estado sobre a obrigatoriedade.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 14, :wEntrada, 'C110' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) IN (20, 30, 40, 41, 50, 51, 70)
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 14, :wSaida, 'C110' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) IN (20, 30, 40, 41, 50, 51, 70);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*15 - Diverg?ncia entre CST e CFOP em opera??o sujeita ao regime de substitui??o tribut?ria no Registro C170. O CST deve possuir final 10,30,60 e 70 ou os c?digos 201,202,203 e 500.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 15, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDCODNAT
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE (((MOV.BDCODNAT >= 1401000) AND (MOV.BDCODNAT <= 1415000)) OR ((MOV.BDCODNAT >= 2401000) AND (MOV.BDCODNAT <= 2415000)))
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) NOT IN(10, 30, 60, 70)
  AND CST.BDCSTICMS NOT IN(201, 202, 203, 500);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
    
  /*16 - Diverg?ncia entre CST e CFOP em opera??o de compra de material para uso ou consumo. Para CFOP?s de compra de material para uso ou consumo (1.556 e 2.556), o CST deve ter os 2? e 3? d?gitos iguais a 90 ? outras.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 16, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE MOV.BDCODNAT IN(1556, 2556)
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) <> '90';
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*17 - Foram detectados CFOP(s) de energia el?trica, comunica??o/telecomunica??o e/ou transportes indevidamente declarado(s) no Registro C190.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 17, :wEntrada, 'C190' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO = 1
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND
                                       SUBSTRING(I.BDCODNAT FROM 1 FOR 4) IN(1207, 1153, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 2153, 2207, 2251, 2252, 2253, 2254, 2255, 2256, 2257,
                                                                             3207, 3251, 5153, 5207, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 6153, 6207, 6251, 6252, 6253, 6254,
                                                                             6255, 6256, 6257, 6258, 7207, 7251, 1205, 1301, 1302, 1303, 1304, 1305, 1306, 2205, 2301, 2302, 2303, 2304,
                                                                             2305, 2306, 3205, 3301, 5205, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 6205, 6301, 6302, 6303, 6304, 6305,
                                                                             6306, 6307, 7205, 7301, 1206, 1351, 1352, 1353, 1354, 1355, 1356, 1360, 1931, 1932, 2206, 2351, 2352, 2353,
                                                                             2354, 2355, 2356, 2931, 2932, 3206, 3351, 3352, 3353, 3354, 3355, 3356, 5206, 5351, 5352, 5353, 5354, 5355,
                                                                             5356, 5357, 5359, 5360, 5931, 5932, 6206, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6359, 6360, 7206, 7358))
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 17, :wSaida, 'C190' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO = 1
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND
                                       SUBSTRING(I.BDCODNAT FROM 1 FOR 4) IN(1207, 1153, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 2153, 2207, 2251, 2252, 2253, 2254, 2255, 2256, 2257,
                                                                             3207, 3251, 5153, 5207, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 6153, 6207, 6251, 6252, 6253, 6254,
                                                                             6255, 6256, 6257, 6258, 7207, 7251, 1205, 1301, 1302, 1303, 1304, 1305, 1306, 2205, 2301, 2302, 2303, 2304,
                                                                             2305, 2306, 3205, 3301, 5205, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 6205, 6301, 6302, 6303, 6304, 6305,
                                                                             6306, 6307, 7205, 7301, 1206, 1351, 1352, 1353, 1354, 1355, 1356, 1360, 1931, 1932, 2206, 2351, 2352, 2353,
                                                                             2354, 2355, 2356, 2931, 2932, 3206, 3351, 3352, 3353, 3354, 3355, 3356, 5206, 5351, 5352, 5353, 5354, 5355,
                                                                             5356, 5357, 5359, 5360, 5931, 5932, 6206, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6359, 6360, 7206, 7358))
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM);
    
  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  /*18 - Sem produto.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, MOV.BDCHAVE, 18, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVENT M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  WHERE PRO.BDORDEMPRO IS NULL
  UNION ALL
  SELECT :PRARQUIVO, MOV.BDCHAVE, 18, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVSAI M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  WHERE PRO.BDORDEMPRO IS NULL;
    
  /*19 - Com indicador de pagamento a prazo sem informa??o de parcelas.*/
  /*A partir dos produtos*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, MOV.BDCHAVE, 19, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE
        FROM VEF_EMP_TMOVENT M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO = 1
        AND M.BDCONDPGTO = 1 /*Prazo*/
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVENTPAR PAR ON(PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
  WHERE PAR.BDORDEMPAR IS NULL
  UNION ALL
  SELECT :PRARQUIVO, MOV.BDCHAVE, 19, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVSAI M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND M.BDCONDPGTO = 1 /*Prazo*/        
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON(PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
  WHERE PAR.BDORDEMPAR IS NULL;
    
  /*20 - Existe diferen?a entre base/valor de ICMS da nota e a base/valor de ICMS dos produtos.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 20, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = ENT.BDORDEM)
  WHERE ENT.BDBCICMS <> I.BDBASEICMS
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 20, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
  WHERE SAI.BDBCICMS <> I.BDBASEICMS;
    
  /*21 - Existe diferen?a entre base/valor de IPI da nota e a base/valor de IPI dos produtos.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 21, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = ENT.BDORDEM)
  WHERE ENT.BDBCIPI <> I.BDBASEIPI
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 21, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
  WHERE SAI.BDBCIPI <> I.BDBASEIPI;
    END
  ELSE
  IF (:PRBLOCO = 'D100') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
      SELECT :PRARQUIVO, MOV.BDCHAVE, 22, :wEntrada, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, COALESCE(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))), '') BDCHAVECTEREF
            FROM VEF_EMP_TMOVENT E
            JOIN VEF_EMP_TD100ENT D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE MOV.BDCHAVECTEREF <> ''
      UNION ALL
      SELECT :PRARQUIVO, MOV.BDCHAVE, 22, :wSaida, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, COALESCE(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))), '') BDCHAVECTEREF
            FROM VEF_EMP_TMOVSAI E
            JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE MOV.BDCHAVECTEREF <> '';
    END
END
^

/* empty dependent procedure body */
/* Clear: SP_VALIDA_EXPORTACAO_SPED for: SP_VALIDACHAVE_NFE */
ALTER PROCEDURE SP_VALIDA_EXPORTACAO_SPED(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRBLOCO CHAR(4))
 AS
 BEGIN EXIT; END
^

/* Alter (SP_VALIDACHAVE_NFE) */
ALTER PROCEDURE SP_VALIDACHAVE_NFE(PRCHAVENFE VARCHAR(60))
 RETURNS(BDISVALID DM_BOOLEAN)
 AS
DECLARE VARIABLE WVERIFICADOR INTEGER;
DECLARE VARIABLE WSOMA INTEGER;
BEGIN
  wSoma = 0;

  SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:PRCHAVENFE) INTO :PRCHAVENFE;

  SELECT SUM (
              (CAST(SUBSTRING(:PRCHAVENFE FROM 43 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 42 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 41 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 40 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 39 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 38 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 37 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 36 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 35 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 34 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 33 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 32 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 31 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 30 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 29 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 28 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 27 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 26 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 25 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 24 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 23 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 22 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 21 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 20 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 19 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 18 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 17 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 16 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 15 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 14 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 13 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 12 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 11 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 10 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 9 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 8 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 7 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 6 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 5 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 4 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 3 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 2 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 1 FOR 1) AS INTEGER) * 4)
             )
  FROM RDB$DATABASE
  GROUP BY :PRCHAVENFE
  INTO :wSOMA;

  IF (:wSOMA = 0) THEN
    BEGIN
      BDISVALID = 'FALSE';
      SUSPEND;
    END
  ELSE
    BEGIN
      wSoma = wSoma - (11 * (TRUNC(wSoma / 11)));
      IF ((wSoma = 0) OR (wSoma = 1)) THEN
        BEGIN
          wVerificador = 0;
        END
      ELSE
        BEGIN
          wVerificador = 11 - wSoma;
        END

      IF (wVerificador = (CAST(SUBSTRING(:PRCHAVENFE FROM 44 FOR 1) AS INTEGER))) THEN
        BEGIN
          BDISVALID = 'TRUE';
          SUSPEND;
        END
      ELSE
        BEGIN
          BDISVALID = 'FALSE';
          SUSPEND;
        END
    END
END
^

/* Alter (SP_VEF_DAS_TOTALIZADOR_UF) */
ALTER PROCEDURE SP_VEF_DAS_TOTALIZADOR_UF(PREMP VARCHAR(60),
PRDATAINI VARCHAR(10),
PRDATAFIM VARCHAR(10),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDCODBASESN INTEGER,
BDVLRBASE NUMERIC(18,2),
BDCODFED INTEGER)
 AS
DECLARE VARIABLE WSOBRAS NUMERIC(15,2);
  DECLARE VARIABLE WCONT INTEGER;
  DECLARE VARIABLE WSQL VARCHAR(6000);
  DECLARE VARIABLE WTOTAL NUMERIC(18,2);
  DECLARE VARIABLE WANULACAO NUMERIC(18,2);
BEGIN
  wSQL =         'SELECT tot.BDCODEMP, tot.BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN, SUM(tot.BDVLRBASE) BDVLRBASE, SUM(tot.BDVLRANULACAO) BDVLRANULACAO ';
  wSQL = wSQL || 'FROM ( ';
  wSQL = wSQL ||        'SELECT sai.BDCODEMP, sai.BDSIGLAUF, sai.BDNOMCID, sai.BDCODFED, sai.BDCODBASESN, SUM(sai.BDVLRBASE) BDVLRBASE, 0 BDVLRANULACAO ';
  wSQL = wSQL ||        'FROM ( ';
  wSQL = wSQL ||               'SELECT sai.BDCODEMP, sai.BDCHAVE, sai.BDORDEM, sai.BDCODTER, sai.BDCODBASESN, sai.BDVLRBASE, cid.BDNOMCID, cid.BDCODFED, ';
  wSQL = wSQL ||               '       CASE WHEN uf.BDSIGLAUF = ''EX'' THEN emp.BDSIGLAUF ELSE uf.BDSIGLAUF END BDSIGLAUF ';
  wSQL = wSQL ||               'FROM ( ';
  wSQL = wSQL ||                      'SELECT sai.BDCODEMP, sai.BDCHAVE, saiitens.BDORDEM, sai.BDCODTER, sai.BDCODCID, sn.BDCODBASESN, SUM(sn.BDVLRBASE) BDVLRBASE ';
  wSQL = wSQL ||                      'FROM ( ';
  wSQL = wSQL ||                             'SELECT BDCODEMP, BDCHAVE, BDCODTER, BDCODCID ';
  wSQL = wSQL ||                             'FROM VEF_EMP_TMOVSAI ';
  wSQL = wSQL ||                             'WHERE '||PREMP;
  wSQL = wSQL ||                               'AND (BDCODSITNF NOT IN (2,3,4,5) ) ';
  wSQL = wSQL ||                               'AND BDDATAEMISSAO BETWEEN '''||PRDATAINI||''' AND '''||PRDATAFIM||'''';
  wSQL = wSQL ||                            ') SAI ';
  wSQL = wSQL ||                      'JOIN VEF_EMP_TMOVSAIITENS saiitens ON (saiitens.BDCODEMP = sai.BDCODEMP and saiitens.BDCHAVE = sai.BDCHAVE) ';
  wSQL = wSQL ||                      'JOIN VEF_BASE_TNATOP nat ON (saiitens.BDCODNAT = nat.BDCODNAT) ';
  wSQL = wSQL ||                      'JOIN VEF_EMP_TMOVSAISN sn ON (sn.BDCODEMP = sai.BDCODEMP AND sn.BDCHAVE = sai.BDCHAVE and sn.BDORDEM = saiitens.BDORDEM) ';
  wSQL = wSQL ||                      'WHERE sn.BDCODBASESN IN (18, 19, 20, 21, 22, 23, 24) ';
  wSQL = wSQL ||                        'AND nat.BDNAOLEVARSN <> ''TRUE'' ';
  wSQL = wSQL ||                      'GROUP BY sai.BDCODEMP, sai.BDCHAVE, saiitens.BDORDEM, sai.BDCODTER, sai.BDCODTER, SAI.BDCODCID, sn.BDCODBASESN ';
  wSQL = wSQL ||                     ') sai ';
  wSQL = wSQL ||               'LEFT OUTER JOIN SP_CONSULTAEMPRESAS('||PRREF||', sai.BDCODEMP, 0) emp ON (sai.BDCODEMP = emp.BDCODEMP) ';
  wSQL = wSQL ||               'LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (sai.BDCODTER = ter.BDCODTER) ';
  wSQL = wSQL ||               'LEFT OUTER JOIN TCIDADE cid on (sai.BDCODCID = cid.BDCODCID) ';
  wSQL = wSQL ||               'LEFT OUTER JOIN TUF uf ON (cid.BDCODUF = uf.BDCODUF) ';
  wSQL = wSQL ||              ') sai ';
  wSQL = wSQL ||        'GROUP BY sai.BDCODEMP, sai.BDSIGLAUF, sai.BDNOMCID, sai.BDCODFED, sai.BDCODBASESN ';
  wSQL = wSQL ||        'UNION ALL ';
  wSQL = wSQL ||        'SELECT deb.BDCODEMP, deb.BDSIGLAUF, null as BDNOMCID, null as BDCODFED, deb.BDCODBASESN, 0 as BDVLRBASE, SUM(deb.BDVALORDEB) as BDVLRANULACAO ';
  wSQL = wSQL ||        'FROM ( ';
  wSQL = wSQL ||               'SELECT deb.BDCODEMP, uf.BDSIGLAUF, deb.BDCODBASESN, deb.BDVALORDEB ';
  wSQL = wSQL ||               'FROM VEF_EMP_TPLANILHASNDEB deb ';
  wSQL = wSQL ||               'LEFT OUTER JOIN TUF uf ON (uf.BDCODUF = deb.BDCODUF) ';
  wSQL = wSQL ||               'WHERE deb.'||PREMP;
  wSQL = wSQL ||                 'AND deb.BDREFERENCIA = '||PRREF;
  wSQL = wSQL ||              ') deb ';
  wSQL = wSQL ||        'GROUP BY deb.BDCODEMP, deb.BDSIGLAUF, deb.BDCODBASESN ';
  wSQL = wSQL ||        'UNION ALL '; /* Descontar base de cfop de anula??o das entradas */
  wSQL = wSQL ||        'select ENT.BDCODEMP, ENT.BDSIGLAUF, ENT.BDNOMCID, ent.BDCODFED, ENT.BDCODBASESN, 0 BDVLRBASE, sum(ENT.BDVLRBASE) BDVLRANULACAO ';
  wSQL = wSQL ||        'from ( ';
  wSQL = wSQL ||               'select ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDORDEM, ENT.BDCODTER, ENT.BDCODBASESN, ENT.BDVLRBASE, CID.BDNOMCID, cid.BDCODFED, ';
  wSQL = wSQL ||               '       case when UF.BDSIGLAUF = ''EX'' then EMP.BDSIGLAUF else UF.BDSIGLAUF end BDSIGLAUF ';
  wSQL = wSQL ||               'from ( ';
  wSQL = wSQL ||                      'select ENT.BDCODEMP, ENT.BDCHAVE, ENTITENS.BDORDEM, ENT.BDCODTER, SN.BDCODBASESN, sum(SN.BDVLRBASE) BDVLRBASE ';
  wSQL = wSQL ||                      'from ( ';
  wSQL = wSQL ||                             'select BDCODEMP, BDCHAVE, BDCODTER ';
  wSQL = wSQL ||                             'from VEF_EMP_TMOVENT ';
  wSQL = wSQL ||                             'where '||PREMP;
  wSQL = wSQL ||                               'and (BDCODSITNF not in (2,3,4,5) ) ';
  wSQL = wSQL ||                               'and BDDATAENTRADAENT between '''||PRDATAINI||''' and '''||PRDATAFIM||'''';
  wSQL = wSQL ||                            ') ENT ';
  wSQL = wSQL ||                      'join VEF_EMP_TMOVENTITENS ENTITENS on (ENTITENS.BDCODEMP = ENT.BDCODEMP and ENTITENS.BDCHAVE = ENT.BDCHAVE) ';
  wSQL = wSQL ||                      'join VEF_BASE_TNATOP NAT on (ENTITENS.BDCODNAT = NAT.BDCODNAT) ';
  wSQL = wSQL ||                      'join VEF_EMP_TMOVENTSN SN on (SN.BDCODEMP = ENT.BDCODEMP and SN.BDCHAVE = ENT.BDCHAVE and SN.BDORDEM = ENTITENS.BDORDEM) ';
  wSQL = wSQL ||                      'where SN.BDCODBASESN in (18, 19, 20, 21, 22, 23, 24) ';
  wSQL = wSQL ||                        'and NAT.BDNAOLEVARSN <> ''TRUE'' ';
  wSQL = wSQL ||                      'group by ENT.BDCODEMP, ENT.BDCHAVE, ENTITENS.BDORDEM, ENT.BDCODTER, SN.BDCODBASESN ';
  wSQL = wSQL ||                     ') ENT ';
  wSQL = wSQL ||               'left outer join SP_CONSULTAEMPRESAS(201702, ENT.BDCODEMP, 0) EMP on (ENT.BDCODEMP = EMP.BDCODEMP) ';
  wSQL = wSQL ||               'left outer join VW_TTERCEIRO_SIMPLES TER on (ENT.BDCODTER = TER.BDCODTER) ';
  wSQL = wSQL ||               'left outer join TCIDADE CID on (TER.BDCODCID = CID.BDCODCID) ';
  wSQL = wSQL ||               'left outer join TUF UF on (CID.BDCODUF = UF.BDCODUF) ';
  wSQL = wSQL ||              ') ENT ';
  wSQL = wSQL ||        'group by ENT.BDCODEMP, ENT.BDSIGLAUF, ENT.BDNOMCID, ent.BDCODFED, ENT.BDCODBASESN ';
  wSQL = wSQL ||       ') tot ';
  wSQL = wSQL || 'GROUP BY tot.BDCODEMP, tot.BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN ';

  /* Caso tenha valor na vari?vel de anula??o, h? um valor de anula??o maior que as receitas nesta base em algum estado, por isso deve descontar proporcionalmente dos outros estados da mesma base */
  EXECUTE STATEMENT 'SELECT SUM(IIF(tot.BDVLRBASE > tot.BDVLRANULACAO, (tot.BDVLRBASE - tot.BDVLRANULACAO), 0)) as BDVLRBASE, '||
                    '       SUM(IIF(tot.BDVLRBASE > tot.BDVLRANULACAO, 0, tot.BDVLRANULACAO - tot.BDVLRBASE)) as BDVLRANULACAO '||
                    'FROM ( '||wSQL||' ) tot ' INTO :wTOTAL, :wANULACAO;

  wsobras = wtotal;
  EXECUTE STATEMENT 'SELECT COUNT(BDVLRBASE) FROM (' ||wSQL || ')' INTO wcont;

  FOR EXECUTE STATEMENT 'SELECT tot.BDCODEMP, tot.BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN, SUM(IIF(tot.BDVLRBASE > tot.BDVLRANULACAO, (tot.BDVLRBASE - tot.BDVLRANULACAO), 0)) as BDVLRBASE '||
                        'FROM ( '||wSQL||' ) tot '||
                        'GROUP BY tot.BDCODEMP, tot.BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN ' INTO
    BDCODEMP, BDSIGLAUF, BDNOMCID, BDCODFED, BDCODBASESN, BDVLRBASE DO
  BEGIN
    /* Caso tenha anulacao, desconta do valor da base deste estado a parte proporcional referente a este valor de anula??o */
    IF ((wANULACAO > 0) AND (BDVLRBASE > 0)) THEN
      BEGIN
        BDVLRBASE = BDVLRBASE - ((BDVLRBASE * wANULACAO) / wTOTAL);
      END

    IF (BDVLRBASE < 0) THEN
      BEGIN
        BDVLRBASE = 0;
      END

    wsobras = wsobras - bdvlrbase;
    wcont = wcont - 1;

    IF ((wcont = 0) AND ((wsobras - wanulacao) > 0)) THEN
        bdvlrbase = bdvlrbase - (wsobras - wanulacao);

    IF ((wcont = 0) AND ((wsobras - wanulacao) < 0)) THEN
        bdvlrbase = bdvlrbase - (wanulacao - wsobras);

    SUSPEND;
  END
END
^

/* Alter (SP_VEF_EMP_PODEEXCLUIRVINCPROD) */
ALTER PROCEDURE SP_VEF_EMP_PODEEXCLUIRVINCPROD(PRCODEMP INTEGER,
PRCODPROD INTEGER)
 RETURNS(BDTABELA_VINCULADA VARCHAR(100))
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WTABLE VARCHAR(2000);
DECLARE VARIABLE WSQL VARCHAR(20000);
DECLARE VARIABLE WSQLP VARCHAR(20000);
DECLARE VARIABLE WCAMPO VARCHAR(100);
BEGIN

 WSQLP = 'select x.RDB$RELATION_NAME BDNAME, NULL BDTABELA_VINCULADA ';
 WSQLP = WSQLP||' from RDB$RELATION_CONSTRAINTS x ';
 WSQLP = WSQLP||' join RDB$REF_CONSTRAINTS y on (x.RDB$CONSTRAINT_NAME = y.RDB$CONSTRAINT_NAME) ';
 WSQLP = WSQLP||' join RDB$RELATION_CONSTRAINTS z on (Z.RDB$CONSTRAINT_NAME = y.RDB$CONST_NAME_UQ) ';
 WSQLP = WSQLP||' WHERE x.RDB$CONSTRAINT_TYPE = '||'''FOREIGN KEY'''||' and y.RDB$DELETE_RULE <> '||'''CASCADE''';
 WSQLP = WSQLP||' and Z.RDB$RELATION_NAME = '||'''TCADPRO''';
 WSQLP = WSQLP||' AND x.RDB$RELATION_NAME <> '||'''TCADPRO_VINC''';--TABELA QUE EST? CHAMANDO A ROTINA

 FOR EXECUTE STATEMENT WSQLP
  INTO
    wtable,
    BDTABELA_VINCULADA
  DO
   BEGIN
      WCAMPO = NULL;

      SELECT FIRST 1 f.rdb$field_name BDCAMPO FROM rdb$relations r LEFT JOIN rdb$relation_fields f ON f.rdb$relation_name = r.rdb$relation_name
      WHERE ((r.rdb$relation_name IN (:wtable))) AND (UPPER(F.rdb$field_name) = 'BDCODEMP') ORDER BY r.rdb$relation_name, f.rdb$field_position INTO :WCAMPO;

      IF (WCAMPO IS NOT NULL) THEN
         BEGIN
           WCAMPO = NULL;

           SELECT FIRST 1 f.rdb$field_name BDCAMPO FROM rdb$relations r LEFT JOIN rdb$relation_fields f ON f.rdb$relation_name = r.rdb$relation_name
           WHERE ((r.rdb$relation_name IN (:wtable))) AND (UPPER(F.rdb$field_name) = 'BDCODPROD') ORDER BY r.rdb$relation_name, f.rdb$field_position INTO :WCAMPO;
         END

      IF (WCAMPO IS NOT NULL) THEN
         BEGIN

          wsql = 'SELECT first 1 coalesce(bdcodemp,0) from '||wtable||' where bdcodemp = '||:prcodemp||' and BDCODPROD = '||:PRCODPROD;
    
          WCODEMP = 0;
          FOR EXECUTE STATEMENT wsql
          INTO
            WCODEMP
          DO
          BEGIN
            IF (WCODEMP > 0) THEN
               BEGIN
                 BREAK;
               END
          END
    
          IF (WCODEMP > 0) THEN
            BEGIN
              BDTABELA_VINCULADA = wtable;
              WCODEMP = 0;
              SUSPEND;
            END
         END
   END
END
^

/* Alter (SP_VEF_ENT_FORMULAS_DAPI) */
ALTER PROCEDURE SP_VEF_ENT_FORMULAS_DAPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDCODOPDAPI INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPAPCREDDAPI NUMERIC(15,2),
BDISENTASDAPI NUMERIC(15,2),
BDNTRIBDAPI NUMERIC(15,2),
BDPARBCCREDDAPI NUMERIC(15,2),
BDDIFERIDASTDAPI NUMERIC(15,2),
BDSUSPENSASDAPI NUMERIC(15,2),
BDSTDAPI NUMERIC(15,2),
BDOUTRASDAPI NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODTIPODAPI INTEGER;
DECLARE VARIABLE WVALORDAPI NUMERIC(15,2);
DECLARE VARIABLE WBDOUTRASIPIST NUMERIC(15,2);
DECLARE VARIABLE WOUTRASIPIST NUMERIC(15,2);
DECLARE VARIABLE WOUTRASIPIST2 NUMERIC(15,2);
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WCHAVEAUX INTEGER;
DECLARE VARIABLE WORDEMAUX INTEGER;
DECLARE VARIABLE WREFLANAUX INTEGER;
DECLARE VARIABLE WCODNATAUX INTEGER;
DECLARE VARIABLE WCODOPDAPIAUX INTEGER;
DECLARE VARIABLE WVLRCONTABAUX NUMERIC(15,2);
DECLARE VARIABLE WBASEICMSAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRICMSAUX NUMERIC(15,2);
DECLARE VARIABLE WISENTASICMSAUX NUMERIC(15,2);
DECLARE VARIABLE WISENTASDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRSTAUX NUMERIC(15,2);
DECLARE VARIABLE WOUTRASDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WIMPAPCREDDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WNTRIBDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WPARBCCREDDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WDIFERIDASTDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WSUSPENSASDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WSTDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WCODEMPAUX2 INTEGER;
DECLARE VARIABLE WREFLANAUX2 INTEGER;
DECLARE VARIABLE WCODNATAUX2 INTEGER;
DECLARE VARIABLE WCODOPDAPIAUX2 INTEGER;
DECLARE VARIABLE WVLRCONTABAUX2 NUMERIC(15,2);
DECLARE VARIABLE WBASEICMSAUX2 NUMERIC(15,2);
DECLARE VARIABLE WVLRICMSAUX2 NUMERIC(15,2);
DECLARE VARIABLE WISENTASICMSAUX2 NUMERIC(15,2);
DECLARE VARIABLE WISENTASDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WVLRSTAUX2 NUMERIC(15,2);
DECLARE VARIABLE WOUTRASDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WIMPAPCREDDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WNTRIBDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WPARBCCREDDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WDIFERIDASTDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WSUSPENSASDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WSTDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WIMPRIMIRFINAL INTEGER;
DECLARE VARIABLE WBDCHAVE INTEGER;
DECLARE VARIABLE WBDORDEM INTEGER;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> '')) THEN
     BEGIN
        wwhere = ' where ('||:PRCODEMP;
        wwhere = wwhere||')';
     END

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'(';
       wwhere = wwhere||'AUX.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'AUX.BDREFLAN <= '||:pranomesfinal;
       wwhere = wwhere||')';
     END

/*  wsql = 'select MOV.bdcodemp, MOV.bdchave,itens.bdordem, MOV.bdreflan,nat.BDCODNAT,nat.bdcodopdapi, dapi.bdcodtipodapi, ';
  wsql = wsql || '       coalesce(SUM(itens.BDVLRCONTAB),0) BDVLRCONTAB, coalesce(sum(itens.BDBASEICMS),0) BDBASEICMS, ';
  wsql = wsql || '       coalesce(sum(itens.BDVLRICMS),0) BDVLRICMS, coalesce(sum(itens.BDISENTASICMS),0) BDISENTASICMS, coalesce(sum(itens.BDVLRST),0) BDVLRST,  ';
  wsql = wsql || '       coalesce(sum(dapi.BDVALOR),0) BDVALORDAPI, coalesce(sum(itens.BDVLRIPI + itens.BDVLRST),0) BDOUTRASIPIST, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (1) then SUM(dapi.BDVALOR) else 0 end BDISENTASDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (2) then SUM(dapi.BDVALOR) else 0 end BDNTRIBDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (3) then SUM(dapi.BDVALOR) else 0 end BDPARBCCREDDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (4) then SUM(dapi.BDVALOR) else 0 end BDDIFERIDASTDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (5) then SUM(dapi.BDVALOR) else 0 end BDSUSPENSASDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (6) then SUM(dapi.BDVALOR) else 0 end BDSTDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (7) then SUM(dapi.BDVALOR) else 0 end BDIMPAPCREDDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (8) then SUM(dapi.BDVALOR) else 0 end BDOUTRASDAPI ';
  wsql = wsql || 'from ( ';
  wsql = wsql || '        select * from vef_emp_tmovent aux ';
  wsql = wsql||wwhere;
  wsql = wsql || '     ) MOV ';
  wsql = wsql || 'join vef_emp_tmoventitens itens on ((itens.bdcodemp = MOV.bdcodemp) and (itens.bdchave = MOV.bdchave)) ';
  wsql = wsql || 'join VEF_BASE_TNATOP nat on (itens.bdcodnat = nat.bdcodnat) ';
  wsql = wsql || 'left outer join VEF_EMP_TMOVENTSTDAPI dapi on (dapi.bdcodemp = mov.bdcodemp and dapi.bdchave = mov.bdchave and dapi.bdordem = itens.bdordem) ';
  wsql = wsql || 'where (MOV.BDCODSITNF <> 2) and (nat.bdcodopdapi is not null and nat.bdcodopdapi <> 1) ';
  wsql = wsql || 'group by MOV.bdcodemp, MOV.bdchave,itens.bdordem, MOV.bdreflan,nat.BDCODNAT,nat.bdcodopdapi, dapi.bdcodtipodapi ';
  wsql = wsql || 'order by MOV.bdcodemp, MOV.bdchave,itens.bdordem, MOV.bdreflan,nat.BDCODNAT,nat.bdcodopdapi, dapi.bdcodtipodapi ';
          */
  --alt:# 7279
/*  wsql = '    select D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDBASEICMS, 0)) BDBASEICMS, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRICMS, 0)) BDVLRICMS, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDISENTASICMS, 0)) BDISENTASICMS, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRST, 0)) BDVLRST, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRIPI, 0)) + ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRST, 0)) BDOUTRASIPIST, ';
  wsql = wsql || '         sum(BDVALORDAPI) BDVALORDAPI, ';
  wsql = wsql || '         sum(D.BDISENTASDAPI) BDISENTASDAPI, ';
  wsql = wsql || '         sum(D.BDNTRIBDAPI) BDNTRIBDAPI, ';
  wsql = wsql || '         sum(D.BDPARBCCREDDAPI) BDPARBCCREDDAPI, ';
  wsql = wsql || '         sum(D.BDDIFERIDASTDAPI) BDDIFERIDASTDAPI, ';
  wsql = wsql || '         sum(D.BDSUSPENSASDAPI) BDSUSPENSASDAPI, ';
  wsql = wsql || '         sum(D.BDSTDAPI) BDSTDAPI, ';
  wsql = wsql || '         sum(D.BDIMPAPCREDDAPI) BDIMPAPCREDDAPI, ';
  wsql = wsql || '         sum(D.BDOUTRASDAPI) BDOUTRASDAPI ';
  wsql = wsql || '  from ( ';
  wsql = wsql || '        select MOV.BDCODEMP, MOV.BDCHAVE, mov.bdordem, MOV.BDREFLAN, DAPI.BDCODTIPODAPI, sum(coalesce(DAPI.BDVALOR, 0)) BDVALORDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (1) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDISENTASDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (2) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDNTRIBDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (3) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDPARBCCREDDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (4) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0 ';
  wsql = wsql || '               end BDDIFERIDASTDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (5) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDSUSPENSASDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (6) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDSTDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (7) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDIMPAPCREDDAPI, ';
  wsql = wsql || '               case ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (8) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDOUTRASDAPI  ';
  wsql = wsql || '        from ( ';
  wsql = wsql || '         select mov.bdcodemp,mov.bdchave,mov.bdreflan, i.bdordem from ( ';
  wsql = wsql || '                         select aux.bdcodemp,aux.bdchave,aux.bdreflan ';
  wsql = wsql || '                              from VEF_EMP_TMOVENT AUX  ';
  wsql = wsql||wwhere;
  wsql = wsql || '                       ) MOV ';
  wsql = wsql || '        join vef_emp_tmoventitens i on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave)) mov ';
  wsql = wsql || '        join VEF_EMP_TMOVENTSTDAPI DAPI on (DAPI.BDCODEMP = MOV.BDCODEMP and DAPI.BDCHAVE = MOV.BDCHAVE and dapi.bdordem = mov.bdordem) ';
  wsql = wsql || '        group by MOV.BDCODEMP, MOV.BDCHAVE,mov.bdordem, MOV.BDREFLAN, DAPI.BDCODTIPODAPI, DAPI.BDCODTIPODAPI ';
  wsql = wsql || '        ) D ';
  wsql = wsql || '  join VEF_EMP_TMOVENTITENS ITENS on ((ITENS.BDCODEMP = D.BDCODEMP) and (ITENS.BDCHAVE = D.BDCHAVE) and itens.bdordem = d.bdordem) ';
  wsql = wsql || '  join VEF_BASE_TNATOP NAT on (ITENS.BDCODNAT = NAT.BDCODNAT) ';
  wsql = wsql || '  where (NAT.BDCODOPDAPI is not null and ';
  wsql = wsql || '        NAT.BDCODOPDAPI <> 1)  ';
  wsql = wsql || ' group by D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI ';
  wsql = wsql || ' order by D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI ';
   */

  wsql = '  select BDCODEMP, BDCHAVE, BDORDEM, BDREFLAN, BDCODNAT, BDCODOPDAPI, BDCODTIPODAPI,BDVLRCONTAB, ';
  wsql = wsql || '          BDBASEICMS,BDVLRICMS,BDISENTASICMS,BDVLRST,BDOUTRASIPIST,BDVALORDAPI,BDISENTASDAPI,BDNTRIBDAPI, ';
  wsql = wsql || '          BDPARBCCREDDAPI,BDDIFERIDASTDAPI,BDSUSPENSASDAPI,BDSTDAPI,BDIMPAPCREDDAPI,BDOUTRASDAPI ';
  wsql = wsql || '   from ( ';
  wsql = wsql || '   select D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDBASEICMS, 0)) BDBASEICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRICMS, 0)) BDVLRICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDISENTASICMS, 0)) BDISENTASICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRST, 0)) BDVLRST, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRIPI, 0)) + ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRST, 0)) BDOUTRASIPIST, ';
  wsql = wsql || '          sum(BDVALORDAPI) BDVALORDAPI, ';
  wsql = wsql || '          sum(D.BDISENTASDAPI) BDISENTASDAPI, ';
  wsql = wsql || '          sum(D.BDNTRIBDAPI) BDNTRIBDAPI, ';
  wsql = wsql || '          sum(D.BDPARBCCREDDAPI) BDPARBCCREDDAPI, ';
  wsql = wsql || '          sum(D.BDDIFERIDASTDAPI) BDDIFERIDASTDAPI, ';
  wsql = wsql || '          sum(D.BDSUSPENSASDAPI) BDSUSPENSASDAPI, ';
  wsql = wsql || '          sum(D.BDSTDAPI) BDSTDAPI, ';
  wsql = wsql || '          sum(D.BDIMPAPCREDDAPI) BDIMPAPCREDDAPI, ';
  wsql = wsql || '          sum(D.BDOUTRASDAPI) BDOUTRASDAPI ';
  wsql = wsql || '   from ( ';
  wsql = wsql || '         select MOV.BDCODEMP, MOV.BDCHAVE, mov.bdordem, MOV.BDREFLAN, DAPI.BDCODTIPODAPI, sum(coalesce(DAPI.BDVALOR, 0)) BDVALORDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (1) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDISENTASDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (2) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDNTRIBDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (3) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDPARBCCREDDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (4) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDDIFERIDASTDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (5) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDSUSPENSASDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (6) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDSTDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (7) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDIMPAPCREDDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (8) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDOUTRASDAPI  ';
  wsql = wsql || '         from ( ';
  wsql = wsql || '          select mov.bdcodemp,mov.bdchave,mov.bdreflan, i.bdordem from ( ';
  wsql = wsql || '                          select aux.bdcodemp,aux.bdchave,aux.bdreflan ';
  wsql = wsql || '                               from VEF_EMP_TMOVENT AUX  ';
  wsql = wsql||wwhere;
  wsql = wsql || '                        ) MOV ';
  wsql = wsql || '         join vef_emp_tmoventitens i on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave)) mov ';
  wsql = wsql || '         join VEF_EMP_TMOVENTSTDAPI DAPI on (DAPI.BDCODEMP = MOV.BDCODEMP and DAPI.BDCHAVE = MOV.BDCHAVE and dapi.bdordem = mov.bdordem) ';
  wsql = wsql || '         group by MOV.BDCODEMP, MOV.BDCHAVE,mov.bdordem, MOV.BDREFLAN, DAPI.BDCODTIPODAPI, DAPI.BDCODTIPODAPI ';
  wsql = wsql || '         ) D ';
  wsql = wsql || '   join VEF_EMP_TMOVENTITENS ITENS on ((ITENS.BDCODEMP = D.BDCODEMP) and (ITENS.BDCHAVE = D.BDCHAVE) and itens.bdordem = d.bdordem) ';
  wsql = wsql || '   join VEF_BASE_TNATOP NAT on (ITENS.BDCODNAT = NAT.BDCODNAT) ';
  wsql = wsql || '   where (NAT.BDCODOPDAPI is not null and ';
  wsql = wsql || '         NAT.BDCODOPDAPI <> 1)  ';
  wsql = wsql || '   group by D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI ';
  wsql = wsql || '   union all ';
  wsql = wsql || '   select D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDBASEICMS, 0)) BDBASEICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRICMS, 0)) BDVLRICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDISENTASICMS, 0)) BDISENTASICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRST, 0)) BDVLRST, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRIPI, 0)) + ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRST, 0)) BDOUTRASIPIST, ';
  wsql = wsql || '          sum(BDVALORDAPI) BDVALORDAPI, ';
  wsql = wsql || '          sum(D.BDISENTASDAPI) BDISENTASDAPI, ';
  wsql = wsql || '          sum(D.BDNTRIBDAPI) BDNTRIBDAPI, ';
  wsql = wsql || '          sum(D.BDPARBCCREDDAPI) BDPARBCCREDDAPI, ';
  wsql = wsql || '          sum(D.BDDIFERIDASTDAPI) BDDIFERIDASTDAPI, ';
  wsql = wsql || '          sum(D.BDSUSPENSASDAPI) BDSUSPENSASDAPI, ';
  wsql = wsql || '          sum(D.BDSTDAPI) BDSTDAPI, ';
  wsql = wsql || '          sum(D.BDIMPAPCREDDAPI) BDIMPAPCREDDAPI, ';
  wsql = wsql || '          sum(D.BDOUTRASDAPI) BDOUTRASDAPI ';
  wsql = wsql || '   from ( ';
  wsql = wsql || '         select MOV.BDCODEMP, MOV.BDCHAVE, mov.bdordem, MOV.BDREFLAN, 0 BDCODTIPODAPI, 0 BDVALORDAPI, ';
  wsql = wsql || '                0 BDISENTASDAPI,0 BDNTRIBDAPI,0 BDPARBCCREDDAPI,0 BDDIFERIDASTDAPI,0 BDSUSPENSASDAPI,0 BDSTDAPI,0 BDIMPAPCREDDAPI,0 BDOUTRASDAPI ';
  wsql = wsql || '         from ( ';
  wsql = wsql || '          select mov.bdcodemp,mov.bdchave,mov.bdreflan, i.bdordem from ( ';
  wsql = wsql || '                          select aux.bdcodemp,aux.bdchave,aux.bdreflan ';
  wsql = wsql || '                               from VEF_EMP_TMOVENT AUX  ';
  wsql = wsql||wwhere;
  wsql = wsql || '                        ) MOV ';
  wsql = wsql || '         join vef_emp_tmoventitens i on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave) ';
  wsql = wsql || '         where not exists (select dapi.bdcodemp from VEF_EMP_TMOVENTSTDAPI dapi ';
  wsql = wsql || '                           where dapi.bdcodemp = mov.bdcodemp and dapi.bdchave = mov.bdchave and dapi.bdordem = i.bdordem ';
  wsql = wsql || '                          ) ';
  wsql = wsql || '         ) mov ';
  wsql = wsql || '         group by MOV.BDCODEMP, MOV.BDCHAVE,mov.bdordem, MOV.BDREFLAN, BDCODTIPODAPI,  BDCODTIPODAPI ';
  wsql = wsql || '         ) D ';
  wsql = wsql || '   join VEF_EMP_TMOVENTITENS ITENS on ((ITENS.BDCODEMP = D.BDCODEMP) and (ITENS.BDCHAVE = D.BDCHAVE) and itens.bdordem = d.bdordem) ';
  wsql = wsql || '   join VEF_BASE_TNATOP NAT on (ITENS.BDCODNAT = NAT.BDCODNAT) ';
  wsql = wsql || '   where (NAT.BDCODOPDAPI is not null and ';
  wsql = wsql || '         NAT.BDCODOPDAPI <> 1)  ';
  wsql = wsql || '   group by D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI ';
  wsql = wsql || '   ) ';
  wsql = wsql || '   order by BDCODEMP, BDCHAVE, BDORDEM, BDREFLAN, BDCODNAT, BDCODOPDAPI, BDCODTIPODAPI ';



  wVLRCONTABaux = 0;
  wBASEICMSaux = 0;
  wVLRICMSaux = 0;
  wisentasicmsaux = 0;
  wVLRSTaux = 0;
  WOUTRASIPIST = 0;

  WIMPAPCREDDAPIAUX = 0;
  WISENTASDAPIAUX = 0;
  WNTRIBDAPIAUX = 0;
  WPARBCCREDDAPIAUX = 0;
  WDIFERIDASTDAPIAUX = 0;
  WSUSPENSASDAPIAUX = 0;
  WSTDAPIAUX = 0;
  WOUTRASDAPIAUX = 0;

  WIMPRIMIRFINAL = 0;
  WCHAVEAUX = 0;
  WORDEMAUX = 0;
  WOUTRASIPIST = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    :WBDCHAVE,
    :WBDORDEM,
    BDREFLAN,
    BDCODNAT,
    BDCODOPDAPI,
    :WCODTIPODAPI,
    BDVLRCONTAB,
    BDBASEICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDVLRST,
    :WVALORDAPI,
    :WBDOUTRASIPIST,
    BDISENTASDAPI,
    BDNTRIBDAPI,
    BDPARBCCREDDAPI,
    BDDIFERIDASTDAPI,
    BDSUSPENSASDAPI,
    BDSTDAPI,
    BDIMPAPCREDDAPI,
    BDOUTRASDAPI
  DO
  BEGIN
    WIMPRIMIRFINAL = 1;
    IF ((wcodempaux IS NULL) OR ((wcodempaux = bdcodemp) AND (wREFLANaux = BDREFLAN) AND (wCODNATaux = BDCODNAT))) THEN
       BEGIN
          wcodempaux = bdcodemp;
          wREFLANaux = bdREFLAN;
          wCODNATaux = bdCODNAT;
          wcodopdapiaux = bdcodopdapi;

          IF ((WCHAVEAUX <> WBDCHAVE) OR (WORDEMAUX <> WBDORDEM)) THEN
            BEGIN
              wVLRCONTABaux = wVLRCONTABaux + bdVLRCONTAB;
              wBASEICMSaux = wBASEICMSaux + bdBASEICMS;
              wVLRICMSaux = wVLRICMSaux + bdVLRICMS;
              wisentasicmsaux = wisentasicmsaux + bdisentasicms;
              wVLRSTaux = wVLRSTaux + bdVLRST;
              WOUTRASIPIST = WOUTRASIPIST + WBDOUTRASIPIST;
            END

          WCHAVEAUX = WBDCHAVE;
          WORDEMAUX = WBDORDEM;

          WIMPAPCREDDAPIAUX = WIMPAPCREDDAPIAUX + BDIMPAPCREDDAPI;
          WISENTASDAPIAUX = WISENTASDAPIAUX + BDISENTASDAPI;
          WNTRIBDAPIAUX = WNTRIBDAPIAUX + BDNTRIBDAPI;
          WPARBCCREDDAPIAUX = WPARBCCREDDAPIAUX + BDPARBCCREDDAPI;
          WDIFERIDASTDAPIAUX = WDIFERIDASTDAPIAUX + BDDIFERIDASTDAPI;
          WSUSPENSASDAPIAUX = WSUSPENSASDAPIAUX + BDSUSPENSASDAPI;
          WSTDAPIAUX = WSTDAPIAUX + BDSTDAPI;
          WOUTRASDAPIAUX = WOUTRASDAPIAUX + BDOUTRASDAPI;
       END
    ELSE
       BEGIN
          wcodempaux2 = bdcodemp;
          wREFLANaux2 = bdREFLAN;
          wCODNATaux2 = bdCODNAT;
          wcodopdapiaux2 = bdcodopdapi;
          wVLRCONTABaux2 = bdVLRCONTAB;
          wBASEICMSaux2 = bdBASEICMS;
          wVLRICMSaux2 = bdVLRICMS;
          wisentasicmsaux2 = bdisentasicms;
          wVLRSTaux2 = bdVLRST;
          WOUTRASIPIST2 = WBDOUTRASIPIST;
          WIMPAPCREDDAPIAUX2 = BDIMPAPCREDDAPI;
          WISENTASDAPIAUX2 = BDISENTASDAPI;
          WNTRIBDAPIAUX2 = BDNTRIBDAPI;
          WPARBCCREDDAPIAUX2 = BDPARBCCREDDAPI;
          WDIFERIDASTDAPIAUX2 = BDDIFERIDASTDAPI;
          WSUSPENSASDAPIAUX2 = BDSUSPENSASDAPI;
          WSTDAPIAUX2 = BDSTDAPI;
          WOUTRASDAPIAUX2 = BDOUTRASDAPI;

          bdcodemp = wcodempaux;
          bdREFLAN = wREFLANaux;
          bdCODNAT = wCODNATaux;
          bdcodopdapi = wcodopdapiaux;
          bdVLRCONTAB = wVLRCONTABaux;
          bdBASEICMS = wBASEICMSaux;
          bdVLRICMS = wVLRICMSaux;
          bdisentasicms = wisentasicmsaux;
          bdVLRST = wVLRSTaux;
          WBDOUTRASIPIST = WOUTRASIPIST;
          BDIMPAPCREDDAPI = WIMPAPCREDDAPIAUX;
          BDISENTASDAPI = WISENTASDAPIAUX;
          BDNTRIBDAPI = WNTRIBDAPIAUX;
          BDPARBCCREDDAPI = WPARBCCREDDAPIAUX;
          BDDIFERIDASTDAPI = WDIFERIDASTDAPIAUX;
          BDSUSPENSASDAPI = WSUSPENSASDAPIAUX;
          BDSTDAPI = WSTDAPIAUX;
          BDOUTRASDAPI = WOUTRASDAPIAUX;

          SUSPEND;

          wcodempaux = wcodempaux2;
          wREFLANaux = wREFLANaux2;
          wCODNATaux = wCODNATaux2;
          wcodopdapiaux = wcodopdapiaux2;
          WCHAVEAUX = WBDCHAVE;
          WORDEMAUX = WBDORDEM;
          wVLRCONTABaux = wVLRCONTABaux2;
          wBASEICMSaux = wBASEICMSaux2;
          wVLRICMSaux = wVLRICMSaux2;
          wisentasicmsaux = wisentasicmsaux2;
          wVLRSTaux = wVLRSTaux2;
          WOUTRASIPIST = WOUTRASIPIST2;
          WIMPAPCREDDAPIAUX = WIMPAPCREDDAPIAUX2;
          WISENTASDAPIAUX = WISENTASDAPIAUX2;
          WNTRIBDAPIAUX = WNTRIBDAPIAUX2;
          WPARBCCREDDAPIAUX = WPARBCCREDDAPIAUX2;
          WDIFERIDASTDAPIAUX = WDIFERIDASTDAPIAUX2;
          WSUSPENSASDAPIAUX = WSUSPENSASDAPIAUX2;
          WSTDAPIAUX = WSTDAPIAUX2;
          WOUTRASDAPIAUX = WOUTRASDAPIAUX2;
       END
  END

  IF (WIMPRIMIRFINAL = 1) THEN
    BEGIN
      bdcodemp = wcodempaux;
      bdREFLAN = wREFLANaux;
      bdCODNAT = wCODNATaux;
      bdcodopdapi = wcodopdapiaux;
      bdVLRCONTAB = wVLRCONTABaux;
      bdBASEICMS = wBASEICMSaux;
      bdVLRICMS = wVLRICMSaux;
      bdisentasicms = wisentasicmsaux;
      bdVLRST = wVLRSTaux;
--      WBDOUTRASIPIST = WOUTRASIPIST;
      BDIMPAPCREDDAPI = WIMPAPCREDDAPIAUX;
      BDISENTASDAPI = WISENTASDAPIAUX;
      BDNTRIBDAPI = WNTRIBDAPIAUX;
      BDPARBCCREDDAPI = WPARBCCREDDAPIAUX;
      BDDIFERIDASTDAPI = WDIFERIDASTDAPIAUX;
      BDSUSPENSASDAPI = WSUSPENSASDAPIAUX;
      BDSTDAPI = WSTDAPIAUX;
      BDOUTRASDAPI = WOUTRASDAPIAUX;

      SUSPEND;
  END

END
^

/* Alter (SP_VEF_EXPREG30_GIASP) */
ALTER PROCEDURE SP_VEF_EXPREG30_GIASP(PRCODEMP VARCHAR(10000),
PRREFERENCIAINICIAL INTEGER,
PRREFERENCIAFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDCODEST INTEGER,
BDCODDIPAM VARCHAR(3),
BDVALOR NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WPREFIXONAT INTEGER;
DECLARE VARIABLE WCODESTSP INTEGER;
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIAFINAL, NULL, NULL);

  SELECT FIRST 1 c.bdcodgiars FROM tuf u,tcidade c WHERE u.bdcoduf = c.bdcoduf AND (UPPER(c.bdnomcid) = 'S?O PAULO')  AND UPPER(u.bdsiglauf) = 'SP' INTO WCODESTSP;

  wwhere = '';
  IF (:PRCODEMP IS NOT NULL) THEN
    wwhere = :PRCODEMP;

  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
--       else
--          wwhere = wwhere||' where ';

       wwhere = wwhere||'M.bdreflan >= '||:PRREFERENCIAINICIAL;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'M.bdreflan <= '||:PRREFERENCIAFINAL;
     END

  wsql = 'select ent.bdcodemp,ent.bdreflan referencia,null bdprefixonat, ';
  wsql = wsql||'       upper(ent.bdsiglauf),ent.bdcodest,''1.1'' BDCODDIPAM, ';
  wsql = wsql||'       (coalesce(ent.bdbaseicms, 0) + coalesce(ent.bdisentasicms, 0) + coalesce(ent.bdoutrasicms, 0)) bdVALOR ';
  wsql = wsql||'from (select ent.bdcodemp,ent.bdreflan,uf.bdsiglauf,cid.bdcodgiars bdcodest, ';
  wsql = wsql||'             coalesce(sum(itens.bdbaseicms), 0) bdbaseicms, ';
  wsql = wsql||'             coalesce(sum(itens.bdisentasicms), 0) bdisentasicms, ';
  wsql = wsql||'             coalesce(sum(itens.bdoutrasicms), 0) bdoutrasicms ';
  wsql = wsql||'      from ( select m.* from vef_emp_tmovent m where '||wwhere||' and ( m.bdcodsitnf not in (2,3,4,5) )   ) ent ';
  wsql = wsql||'      inner join vef_emp_tmoventitens itens on itens.bdcodemp = ent.bdcodemp and itens.bdchave = ent.bdchave and substring(itens.bdprefixonat from 1 for 1) = ''1'' ';
  wsql = wsql||'      inner join vw_tterceiro ter on ter.bdcodter = ent.bdcodter and upper(ter.bdpruralter) = ''TRUE'' ';
  wsql = wsql||'      left outer join tcidade cid on cid.bdcodcid = ter.bdcodcid ';
  wsql = wsql||'      left outer join tuf uf on uf.bdcoduf = cid.bdcoduf and uf.bdsiglauf <> ''EX'' ';
  wsql = wsql||'      where upper(uf.BDSIGLAUF) = ''SP'' ';
  wsql = wsql||'        and ( (itens.bdbaseicms > 0) or (itens.bdisentasicms > 0) or (itens.bdoutrasicms > 0) ) ';
  wsql = wsql||'      group by bdcodemp, bdreflan, bdsiglauf, bdcodest) ent ';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDREFERENCIA,
    WPREFIXONAT,
    WSIGLAUF,
    BDCODEST,
    BDCODDIPAM,
    BDVALOR
  DO
  BEGIN
    SUSPEND;
  END

  wsql = 'SELECT m.bdcodemp, m.bdreflan referencia, i.bdprefixonat, upper(u.bdsiglauf),c.BDCODGIARS, NULL BDCODDIPAM, ';
  wsql = wsql||' SUM(coalesce(i.bdbaseicms, 0) + coalesce(i.bdisentasicms, 0) + coalesce(i.bdoutrasicms, 0)) bdVALOR ';
  wsql = wsql||' FROM vef_emp_tmovSAI m, vef_emp_tmovSAIitens i, vw_tterceiro t, tcidade c, tuf u';
  wsql = wsql||' WHERE (i.bdcodemp = m.bdcodemp AND i.bdchave = m.bdchave)';
  wsql = wsql||'   and (m.bdcodsitnf not in (2,3,4,5)) ';
  wsql = wsql||'   and ( (i.bdbaseicms > 0) or (i.bdisentasicms > 0) or (i.bdoutrasicms > 0) ) ';
  wsql = wsql||'   and (t.bdcodter = m.bdcodter)';
  wsql = wsql||'   and (m.bdcodcid = c.bdcodcid and u.bdCODUF = c.bdCODUF)';
  wsql = wsql||'   and (u.bdsiglauf <> '''||'EX'||''')';
  wsql = wsql||'   and (upper(u.bdsiglauf) = ''SP'')';
  wsql = wsql||'   and ((coalesce(i.bdbaseicms, 0) + coalesce(i.bdisentasicms, 0) + coalesce(i.bdoutrasicms, 0)) > 0) AND (';
  wsql = wsql||wwhere;
  wsql = wsql||') and (((i.bdprefixonat >= 5351) and (i.bdprefixonat <= 5399)) or';
  wsql = wsql||'       (((i.bdprefixonat >= 6351) and (i.bdprefixonat <= 6399)) or';
  wsql = wsql||'       ((i.bdprefixonat >= 7351) and (i.bdprefixonat <= 7399)) or';
  wsql = wsql||'       ((i.bdprefixonat >= 5301) and (i.bdprefixonat <= 5349)) or';
  wsql = wsql||'       ((i.bdprefixonat >= 6301) and (i.bdprefixonat <= 6349)) or';
  wsql = wsql||'       ((i.bdprefixonat >= 7301) and (i.bdprefixonat <= 7349)) or';
  wsql = wsql||'       ((i.bdprefixonat >= 5251) and (i.bdprefixonat <= 5299)) or';
  wsql = wsql||'       ((i.bdprefixonat >= 6251) and (i.bdprefixonat <= 6299)) or';
  wsql = wsql||'       ((i.bdprefixonat >= 7251) and (i.bdprefixonat <= 7299))) ) ';
  wsql = wsql||'group by m.bdcodemp, referencia, i.bdprefixonat, u.bdsiglauf,c.BDCODGIARS';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDREFERENCIA,
    WPREFIXONAT,
    WSIGLAUF,
    BDCODEST,
    BDCODDIPAM,
    BDVALOR
  DO
  BEGIN
--    IF (WSIGLAUF = 'SP') THEN
--       BDCODEST = WCODESTSP;

    -- Transportes
    IF (((wprefixonat >= 5351) AND (wprefixonat <= 5399)) OR
       ((wprefixonat >= 6351) AND (wprefixonat <= 6399)) OR
       ((wprefixonat >= 7351) AND (wprefixonat <= 7399))) THEN
       BDCODDIPAM = '2.3';
    ELSE
       -- Comunica??es
       IF (((wprefixonat >= 5301) AND (wprefixonat <= 5349)) OR
          ((wprefixonat >= 6301) AND (wprefixonat <= 6349)) OR
          ((wprefixonat >= 7301) AND (wprefixonat <= 7349))) THEN
          BDCODDIPAM = '2.4';
       ELSE
          -- Energia El?trica
          IF (((wprefixonat >= 5251) AND (wprefixonat <= 5299)) OR
             ((wprefixonat >= 6251) AND (wprefixonat <= 6299)) OR
             ((wprefixonat >= 7251) AND (wprefixonat <= 7299))) THEN
             BDCODDIPAM = '2.5';
    SUSPEND;
  END

END
^

/* Alter (SP_VEF_LIVROENTRADA) */
ALTER PROCEDURE SP_VEF_LIVROENTRADA(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRIMPSUFIXONAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAENTRADAENT DATE,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDCODTER INTEGER,
BDCODCID INTEGER,
BDNOMETER VARCHAR(100),
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDSIGLAUF VARCHAR(2),
BDCODSITNF INTEGER,
BDVLRCONTAB NUMERIC(18,6),
BDPREFIXONAT INTEGER,
BDBASEICMS NUMERIC(18,6),
BDBASEICMSVARALIQ NUMERIC(18,6),
BDALIQICMS NUMERIC(18,6),
BDVLRICMS NUMERIC(18,6),
BDISENTASICMS NUMERIC(18,6),
BDOUTRASICMS NUMERIC(18,6),
BDBASEIPI NUMERIC(18,6),
BDDIFALIQENT NUMERIC(18,6),
BDVLRIPI NUMERIC(18,6),
BDISENTASIPI NUMERIC(18,6),
BDOUTRASIPI NUMERIC(18,6),
BDBASEST NUMERIC(18,6),
BDVLRST NUMERIC(18,6),
BDNOMEOBS VARCHAR(100),
BDLINHABRANCO VARCHAR(1),
BDLANCVARALIQ INTEGER,
BDVALNTRIBST NUMERIC(18,6),
BDICMSRETENT NUMERIC(18,6),
BDBCSTNAORET NUMERIC(18,6),
BDVLRSTNAORET NUMERIC(18,6),
BDBCSTNAORETRE NUMERIC(18,6),
BDVLRSTNAORETRE NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE FDIVOUTRASICMS NUMERIC(18,6);
DECLARE VARIABLE FDIVBASEICMS NUMERIC(18,6);
DECLARE VARIABLE FDIVALIQICMS NUMERIC(18,6);
DECLARE VARIABLE FDIVVLRICMS NUMERIC(18,6);
DECLARE VARIABLE FDIVISENTASICMS NUMERIC(18,6);
DECLARE VARIABLE BDCODEMP_BKP INTEGER;
DECLARE VARIABLE BDCHAVE_BKP INTEGER;
DECLARE VARIABLE FORDEMALIQ NUMERIC(18,6);
DECLARE VARIABLE BDORDEM_BKP INTEGER;
DECLARE VARIABLE FSTREGESP VARCHAR(5);
DECLARE VARIABLE FBCSTNAORET NUMERIC(18,6);
DECLARE VARIABLE FVLRSTNAORET NUMERIC(18,6);
BEGIN

  WSQL = 'select m.BDCODEMP, m.bdreflan, m.BDDATAENTRADAENT, m.BDCHAVE, I.BDORDEM, m.bdcodter, t.bdcodcid,t.BDNOMETER,t.BDCGCTER,t.bdieter, m.BDESPECIE, m.BDSERIE||Coalesce(M.BDSUBSERIE,'''') BDSERIE, m.BDNUMDOCINI, m.BDDATAEMISSAO, u.BDSIGLAUF,';
  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDCODSITNF, i.BDVLRCONTAB, i.BDPREFIXONAT, i.BDBASEICMS, ';
  ELSE
     WSQL = WSQL||' m.BDCODSITNF, i.BDVLRCONTAB, i.BDCODNAT BDPREFIXONAT, i.BDBASEICMS, ';

  --WSQL = WSQL||' a.BDBASEICMS BDBASEICMSVARALIQ, ';--alt.:3860
  WSQL = WSQL||' case when a.bdordemicms is not null then coalesce(';

  WSQL = WSQL||' case ';
  WSQL = WSQL||' when A.bdbaseredicms > 0 then A.bdbaseredicms ';
  WSQL = WSQL||' else A.BDBASEICMS ';
  WSQL = WSQL||' end ';

  WSQL = WSQL||' ,0) else A.BDBASEICMS end BDBASEICMSVARALIQ, ';

  WSQL = WSQL||' i.BDALIQICMS, i.BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI,i.BDDIFALIQENT, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, i.bdbasest,i.bdvlrst, Coalesce(i.bdobservacao, o.bdnomeobs) bdnomeobs,';

  --WSQL = WSQL||' sum(a.bdoutrasicms) bddivoutrasicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdoutrasicms,0) else A.bdoutrasicms end) bddivoutrasicms, ';
  --WSQL = WSQL||' sum(a.bdbaseredicms) bdDIVbaseicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(';
  --WSQL = WSQL||' A.bdbaseredicms';  -- alt.:3860 - na importa??o esse campo vem zerado. Por isso ele calculado aqui
  WSQL = WSQL||' case when a.bdredbcicms = 0 then A.BDBASEICMS when a.bdredbcicms = 100 then 0 else A.BDBASEICMS * ((100 - a.bdredbcicms)/100) end ';
  WSQL = WSQL||' ,0) else A.bdbaseredicms end) bdDIVbaseicms, ';

  --WSQL = WSQL||' a.bdaliqicms bdDIValiqicms, ';--alt.:3860
  WSQL = WSQL||' case when a.bdordemicms is not null then coalesce(A.bdaliqicms,0) else A.bdaliqicms end bdDIValiqicms, ';
  --WSQL = WSQL||' sum(a.bdvlricms) bdDIVvlricms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdvlricms,0) else A.bdvlricms end) bdDIVvlricms, ';
  --WSQL = WSQL||' sum(a.bdisentasicms) bdDIVisentasicms,';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdisentasicms,0) else A.bdisentasicms end) bdDIVisentasicms, ';

  wSQL = WSQL||' case when (a.bdaliqicms = 0) then 999.0 end bdordemaliq, a.bdchave bdLancVarAliq, i.BDVALNTRIBST, i.BDICMSRETENT ';
  WSQL = WSQL||' from (select m.BDCODEMP, m.BDREFLAN, m.BDDATAENTRADAENT, m.BDCHAVE, m.BDCODTER, m.BDESPECIE, m.BDSERIE, m.BDSUBSERIE, m.BDNUMDOCINI, m.BDDATAEMISSAO, m.BDCODSITNF ';
  WSQL = WSQL||'       from VEF_EMP_TMOVENT m ';

  IF (:prcodemp IS NULL) THEN
     WSQL = WSQL||'       where (BDDATAENTRADAENT between '''||:PRDATAINI||''' and '''||:PRDATAFIM||''') ';
  ELSE
     WSQL = WSQL||'       where ('||:PRCODEMP||') and (BDDATAENTRADAENT between '''||:PRDATAINI||''' and '''||:PRDATAFIM||''')  ';

  WSQL = WSQL||'       ) m ';
  WSQL = WSQL||' inner join VEF_EMP_TMOVENTITENS i on (m.bdcodemp = i.bdcodemp and m.bdchave = i.bdchave)';
  WSQL = WSQL||' left outer join VEF_EMP_TMOVENTVARALIQ a on (m.bdcodemp = a.bdcodemp and m.bdchave = a.bdchave and I.BDORDEM = a.BDORDEM)';
  WSQL = WSQL||' left outer join vw_tterceiro t on (m.bdcodter = t.bdcodter)';
  WSQL = WSQL||' left outer join TCIDADE c on (t.bdcodcid = c.bdcodcid)';
  WSQL = WSQL||' left outer join TUF u on (c.bdcoduf = u.bdcoduf)';
  WSQL = WSQL||' left outer join VEF_BASE_TOBSERVACAO o on (o.bdcodobs = i.bdcodobs)';

  WSQL = wSQL||' group by m.BDCODEMP, m.bdreflan, m.BDDATAENTRADAENT, m.BDCHAVE, I.BDORDEM, m.bdcodter, t.bdcodcid,t.BDNOMETER,t.BDCGCTER,t.bdieter, ';
  WSQL = wSQL||' m.BDESPECIE, BDSERIE, m.BDNUMDOCINI, m.BDDATAEMISSAO, u.BDSIGLAUF,';
  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDCODSITNF, i.BDVLRCONTAB, i.BDPREFIXONAT, i.BDBASEICMS, BDBASEICMSVARALIQ, i.BDALIQICMS, ';
  ELSE
     WSQL = WSQL||' m.BDCODSITNF, i.BDVLRCONTAB, i.BDCODNAT, i.BDBASEICMS, BDBASEICMSVARALIQ, i.BDALIQICMS, ';

  WSQL = WSQL||' i.BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI,i.BDDIFALIQENT, i.BDVLRIPI, i.bdisentasipi, ';
  WSQL = WSQL||' i.bdoutrasipi, i.bdbasest,i.bdvlrst, bdnomeobs, bdDIValiqicms, bdLancVarAliq, i.BDVALNTRIBST, i.BDICMSRETENT,bdordemaliq ';

  WSQL = WSQL||' order by m.BDCODEMP, m.bdreflan, m.BDDATAENTRADAENT, m.bdchave, I.BDORDEM, bdaliqicms, bdordemaliq';


  BDCODEMP_BKP = 0;
  BDCHAVE_BKP = 0;
  BDORDEM_BKP = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDREFLAN,
    BDDATAENTRADAENT,
    BDCHAVE,
    BDORDEM,
    BDCODTER,
    BDCODCID,
    BDNOMETER,
    BDCGCTER,
    BDIETER,
    BDESPECIE,
    BDSERIE,
    BDNUMDOCINI,
    BDDATAEMISSAO,
    BDSIGLAUF,
    BDCODSITNF,
    BDVLRCONTAB,
    BDPREFIXONAT,
    BDBASEICMS,
    BDBASEICMSVARALIQ,
    BDALIQICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDBASEIPI,
    BDDIFALIQENT,
    BDVLRIPI,
    BDISENTASIPI,
    BDOUTRASIPI,
    BDBASEST,
    BDVLRST,
    BDNOMEOBS,
    FDIVOUTRASICMS,
    FDIVBASEICMS,
    FDIVALIQICMS,
    FDIVVLRICMS,
    FDIVISENTASICMS,
    FORDEMALIQ,
    bdLancVarAliq,
    BDVALNTRIBST,
    BDICMSRETENT
  DO
  BEGIN
    IF ((BDCODEMP = BDCODEMP_BKP) AND (bdchave = BDCHAVE_BKP) AND (BDORDEM_BKP = BDORDEM)) THEN
       BEGIN
          BDLINHABRANCO = 'S';
          BDVLRCONTAB = 0;
          BDBASEIPI = 0;
          BDVLRIPI = 0;
          BDISENTASIPI = 0;
          BDOUTRASIPI = 0;
          BDBASEST = 0;
          BDVLRST = 0;
          BDDIFALIQENT = 0;
          BDVALNTRIBST = 0;
          BDICMSRETENT = 0;
       END
    ELSE
       BDLINHABRANCO = 'N';

    IF (BDLINHABRANCO = 'S') THEN
       BEGIN
         BDBCSTNAORET = 0;
         BDVLRSTNAORET = 0;
         BDBCSTNAORETRE = 0;
         BDVLRSTNAORETRE = 0;
       END
    ELSE
       BEGIN
         BDBCSTNAORET = 0;
         BDVLRSTNAORET = 0;
         BDBCSTNAORETRE = 0;
         BDVLRSTNAORETRE = 0;

         WSQL = 'select mva.bdregesp, sum(mva.BDBCRETENCAO) BDBCRETENCAO, sum(mva.BDVLRIMPREC) BDVLRIMPREC from vef_emp_tmoventmva mva';
         WSQL = WSQL||' where mva.bdcodemp = '||BDCODEMP||' and mva.bdchave = '||BDCHAVE||' and mva.bdordem = '||BDORDEM;
         WSQL = WSQL||' group by mva.bdregesp';

         FOR EXECUTE STATEMENT wsql
         INTO
           FSTREGESP,
           FBCSTNAORET,
           FVLRSTNAORET
         DO
         BEGIN
           IF (FSTREGESP = 'TRUE') THEN
              BEGIN
                BDBCSTNAORETRE = FBCSTNAORET;
                BDVLRSTNAORETRE = FVLRSTNAORET;
              END
           ELSE
              BEGIN
                BDBCSTNAORET = FBCSTNAORET;
                BDVLRSTNAORET = FVLRSTNAORET;
              END
         END
       END

    IF (FDIVOUTRASICMS IS NOT NULL) THEN
       BDOUTRASICMS = FDIVOUTRASICMS;

    IF ((FDIVBASEICMS IS NOT NULL) AND (FDIVBASEICMS > 0)) THEN
       BDBASEICMS = FDIVBASEICMS;

    IF ((BDBASEICMSVARALIQ IS NOT NULL) AND (BDBASEICMSVARALIQ > 0)) THEN
       BDBASEICMS = BDBASEICMSVARALIQ;  

    IF (FDIVALIQICMS IS NOT NULL) THEN
       BDALIQICMS = FDIVALIQICMS;

    IF (FDIVVLRICMS IS NOT NULL) THEN
       BDVLRICMS = FDIVVLRICMS;

    IF (FDIVISENTASICMS IS NOT NULL) THEN
       BDISENTASICMS = FDIVISENTASICMS;

    BDCODEMP_BKP = BDCODEMP;
    BDCHAVE_BKP = BDCHAVE;
    BDORDEM_BKP = BDORDEM;

    SUSPEND;
  END
END
^

/* Alter (SP_VEF_LIVROICMSMG) */
ALTER PROCEDURE SP_VEF_LIVROICMSMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDNUMCAMPO INTEGER,
BDDESCFORM VARCHAR(150),
BDCODQUADRO INTEGER,
BDCODTIPO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDSEQLIVRO VARCHAR(3),
BDTITULOQ VARCHAR(150),
BDDESCQ VARCHAR(150),
BDVALOR NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select t.BDCODEMP, t.BDREFERENCIA, empresas2.BDNOMEMP, t.BDNUMCAMPO, TCONFGIAMGFORM.BDDESCFORM, TCONF.bdcodquadro, TCONF.bdcodtipo ,TCONF.BDDESCQUADRO, TCONFGIAMGFORM.BDSEQLIVRO, null bdtituloq, null bddescq, t.BDVALOR ';
  wsql = wsql || 'from VEF_EMP_TGIAMGGERREG t ';
  wsql = wsql || 'join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = t.bdcodemp) ';
  wsql = wsql || 'join VEF_BASE_TEMPPARESTMG parmg on (parmg.bdcodemp = empresas2.bdcodemp and parmg.bdrefemp = empresas2.BDEMPREF) ';
  wsql = wsql || 'join VEF_ESTADOS_TCONFGIAMGQ TCONF on (TCONF.bdcodquadro = t.bdcodquadro) ';
  wsql = wsql || 'join VEF_ESTADOS_TCONFGIAMGFORM TCONFGIAMGFORM on (TCONFGIAMGFORM.bdcodconf = parmg.bdcodconfgiamg and  TCONFGIAMGFORM.bdcodquadro = T.BDCODQUADRO and TCONFGIAMGFORM.bdnumcampo = T.BDNUMCAMPO) ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';
  ELSE
     wwhere = wwhere||' where ';

   wwhere = wwhere||' (((TCONFGIAMGFORM.BDSEQLIVRO is not NULL) and (TCONFGIAMGFORM.BDSEQLIVRO <> ''''))';
   wwhere = wwhere||' or ((t.bdnumcampo in (2,5)) and (TCONF.bdcodtipo = 180))';
   wwhere = wwhere||' or ((t.bdnumcampo in (5)) and (TCONF.bdcodtipo = 187)))';

  wsql = wsql||wwhere || ' order by t.bdcodemp, t.bdreferencia desc, TCONFGIAMGFORM.BDSEQLIVRO' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDREFERENCIA,
    BDNOMEMP,
    BDNUMCAMPO,
    BDDESCFORM,
    bdcodquadro,
    bdcodtipo,
    BDDESCQUADRO,
    BDSEQLIVRO,
    bdtituloq,
    bddescq,
    BDVALOR
  DO
  BEGIN
     IF ((BDSEQLIVRO = '001') OR (BDSEQLIVRO = '002') OR (BDSEQLIVRO = '003') OR (BDSEQLIVRO = '004')) THEN
        BEGIN
           bdtituloq = 'DÉBITO DO IMPOSTO';
           bddescq = 'DÉBITO';
        END
     ELSE
     IF ((BDSEQLIVRO = '005') OR (BDSEQLIVRO = '006') OR (BDSEQLIVRO = '007') OR (BDSEQLIVRO = '008') OR (BDSEQLIVRO = '009') OR (BDSEQLIVRO = '010')) THEN
        BEGIN
           bdtituloq = 'CRÉDITO DO IMPOSTO';
           bddescq = 'CRÉDITO';
        END
     ELSE
     IF ((BDSEQLIVRO = '011') OR (BDSEQLIVRO = '012') OR (BDSEQLIVRO = '013') OR (BDSEQLIVRO = '014')) THEN
        BEGIN
           bdtituloq = 'APURAÇÃO DO SALDO';
           bddescq = 'SALDO';
        END

     SUSPEND;
  END
END
^

/* Alter (SP_VEF_LIVROSAIDA) */
ALTER PROCEDURE SP_VEF_LIVROSAIDA(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRIMPSUFIXONAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAEMISSAO DATE,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDCODTER INTEGER,
BDCODCID INTEGER,
BDNOMETER VARCHAR(100),
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDNUMDOCINI INTEGER,
BDNUMDOCFIM INTEGER,
BDCODSITNF INTEGER,
BDSIGLAUF VARCHAR(2),
BDVLRCONTAB NUMERIC(18,6),
BDPREFIXONAT INTEGER,
BDBASEICMS NUMERIC(18,6),
BDALIQICMS NUMERIC(18,6),
BDVLRICMS NUMERIC(18,6),
BDISENTASICMS NUMERIC(18,6),
BDOUTRASICMS NUMERIC(18,6),
BDBASEIPI NUMERIC(18,6),
BDVLRIPI NUMERIC(18,6),
BDISENTASIPI NUMERIC(18,6),
BDOUTRASIPI NUMERIC(18,6),
BDBASEST NUMERIC(18,6),
BDVLRST NUMERIC(18,6),
BDNOMEOBS VARCHAR(100),
BDLINHABRANCO VARCHAR(1),
BDIMPSOMENTECFOP VARCHAR(1),
BDVLRCONTABTOT NUMERIC(18,6),
BDLANCVARALIQ INTEGER,
BDSAIREDZ VARCHAR(1),
BDOBSERVACAO VARCHAR(100),
BDVALGTFINAL NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQLTOT VARCHAR(32700);
DECLARE VARIABLE FDIVOUTRASICMS NUMERIC(18,6);
DECLARE VARIABLE FDIVBASEICMS NUMERIC(18,6);
DECLARE VARIABLE FDIVALIQICMS NUMERIC(18,6);
DECLARE VARIABLE FDIVVLRICMS NUMERIC(18,6);
DECLARE VARIABLE FDIVISENTASICMS NUMERIC(18,6);
DECLARE VARIABLE BDCODEMP_BKP INTEGER;
DECLARE VARIABLE BDCHAVE_BKP INTEGER;
DECLARE VARIABLE BDORDEM_BKP INTEGER;
DECLARE VARIABLE BDPREFIXONAT_BKP INTEGER;
DECLARE VARIABLE WVLRCONT NUMERIC(18,6);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WNAT INTEGER;
DECLARE VARIABLE WSTTRANSPORTE NUMERIC(15,6);
BEGIN

  WSQL = 'select m.BDCODEMP, m.BDREFLAN, m.bddataemissao, m.BDCHAVE, I.BDORDEM, m.bdcodter, m.bdcodcid,t.BDNOMETER,t.BDCGCTER,t.bdieter, m.BDESPECIE, m.BDSERIE||Coalesce(M.BDSUBSERIE,'''') BDSERIE, m.BDNUMDOCINI, m.bdnumdocfim, ';
  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDCODSITNF, u.BDSIGLAUF, i.BDVLRCONTAB, i.BDPREFIXONAT, i.BDBASEICMS, i.BDALIQICMS, i.BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, ';
  ELSE
     WSQL = WSQL||' m.BDCODSITNF, u.BDSIGLAUF, i.BDVLRCONTAB, i.BDCODNAT BDPREFIXONAT, i.BDBASEICMS, i.BDALIQICMS, i.BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, ';

  WSQL = WSQL||' i.bdbasest, i.bdvlrst, CASE WHEN ((Coalesce(i.bdobservacao, o.bdnomeobs) is null) and (i.bdsttransporte > 0)) THEN '||'''ICMS ST transporte R$'''||'||CAST(CAST(i.bdsttransporte as numeric(15,2)) as VARCHAR(25)) ELSE Coalesce(i.bdobservacao, o.bdnomeobs) END bdnomeobs,';

  --WSQL = WSQL||' a.bdaliqicms bdDIValiqicms, ';--alt.:3860
  WSQL = WSQL||' case when a.bdordemicms is not null then coalesce(A.bdaliqicms,0) else A.bdaliqicms end bdDIValiqicms, ';
  --WSQL = WSQL||' sum(a.bdoutrasicms) bddivoutrasicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdoutrasicms,0) else A.bdoutrasicms end) bddivoutrasicms, ';
  --WSQL = WSQL||' sum(a.bdbaseredicms) bdDIVbaseicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(';
  --WSQL = WSQL||' A.bdbaseredicms ';-- alt.:3860 - na importa??o esse campo vem zerado. Por isso ele calculado aqui
  WSQL = WSQL||' case when a.bdredbcicms = 0 then ';
  WSQL = WSQL||' case ';
  WSQL = WSQL||' when A.bdbaseredicms > 0 then A.bdbaseredicms ';
  WSQL = WSQL||' else A.BDBASEICMS ';
  WSQL = WSQL||' end ';
  WSQL = WSQL||' when a.bdredbcicms = 100 then 0 else A.BDBASEICMS * ((100 - a.bdredbcicms)/100) end ';
  WSQL = WSQL||' ,0) else A.bdbaseredicms end) bdDIVbaseicms, ';
  --WSQL = WSQL||' sum(a.bdvlricms) bdDIVvlricms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdvlricms,0) else A.bdvlricms end) bdDIVvlricms, ';
  --WSQL = WSQL||' sum(a.bdisentasicms) bdDIVisentasicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdisentasicms,0) else A.bdisentasicms end) bdDIVisentasicms, ';

  WSQL = WSQL||' a.bdchave bdLancVarAliq, i.bdsttransporte, '||'''S'''||' bdSAIREDZ ';

  WSQL = WSQL||' from ( select M.BDCODEMP, M.BDREFLAN, M.BDDATAEMISSAO, M.BDCHAVE, M.BDCODTER, M.BDCODCID, ';
  WSQL = WSQL||'               M.BDESPECIE, M.BDSERIE, M.BDSUBSERIE, M.BDNUMDOCINI, M.BDNUMDOCFIM, M.BDCODSITNF ';
  WSQL = WSQL||'        from VEF_EMP_TMOVSAI M ';

  IF (:prcodemp IS NULL) THEN
     WSQL = WSQL||'        where (m.bddataemissao >= '''||:PRDATAINI||''' and m.bddataemissao <= '''||:PRDATAFIM||''')';
  ELSE
     WSQL = WSQL||'        where ('||:PRCODEMP||') and (m.bddataemissao >= '''||:PRDATAINI||''' and m.bddataemissao <= '''||:PRDATAFIM||''')';

  WSQL = WSQL||'       ) m ';
  WSQL = WSQL||' inner join VEF_EMP_TMOVSAIITENS i on (m.bdcodemp = i.bdcodemp and m.bdchave = i.bdchave)';
  WSQL = WSQL||' left outer join VEF_EMP_TMOVSAIVARALIQ a on (m.bdcodemp = a.bdcodemp and m.bdchave = a.bdchave and I.BDORDEM = a.BDORDEM)';
  WSQL = WSQL||' left outer join vw_tterceiro t on (m.bdcodter = t.bdcodter)';
  WSQL = WSQL||' left outer join TCIDADE c on (m.bdcodcid = c.bdcodcid)';
  WSQL = WSQL||' left outer join TUF u on (c.bdcoduf = u.bdcoduf)';
  WSQL = WSQL||' left outer join VEF_BASE_TOBSERVACAO o on (o.bdcodobs = i.bdcodobs)';

  WSQL = WSQL||' group by m.BDCODEMP, m.BDREFLAN, m.bddataemissao, m.BDCHAVE, I.BDORDEM, m.bdcodter, m.bdcodcid,t.BDNOMETER,t.BDCGCTER,t.bdieter, m.BDESPECIE, BDSERIE, m.BDNUMDOCINI, m.bdnumdocfim, ';

  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDCODSITNF, u.BDSIGLAUF, i.BDVLRCONTAB, i.BDPREFIXONAT, i.BDBASEICMS, i.BDALIQICMS, i.BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, ';
  ELSE
     WSQL = WSQL||' m.BDCODSITNF, u.BDSIGLAUF, i.BDVLRCONTAB, i.BDCODNAT, i.BDBASEICMS, i.BDALIQICMS, i.BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, ';

  WSQL = WSQL||' i.bdbasest, i.bdvlrst, bdnomeobs, bdDIValiqicms, bdLancVarAliq, i.bdsttransporte, bdSAIREDZ ';

  WSQL = WSQL||' order by m.BDCODEMP, m.bdreflan, m.bddataemissao, m.bdchave, I.BDORDEM';
  BDCODEMP_BKP = 0;
  BDCHAVE_BKP = 0;
  BDORDEM_BKP = 0;

  FOR EXECUTE STATEMENT wsql
  INTO 
    BDCODEMP,
    BDREFLAN, 
    BDDATAEMISSAO, 
    BDCHAVE, 
    BDORDEM, 
    BDCODTER, 
    BDCODCID, 
    BDNOMETER, 
    BDCGCTER, 
    BDIETER, 
    BDESPECIE, 
    BDSERIE, 
    BDNUMDOCINI, 
    BDNUMDOCFIM, 
    BDCODSITNF, 
    BDSIGLAUF, 
    BDVLRCONTAB, 
    BDPREFIXONAT, 
    BDBASEICMS, 
    BDALIQICMS, 
    BDVLRICMS, 
    BDISENTASICMS, 
    BDOUTRASICMS, 
    BDBASEIPI, 
    BDVLRIPI, 
    BDISENTASIPI, 
    BDOUTRASIPI, 
    BDBASEST, 
    BDVLRST, 
    BDNOMEOBS, 
    FDIVALIQICMS,
    FDIVOUTRASICMS,
    FDIVBASEICMS,
    FDIVVLRICMS,
    FDIVISENTASICMS,
    BDLANCVARALIQ, 
    WSTTRANSPORTE,
    BDSAIREDZ

  DO
  BEGIN
    IF ((BDCODEMP = BDCODEMP_BKP) AND (bdchave = BDCHAVE_BKP) AND (BDORDEM_BKP = BDORDEM)) THEN
       BEGIN
          BDLINHABRANCO = 'S';
          BDVLRCONTAB = 0;
          BDBASEIPI = 0;
          BDVLRIPI = 0;
          BDISENTASIPI = 0;
          BDOUTRASIPI = 0;
          BDBASEST = 0;
          BDVLRST = 0;
       END
    ELSE
       BDLINHABRANCO = 'N';

    BDVLRCONTABTOT = BDVLRCONTAB;
    BDIMPSOMENTECFOP = 'N';

    IF (FDIVOUTRASICMS IS NOT NULL) THEN
       BDOUTRASICMS = FDIVOUTRASICMS;

    IF (FDIVBASEICMS IS NOT NULL) THEN
       BDBASEICMS = FDIVBASEICMS;

    IF (FDIVALIQICMS IS NOT NULL) THEN
       BDALIQICMS = FDIVALIQICMS;

    IF (FDIVVLRICMS IS NOT NULL) THEN
       BDVLRICMS = FDIVVLRICMS;

    IF (FDIVISENTASICMS IS NOT NULL) THEN
       BDISENTASICMS = FDIVISENTASICMS;

    BDCODEMP_BKP = BDCODEMP;
    BDCHAVE_BKP = BDCHAVE;
    BDORDEM_BKP = BDORDEM;

    SUSPEND;

  END

  WSQL = 'select M.BDCODEMP, M.BDREFLAN, M.BDDATAREDZ BDDATAEMISSAO, M.BDCHAVE, C.BDORDEMVARCFOP BDORDEM, C.BDCODTER, null BDCODCID, ';
  WSQL = WSQL||' t.BDNOMETER, t.BDCGCTER, t.BDIETER, R.BDESPECIE, R.BDSERIE, ';

  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDNUMCUPINI BDNUMDOCINI,m.BDNUMCUPFIN bdnumdocfim,null BDCODSITNF, '''' BDSIGLAUF, m.bdvalvenbru,CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 4) AS INTEGER) BDPREFIXONAT,';
  ELSE
     WSQL = WSQL||' m.BDNUMCUPINI BDNUMDOCINI,m.BDNUMCUPFIN bdnumdocfim,null BDCODSITNF, '''' BDSIGLAUF, m.bdvalvenbru,CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 7) AS INTEGER) BDPREFIXONAT,';

  WSQL = WSQL||' C.BDBASEICMS, C.BDALIQICMS, C.BDVLRICMS, C.BDISENTASICMS, C.BDOUTRASICMS, null BDBASEIPI, null BDVLRIPI, null BDISENTASIPI, ';
  WSQL = WSQL||' null BDOUTRASIPI, null BDBASEST, null BDVLRST, null BDNOMEOBS, null FDIVOUTRASICMS, 0 FDIVBASEICMS, ';
  WSQL = WSQL||' null FDIVALIQICMS, null FDIVVLRICMS, null FDIVISENTASIC, '||'''Z'''||' BDSAIREDZ, IIF(TRIM(C.BDOBSERVACAO) <> '''', C.BDOBSERVACAO, '||'''Contador de Redu??o Z: '''||'||M.BDPOSCRZ||'||''' GT Final: '') BDOBSERVACAO, M.BDVALGTFINAL ';

  WSQL = WSQL||'from ( select M.BDCODEMP, M.BDREFLAN, M.BDDATAREDZ, M.BDCHAVE, M.BDNUMCUPINI, M.BDNUMCUPFIN, M.BDVALVENBRU, M.BDPOSCRZ, M.BDVALGTFINAL, M.BDORDEMMAQ  ';
  WSQL = WSQL||'       from VEF_EMP_TREDZ M  ';
  IF (:prcodemp IS NULL) THEN
     WSQL = WSQL||'       where (m.BDDATAREDZ >= '''||:PRDATAINI||''' and m.BDDATAREDZ <= '''||:PRDATAFIM||''')';
  ELSE
     WSQL = WSQL||'       where ('||:PRCODEMP||') and (m.BDDATAREDZ >= '''||:PRDATAINI||''' and m.BDDATAREDZ <= '''||:PRDATAFIM||''')';
  WSQL = WSQL||'      ) M  ';

  WSQL = WSQL||' join VEF_EMP_TREDZVARCFOP C on (M.BDCODEMP = C.BDCODEMP and M.BDCHAVE = C.BDCHAVE) ';
  WSQL = WSQL||' join VEF_BASE_TCADMAQMRC R on (M.BDCODEMP = R.BDCODEMP and M.BDORDEMMAQ = R.BDORDEMMAQ) ';
  WSQL = WSQL||' left outer join vw_tterceiro t on (c.bdcodter = t.bdcodter) ';

  WSQL = WSQL||' where (m.bdcodemp = c.bdcodemp and m.bdchave = c.bdchave and m.bdcodemp = r.bdcodemp and m.bdordemmaq = r.bdordemmaq)';

  wSQL = WSQL||' order by m.BDCODEMP, m.BDCHAVE, BDPREFIXONAT, BDORDEM';

  BDCODEMP_BKP = 0;
  BDCHAVE_BKP = 0;
  BDPREFIXONAT_BKP = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDREFLAN,
    BDDATAEMISSAO,
    BDCHAVE,
    BDORDEM,
    BDCODTER,
    BDCODCID,
    BDNOMETER,
    BDCGCTER,
    BDIETER,
    BDESPECIE,
    BDSERIE,
    BDNUMDOCINI,
    bdnumdocfim,
    BDCODSITNF,
    BDSIGLAUF,
    BDVLRCONTAB,
    BDPREFIXONAT,
    BDBASEICMS,
    BDALIQICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDBASEIPI,
    BDVLRIPI,
    BDISENTASIPI,
    BDOUTRASIPI,
    BDBASEST,
    BDVLRST,
    BDNOMEOBS,
    FDIVALIQICMS,
    FDIVOUTRASICMS,
    FDIVBASEICMS,    
    FDIVVLRICMS,
    FDIVISENTASICMS,
    BDSAIREDZ,
    BDOBSERVACAO,
    BDVALGTFINAL
  DO
  BEGIN
    IF ((BDCODEMP = BDCODEMP_BKP) AND (bdchave = BDCHAVE_BKP) AND (BDPREFIXONAT = BDPREFIXONAT_BKP)) THEN
       BDLINHABRANCO = 'S';
    ELSE
       BDLINHABRANCO = 'N';

    /* Quando muda somente CFOP da nota ? preciso imprim?-la para separar */
    IF ((BDCODEMP = BDCODEMP_BKP) AND (bdchave = BDCHAVE_BKP)) THEN
       BEGIN
          IF (BDPREFIXONAT <> BDPREFIXONAT_BKP) THEN
             BEGIN
                BDIMPSOMENTECFOP = 'S';
             END
          ELSE
             BDIMPSOMENTECFOP = 'N';
       END
    ELSE
       BDIMPSOMENTECFOP = 'N';

    BDVLRCONTABTOT = BDVLRCONTAB;

    /* SQL que busca o valor por CFOP dos registros de v?rias al?quotas da redu??o Z */
    IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
       WSQLTOT = 'select m.BDCODEMP, m.BDCHAVE, CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 4) AS INTEGER) BDPREFIXONAT, SUM(c.bdvlrcontab)';
    ELSE
       WSQLTOT = 'select m.BDCODEMP, m.BDCHAVE, CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 7) AS INTEGER) BDPREFIXONAT, SUM(c.bdvlrcontab)';

    WSQLTOT = WSQLTOT||' from ( select M.BDCODEMP, M.BDCHAVE ';
    WSQLTOT = WSQLTOT||'        from VEF_EMP_TREDZ M ';
    WSQLTOT = WSQLTOT||'        where (m.BDDATAREDZ = '''||:BDDATAEMISSAO||''') ';
    WSQLTOT = WSQLTOT||'          and (m.BDCODEMP = '||BDCODEMP||') and (m.BDCHAVE = '||BDCHAVE||') ';
    WSQLTOT = WSQLTOT||'       ) m ';

    WSQLTOT = WSQLTOT||' join VEF_EMP_TREDZVARCFOP C on (c.BDCODEMP = m.BDCODEMP and c.BDCHAVE = m.BDCHAVE) ';

    IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
       WSQLTOT = WSQLTOT||' where (CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 4) AS INTEGER) = '||BDPREFIXONAT||')';
    ELSE
       WSQLTOT = WSQLTOT||' where (CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 7) AS INTEGER) = '||BDPREFIXONAT||')';
    
    WSQLTOT = WSQLTOT||' group by m.BDCODEMP, m.BDCHAVE, BDPREFIXONAT';
    WSQLTOT = WSQLTOT||' order by m.BDCODEMP, m.BDCHAVE, BDPREFIXONAT';

    EXECUTE STATEMENT WSQLTOT INTO :WCODEMP,wchave, :WNAT,:WVLRCONT;

    --select bdvlrcont FROM SP_VEF_VALORREDZLIVRO(:BDCODEMP,:BDPREFIXONAT,:bdchave,:BDDATAEMISSAO) into :WVLRCONT;
    BDVLRCONTAB = WVLRCONT;

    SUSPEND;

    BDCODEMP_BKP = BDCODEMP;
    BDCHAVE_BKP = BDCHAVE;
    BDPREFIXONAT_BKP = BDPREFIXONAT;
  END
END
^

/* Alter (SP_VEF_REL_APURACAO_GIAMG) */
ALTER PROCEDURE SP_VEF_REL_APURACAO_GIAMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDNUMITEM VARCHAR(5),
BDAREACONS VARCHAR(10),
BDESCCENTRAL VARCHAR(5),
BDTITULO VARCHAR(60),
BDREGISTRO VARCHAR(60),
BDSUBTITULO VARCHAR(80),
BDNUMITEMORD VARCHAR(7))
 AS
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable PRQUADROANT integer;
declare variable PRULTIMOCLASSIFITIT varchar(11);
declare variable WCLASSIFITITULO varchar(11);
declare variable WCLASSIFIPRINC varchar(11);
declare variable WAUX integer;
declare variable WAUX2 integer;
declare variable WTIT integer;
declare variable WULTIMOCLASSIFITIT varchar(11);
declare variable WTITULO varchar(60);
declare variable WREGISTRO varchar(60);
declare variable WDESCFORM varchar(150);
declare variable WSUBTITULO varchar(80);
declare variable WCODTIPO integer;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas2.BDNOMEMP, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQUADRO,';
  wsql = wsql || 'TCONF.bdclassificacao, ';
  wsql = wsql || 'TCONF.bddescquadro,';
  wsql = wsql || 'TCONFGIAMGFORM.bddescform,';
  wsql = wsql || 'T.BDVALOR BDVALOR, ';
  wsql = wsql || 'TCONF.bdcodtipo, ';
  wsql = wsql || 'TCONFGIAMGFORM.BDNUMITEM, ';
--  wsql = wsql || 'cast(TCONFGIAMGFORM.BDNUMITEM as numeric(5,2)) BDNUMITEM, ';

  wsql = wsql || 'parmg.BDAREACONS, ';
  wsql = wsql || 'parmg.BDESCCENTRAL, ';
  wsql = wsql || 'null BDTITULO, ';
  wsql = wsql || 'null BDREGISTRO, ';
  wsql = wsql || 'null BDSUBTITULO, ';
  wsql = wsql || 'lPad(cast(TCONFGIAMGFORM.BDNUMITEM as numeric(5,2)),6,''0'') BDNUMITEMORD ';

  wsql = wsql || ' from VEF_EMP_TGIAMGGERREG T';

  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join VEF_BASE_TEMPPARESTMG parmg on (parmg.bdcodemp = empresas2.bdcodemp and parmg.bdrefemp = empresas2.BDEMPREF) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIAMGQ TCONF on (TCONF.bdcodquadro = t.bdcodquadro) ' ;
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIAMGFORM TCONFGIAMGFORM on (TCONFGIAMGFORM.bdcodconf = parmg.BDCODCONFGIAMG and ';
  wsql = wsql||' TCONFGIAMGFORM.bdcodquadro = T.BDCODQUADRO and TCONFGIAMGFORM.bdnumcampo = T.BDNUMCAMPO) ' ;
  wwhere = '';

  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> '')) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQUADRO, cast(TCONFGIAMGFORM.BDNUMITEM as numeric(5,2))' ;

  prquadroant = 0;
  PRULTIMOCLASSIFITIT = '';
  WCLASSIFIPRINC = '';
  WTIT = 1;

  WTITULO = '';
  WREGISTRO = '';
  WSUBTITULO = '';
  WCODTIPO = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP ,
    BDREFERENCIA ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCQUADRO ,
    BDDESCFORM ,
    BDVALOR ,
    BDCODTIPO,
    BDNUMITEM,
    BDAREACONS,
    BDESCCENTRAL,
    BDTITULO,
    BDREGISTRO,
    BDSUBTITULO,
    BDNUMITEMORD
  DO
  BEGIN
    IF ((prquadroant <> bdcodquadro)) THEN   -- mostra o nome do quadro atual na consulta
      BEGIN
        SELECT FIRST 1 tpos.BDRPOS FROM rpos('.',  :bdclassificacao) tpos INTO :waux;

        IF ((WCLASSIFIPRINC = '') AND (waux > 1)) THEN
           BEGIN
              WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);
              WTIT = 1;
           END
        ELSE
           BEGIN
             IF (WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1)) THEN
                BEGIN
                   WTIT = 0;
                END
             ELSE
                BEGIN
                   WTIT = 1;
                END
    
             IF (waux > 1) THEN
                WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);
           END

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux2;

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux2-1);

            SELECT FIRST 1 tpos.pos FROM pos('.', :prultimoclassifitit) tpos INTO :waux2;

            IF (waux2 > 0) THEN
               wultimoclassifitit = SUBSTRING(prultimoclassifitit FROM 1 FOR waux2-1);
            ELSE
               wultimoclassifitit = prultimoclassifitit;

            IF ((wultimoclassifitit <> wclassifititulo) AND (WTIT = 1)) THEN
              BEGIN

                SELECT x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :WDESCFORM;

                WTITULO = WDESCFORM;
              END

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF ((prultimoclassifitit <> wclassifititulo) AND (WTIT = 1)) THEN
              BEGIN

                SELECT x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :WDESCFORM;

                WREGISTRO = WDESCFORM;
              END

            IF (WCODTIPO <> BDCODTIPO) THEN
               SELECT x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.BDCODTIPO = :BDCODTIPO INTO
                      :WSUBTITULO;

            WCODTIPO = BDCODTIPO;
          END
      END

    BDREGISTRO = WREGISTRO;
    BDTITULO = WTITULO;
    BDSUBTITULO = WSUBTITULO;

    bddescform = '['||BDNUMITEM||'] - '||bddescform;
    SUSPEND;
  END

END
^

/* Alter (SP_VEF_REL_RETENCOES) */
ALTER PROCEDURE SP_VEF_REL_RETENCOES(PRCODEMP VARCHAR(10000),
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPOMOV INTEGER,
PRCODTER INTEGER,
PRDETALHADO INTEGER,
PRTIPOLANSERV INTEGER,
PRTIPOAPURACAORET INTEGER,
PRTIPOAPURACAORETIR INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCODTER INTEGER,
BDNOMETER VARCHAR(100),
BDCGCTER VARCHAR(18),
BDENDTER VARCHAR(60),
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDVLRCONTAB NUMERIC(15,2),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDVLRIR NUMERIC(15,2),
BDVLRINSS NUMERIC(15,2),
BDVLRISS NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDCONDPGTO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WMES CHAR(2);
DECLARE VARIABLE WANO CHAR(4);
DECLARE VARIABLE WREFINCIAL INTEGER;
DECLARE VARIABLE WREFFINAL INTEGER;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCODTERATUAL INTEGER;
DECLARE VARIABLE WDATAAUX DATE;
DECLARE VARIABLE WCHAVE INTEGER;
BEGIN
  /* giovanni */

  /* Procedure Text */

  --sol:15749 - select externo responsavel por modificar os c?digos das filiais em c?digo da matriz, para que o relatorio agrupe tudo na mesma empresa
  wsql = 'Select Coalesce(Emp.bdCodMatriz, Mov.BDCODEMP) BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDNOMETER,Mov.BDCGCTER,Mov.BDENDTER,Mov.BDCODCID,Mov.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB,';
  wsql = wSql || 'Mov.BDVLRPIS,Mov.BDVLRCOFINS,Mov.BDVLRCSOCIAL,Mov.BDVLRIR,Mov.BDVLRINSS,';

  IF ((prtipomov = 2) OR (prtipomov = 3))  THEN
     wsql = wSql || 'Mov.BDVLRISSSER';
  ELSE
     wsql = wSql || 'Mov.BDVLRISS';

  wsql = wSql || ',Mov.BDVLRIRSER from (';

  IF (prtipomov = 0) THEN -- entradas
    BEGIN
      wsql = wSql || 'Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB BDVLRCONTAB,';
      /*IF (prtipoapuracaoret = 1) THEN -- Tipo de apura??o das reten??es = Regime de caixa
        BEGIN
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETPIS) else SUM(MOV.BDVLRPIS) end BDVLRPIS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETCOFINS) else SUM(MOV.BDVLRCOFINS) end BDVLRCOFINS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETCSLL) else SUM(MOV.BDVLRCSOCIAL) end BDVLRCSOCIAL,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETIRRF) else SUM(MOV.BDVLRIR) end BDVLRIR,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETINSS) else SUM(MOV.BDVLRINSS) end BDVLRINSS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETISSQN) else SUM(MOV.BDVLRISS) end BDVLRISS,';
          wsql = wSql || 'SUM(Mov.BDVLRIRSER) BDVLRIRSER ';
        END
      ELSE*/
        wsql = wSql || 'SUM(Mov.BDVLRPIS) BDVLRPIS,SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,';
        wsql = wSql || 'SUM(Mov.BDVLRIR) BDVLRIR,SUM(Mov.BDVLRINSS) BDVLRINSS,SUM(Mov.BDVLRISS) BDVLRISS,SUM(Mov.BDVLRIRSER) BDVLRIRSER from (';

      --sol:17084 - Competencia e regime de caixa PIS/Cofins/CSLL
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,SUM(Mov.BDVLRPIS) BDVLRPIS,';
      wsql = wSql || '      SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,0 as BDVLRIR,0 as BDVLRINSS,';
      wsql = wsql || '      0 as BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVENT_E_ITENS Mov ';
      wsql = wSql || '      where (' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ')';
      wsql = wsql || '      and (Mov.BDDATAENTRADAENT BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0))';
      IF (prtipoapuracaoret = 1) THEN
        wsql = wsql || '   and (Mov.BDCONDPGTO <> 1)';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO ';

      IF (prtipoapuracaoret = 1) THEN
        BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, SUM(Pgto.BDVALORRETPIS) BDVLRPIS, SUM(Pgto.BDVALORRETCOFINS) BDVLRCOFINS,';
          wsql = wsql || '  SUM(Pgto.BDVALORRETCSLL) BDVLRCSOCIAL,0 as BDVLRIR,0 as BDVLRINSS,';
          wsql = wsql || '  0 as BDVLRISS, 0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVENTRET Ret, VEF_EMP_TMOVENT Mov, VEF_EMP_TMOVENTPARPGTO Pgto ';
          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (Ret.' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0)) ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        END

      --sol:17084 - Competencia e regime de caixa IR
      wsql = wsql || '      union all ';
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 as BDVLRPIS,';
      wsql = wSql || '      0 as BDVLRCOFINS,0 as BDVLRCSOCIAL,SUM(Mov.BDVLRIR) BDVLRIR,0 as BDVLRINSS,';
      wsql = wsql || '      0 as BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVENT_E_ITENS Mov ';
      wsql = wSql || '      where (' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ')';
      wsql = wsql || '      and (Mov.BDDATAENTRADAENT BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and (BDVLRIR > 0)';
      IF (prtipoapuracaoretir = 1) THEN
        wsql = wsql || '   and (Mov.BDCONDPGTO <> 1)';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO ';

      IF (prtipoapuracaoretir = 1) THEN
        BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, 0 as BDVLRPIS, 0 as BDVLRCOFINS,';
          wsql = wsql || '  0 as BDVLRCSOCIAL,SUM(Pgto.BDVALORRETIRRF) as BDVLRIR,0 as BDVLRINSS,';
          wsql = wsql || '  0 as BDVLRISS, 0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVENTRET Ret, VEF_EMP_TMOVENT Mov, VEF_EMP_TMOVENTPARPGTO Pgto ';
          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (Ret.' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and (BDVLRIR > 0) ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        END

      --sol:17084 - ISS e INSS
      wsql = wsql || '      union all ';
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 as BDVLRPIS,';
      wsql = wSql || '      0 as BDVLRCOFINS,0 as BDVLRCSOCIAL,0 as BDVLRIR,SUM(Mov.BDVLRINSS) BDVLRINSS,';
      wsql = wsql || '      SUM(Mov.BDVLRISS) BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVENT_E_ITENS Mov ';
      wsql = wSql || '      where (' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ')';
      wsql = wsql || '      and (Mov.BDDATAENTRADAENT BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and ((BDVLRINSS > 0) or (BDVLRISS > 0))';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO ';

      wsql = wsql || ') Mov ';
      wsql = wSql || 'LEFT OUTER JOIN VW_TTERCEIRO Ter ON (Ter.BDCODTER = Mov.BDCODTER) ';
      wsql = wSql || 'LEFT OUTER JOIN TCIDADE Cid ON (CID.BDCODCID = Ter.BDCODCID) ';
      --IF (prtipoapuracaoret = 1) THEN -- Tipo de apura??o das reten??es = Regime de caixa
      --  wsql = wsql || 'LEFT OUTER JOIN VEF_EMP_TMOVENTPARPGTO Pgto on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE and Pgto.BDDATAPGTOPAR between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || 'Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB ';
      wsql = wSql || 'Order by Mov.BDCODEMP,Mov.BDCODTER,Mov.BDREFLAN';
    END
  ELSE
  IF (prtipomov = 1) THEN -- saidas
    BEGIN
      wsql = wSql || 'Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB BDVLRCONTAB,';
      /*IF (prtipoapuracaoret = 1) THEN -- Tipo de apura??o das reten??es = Regime de caixa
        BEGIN
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETPIS) else SUM(MOV.BDVLRPIS) end BDVLRPIS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETCOFINS) else SUM(MOV.BDVLRCOFINS) end BDVLRCOFINS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETCSLL) else SUM(MOV.BDVLRCSOCIAL) end BDVLRCSOCIAL,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETIRRF) else SUM(MOV.BDVLRIR) end BDVLRIR,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETINSS) else SUM(MOV.BDVLRINSS) end BDVLRINSS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETISSQN) else SUM(MOV.BDVLRISS) end BDVLRISS,';
          wsql = wSql || 'SUM(Mov.BDVLRIRSER) BDVLRIRSER ';
        END
      ELSE*/
        wsql = wSql || 'SUM(Mov.BDVLRPIS) BDVLRPIS,SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,SUM(Mov.BDVLRIR) BDVLRIR,';
        wsql = wSql || 'SUM(Mov.BDVLRINSS) BDVLRINSS,SUM(Mov.BDVLRISS) BDVLRISS,SUM(Mov.BDVLRIRSER) BDVLRIRSER from (';

      --sol:17084 - Competencia e regime de caixa PIS/Cofins/CSLL
      wsql = wsql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,SUM(Mov.BDVLRPIS) BDVLRPIS,';
      wsql = wSql || '      SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,0 AS BDVLRIR,0 AS BDVLRINSS,';
      wsql = wsql || '      0 AS BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVSAI_E_ITENS Mov ';
      wsql = wSql || '      where (' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql || '      and (Mov.BDDATASAIDA BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0)) ';
      IF (prtipoapuracaoret = 1) THEN
        wsql = wsql || '   and (Mov.BDCONDPGTO <> 1)';
      wsql = wsql || '     Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';

      IF (prtipoapuracaoret = 1) THEN
        BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, SUM(Pgto.BDVALORRETPIS) BDVLRPIS, SUM(Pgto.BDVALORRETCOFINS) BDVLRCOFINS,';
          wsql = wsql || '  SUM(Pgto.BDVALORRETCSLL) BDVLRCSOCIAL, 0 as BDVLRIR,0 AS BDVLRINSS,';
          wsql = wsql || '  0 AS BDVLRISS, 0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVSAIRET Ret, VEF_EMP_TMOVSAI Mov, VEF_EMP_TMOVSAIPARPGTO Pgto ';
          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (Ret.' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0)) ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        END

      --sol:17084 - Competencia e regime de caixa IR
      wsql = wsql || '      union all ';
      wsql = wsql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB, 0 AS BDVLRPIS,';
      wsql = wSql || '      0 AS BDVLRCOFINS, 0 AS BDVLRCSOCIAL,SUM(Mov.BDVLRIR) BDVLRIR, 0 AS BDVLRINSS,';
      wsql = wsql || '      0 AS BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVSAI_E_ITENS Mov ';
      wsql = wSql || '      where (' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql || '      and (Mov.BDDATASAIDA BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and (BDVLRIR > 0) ';
      IF (prtipoapuracaoretir = 1) THEN
        wsql = wsql || '   and (Mov.BDCONDPGTO <> 1)';
      wsql = wsql || '     Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';

      IF (prtipoapuracaoretir = 1) THEN
        BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, 0 AS BDVLRPIS, 0 AS BDVLRCOFINS,';
          wsql = wsql || '  0 AS BDVLRCSOCIAL,SUM(Pgto.BDVALORRETIRRF) as BDVLRIR,0 AS BDVLRINSS,';
          wsql = wsql || '  0 AS BDVLRISS, 0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVSAIRET Ret, VEF_EMP_TMOVSAI Mov, VEF_EMP_TMOVSAIPARPGTO Pgto ';
          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (Ret.' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and (BDVLRIR > 0) ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        END

      --sol:17084 - ISS e INSS
      wsql = wsql || '      union all ';
      wsql = wsql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 AS  BDVLRPIS,';
      wsql = wSql || '      0 AS BDVLRCOFINS,0 AS BDVLRCSOCIAL,0 AS BDVLRIR,SUM(Mov.BDVLRINSS) BDVLRINSS,';
      wsql = wsql || '      SUM(Mov.BDVLRISS) BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVSAI_E_ITENS Mov ';
      wsql = wSql || '      where (' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql || '      and (Mov.BDDATASAIDA BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and ((BDVLRINSS > 0) or (BDVLRISS > 0)) ';
      wsql = wsql || '     Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';

      wsql = wsql || ') Mov ';
      wsql = wSql || 'LEFT OUTER JOIN VW_TTERCEIRO Ter ON (Ter.BDCODTER = Mov.BDCODTER) ';
      wsql = wSql || 'LEFT OUTER JOIN TCIDADE Cid ON (Cid.BDCODCID = Ter.BDCODCID) ';
      --IF (prtipoapuracaoret = 1) THEN -- Tipo de apura??o das reten??es = Regime de caixa
      --  wsql = wsql || 'LEFT OUTER JOIN VEF_EMP_TMOVSAIPARPGTO Pgto on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE and Pgto.BDDATAPGTOPAR between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || 'Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB ';
      wsql = wSql || 'Order by Mov.BDCODEMP,Mov.BDCODTER,Mov.BDREFLAN';
    END
  ELSE
  IF (prtipomov = 2) THEN -- servicos
    BEGIN
      wsql = wSql || 'Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB BDVLRCONTAB,';
      /*IF (prtipoapuracaoret = 1) THEN -- Tipo de apura??o das reten??es = Regime de caixa
        BEGIN
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETPIS) else SUM(MOV.BDVLRPIS) end BDVLRPIS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETCOFINS) else SUM(MOV.BDVLRCOFINS) end BDVLRCOFINS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETCSLL) else SUM(MOV.BDVLRCSOCIAL) end BDVLRCSOCIAL,';
          wsql = wSql || 'SUM(BDVLRIR) BDVLRIR,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETINSS) else SUM(MOV.BDVLRINSS) end BDVLRINSS,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETISSQN) else SUM(MOV.BDVLRISSSER) end BDVLRISSSER,';
          wsql = wSql || 'case when MOV.BDCONDPGTO = 1 then SUM(Pgto.BDVALORRETIRRF) else SUM(MOV.BDVLRIRSER) end BDVLRIRSER ';
        END
      ELSE*/
        wsql = wSql || 'SUM(Mov.BDVLRPIS) BDVLRPIS,SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,SUM(Mov.BDVLRIR) BDVLRIR,';
        wsql = wSql || 'SUM(Mov.BDVLRINSS) BDVLRINSS,SUM(Mov.BDVLRISSSER) BDVLRISSSER,SUM(Mov.BDVLRIRSER) BDVLRIRSER from (';

      --sol:17084 - Competencia e regime de caixa PIS/Cofins/CSLL
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,SUM(Mov.BDVLRPIS) BDVLRPIS,';
      wsql = wSql || '      SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL, 0 AS BDVLRIR,0 AS BDVLRINSS,0 AS BDVLRISSSER,';
      wsql = wsql || '      0 AS BDVLRIRSER ';
      /*sol:10642 - substituido o VW_VEF_EMP_TMOVSER_E_ITENS pela tabela de servi?o (com join para as dedu??es/reten??es) pois essa view tras os valores de ded/ret matriciado se o lanc tiver mais de uma cfop
      wsql = wSql || '      from VW_VEF_EMP_TMOVSER_E_ITENS Mov ';*/
      wsql = wSql || '     from (select MOV.*, coalesce(RET.BDISSRET, 0) BDVLRISSSER, coalesce(DED.BDRETINSS, 0) BDVLRINSS, COALESCE(RET.bdvlrpis,0.0) BDVLRPIS, ';
      wsql = wSql || '                 COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS, COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL ';
      wsql = wSql || '          from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                       MOV.BDNUMDOCINI, MOV.BDCONDPGTO, Mov.BDREFLAN, sum(ITEM.BDVLRCONTAB) BDVLRCONTAB, sum(COALESCE(ITEM.bdvlrirser,0)) bdvlrirser ';
      wsql = wSql || '                from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                             MOV.BDNUMDOCINI, MOV.BDCONDPGTO,Mov.BDREFLAN ';
      wsql = wSql || '                      from VEF_EMP_TMOVSER MOV ';
      wsql = wSql || '                      where (' || :prcodemp || ') and ';
      wsql = wSql || '                            (MOV.BDCODSITNF not in (2, 3, 4, 5)) and ';
      IF (prcodter > 0) THEN
         wsql = wSql || '                          Mov.BDCODTER = (' || :prcodter || ') and ';
      wsql = wSql || '                            (MOV.BDDATAEMISSAO between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      IF (prtipolanserv = 0) THEN /* Servico emitido */
         wsql = wSql || '                         and (Mov.BDTIPLAN = 0) ';
      ELSE
         wsql = wSql || '                         and (Mov.BDTIPLAN = 1) ';
      IF (prtipoapuracaoret = 1) THEN
        wsql = wsql || '                          and (Mov.BDCONDPGTO <> 1) ';
      wsql = wSql || '                      ) MOV ';
      wsql = wSql || '                left outer join VEF_EMP_TMOVSERITENS ITEM on (ITEM.BDCODEMP = MOV.BDCODEMP and ITEM.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '                group by MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCONDPGTO, MOV.bdreflan) MOV ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERRET RET on (RET.BDCODEMP = MOV.BDCODEMP and RET.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = MOV.BDCODEMP and DED.BDCHAVE = MOV.BDCHAVE)) MOV ';
      /*sol:10642 - feito o filtro no sql mais interno
      wsql = wSql || '      where (' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql || '      and (BDDATAEMISSAO BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';*/
      wsql = wSql || '      where (Mov.BDVLRCONTAB > 0) and ((Mov.BDVLRPIS > 0) or (Mov.BDVLRCOFINS > 0) or (Mov.BDVLRCSOCIAL > 0)) ';
      /*IF (prtipolanserv = 0) THEN --Servico emitido
         wsql = wSql || '   and (Mov.BDTIPLAN = 0) ';
      ELSE
         wsql = wSql || '   and (Mov.BDTIPLAN = 1) ';
      IF (prtipoapuracaoret = 1) THEN
        wsql = wsql || '    and (Mov.BDCONDPGTO <> 1) ';*/
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';

      IF (prtipoapuracaoret = 1) THEN
        BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, SUM(Pgto.BDVALORRETPIS) BDVLRPIS, SUM(Pgto.BDVALORRETCOFINS) BDVLRCOFINS,';
          wsql = wsql || '  SUM(Pgto.BDVALORRETCSLL) BDVLRCSOCIAL,0 as BDVLRIR,0 as BDVLRINSS,';
          wsql = wsql || '  0 as BDVLRISS,0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVSERRET Ret, VEF_EMP_TMOVSER Mov, VEF_EMP_TMOVSERPARPGTO Pgto ';
          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (Ret.' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0)) ';
          IF (prtipolanserv = 0) THEN /* Servico emitido */
            wsql = wSql || 'and (Mov.BDTIPLAN = 0) ';
          ELSE
            wsql = wSql || 'and (Mov.BDTIPLAN = 1) ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        END

      --sol:17084 - Competencia e regime de caixa IR
      wsql = wsql || '      union all ';
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 AS BDVLRPIS,';
      wsql = wSql || '      0 AS BDVLRCOFINS,0 AS BDVLRCSOCIAL, 0 AS BDVLRIR,0 AS BDVLRINSS,0 AS BDVLRISSSER,';
      wsql = wsql || '      SUM(Mov.BDVLRIRSER) BDVLRIRSER ';
      wsql = wSql || '     from (select MOV.*, coalesce(RET.BDISSRET, 0) BDVLRISSSER, coalesce(DED.BDRETINSS, 0) BDVLRINSS, COALESCE(RET.bdvlrpis,0.0) BDVLRPIS, ';
      wsql = wSql || '                 COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS, COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL ';
      wsql = wSql || '          from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                       MOV.BDNUMDOCINI, MOV.BDCONDPGTO, Mov.BDREFLAN, sum(ITEM.BDVLRCONTAB) BDVLRCONTAB, sum(COALESCE(ITEM.bdvlrirser,0)) bdvlrirser ';
      wsql = wSql || '                from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                             MOV.BDNUMDOCINI, MOV.BDCONDPGTO,Mov.BDREFLAN ';
      wsql = wSql || '                      from VEF_EMP_TMOVSER MOV ';
      wsql = wSql || '                      where (' || :prcodemp || ') and ';
      wsql = wSql || '                            (MOV.BDCODSITNF not in (2, 3, 4, 5)) and ';
      IF (prcodter > 0) THEN
         wsql = wSql || '                          Mov.BDCODTER = (' || :prcodter || ') and ';
      wsql = wSql || '                            (MOV.BDDATAEMISSAO between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      IF (prtipolanserv = 0) THEN /* Servico emitido */
         wsql = wSql || '                         and (Mov.BDTIPLAN = 0) ';
      ELSE
         wsql = wSql || '                         and (Mov.BDTIPLAN = 1) ';
      IF (prtipoapuracaoretir = 1) THEN
        wsql = wsql || '                          and (Mov.BDCONDPGTO <> 1) ';
      wsql = wSql || '                      ) MOV ';
      wsql = wSql || '                left outer join VEF_EMP_TMOVSERITENS ITEM on (ITEM.BDCODEMP = MOV.BDCODEMP and ITEM.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '                group by MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCONDPGTO, MOV.bdreflan) MOV ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERRET RET on (RET.BDCODEMP = MOV.BDCODEMP and RET.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = MOV.BDCODEMP and DED.BDCHAVE = MOV.BDCHAVE)) MOV ';
      wsql = wSql || '      where (Mov.BDVLRCONTAB > 0) and (Mov.BDVLRIRSER > 0) ';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';

      IF (prtipoapuracaoretir = 1) THEN
        BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, 0 AS BDVLRPIS, 0 AS BDVLRCOFINS,';
          wsql = wsql || '  0 AS BDVLRCSOCIAL,0 as BDVLRIR,0 AS BDVLRINSS,';
          wsql = wsql || '  0 AS BDVLRISS,SUM(Pgto.BDVALORRETIRRF) as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVSERRET Ret, VEF_EMP_TMOVSER Mov, VEF_EMP_TMOVSERPARPGTO Pgto ';
          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (Ret.' || :prcodemp || ') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and (BDVALORRETIRRF > 0) ';
          IF (prtipolanserv = 0) THEN /* Servico emitido */
            wsql = wSql || 'and (Mov.BDTIPLAN = 0) ';
          ELSE
            wsql = wSql || 'and (Mov.BDTIPLAN = 1) ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        END

      --sol:17084 - ISS e INSS
      wsql = wsql || '      union all ';
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 AS BDVLRPIS,';
      wsql = wSql || '      0 AS BDVLRCOFINS,0 AS BDVLRCSOCIAL, 0 AS BDVLRIR,SUM(Mov.BDVLRINSS) BDVLRINSS,SUM(Mov.BDVLRISSSER) BDVLRISSSER,';
      wsql = wsql || '      0 AS BDVLRIRSER ';
      wsql = wSql || '     from (select MOV.*, coalesce(RET.BDISSRET, 0) BDVLRISSSER, coalesce(DED.BDRETINSS, 0) BDVLRINSS, COALESCE(RET.bdvlrpis,0.0) BDVLRPIS, ';
      wsql = wSql || '                 COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS, COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL ';
      wsql = wSql || '          from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                       MOV.BDNUMDOCINI, MOV.BDCONDPGTO, Mov.BDREFLAN, sum(ITEM.BDVLRCONTAB) BDVLRCONTAB, sum(COALESCE(ITEM.bdvlrirser,0)) bdvlrirser ';
      wsql = wSql || '                from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                             MOV.BDNUMDOCINI, MOV.BDCONDPGTO,Mov.BDREFLAN ';
      wsql = wSql || '                      from VEF_EMP_TMOVSER MOV ';
      wsql = wSql || '                      where (' || :prcodemp || ') and ';
      wsql = wSql || '                            (MOV.BDCODSITNF not in (2, 3, 4, 5)) and ';
      IF (prcodter > 0) THEN
         wsql = wSql || '                          Mov.BDCODTER = (' || :prcodter || ') and ';
      wsql = wSql || '                            (MOV.BDDATAEMISSAO between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      IF (prtipolanserv = 0) THEN /* Servico emitido */
         wsql = wSql || '                         and (Mov.BDTIPLAN = 0) ';
      ELSE
         wsql = wSql || '                         and (Mov.BDTIPLAN = 1) ';
      wsql = wSql || '                      ) MOV ';
      wsql = wSql || '                left outer join VEF_EMP_TMOVSERITENS ITEM on (ITEM.BDCODEMP = MOV.BDCODEMP and ITEM.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '                group by MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCONDPGTO, MOV.bdreflan) MOV ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERRET RET on (RET.BDCODEMP = MOV.BDCODEMP and RET.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = MOV.BDCODEMP and DED.BDCHAVE = MOV.BDCHAVE)) MOV ';
      wsql = wSql || '      where (Mov.BDVLRCONTAB > 0) and ((Mov.BDVLRISSSER > 0) or (Mov.BDVLRINSS > 0)) ';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';

      wsql = wsql || ') Mov ';
      wsql = wSql || 'LEFT OUTER JOIN VW_TTERCEIRO Ter ON (Ter.BDCODTER = Mov.BDCODTER) ';
      wsql = wSql || 'LEFT OUTER JOIN TCIDADE Cid ON (Cid.BDCODCID = Ter.BDCODCID) ';
      --IF (prtipoapuracaoret = 1) THEN -- Tipo de apura??o das reten??es = Regime de caixa
      --  wsql = wsql || 'LEFT OUTER JOIN VEF_EMP_TMOVSERPARPGTO Pgto on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE and Pgto.BDDATAPGTOPAR between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || 'Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB ';
      wsql = wSql || 'Order by Mov.BDCODEMP,Mov.BDCODTER,Mov.BDREFLAN';
    END
  ELSE
  IF (prtipomov = 3) THEN -- demais documentos
    BEGIN
      wsql = wSql || 'Select  Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) as BDVLRCONTAB,SUM(Mov.BDVLRPIS) as BDVLRPIS,';
      wsql = wSql || 'SUM(Mov.BDVLRCOFINS) as BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) as BDVLRCSOCIAL,SUM(Mov.BDVLRIR) as BDVLRIR,SUM(Mov.BDVLRINSS) as BDVLRINSS,SUM(Mov.BDVLRISSSER) as BDVLRISSSER,SUM(Mov.BDVLRIRSER) as BDVLRIRSER ';
      wsql = wSql || 'from ( Select Mov.BDCODEMP, Mov.BDCHAVE, Mov.BDREFLAN, Mov.BDCODTER, Mov.BDCONDPGTO, ';
      wsql = wsql || '              IIF(' || prtipoapuracaoret || ' = 1, SUM(Mov.BDVL_OPER), 0) as BDVLRCONTAB, ';
      wsql = wsql || '              IIF(' || prtipoapuracaoret || ' = 1, SUM(Ret.BDVLRPIS), 0) as BDVLRPIS, ';
      wsql = wsql || '              IIF(' || prtipoapuracaoret || ' = 1, SUM(Ret.BDVLRCOFINS), 0) as BDVLRCOFINS, ';
      wsql = wsql || '              IIF(' || prtipoapuracaoret || ' = 1, SUM(Ret.BDVLRCSOCIAL), 0) as BDVLRCSOCIAL, ';
      --wsql = wsql || '              IIF(' || prtipoapuracaoretir || ' = 1, SUM(Ret.BDVLRIR), 0) as BDVLRIR, ';
      wsql = wsql || '              SUM(Ret.BDVLRIR) as BDVLRIR, ';
      wsql = wsql || '              0 BDVLRINSS, 0 BDVLRISSSER, 0 BDVLRIRSER ';
      wsql = wSql || '       from VEF_EMP_TMOVDEMAISDOC_F100 Mov ';
      wsql = wsql || '       Left outer join VEF_EMP_TMOVDEMRET Ret on (Ret.BDCODEMP = Mov.BDCODEMP and Ret.BDCHAVE = Mov.BDCHAVE) ';
      wsql = wsql || '       Left outer join VEF_BASE_TAB_TIPO_OPERACAO tipo on (tipo.BDIND_OPER = Mov.BDIND_OPER) ';
      wsql = wSql || '       where (Mov.' || :prcodemp || ') ';
      IF (prcodter > 0) THEN
        wsql = wSql|| ' and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql ||  '     and (Mov.BDDT_OPER BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql ||  '     and ((Mov.BDVL_OPER > 0) and ((Ret.BDVLRPIS > 0) or (Ret.BDVLRCOFINS > 0) or (Ret.BDVLRCSOCIAL > 0))) ';

      IF (prTipoLanServ = 1) THEN -- Receita
        wsql = wsql || ' and tipo.BDINDICADOR > 0 ';
      ELSE -- Aquisi??o
        wsql = wsql || ' and tipo.BDINDICADOR = 0 ';

      IF ((prtipoapuracaoret = 1) OR (prtipoapuracaoretir = 1))  THEN -- Tipo de apura??o das reten??es = Regime de caixa
        wsql = wsql || '    and (Mov.BDCONDPGTO = 0) ';
      wsql = wsql || '      Group by Mov.BDCODEMP, Mov.BDCHAVE, Mov.BDREFLAN, Mov.BDCODTER, Mov.BDCONDPGTO, Ret.BDVLRIR';

      IF ((prtipoapuracaoret = 1) OR (prtipoapuracaoretir = 1))  THEN -- Tipo de apura??o das reten??es = Regime de caixa
        BEGIN
          wsql = wsql || ' union all ';
          wsql = wsql || ' Select Pgto.BDCODEMP,Pgto.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,Mov.BDCODTER,Pgto.BDCODPGTOPAR as BDCONDPGTO, ';
          IF ((prtipoapuracaoret = 1) AND (prtipoapuracaoretir = 1))  THEN
            wsql = wsql || '   IIF(' || prtipoapuracaoret || ' = 1, SUM(Coalesce(Pgto.BDVALORPGTOPAR, 0) + Coalesce(Pgto.BDVALORRETPIS, 0) + Coalesce(Pgto.BDVALORRETCOFINS, 0) + Coalesce(Pgto.BDVALORRETCSLL, 0) + Coalesce(Pgto.BDVALORRETINSS, 0) + Coalesce(Pgto.BDVALORRETIRRF, 0)), 0) as BDVLRCONTAB, ';
          ELSE
          IF (prtipoapuracaoret = 1) THEN
            wsql = wsql || '   IIF(' || prtipoapuracaoret || ' = 1, SUM(Coalesce(Pgto.BDVALORPGTOPAR, 0) + Coalesce(Pgto.BDVALORRETPIS, 0) + Coalesce(Pgto.BDVALORRETCOFINS, 0) + Coalesce(Pgto.BDVALORRETCSLL, 0) + Coalesce(Pgto.BDVALORRETINSS, 0)), 0) as BDVLRCONTAB, ';
          ELSE
          IF (prtipoapuracaoretir = 1)  THEN
            wsql = wsql || '   IIF(' || prtipoapuracaoretir || ' = 1, SUM(Coalesce(Pgto.BDVALORPGTOPAR, 0) + Coalesce(Pgto.BDVALORRETIRRF, 0)), 0) as BDVLRCONTAB, ';

          IF ((prtipoapuracaoret = 1) OR (prtipoapuracaoretir = 1)) THEN -- Tipo de apura??o das reten??es = Regime de caixa
            BEGIN
              wsql = wsql || '   IIF(' || prtipoapuracaoret || ' = 1, SUM(Pgto.BDVALORRETPIS), 0) as BDVLRPIS, ';
              wsql = wsql || '   IIF(' || prtipoapuracaoret || ' = 1, SUM(Pgto.BDVALORRETCOFINS), 0) as BDVLRCOFINS, ';
              wsql = wsql || '   IIF(' || prtipoapuracaoret || ' = 1, SUM(Pgto.BDVALORRETCSLL), 0) as BDVLRCSOCIAL, ';
              wsql = wsql || '   IIF(' || prtipoapuracaoretir || ' = 1, SUM(Pgto.BDVALORRETIRRF), 0) as BDVLRIR, ';
              wsql = wsql || '   IIF(' || prtipoapuracaoret || ' = 1, SUM(Pgto.BDVALORRETINSS), 0) as BDVLRINSS, ';
              wsql = wsql || '   IIF(' || prtipoapuracaoret || ' = 1, SUM(Pgto.BDVALORRETINSS), 0) as BDVLRISSSER, ';
            END
          ELSE
            wsql = wsql || '   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRIR, 0 as BDVLRINSS, 0 as BDVLRISSSER, ';

          IF (prtipoapuracaoretir = 1)  THEN          
            wsql = wsql || '   IIF(' || prtipoapuracaoretir || ' = 1, SUM(Pgto.BDVALORRETIRRF), 0) as BDVLRIRSER ';
          ELSE
            wsql = wsql || '   0 as BDVLRIRSER ';

          wsql = wsql || ' from VEF_EMP_TMOVF100PARPGTO Pgto ';
          wsql = wsql || ' left outer join VEF_EMP_TMOVDEMAISDOC_F100 Mov on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE) ';
          wsql = wsql || ' left outer join VEF_BASE_TAB_TIPO_OPERACAO tipo on (tipo.BDIND_OPER = Mov.BDIND_OPER) ';
          wsql = wsql || ' Where (Pgto.BDDATAPGTOPAR Between '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '       (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '       ((Pgto.BDVALORRETPIS > 0) or (Pgto.BDVALORRETCOFINS > 0) or (Pgto.BDVALORRETCSLL > 0) or (Pgto.BDVALORRETIRRF > 0) or (Pgto.BDVALORRETINSS > 0) or (Pgto.BDVALORRETINSS > 0) or (Pgto.BDVALORRETIRRF > 0)) ';

          IF (prTipoLanServ = 1) THEN
            wsql = wsql || '       and tipo.BDINDICADOR > 0 ';
          ELSE
            wsql = wsql || '       and tipo.BDINDICADOR = 0 ';

          wsql = wsql || ' group by BDCODEMP, BDCHAVE, BDREFLAN, BDCODTER, BDCONDPGTO ';
        END

      wsql = wsql || ') Mov ';
      wsql = wSql || 'LEFT OUTER JOIN VW_TTERCEIRO Ter ON (Ter.BDCODTER = Mov.BDCODTER) ';
      wsql = wSql || 'LEFT OUTER JOIN TCIDADE Cid ON (Cid.BDCODCID = Ter.BDCODCID) ';

      IF ((prtipoapuracaoret = 1) OR (prtipoapuracaoretir = 1))  THEN -- Tipo de apura??o das reten??es = Regime de caixa
        wsql = wsql || 'LEFT OUTER JOIN VEF_EMP_TMOVSERPARPGTO Pgto on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE and Pgto.BDDATAPGTOPAR between '''||prdatainicial||''' and '''||prdatafinal||''') ';

      wsql = wSql || 'Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO ';
      wsql = wSql || 'Order by Mov.BDCODEMP,Mov.BDCODTER,Mov.BDREFLAN';
    END

  wsql = wSql || ') Mov ';
  wsql = wSql || 'join TEMPRESAS Emp on (Emp.BDCODEMP = Mov.BDCODEMP)';

  wrefincial = SUBSTRING(CAST(prdatainicial AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatainicial AS VARCHAR(40)) FROM 6 FOR 2);
  wreffinal = SUBSTRING(CAST(prdatafinal AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatafinal AS VARCHAR(40)) FROM 6 FOR 2);
  wdata_final = prdatafinal;
  wcodteratual = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    :wchave, 
    bdref,
    bdcodter,
    bdnometer,
    bdcgcter,
    bdendter,
    bdcodcid,
    bdnomcid,
    bdcondpgto,
    bdvlrcontab,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,
    bdvlrir,
    bdvlrinss,
    bdvlriss,
    bdvlrirser
  DO
   BEGIN
    wano = SUBSTRING(bdref FROM 1 FOR 4);
    wmes = SUBSTRING(bdref FROM 5 FOR 2);

    IF (prdetalhado = 0) THEN
      BEGIN
         IF (wmes = '01') THEN
            bdmesextenso =  'Janeiro / ' || wano;
         IF (wmes = '02') THEN
            bdmesextenso =  'Fevereiro / ' || wano;
         IF (wmes = '03') THEN
            bdmesextenso =  'Mar?o / ' || wano;
         IF (wmes = '04') THEN
            bdmesextenso =  'Abril / ' || wano;
         IF (wmes = '05') THEN
            bdmesextenso =  'Maio / ' || wano;
         IF (wmes = '06') THEN
            bdmesextenso =  'Junho / ' || wano;
         IF (wmes = '07') THEN
            bdmesextenso =  'Julho / ' || wano;
         IF (wmes = '08') THEN
            bdmesextenso =  'Agosto / ' || wano;
         IF (wmes = '09') THEN
            bdmesextenso =  'Setembro / ' || wano;
         IF (wmes = '10') THEN
            bdmesextenso =  'Outubro / ' || wano;
         IF (wmes = '11') THEN
            bdmesextenso =  'Novembro / ' || wano;
         IF (wmes = '12') THEN
            bdmesextenso =  'Dezembro / ' || wano;

         SUSPEND;

         IF (wcodteratual <> bdcodter) THEN
           BEGIN
             wrefincial = SUBSTRING(CAST(prdatainicial AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatainicial AS VARCHAR(40)) FROM 6 FOR 2);
           END

         /* verifica se precisa adicionar referencias anteriores da atual ex so tem o mes 3 precisa gerar janeiro e fevereiro vazios... */
         WHILE (wrefincial <= wreffinal) DO
          BEGIN
            wcodteratual = bdcodter;
            bdref = wrefincial;
            wano = SUBSTRING(bdref FROM 1 FOR 4);
            wmes = SUBSTRING(bdref FROM 5 FOR 2);

            bdvlrcontab = 0;
            bdvlrpis    = 0;
            bdvlrcofins = 0;
            bdvlrcsocial = 0;
            bdvlrir = 0;
            bdvlrinss = 0;
            bdvlriss = 0;
            bdvlrirser = 0;

            IF (wmes = '01') THEN
               bdmesextenso =  'Janeiro / ' || wano;
            IF (wmes = '02') THEN
               bdmesextenso =  'Fevereiro / ' || wano;
            IF (wmes = '03') THEN
               bdmesextenso =  'Mar?o / ' || wano;
            IF (wmes = '04') THEN
               bdmesextenso =  'Abril / ' || wano;
            IF (wmes = '05') THEN
               bdmesextenso =  'Maio / ' || wano;
            IF (wmes = '06') THEN
               bdmesextenso =  'Junho / ' || wano;
            IF (wmes = '07') THEN
               bdmesextenso =  'Julho / ' || wano;
            IF (wmes = '08') THEN
               bdmesextenso =  'Agosto / ' || wano;
            IF (wmes = '09') THEN
               bdmesextenso =  'Setembro / ' || wano;
            IF (wmes = '10') THEN
               bdmesextenso =  'Outubro / ' || wano;
            IF (wmes = '11') THEN
               bdmesextenso =  'Novembro / ' || wano;
            IF (wmes = '12') THEN
               bdmesextenso =  'Dezembro / ' || wano;
            SUSPEND;


            wdataaux = CAST(SUBSTRING(CAST(wrefincial AS VARCHAR(6)) FROM 5 FOR 2)||'-'||'01'||'-'||SUBSTRING(CAST(wrefincial AS VARCHAR(6)) FROM 1 FOR 4) AS DATE);

            wdataaux = addmonth(wdataaux, 1);

            wrefincial = SUBSTRING(CAST(wdataaux AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataaux AS VARCHAR(40)) FROM 6 FOR 2);

          END
      END
    ELSE
      BEGIN
        IF (wmes = '01') THEN
           bdmesextenso =  'Janeiro / ' || wano;
        IF (wmes = '02') THEN
           bdmesextenso =  'Fevereiro / ' || wano;
        IF (wmes = '03') THEN
           bdmesextenso =  'Mar?o / ' || wano;
        IF (wmes = '04') THEN
           bdmesextenso =  'Abril / ' || wano;
        IF (wmes = '05') THEN
           bdmesextenso =  'Maio / ' || wano;
        IF (wmes = '06') THEN
           bdmesextenso =  'Junho / ' || wano;
        IF (wmes = '07') THEN
           bdmesextenso =  'Julho / ' || wano;
        IF (wmes = '08') THEN
           bdmesextenso =  'Agosto / ' || wano;
        IF (wmes = '09') THEN
           bdmesextenso =  'Setembro / ' || wano;
        IF (wmes = '10') THEN
           bdmesextenso =  'Outubro / ' || wano;
        IF (wmes = '11') THEN
           bdmesextenso =  'Novembro / ' || wano;
        IF (wmes = '12') THEN
           bdmesextenso =  'Dezembro / ' || wano;

        SUSPEND;

      END
   END
END
^

/* Alter (SP_VEF_RETORNA_SALDO_DIME) */
ALTER PROCEDURE SP_VEF_RETORNA_SALDO_DIME(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRREFEMP INTEGER,
PRANO INTEGER)
 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDQUADRO VARCHAR(5),
BDCODEXP INTEGER,
BDSALDO NUMERIC(15,2),
BDDETFILIAL VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WSQL2 VARCHAR(5000);
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCODITEM_81_91 INTEGER;
DECLARE VARIABLE WCODITEM_82_92 INTEGER;
DECLARE VARIABLE WCODITEM_83_93 INTEGER;
DECLARE VARIABLE WCODITEM_84_94 INTEGER;
DECLARE VARIABLE WPLANOCONTAS INTEGER;
BEGIN

  wsql2 = '';
  wsql2 = wsql2||'select emp.bdcodemp, emp.bdcodmatriz, ref.bdcodplapadrao, parser.bddetfilial from tempresas emp ';
  wsql2 = wsql2||'left outer join VW_EMPRESAS_REF_ATUAL ref on (ref.bdcodemp = emp.bdcodemp) ';
  wsql2 = wsql2||'left outer join VW_VEF_BASE_TEMPPARESTSC parser on (parser.bdcodemp = emp.bdcodemp) ';
  IF (:prcodemp <> '') THEN
      wsql2 = wsql2||'where '||:PRCODEMP; -- 11418 - Maicon S. Filtrar todas

  FOR EXECUTE STATEMENT wSQL2 INTO :bdcodemp, :bdcodmatriz, :WPLANOCONTAS, :bddetfilial DO
    BEGIN
      IF ((bdcodmatriz = 0) OR (bdcodmatriz IS NULL)) THEN
         bdcodmatriz = bdcodemp;

      --81_91
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_81_91, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_81_91) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_81_91 is not null) order by tpla.BDCODITEM_81_91'; --and tpla.BDANO = '||:prano||'
    
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_81_91,:bdCODEXP DO
        BEGIN
          bdquadro = '81_91';
    
          --sol:3520 - a rotina da exporta??o da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
          --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
          --alt:#10458 - Quadros 81 e 82 devem igonar o zeramento (quinto parametro da sp)
--          select SALDO_ATUAL from SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, 0, 1, 0)
          SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 0, NULL, NULL, :PRREFEMP, 0, 1, 0)
          INTO :bdSALDO;
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END

      --82_92
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_82_92, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_82_92) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_82_92 is not null) order by tpla.BDCODITEM_82_92'; --and tpla.BDANO = '||:prano||'
    
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_82_92,:bdCODEXP DO
        BEGIN
          bdquadro = '82_92';
    
          --sol:3520 - a rotina da exporta??o da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
          --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
          --alt:#10458 - Quadros 81 e 82 devem igonar o zeramento (quinto parametro da sp)
--          select SALDO_ATUAL from SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, 0, 1, 0)
          SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 0, NULL, NULL, :PRREFEMP, 0, 1, 0)
          INTO :bdSALDO;
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END

      --83_93
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_83_93, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_83_93) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_83_93 is not null) order by tpla.BDCODITEM_83_93'; --and tpla.BDANO = '||:prano||'
    
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_83_93,:bdCODEXP DO
        BEGIN
          bdquadro = '83_93';
    
          IF (bdCODEXP = 353) THEN
             BEGIN
                  --sol:3520 - a rotina da exporta??o da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
                  --select SALDO_DEB from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
                  SELECT SALDO_DEB FROM SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 1, NULL, NULL, :PRREFEMP, 0, 1, 0)
                  INTO :bdSALDO;
             END
          ELSE
             BEGIN
                  --sol:3520 - a rotina da exporta??o da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
                  --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
                  SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 1, NULL, NULL, :PRREFEMP, 0, 1, 0)
                  INTO :bdSALDO;
             END
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END

      --84_94
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_84_94, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_84_94) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_84_94 is not null) order by tpla.BDCODITEM_84_94'; --and tpla.BDANO = '||:prano||'
    
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_84_94,:bdCODEXP DO
        BEGIN
          bdquadro = '84_94';
    
          --sol:3520 - a rotina da exporta??o da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
          --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
          SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 1, NULL, NULL, :PRREFEMP, 0, 1, 0)
          INTO :bdSALDO;
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END
    END

  --suspend;
END
^

/* Alter (SP_VEF_TREEVIEW_CONS_ANUAL_CON2) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ANUAL_CON2(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WQUADROANT INTEGER;
DECLARE VARIABLE WDESQUADROANT VARCHAR(80);
DECLARE VARIABLE WORDEMANT INTEGER;
DECLARE VARIABLE WDESCORDEMANT VARCHAR(80);
DECLARE VARIABLE WANO CHAR(10);
DECLARE VARIABLE WPRIMEIROQUADRO INTEGER;
BEGIN
  /* giovanni */

  /* Procedure Text */

  /* SP Padrao para montar a treeview DA Consulta anual configuravel */

  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wano = SUBSTRING(prref FROM 1 FOR 4);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || 'T.BDREF, ';
  wsql = wsql || 'T.BDCODQPLACONSCONF, ';
  wsql = wsql || 'QUADRO.BDDESCRICAO, ';
  wsql = wsql || 'T.BDORDEM, ';
  wsql = wsql || 'T.BDDESCRICAO,';
  wsql = wsql || 'T.BDVALOR';

  wsql = wsql || ' from VEF_REL_CONS_ANUAL_CONF T';


  /* tirado a spconsultaempresas_sis muito lenta... */
  --  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas on (empresas.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join TPLANOCONSCONF_Q QUADRO on (QUADRO.BDCODQPLACONSCONF = t.BDCODQPLACONSCONF AND QUADRO.BDCODPLACONSCONF = T.BDCODPLACONSCONF) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQPLACONSCONF  = '||:prcodquadro;
    END

  -- wsql = wsql||wwhere || ' order by bdcodemp, bdref desc, BDCODQPLACONSCONF, bdordem' ;
  wsql = wsql||wwhere || ' order by bdcodemp, BDCODQPLACONSCONF, bdordem, bdref  ' ;

  wquadroant = 0;
  wordemant = 0;
  wdesquadroant = '';
  wdescordemant = '';

  wPrimeiroQuadro = 1;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdref,
    bdcodquadro,
    bddescquadro,
    bdordem,
    bddescricao,
    bdvalor

  DO
  BEGIN

     IF (((wordemant = bdordem) OR (wordemant = 0)) AND ((wquadroant = bdcodquadro) OR (wquadroant = 0))) THEN   /* totaliza o quadro e a ordem atual */ -- (((wquadroant = bdcodquadro) or (wquadroant = 0))
        BEGIN
          wquadroant = bdcodquadro;
          wdesquadroant = bddescquadro;
          wordemant = bdordem;
          wdescordemant = bddescricao;

          IF (bdtotal <> 0) THEN
             bdtotal = bdtotal + bdvalor;
          ELSE
             bdtotal = bdvalor;

          IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
             bdjan = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
             bdfev = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
             bdmar = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
             bdabr = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
             bdmai = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
             bdjun = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
             bdjul = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
             bdago = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
             bdset = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
             bdout = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
             bdnov = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
             bddez = bdvalor;

        END

     ELSE
       BEGIN

          IF (((prdetalhaquadro = 1) AND (wquadroant <> bdcodquadro)) OR (wprimeiroquadro = 1)) THEN  /* quebra por quadro */
--         if  ((wprimeiroquadro = 1) and (prdetalhaquadro = 1)) then  /* quebra por quadro */
           BEGIN
             wprimeiroquadro = 0;
             bdordem = NULL;
             bddescricao = bddescquadro;
             SUSPEND;
           END


         bdordem = wordemant;
         bdcodquadro = wquadroant;
         bddescquadro = wdesquadroant;
         bddescricao = wdescordemant;
         SUSPEND;
         wquadroant = 0;
         wordemant = 0;
         bdtotal = 0;

          IF (bdtotal <> 0) THEN
             bdtotal = bdtotal + bdvalor;
          ELSE
             bdtotal = bdvalor;

          IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
             bdjan = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
             bdfev = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
             bdmar = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
             bdabr = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
             bdmai = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
             bdjun = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
             bdjul = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
             bdago = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
             bdset = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
             bdout = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
             bdnov = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
             bddez = bdvalor;


         wdesquadroant = '';
         wdescordemant = '';
       END

  END

  IF (wprimeiroquadro = 1) THEN  /* quebra por quadro */
     BEGIN
       wprimeiroquadro = 0;
       bdordem = NULL;
       bddescricao = bddescquadro;
       SUSPEND;
     END


  bdordem = wordemant;
  bdcodquadro = wquadroant;
  bddescquadro = wdesquadroant;
  bddescricao = wdescordemant;
  SUSPEND;


END
^

/* Alter (SP_VEF_TREEVIEW_CONS_BLOCOM) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOM(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRCLASSIFICACAO VARCHAR(11) = NULL,
PRCODQUADRO INTEGER = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDREFERENCIA INTEGER,
BDCODQUADRO INTEGER,
BDNUMCAMPO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,2),
BDTIPO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WNUMCAMPO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(11);
DECLARE VARIABLE WDESCRICAO VARCHAR(80);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA, NULL, NULL);

  wSQL =       'select reg.BDCODEMP, reg.BDCODMATRIZ, reg.BDREFERENCIA, reg.BDCODQUADRO, reg.BDNUMCAMPO, reg.BDVALOR, ';
  wSQL = wSQL||       'q.BDCLASSIFICACAO, ';
  wSQL = wSQL||       'case ';
  wSQL = wSQL||         'when reg.BDCODQUADRO in (15,33) then '; -- 15 - M200 - Consolida??o da contribui??o para o PIS/PASEP / 33 - M600 - Consolida??o da contribui??o para o Cofins
  wSQL = wSQL||            'case reg.BDNUMCAMPO ';
  wSQL = wSQL||               'when  2 then ''Valor total do per?odo'' ';
  wSQL = wSQL||               'when  3 then ''Valor do cr?dito descontado, apurado no per?odo'' ';
  wSQL = wSQL||               'when  4 then ''Valor do cr?dito descontado, apurado em per?odo anterior'' ';
  wSQL = wSQL||               'when  5 then ''Valor total da contribui??o n?o cumulativa devida'' ';
  wSQL = wSQL||               'when  6 then ''Valor retido na fonte deduzido'' ';
  wSQL = wSQL||               'when  7 then ''Outras dedu??es no per?odo'' ';
  wSQL = wSQL||               'when  8 then ''Valor da contribui??o n?o cumulativa a recolher/pagar'' ';
  wSQL = wSQL||               'when  9 then ''Valor Total da Contribui??o Cumulativa'' ';
  wSQL = wSQL||               'when 10 then ''Valor retido na fonte deduzido'' ';
  wSQL = wSQL||               'when 11 then ''Outras dedu??es do per?odo'' ';
  wSQL = wSQL||               'when 12 then ''Valor da contribui??o cumulativa a recolher/pagar'' ';
  wSQL = wSQL||               'when 13 then ''Valor total da contribui??o a recolher/pagar no per?odo'' ';
  wSQL = wSQL||            'end ';
  wSQL = wSQL||         'when reg.BDCODQUADRO in (34) then '; -- 34 - Contribui??o n?o cumulativa
  wSQL = wSQL||            'case reg.BDNUMCAMPO ';
  wSQL = wSQL||               'when 1 then ''Tributada no mercado interno'' ';
  wSQL = wSQL||               'when 2 then ''N?o tributada no mercado interno'' ';
  wSQL = wSQL||               'when 3 then ''Exporta??o'' ';
  wSQL = wSQL||            'end ';
  wSQL = wSQL||         'when reg.BDCODQUADRO in (35) then '; -- 35 - Contribui??o cumulativa
  wSQL = wSQL||               ' ''Receita bruta cumulativa'' ';
  wSQL = wSQL||         'when reg.BDCODQUADRO in (36) then '; -- 36 - Contribui??o Total (Valores n?o cumulativos + cumulativos)
  wSQL = wSQL||               ' ''Receita bruta total'' ';
  wSQL = wSQL||       'end as BDDESCRICAO ';
  wSQL = wSQL||'from VEF_EMP_TBLOCOMGERREG reg ';
  wSQL = wSQL||'left outer join VEF_BASE_TCONFBLOCOMQ q on (q.BDCODQUADRO = reg.BDCODQUADRO) ';

  wWhere = '';

  IF (:prCODEMP IS NOT NULL) THEN
    wWhere = ' where reg.BDCODMATRIZ = '||:PRCODEMP;

  IF (:prREFERENCIA IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere || ' and ';
      ELSE
        wWhere = ' where ';

      wWhere = wWhere||' reg.BDREFERENCIA = '||:prREFERENCIA;
    END

  IF (:prCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere || ' and ';
      ELSE
        wWhere = ' where ';

      wWhere = wWhere||' q.BDCLASSIFICACAO LIKE '''||:prCLASSIFICACAO||'%''';
    END

  IF (:prCODQUADRO IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere || ' and ';
      ELSE
        wWhere = ' where ';

      wWhere = wWhere||' reg.BDCODQUADRO'||' = '||:prCODQUADRO;
    END

   wSQL = wSQL||wWhere||' order by reg.BDCODEMP, reg.BDCODMATRIZ, reg.BDREFERENCIA, reg.BDCODQUADRO, reg.BDNUMCAMPO, q.BDCLASSIFICACAO ';

   IF (prCODQUADRO = 1) THEN -- Resumo
     BEGIN
       wSQL =       'select aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODQUADRO, aux.BDNUMCAMPO, ';
       wSQL = wSQL||       'SUM(aux.BDVALOR) as BDVALOR, ';
       wSQL = wSQL||       '0 as BDCLASSIFICACAO, ';
       wSQL = wSQL||       'case when (aux.BDNUMCAMPO = 1) then ''Valor total da contribui??o n?o cumulativa'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 2) then ''Valor do cr?dito descontado, retida na fonte e outras dedu??es'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 3) then ''Valor da contribui??o n?o cumulativa a recolher/pagar'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 4) then ''Valor total da contribui??o cumulativa'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 5) then ''Valor da contribui??o retida na fonte e outras dedu??es'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 6) then ''Valor da contribui??o cumulativa a recolher/pagar'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 7) then ''Valor da contribui??o a recolher no per?odo'' ';
       wSQL = wSQL||       'end as BDDESCRICAO ';
       wSQL = wSQL||'from ( ';
       wSQL = wSQL||      'select reg.BDCODEMP, reg.BDCODMATRIZ, reg.BDREFERENCIA, reg.BDCODQUADRO, reg.BDVALOR, ';
       wSQL = wSQL||             'case when (reg.BDNUMCAMPO = 2) then 1 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO in (3,4,6,7)) then 2 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO = 8) then 3 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO = 9) then 4 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO in (10,11)) then 5 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO = 12) then 6 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO = 13) then 7 ';
       wSQL = wSQL||             'end as BDNUMCAMPO ';
       wSQL = wSQL||      'from VEF_EMP_TBLOCOMGERREG reg ';
       wSQL = wSQL||      'where reg.BDCODQUADRO in (15,33) ';

       IF (:prCODEMP IS NOT NULL) THEN
         wSQL = wSQL||      ' and reg.BDCODMATRIZ = '||:PRCODEMP;
     
       IF (:prREFERENCIA IS NOT NULL) THEN
         wSQL = wSQL||      ' and reg.BDREFERENCIA = '||:prREFERENCIA;

       wSQL = wSQL||      ') aux ';
       wSQL = wSQL||'where aux.BDNUMCAMPO is not null ';
       wSQL = wSQL||'group by aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODQUADRO, aux.BDNUMCAMPO ';
       wSQL = wSQL||'order by aux.BDCODMATRIZ, aux.BDCODEMP, aux.BDREFERENCIA, aux.BDCODQUADRO ';
     END

   FOR
       EXECUTE STATEMENT wSQL
   INTO
     :wCODEMP,
     :wCODMATRIZ,
     :wREFERENCIA,
     :wCODQUADRO,
     :wNUMCAMPO,
     :wVALOR,
     :wCLASSIFICACAO,
     :wDESCRICAO
   DO
     BEGIN
       BDCODEMP        = :wCODEMP;
       BDCODMATRIZ     = :wCODMATRIZ;
       BDREFERENCIA    = :wREFERENCIA;
       BDCODQUADRO     = :wCODQUADRO;
       BDCLASSIFICACAO = :wCLASSIFICACAO;

       IF (prCODQUADRO = 1) THEN -- Resumo
         BEGIN
           IF ((:wCODQUADRO IN (15,33)) AND (:wNUMCAMPO = 1)) THEN
             BEGIN
               BDTIPO     = 0; -- T?tulo
               BDVALOR    = NULL;
               BDNUMCAMPO = NULL;
               IF (:wCODQUADRO = 15) THEN
                 BDDESCRICAO = 'PIS';
               ELSE
               IF (:wCODQUADRO = 33) THEN
                 BDDESCRICAO = 'Cofins';

               SUSPEND;
             END

           /* 15 - M200 - Consolida??o da contribui??o para o PIS/PASEP
              33 - M600 - Consolida??o da contribui??o para o Cofins */
           IF ((:wCODQUADRO IN (15,33)) AND (:wNUMCAMPO IN (1,4,7))) THEN
             BEGIN
               BDTIPO     = 0; -- T?tulo
               BDVALOR    = NULL;
               BDNUMCAMPO = NULL;
               IF (:wNUMCAMPO = 1) THEN
                 BDDESCRICAO = 'Contribui??o n?o cumulativa';
               ELSE
               IF (:wNUMCAMPO = 4) THEN
                 BDDESCRICAO = 'Contribui??o cumulativa';
               ELSE
               IF (:wNUMCAMPO = 7) THEN
                 BDDESCRICAO = 'Contribui??o total(cumulativa + n?o cumulativa)';
    
               SUSPEND;
             END
         END
       ELSE
       /* 15 - M200 - Consolida??o da contribui??o para o PIS/PASEP
          33 - M600 - Consolida??o da contribui??o para o Cofins */
       IF ((:wCODQUADRO IN (15,33)) AND (:wNUMCAMPO IN (2,9,13))) THEN
         BEGIN
           BDTIPO     = 0; -- T?tulo
           BDVALOR    = NULL;
           BDNUMCAMPO = NULL;
           IF (:wNUMCAMPO = 2) THEN
             BDDESCRICAO = 'Contribui??o n?o cumulativa';
           ELSE
           IF (:wNUMCAMPO = 9) THEN
             BDDESCRICAO = 'Contribui??o cumulativa';
           ELSE
           IF (:wNUMCAMPO = 13) THEN
             BDDESCRICAO = 'Contribui??o total(cumulativa + n?o cumulativa)';

           SUSPEND;
         END

       /* 34 - Contribui??o n?o cumulativa
          35 - Contribui??o cumulativa
          36 - Contribui??o Total (Valores n?o cumulativos + cumulativos) */
       IF ((:wCODQUADRO IN (34,35,36)) AND (:wNUMCAMPO IN (1))) THEN
         BEGIN
           BDTIPO     = 0; -- T?tulo
           BDVALOR    = NULL;
           BDNUMCAMPO = NULL;
           IF (:wCODQUADRO = 34) THEN
             BDDESCRICAO = 'Contribui??o n?o cumulativa';
           ELSE
           IF (:wCODQUADRO = 35) THEN
             BDDESCRICAO = 'Contribui??o cumulativa';
           ELSE
           IF (:wCODQUADRO = 36) THEN
             BDDESCRICAO = 'Contribui??o Total (Valores n?o cumulativos + cumulativos)';

           SUSPEND;
         END

       BDTIPO          = 1; -- Analit?ca
       BDNUMCAMPO      = :wNUMCAMPO;
       BDVALOR         = :wVALOR;
       BDCLASSIFICACAO = :wCLASSIFICACAO;
       BDDESCRICAO     = :wDESCRICAO;

       SUSPEND;
     END
     
END
^

/* Alter (SP_VEF_TREEVIEW_CONS_BLOCOP) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCLASSIFICACAO VARCHAR(10),
PRGERAL INTEGER,
PREMPFIL INTEGER,
PRCODIGOAJUSTE VARCHAR(8),
PRREINF DM_BOOLEAN)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM DM_BDNOMEMP,
BDVALOR NUMERIC(15,2),
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODEMPFILIAL INTEGER,
BDORDENATVPREV INTEGER,
BDCODIGOATVPREV VARCHAR(8),
BDDESCPREV VARCHAR(550),
BDNOMEMPFIL VARCHAR(100),
BDCODTIPO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,2);
DECLARE VARIABLE WEMPANT INTEGER;
DECLARE VARIABLE WATVANT INTEGER;
DECLARE VARIABLE PRSALVAQUADROANT INTEGER;
DECLARE VARIABLE PRCLASSIFIANT VARCHAR(10);
DECLARE VARIABLE PRDESCQUADROANT VARCHAR(80);
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WCLASSIFITITULO VARCHAR(10);
DECLARE VARIABLE PRULTIMOCLASSIFITIT VARCHAR(10);
DECLARE VARIABLE WISREINF CHAR(1);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);
  PRREINF = UPPER(:PRREINF);

  wIsReinf = SUBSTRING(:PRREINF FROM 1 FOR 1);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || ' IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) BDCODCONFBLOCOP, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQBLOCOP, ';
  wsql = wsql || 'TCONF.bddescqBLOCOP,';
  wsql = wsql || 'TCONFBLOCOPFORM.bddescformBLOCOP,';
  wsql = wsql || 'T.BDVALOR, ';
  wsql = wsql || 'TCONF.BDCLASSIFICACAO, ';
  wsql = wsql || 'NULL BDCODEMPFILIAL, ';
  wsql = wsql || 'NULL BDORDENATVPREV, ';
  wsql = wsql || 'NULL BDCODIGOATVPREV, ';
  wsql = wsql || 'NULL BDDESCPREV, ';
  wsql = wsql || 'NULL BDNOMEMPFIL, ';
  wsql = wsql || 'TCONF.BDCODTIPO ';

  wsql = wsql || 'from VEF_EMP_TBLOCOPGERREG T';

  wsql = wsql||' JOIN VEF_EMP_TBLOCOPGER GER ON(GER.BDCODEMP = T.BDCODEMP AND GER.BDCODPERIODO = T.BDCODPERIODO AND GER.BDREFERENCIA = T.BDREFERENCIA AND GER.BDREINF = '||''''||:wIsReinf||''''||' AND GER.BDCODCONFBLOCOP = T.BDCODCONFBLOCOP)';
  wsql = wsql||' left outer join vw_emp_ref_total empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFBLOCOPQ TCONF on (TCONF.bdcodqBLOCOP = t.bdcodqBLOCOP ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFBLOCOPFORM TCONFBLOCOPFORM on (TCONFBLOCOPFORM.bdcodconfBLOCOP = IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) and TCONFBLOCOPFORM.bdcodqBLOCOP = T.BDCODQBLOCOP  and TCONFBLOCOPFORM.bdnumcampoBLOCOP = T.BDNUMCAMPO) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (wWhere <> '') THEN
    wWhere = wWhere || ' AND ';
  ELSE
    wWhere = wWhere || ' WHERE ';

  --wWhere = wWhere || 'T.BDCODCONFBLOCOP = '||:wCodConfBlocoP;
  wWhere = wWhere || 'T.BDCODCONFBLOCOP = '||'IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) ';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

/*  if (:prcodquadro is not null) then
    begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       else
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQBLOCOP = '||:prcodquadro;
    end*/

  IF (PRCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'TCONF.bdclassificacao LIKE '''||:PRCLASSIFICACAO||'%''';
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'('||:prcodperiodo||')';
    END


  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQBLOCOP, bdCODPERIODO, bdnumcampo' ;

  prrefant        = 0;
  prquadroant     = 0;
  PRULTIMOCLASSIFITIT = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR,
    BDCLASSIFICACAO,
    BDCODEMPFILIAL,
    BDORDENATVPREV,
    BDCODIGOATVPREV,
    BDDESCPREV,
    BDNOMEMPFIL,
    BDCODTIPO
  DO
  BEGIN
    bdanomesfinal   = pranomesfinal;
    bdanomesinicial = pranomesinicial;
    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;

    --Refer?ncia
    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        SUSPEND;
      END

    --Quadro
    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF  (prultimoclassifitit <> wclassifititulo) THEN
              BEGIN

                SELECT x.bdcodqblocop, x.bddescqblocop FROM vef_base_tconfblocopq x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;


                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
              END

          END

        bdnumcampo = NULL;
        BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        BDVALOR = NULL;
        prquadroant = bdcodquadro;

        SUSPEND;



        --bdnumcampo = null;
        --BDDESCFORM =  BDDESCQUADRO;
        --BDVALOR = null;
        --suspend;
      END

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = prvalor;

    prrefant = bdreferencia;
    prquadroant = bdcodquadro;

    SUSPEND;
  END

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || ' IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) BDCODCONFBLOCOP, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQBLOCOP, ';
  wsql = wsql || 'TCONF.bddescqBLOCOP,';
  wsql = wsql || 'TCONFBLOCOPFORM.bddescformBLOCOP,';
  wsql = wsql || 'T.BDVALOR, ';
  wsql = wsql || 'TCONF.BDCLASSIFICACAO, ';
  wsql = wsql || 'T.BDCODEMPFILIAL, ';
  wsql = wsql || 'T.BDORDENATVPREV, ';
  wsql = wsql || 'prev.bdcodigoatvprev, ';
  wsql = wsql || 'prev.bddescprev, ';
  wsql = wsql || ' (select n2.bdnomemp from vw_emp_ref_total n2 where n2.bdcodemp = T.BDCODEMPFILIAL) as BDNOMEMPFIL, ';
  wsql = wsql || 'TCONF.BDCODTIPO ';

  wsql = wsql || 'from vef_emp_tblocopger_filial T';

  wsql = wsql||' JOIN VEF_EMP_TBLOCOPGER GER ON(GER.BDCODEMP = T.BDCODEMP AND GER.BDCODPERIODO = T.BDCODPERIODO AND GER.BDREFERENCIA = T.BDREFERENCIA AND GER.BDREINF = '||''''||:wIsReinf||''''||' AND GER.BDCODCONFBLOCOP = T.BDCODCONFBLOCOP)';
  wsql = wsql||' left outer join vw_emp_ref_total empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFBLOCOPQ TCONF on (TCONF.bdcodqBLOCOP = t.bdcodqBLOCOP ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFBLOCOPFORM TCONFBLOCOPFORM on (TCONFBLOCOPFORM.bdcodconfBLOCOP = IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) and TCONFBLOCOPFORM.bdcodqBLOCOP = T.BDCODQBLOCOP  and TCONFBLOCOPFORM.bdnumcampoBLOCOP = T.BDNUMCAMPO) ' ;
  wsql = wsql||' join VEF_BASE_TTABATVCONPREV prev on (t.bdordenatvprev = prev.bdordenatvprev) ';
  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (wWhere <> '') THEN
    wWhere = wWhere || ' AND ';
  ELSE
    wWhere = wWhere || ' WHERE ';

  --wWhere = wWhere || 'T.BDCODCONFBLOCOP = '||:wCodConfBlocoP;
  wWhere = wWhere || 'T.BDCODCONFBLOCOP = '||'IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) ';


  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

/*  if (:prcodquadro is not null) then
    begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       else
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQBLOCOP = '||:prcodquadro;

    end*/

  IF (PRCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'TCONF.bdclassificacao LIKE '''||:PRCLASSIFICACAO||'%''';
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'('||:prcodperiodo||')';
    END

  IF (:PREMPFIL IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'(T.BDCODEMPFILIAL = '||:PREMPFIL||')';
    END

  IF (:prcodigoajuste IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'(prev.BDCODIGOATVPREV = '||''''||:prcodigoajuste||''''||')';
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';
  ELSE
     wwhere = wwhere||' where ';

  wwhere = wwhere||' ((T.BDCODQBLOCOP = 4 and T.BDVALOR > 0) or (T.BDCODQBLOCOP <> 4)) ';

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODEMPFILIAL,BDCODQBLOCOP, bdCODPERIODO, BDORDENATVPREV, bdnumcampo' ;

  prrefant        = 0;
  prquadroant     = 0;
  WEMPANT         = 0;
  WATVANT         = 0;

  PRULTIMOCLASSIFITIT = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR,
    BDCLASSIFICACAO,
    BDCODEMPFILIAL,
    BDORDENATVPREV,
    BDCODIGOATVPREV,
    BDDESCPREV,
    BDNOMEMPFIL,
    BDCODTIPO
  DO
  BEGIN
    bdanomesfinal   = pranomesfinal;
    bdanomesinicial = pranomesinicial;
    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;

    --Refer?ncia
    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        SUSPEND;
      END

    --Empresa FILIAL
    IF ((prGeral = 1) AND (WEMPANT <> bdcodempfilial)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  bdcodempfilial||' - '||BDNOMEMPFIL;
        BDVALOR = NULL;
        SUSPEND;
      END

    --Quadro
    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF  (prultimoclassifitit <> wclassifititulo) THEN
              BEGIN

                --select x.bddescqblocop from vef_base_tconfblocopq x where x.bdclassificacao = :wclassifititulo into :bddescform;
                SELECT x.bdcodqblocop, x.bddescqblocop FROM vef_base_tconfblocopq x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;


                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
              END

          END

        bdnumcampo = NULL;
        --BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        BDDESCFORM = BDDESCQUADRO;
        BDVALOR = NULL;
        prquadroant = bdcodquadro;

        SUSPEND;
        --bdnumcampo = null;
        --BDDESCFORM =  BDDESCQUADRO;
        --BDVALOR = null;
        --suspend;

      END

    IF (BDCODTIPO = 73) THEN
       BEGIN
            bdnumcampo = prnumcampo;
            bddescform = prdescform;
            bdvalor = prvalor;
        
            prrefant = bdreferencia;
            prquadroant = bdcodquadro;
            --WEMPANT = bdcodempfilial;
            --WATVANT = bdordenatvprev;

            SUSPEND;
       END
    ELSE
       BEGIN
            --Atividade
            IF ((prGeral = 1) AND (WATVANT <> bdordenatvprev) OR (WEMPANT <> bdcodempfilial)) THEN
              BEGIN
                bdnumcampo = NULL;
                BDDESCFORM =  SUBSTRING(BDCODIGOATVPREV||' - '||BDDESCPREV FROM 1 FOR 80);
                BDVALOR = NULL;
                SUSPEND;
              END
        
            bdnumcampo = prnumcampo;
            bddescform = prdescform;
            bdvalor = prvalor;
        
            prrefant = bdreferencia;
            prquadroant = bdcodquadro;
            WEMPANT = bdcodempfilial;
            WATVANT = bdordenatvprev;
        
            SUSPEND;
       END
  END

END
^

/* Alter (SP_VEF_TREEVIEW_CONS_CALCATIVO) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_CALCATIVO(PRCODEMP VARCHAR(10000),
PRCODBEM VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO VARCHAR(30))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDREFERENCIA INTEGER,
BDFATOR NUMERIC(15,6),
BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE PRCODBEMANT INTEGER;
DECLARE VARIABLE PRNOMEBEMANT VARCHAR(100);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  /*agrupar por empresa*/
  IF (prgrupo = 1) THEN
     BEGIN
       wSql = 'select tativo.BDCODEMP, ';
       wSql = wSql || 'emp.BDNOMEMP ';
     END
  ELSE
  /*agrupar por bem*/
  IF (prGrupo = 2) THEN
     BEGIN
       wSql = 'select tativo.BDCODBEM, ';
       wSql = wSql || 'tbem.BDNOMBEM ';
     END
  ELSE
     BEGIN
       wSql = 'select tativo.BDCODEMP, ';
       wSql = wSql || 'emp.BDNOMEMP, ';
       wSql = wSql || 'tativo.BDCODBEM, ';
       wSql = wSql || 'tbem.BDNOMBEM, ';
       wSql = wSql || 'tativo.BDREFERENCIA, ';
       wSql = wSql || 'tativo.BDFATOR, ';
       wSql = wSql || 'tativo.BDVALOR ';
     END

  wsql = wsql || 'from vef_emp_tfichaativo tativo ';

  wsql = wsql||'left outer join SP_CONSULTAEMPRESAS_SIS('|| prrefatual || ', tativo.bdcodemp, null) emp on (emp.bdcodemp = tativo.bdcodemp ) ' ;

  IF (prgrupo IS NOT NULL) THEN
     wsql = wSql||'left outer join EMPRESAS_TBEM TBEM on (tbem.bdcodemp = emp.bdcodemp and tbem.bdcodbem = tativo.bdCODBEM) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wWhere||PRCODEMP||' ';

  IF ((prcodbem IS NOT NULL) OR (prcodbem > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||PRCODBEM||' ';
     END

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFERENCIA >= '||prrefini||' ';
     END

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFERENCIA <= '||prreffin||' ';
     END

  IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

  IF (prgrupo = 1) THEN
     BEGIN
       wgroupby = 'group by bdcodemp, bdnomemp ';
       worderby = 'order by bdcodemp ';
      END
  ELSE
  IF (prGrupo = 2) THEN
     BEGIN
       wgroupby = 'group by bdcodbem, bdnombem ';
       worderby = 'order by bdcodbem ';
     END
  ELSE
     BEGIN
       wgroupby = '';
       worderby = 'order by bdcodemp, bdcodbem, bdreferencia ';
     END

  wsql = wsql||wwhere||wgroupby||worderby;

  IF (prgrupo = 1) THEN
     BEGIN
        FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODEMP,
            :BDNOMEMP
          DO
          SUSPEND;
    END
 ELSE
 IF (prgrupo = 2) THEN
   BEGIN
     FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODBEM,
            :BDNOMBEM
          DO
          SUSPEND;
   END
 ELSE
    BEGIN
       prcodbemant = 0;
       FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODEMP,
            :BDNOMEMP,
            :BDCODBEM,
            :BDNOMBEM,
            :BDREFERENCIA,
            :BDFATOR,
            :BDVALOR
          DO


       /* Giovanni inicio para nao repetir o nome do bem em todos os meses
       if (prCodBemAnt = bdcodbem) then
         begin
           prCodBemAnt = bdcodbem;
           prnomebemant = bdnombem;

           bdcodbem = null;
           bdnombem = null;
           suspend;
           bdcodbem = prCodBemAnt;
           bdnombem = prnomebemant;
        end
       else
         begin
           suspend;
           prcodbemant = bdcodbem;
         end

         */

       SUSPEND;
    END
END
^

/* Alter (SP_VEF_TREEVIEW_CONS_DACON) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DACON(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRTIPO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(160),
BDDESCFORM VARCHAR(160),
BDVALOR NUMERIC(18,6),
BDVALOR2 NUMERIC(18,6),
BDVALOR3 NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODREC INTEGER,
BDTIPOCREDITO INTEGER,
BDTIPOCONFDACON INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(150);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WVALOR2 NUMERIC(18,6);
DECLARE VARIABLE WVALOR3 NUMERIC(18,6);
DECLARE VARIABLE PRCODPERIODOANT INTEGER;
DECLARE VARIABLE WNUMITEM INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WBDTIPOCREDITO INTEGER;
DECLARE VARIABLE WBDDESCREC VARCHAR(150);
DECLARE VARIABLE WBDDESCTIPOCRED VARCHAR(100);
DECLARE VARIABLE WDESCQUADRO VARCHAR(150);
DECLARE VARIABLE WDESCQUADROBKP VARCHAR(150);
DECLARE VARIABLE WDESC1424 VARCHAR(150);
DECLARE VARIABLE WITEM1424 INTEGER;
DECLARE VARIABLE WCODTIPOQUADRO1424 INTEGER;
DECLARE VARIABLE WBDCNPJPART VARCHAR(18);
DECLARE VARIABLE WSALVACNPJPART VARCHAR(18);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select distinct T.BDCODEMP, ';
  wsql = wsql || 'emp.BDNOMEMP, ';
--  wsql = wsql || 'empresas.BDCODCONFDACON, ';
  wsql = wsql || 'empresas.bdcodconfdacon, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQDACON, ';
  wsql = wsql || 'TCONF.bddescqDACON,';
  wsql = wsql || 'TCONFDACONFORM.bddescformDACON,';
  wsql = wsql || 'T.BDVALOR, ';
  wsql = wsql || 'T.BDVALOR2, ';
  wsql = wsql || 'T.BDVALOR3, ';
  wsql = wsql || 'TCONFDACONFORM.BDNUMITEM, ';
  wsql = wsql || 'TCONF.BDCLASSIFICACAO, ';
  wsql = wsql || 'T.BDCODREC, ';
  wsql = wsql || 'rec.BDDESCREC, ';
  wsql = wsql || 't.BDTIPOCREDITO, ';
  wsql = wsql || 'TIPOCRED.BDDESCTIPOCRED, ';

  wsql = wsql || 'TCONFDACONFORM1424.bddescformdacon, ';
  wsql = wsql || 'TCONFDACONFORM1424.BDNUMITEM, ';
  wsql = wsql || 'TCONF.BDCODTIPO, ';
  wsql = wsql || 'TCONFDACON.BDTIPOCONFDACON, ';
  wsql = wsql || 'T.BDCNPJ ';


--  wsql = wsql || 'BDQBH ';
  wsql = wsql || 'from VW_VEF_EMP_TDACONGERUNION T';


  wsql = wsql||' left outer join VW_VEF_BASE_TEMPPARGER empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join vw_tempresas_ref emp on (emp.bdcodemp = t.bdcodemp ) ' ;
--  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join tcodrec rec on (t.bdcodrec = rec.bdcodrec) ';

  wsql = wsql||' left outer join VEF_BASE_TCONFDACONQ TCONF on (TCONF.bdcodqDACON = t.bdcodqDACON ) ' ;
--  wsql = wsql||' left outer join VEF_BASE_TCONFDACONFORM TCONFDACONFORM on (TCONFDACONFORM.bdcodconfDACON = empresas.bdcodconfDACON  and TCONFDACONFORM.bdcodqDACON = T.BDCODQDACON  and TCONFDACONFORM.bdnumcampoDACON = T.BDNUMCAMPO) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFDACONFORM TCONFDACONFORM on (TCONFDACONFORM.bdcodconfDACON = empresas.bdcodconfdacon  and TCONFDACONFORM.bdcodqDACON = T.BDCODQDACON  and TCONFDACONFORM.bdnumcampoDACON = T.BDNUMCAMPO) ' ;

  wsql = wsql||' left outer join vef_base_tconfdaconf1424 TCONFDACONFORM1424 on (TCONFDACONFORM1424.bdcodconfDACON = empresas.bdcodconfdacon  and TCONFDACONFORM1424.bdcodqDACON = T.BDCODQDACON  and TCONFDACONFORM1424.bdnumcampoDACON = T.BDNUMCAMPO) ' ;

  wsql = wsql||' left outer join VEF_BASE_TTABTIPOSCREDTODOS TIPOCRED on (TIPOCRED.bdtipocredito = T.bdtipocredito ) ' ;

  wsql = wsql||' left outer join VEF_BASE_TCONFDACON TCONFDACON on (empresas.bdcodconfdacon = TCONFDACON.bdcodconfdacon ) ' ;


  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;


  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQDACON = '||:prcodquadro;

    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'('||:prcodperiodo||')';
    END

  IF (:PRTIPO IS NOT NULL) THEN
    BEGIN
       IF (PRTIPO = 2) THEN--PIS
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
            ELSE
               wwhere = wwhere||' where ';
    
            --wwhere = wWhere||'(T.BDCODQDACON in (60,61,62,68,69,70))';
            wwhere = wWhere||'(TCONF.BDCODTIPO in (64,65,66))';
          END
       ELSE
       IF (PRTIPO = 3) THEN--COFINS
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
            ELSE
               wwhere = wwhere||' where ';
    
            --wwhere = wWhere||'(T.BDCODQDACON in (64,65,66,72,73,74))';
            wwhere = wWhere||'(TCONF.BDCODTIPO in (67,68,69))';
          END
       ELSE
       IF (PRTIPO = 4) THEN --Dacon
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
            ELSE
               wwhere = wwhere||' where ';
    
            --wwhere = wWhere||'(T.BDCODQDACON not in (60,61,62,68,69,70,64,65,66,72,73,74))';
            wwhere = wWhere||'(TCONF.BDCODTIPO not in (64,65,66,67,68,69))';
          END
    END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc , BDCLASSIFICACAO/*BDCODQDACON*/ ,bdcodrec,BDCNPJ,BDTIPOCREDITO,bdnumcampo, bdCODPERIODO';

  prrefant        = 0;
  prquadroant     = 0;
  prcodperiodoant = 0;
  wcodrec         = 0;
  wBDTIPOCREDITO  = 0;
  WDESCQUADRO     = '';
  WSALVACNPJPART  = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR,
    BDVALOR2,
    BDVALOR3,
    BDNUMITEM,
    BDCLASSIFICACAO,
    BDCODREC,
    wBDDESCREC,
    BDTIPOCREDITO,
    wbddesctipocred,
    WDESC1424 ,
    WITEM1424,
    Wcodtipoquadro1424,
    BDTIPOCONFDACON,
    WBDCNPJPART

  DO
  BEGIN
    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    wvalor = bdvalor;
    wvalor2 = bdvalor2;
    wvalor3 = bdvalor3;
    wNumItem = bdnumitem;
--    wcodrec  = bdcodrec;

    --Refer?ncia
    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        BDVALOR2 = NULL;
        BDVALOR3 = NULL;
        BDNUMITEM = NULL;
        --prrefant = bdreferencia;
        SUSPEND;
      END

    --Quadro
    IF (/*(prGeral = 1) and */(prquadroant <> bdcodquadro)) THEN
      BEGIN
        IF ((((Wcodtipoquadro1424 = 64) AND (:PRCODQUADRO IS NULL)) OR ((Wcodtipoquadro1424 IN (64,65,66)) AND (:PRCODQUADRO IS NOT NULL))) OR
            (((Wcodtipoquadro1424 = 67) AND (:PRCODQUADRO IS NULL)) OR ((Wcodtipoquadro1424 IN (67,68,69)) AND (:PRCODQUADRO IS NOT NULL))) OR (PRTIPO = 1)) THEN
           BEGIN
            WDESCQUADROBKP = BDDESCQUADRO;
            IF (Wcodtipoquadro1424 IN (64,65,66)) THEN
               BDDESCQUADRO = 'Apura??o do PIS';
            ELSE
               IF (Wcodtipoquadro1424 IN (67,68,69)) THEN
                  BDDESCQUADRO = 'Apura??o do Cofins';
               ELSE
                  BDDESCQUADRO = 'Dacon';

            bdnumcampo = NULL;
            BDDESCFORM =  BDDESCQUADRO;
            BDNUMITEM = NULL;
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            wBDTIPOCREDITO = 0;
            --prquadroant = bdcodquadro;
            IF ((WDESCQUADRO <> BDDESCQUADRO) OR ((:PRTIPO IS NULL) OR (PRTIPO <> 1))) THEN
               SUSPEND;

            WDESCQUADRO = BDDESCQUADRO;
            BDDESCQUADRO = WDESCQUADROBKP;
           END
        ELSE
           IF (WDESCQUADRO = '') THEN
             BEGIN
                WDESCQUADROBKP = BDDESCQUADRO;
                BDDESCQUADRO = 'Dacon';
                bdnumcampo = NULL;
                BDDESCFORM =  BDDESCQUADRO;
                BDNUMITEM = NULL;
                BDVALOR = NULL;
                BDVALOR2 = NULL;
                BDVALOR3 = NULL;
                wBDTIPOCREDITO = 0;
                --prquadroant = bdcodquadro;
                SUSPEND;
    
                WDESCQUADRO = BDDESCQUADRO;
                BDDESCQUADRO = WDESCQUADROBKP;
              END

        bdnumcampo = NULL;
        BDDESCFORM =  BDDESCQUADRO;
        BDNUMITEM = NULL;
        BDVALOR = NULL;
        BDVALOR2 = NULL;
        BDVALOR3 = NULL;
        wBDTIPOCREDITO = 0;
        --prquadroant = bdcodquadro;
        IF ((:PRTIPO IS NULL) OR (PRTIPO <> 1)) THEN
           SUSPEND;
      END

    IF ((:PRTIPO IS NULL) OR (PRTIPO <> 1)) THEN
       BEGIN
        --Per?odo
        IF (((prcodperiodoant <> bdcodperiodo) OR ((prquadroant <> bdcodquadro) AND (prcodperiodoant = bdcodperiodo))) AND (bdCodperiodo IN (2,3,4,5,6))) THEN
          BEGIN
            bdnumcampo = NULL;
            IF (bdcodperiodo = 2) THEN
               BDDESCFORM =  '1? dec?ndio';
            ELSE
            IF (bdcodperiodo = 3) THEN
               BDDESCFORM =  '2? dec?ndo';
            ELSE
            IF (bdcodperiodo = 4) THEN
               BDDESCFORM =  '3? dec?ndio';
            ELSE
            IF (bdcodperiodo = 5) THEN
               BDDESCFORM =  '1? quinzena';
            ELSE
            IF (bdcodperiodo = 6) THEN
               BDDESCFORM =  '2? quinzena';
    
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            BDNUMITEM = NULL;
            --prcodperiodoant = bdcodperiodo;
            SUSPEND;
          END
    
        IF ((BDCODREC IS NOT NULL) AND  (wcodrec <> BDCODREC)) THEN
          BEGIN
            bdnumcampo = NULL;
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            BDNUMITEM = NULL;
            wcodrec = BDCODREC;
            bddescform = bdcodrec || ' - '||wBDDESCREC;
    --        bdcodrec  =  ;
            SUSPEND;
          END
    

        IF ((WBDCNPJPART IS NOT NULL) AND  (WSALVACNPJPART <> WBDCNPJPART)) THEN
          BEGIN
            bdnumcampo = NULL;
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            BDNUMITEM = NULL;
            WSALVACNPJPART = WBDCNPJPART;
            bddescform = WBDCNPJPART;
            SUSPEND;
          END

    
        IF ((BDTIPOCREDITO IS NOT NULL) AND (wBDTIPOCREDITO <> BDTIPOCREDITO)) THEN
          BEGIN
            bdnumcampo = NULL;
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            BDNUMITEM = NULL;
            wBDTIPOCREDITO = BDTIPOCREDITO;
            bddescform = BDTIPOCREDITO || ' - '||wbddesctipocred;
            SUSPEND;
          END
    
    
        bdnumcampo = prnumcampo;
        IF (Wcodtipoquadro1424 IN (36,55)) THEN
          BEGIN
            bddescform = WDESC1424;
            bdnumitem = WITEM1424;
          END
        ELSE
          BEGIN
            bddescform = prdescform;
            bdnumitem = wNumItem;
          END

        bdvalor = wvalor;
        bdvalor2 = wvalor2;
        bdvalor3 = wvalor3;

        prrefant = bdreferencia;
        prquadroant = bdcodquadro;
        prcodperiodoant = bdcodperiodo;
    
        SUSPEND;
      END

   END
END
^

/* Alter (SP_VEF_TREEVIEW_CONS_DIME) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DIME(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCODQUADRO INTEGER,
PRCODQUADROPRINC INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCODQUADROPRINC INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDNUMITEM INTEGER,
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRSALVAQUADROANT INTEGER;
DECLARE VARIABLE PRNATANT INTEGER;
DECLARE VARIABLE PRCLASSIFIANT VARCHAR(10);
DECLARE VARIABLE PRDESCQUADROANT VARCHAR(80);
DECLARE VARIABLE PRDATARECANTQ12 DATE;
DECLARE VARIABLE PRORIGEMDIMEGERQ46ANT INTEGER;
DECLARE VARIABLE PRCLAVENDIMEGERQ12ANT INTEGER;
DECLARE VARIABLE PRCODRECDIMEGERQ12ANT INTEGER;
DECLARE VARIABLE PRULTIMOCLASSIFITIT VARCHAR(10);
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRNUMITEM INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,6);
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODCIDTOT INTEGER;
DECLARE VARIABLE WNOMCID VARCHAR(40);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE PRUFANT INTEGER;
DECLARE VARIABLE WPODETOTUFTIP6 INTEGER;
DECLARE VARIABLE WPODETOTUFTIP7 INTEGER;
DECLARE VARIABLE WQ12 CHAR(5);
DECLARE VARIABLE WQ46 CHAR(5);
DECLARE VARIABLE BDDESCFORMQ12 VARCHAR(150);
DECLARE VARIABLE BDDESCFORMQ46 VARCHAR(150);
DECLARE VARIABLE WCLASSIFITITULO VARCHAR(10);
DECLARE VARIABLE WAUX INTEGER;
BEGIN
  /* giovanni */

  /* SP Padrao para montar a treeview DA DIME */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas2.BDNOMEMP, ';
  wsql = wsql || 'empresas.BDCODCONFDIMESC,';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQDIME,';
  wsql = wsql || 'TCONF.BDCODQDIMEPRINC,';
  wsql = wsql || 'TCONF.bdclassificacao, ';
  wsql = wsql || 'TCONF.bddescqDIME,';
  wsql = wsql || 'TCONFDIMEFORM.bddescformDIME,';
  wsql = wsql || 'TCONFDIMEFORMQ12.bddescformDIMEq12,';
  wsql = wsql || 'TCONFDIMEFORMQ46.bddescformDIMEq46,';
  wsql = wsql || 'T.BDVALOR BDVALOR, ';
  wsql = wsql || 'TCONF.bdcodtipo, ';
  wsql = wsql || 'T.bdcodcid, ';
  wsql = wsql || 'T.bdcodcidtot, ';
  wsql = wsql || 'TCID.BDNOMCID, ';
  wsql = wsql || 'T.BDCODNAT, ';
  wsql = wsql || 'T.BDDATAREC, '; -- Q12
  wsql = wsql || 'T.BDCLAVENDIMEGERQ12, ';
  wsql = wsql || 'T.BDCODRECDIMEGERQ12, ';
  wsql = wsql || 'T.BDORIGEMDIMEGERQ46, ';
  wsql = wsql || 'T.BDCODUF, ';
  wsql = wsql || 'UF.BDSIGLAUF, ';
  wsql = wsql || 'T.BDQ12, ';
  wsql = wsql || 'T.BDQ46, ';
  wsql = wsql || 'TCONFDIMEFORM.bdnumitem ';

  /* Remvida a View "VW_VEF_EMP_TDIMEGERUNION" */
--  wsql = wsql || ' from VW_VEF_EMP_TDIMEGERUNION T';
  wsql = wsql || ' from ( ';
  --------------------------------------------------------------------------------
  --                                                                            --
  --------------------------------------------------------------------------------
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               BDPREFIXONAT as BDCODNAT, ';
  wsql = wsql||'               SUM(COALESCE(BDVALOR,0)) as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, /* Q 47, Q48 BDCODCID */ ';
  wsql = wsql||'               NULL as BDCODCIDTOT, /* Q 47, Q48 BDCODCIDTOT */ ';
  wsql = wsql||'               NULL as BDCODUF, /* Q 49 BDCODUF */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERNAT t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDPREFIXONAT ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ47 t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               t.BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL  as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               CASE WHEN bdcodcidtot = 99999 THEN 999 ELSE BDCODEXP END as BDCODEXP48,  /* Q48 */ ';
  wsql = wsql||'               ALIM.BDALIMPREP as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ48 t ';
  wsql = wsql||'        JOIN  VW_VEF_BASE_TEMPPARESTSC Alim ON (alim.bdcodemp = t.bdcodemp) ';
  wsql = wsql||'        LEFT OUTER JOIN VEF_BASE_TTABATIVQ48 exp48 ON (t.bdcodativq48 = exp48.bdcodativq48) ';
  wsql = wsql||'        WHERE t.bdcodativq48 IS NOT NULL OR BDCODCIDTOT = 99999 ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        AND ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
  IF (:PRANOMESFINAL IS NOT NULL) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               bdcoduf as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ49 t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               SUM(COALESCE(BDVALOR,0)) as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               bdcoduf as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ50 t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDCODNAT, BDCODCID, BDCODCIDTOT,bdcoduf, BDDATAREC, BDCLAVENDIMEGERQ12, BDCODRECDIMEGERQ12, BDORIGEMDIMEGERQ46,BDQ12, BDQ46 ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMESCGERREG t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               BDDATAREC as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               BDCLAVENDIMEGERQ12 as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               r.BDCODRECOF as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''TRUE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ12 t ';
  wsql = wsql||'        left outer join TCODREC r on (r.BDCODREC = t.BDCODRECDIMEGERQ12) ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'      UNION ';
  wsql = wsql||'      select /*null*/7 BDCODPERIODO, ';
  wsql = wsql||'             BDCODEMP, ';
  wsql = wsql||'             BDREFERENCIA, ';
  wsql = wsql||'             /*39*/48 BDCODQDIME, /* Q10*/ ';
  wsql = wsql||'             (BDITEMDEBESP+100) BDNUMCAMPO, /* Q10*/ ';
  wsql = wsql||'             null as BDCODNAT, ';
  wsql = wsql||'             BDVALOR as BDVALOR, ';
  wsql = wsql||'             null as BDCODCID, ';
  wsql = wsql||'             null as BDCODCIDTOT, ';
  wsql = wsql||'             null as BDCODUF, /* Q49 */ ';
  wsql = wsql||'             BDDATAVENCTO as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'             BDCLAVENC as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'             BDCODREC as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'             null as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'             null as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'             ''TRUE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'             ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'             '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'             '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'      from VEF_EMP_TDIMEGERDEBESP t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               BDCODNAT as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               BDCODUF as BDCODUF, ';
  wsql = wsql||'               BDDATAREC as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               BDCLAVENDIMEGERQ12 as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               BDCODRECDIMEGERQ12 as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               BDORIGEMDIMEGERQ46 as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               BDIDENTIFICACAOREGESP as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               BDQ12 as BDQ12, /* Q12 */ ';
  wsql = wsql||'               BDQ46 as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_SP_DIMEQ46 t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  --------------------------------------------------------------------------------
  --                                                                            --
  --------------------------------------------------------------------------------
  wsql = wsql || '        ) T';
  /* tirado a spconsultaempresas_sis muito lenta... */
  --  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql||' left outer join VW_EMP_REF_TOTAL empresas on (empresas.bdcodemp = t.bdcodemp ) ';
  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMEQ TCONF on (TCONF.bdcodqdime = t.bdcodqdime) ' ;
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMEFORM TCONFDIMEFORM on (TCONFDIMEFORM.bdcodconfdimesc = empresas.bdcodconfdimesc and ';
  wsql = wsql||' TCONFDIMEFORM.bdcodqdime = T.BDCODQDIME and TCONFDIMEFORM.bdnumcampodime = T.BDNUMCAMPO) ' ;

--  wsql = wsql||' left outer join vef_estados_tconfdimefq12 TCONFDIMEFORMQ12 on (TCONFDIMEFORMQ12.bdcodconfdimesc = empresas.bdcodconfdimesc and ';
  wsql = wsql||'left outer join ( ';
  wsql = wsql||'                 select BDCODCONFDIMESC, BDCODQDIME, BDNUMCAMPODIMEQ12, BDDESCFORMDIMEQ12 from VEF_ESTADOS_TCONFDIMEFQ12 ';
  wsql = wsql||'                 union all ';
  wsql = wsql||'                 select f.BDCODCONFDIMESC, 48 as BDCODQDIME, (esp.BDITEMDEBESP+100) as BDNUMCAMPODIMEQ12, esp.BDDESCRICAO ';
  wsql = wsql||'                 from VEF_ESTADOS_TCONFDIMEFORM f ';
  wsql = wsql||'                 join VEF_BASE_TTABITEMDEBESP esp on ( esp.bdcodexportar = f.bdnumitem ) ';
  wsql = wsql||'                 where /*f.BDCODCONFDIMESC = EMPRESAS.BDCODCONFDIMESC and*/ f.BDCODQDIME = 39 ';
  wsql = wsql||'                 ) TCONFDIMEFORMQ12 on (TCONFDIMEFORMQ12.BDCODCONFDIMESC = EMPRESAS.BDCODCONFDIMESC and TCONFDIMEFORMQ12.BDCODQDIME = T.BDCODQDIME and TCONFDIMEFORMQ12.BDNUMCAMPODIMEQ12 = T.BDNUMCAMPO) ';

  wsql = wsql||' left outer join vef_estados_tconfdimefq46 TCONFDIMEFORMQ46 on (TCONFDIMEFORMQ46.bdcodconfdimesc = empresas.bdcodconfdimesc and ';
  wsql = wsql||' TCONFDIMEFORMQ46.bdcodqdime = T.BDCODQDIME and TCONFDIMEFORMQ46.bdnumcampodimeq46 = T.BDNUMCAMPO) ' ;


  wsql = wsql||' left outer join TCIDADE TCID on tcid.bdcodcid = t.bdcodcid';
  wsql = wsql||' left outer join TUF UF on UF.bdcoduf = T.BDCODUF';
  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQDIME  = '||:prcodquadro;

    END

  IF (:prcodquadroprinc IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'TCONF.BDCODQDIMEPRINC  = '||:prcodquadroprinc;
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODPERIODO' || ' = '||:prcodperiodo;

    END

--  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQDIME, bdcodnat, bdcoduf desc, bdnumitem' ;
  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, bdclassificacao, bdcodnat, bdcoduf desc, bdnumitem' ;

  prrefant   = 0;
  prquadroant = 0;
  prnatant = 0;
  prufant = 0;
  wpodetotuftip6 = 0;
  wpodetotuftip7 = 0;
  PRULTIMOCLASSIFITIT = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bdcodquadroprinc,
    bdclassificacao,
    BDDESCQUADRO,
    bddescform,
    bddescformq12, 
    bddescformq46,
    BDVALOR,
    bdcodtipo,
    wcodcid,
    wcodcidtot,
    wnomcid,
    bdcodnat,
    BDDATAREC,
    bdclavendimegerq12,
    bdcodrecdimegerq12,
    bdorigemdimegerq46,
    wcoduf,
    wsiglauf,
    wq12,
    wq46,
    bdnumitem
  DO
  BEGIN
    bdanomesfinal   = pranomesfinal;
    bdanomesinicial = pranomesinicial;
    wcodnat = bdcodnat;

    IF (bdcodtipo =74 OR bdcodtipo =76) THEN  /* QUADRO 47 E 48 POR CIDADE */
      BEGIN
        IF (wcodcid IS NULL) THEN
          BEGIN
            IF (wcodcidtot = 99999) THEN
               bddescform = '99999 - TOTALIZADOR';
            ELSE
              bddescform = wcodcidtot ||  ' - Outros Estados';
          END
        ELSE
           bddescform = wcodcid || ' - ' || wnomcid;
      END

    IF (wq12 = 'TRUE') THEN   /* verifica o tipo do quadro para ver de onde vai pegar a descrivao da formula. Conf geral, do quadro 12 ou quadro 46 */
      BEGIN
        bddescform = bddescformq12;
      END
    ELSE
      IF (wq46 = 'TRUE') THEN
        BEGIN
          bddescform = bddescformq46;

          IF (BDNUMCAMPO = 990) THEN
             bddescform = 'TOTAL';
        END

    prnumcampo = bdnumcampo;
    prnumitem  = bdnumitem;
    prdescform = bddescform;
    prvalor = bdvalor;

    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal) ) THEN /* mostra a referencia caso esteja consultando varias */
      BEGIN
        bdnumcampo = NULL;
        bdnumitem = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        prrefant = bdreferencia;
        SUSPEND;
      END

    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN   /* mostra o nome do quadro atual na consulta */
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        prdatarecantq12 = bddatarec;
        prclavendimegerq12ant = bdclavendimegerq12;
        prcodrecdimegerq12ant = bdcodrecdimegerq12;
        prorigemdimegerq46ant = bdorigemdimegerq46;

        SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;

        IF (waux > 1) THEN /* classificacao titulo */
          BEGIN

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF  (prultimoclassifitit <> wclassifititulo) THEN
              BEGIN

                SELECT x.bdcodqdime, x.bddescqdime FROM VEF_ESTADOS_TCONFDIMEQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;


                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                bdnumitem = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                prufant = 0;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;
                bddatarec = NULL;
                bdclavendimegerq12 = NULL;
                bdcodrecdimegerq12 = NULL;
                bdorigemdimegerq46 = NULL;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
              END

          END

        bdnumcampo = NULL;
        bdnumitem = NULL;
        BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        -- BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        bdorigemdimegerq46 = NULL;
        bdclavendimegerq12 = NULL;
        bdcodrecdimegerq12 = NULL;
        bddatarec = NULL;
        prquadroant = bdcodquadro;
        prufant = 0;

        SUSPEND;

        bdorigemdimegerq46 = prorigemdimegerq46ant;
        bdclavendimegerq12 = prclavendimegerq12ant;
        bdcodrecdimegerq12 = prcodrecdimegerq12ant;
        bddatarec = prdatarecantq12;

      END

    IF ((bdcodtipo =2) AND (prnatant <> wcodnat) OR ((bdcodtipo =3) AND (prnatant <> wcodnat)) ) THEN /* mostra a natureza atual na consuta... */
       BEGIN
         bdnumcampo = NULL;
         bdnumitem = NULL;
         bddescform =  SUBSTRING(CAST(wcodnat AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wcodnat AS VARCHAR(10)) FROM 2 FOR 10) ;
         BDVALOR = NULL;
         prnatant = wcodnat;
         SUSPEND;
       END

    --if ((((bdcodtipo =6) and (prufant <> wcoduf))  or ((bdcodtipo =6) and (wcoduf is null)))  and (wpodetotuftip6 = 0)) then /* mostra a sigla do estado atual na consuta... */
    IF ((((bdcodtipo =78) AND (prufant <> wcoduf))  OR ((bdcodtipo =78) AND (wcoduf IS NULL)))  AND (wpodetotuftip6 = 0)) THEN /* mostra a sigla do estado atual na consuta... */
       BEGIN
         bdnumcampo = NULL;
         bdnumitem = NULL;
         IF (wcoduf IS NULL) THEN
           BEGIN
             bddescform =  'TT';
             wpodetotuftip6 = 1;
           END
         ELSE
            bddescform =  wsiglauf;
         BDVALOR = NULL;
         prufant = wcoduf;
         SUSPEND;
       END

    --if ((((bdcodtipo =7) and (prufant <> wcoduf))  or ((bdcodtipo =7) and (wcoduf is null)))  and (wpodetotuftip7 = 0)) then /* mostra a sigla do estado atual na consuta... */
    IF ((((bdcodtipo =80) AND (prufant <> wcoduf))  OR ((bdcodtipo =80) AND (wcoduf IS NULL)))  AND (wpodetotuftip7 = 0)) THEN /* mostra a sigla do estado atual na consuta... */
       BEGIN
         bdnumcampo = NULL;
         bdnumitem = NULL;
         IF (wcoduf IS NULL) THEN
           BEGIN
             bddescform =  'TT';
             wpodetotuftip7 = 1;
           END
         ELSE
            bddescform =  wsiglauf;
         BDVALOR = NULL;
         prufant = wcoduf;
         SUSPEND;
       END

    bdnumcampo = prnumcampo;
    bdnumitem = prnumitem;
    bddescform = prdescform;
    bdvalor = prvalor;

    SUSPEND;

  END

END
^

/* Alter (SP_VEF_TREEVIEW_CONS_GIAES) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAES(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRTIPOAPU INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDTIPOAPU INTEGER,
BDCODNAT INTEGER,
BDAUXCFOP INTEGER,
BDORDEMTTNAT INTEGER,
BDCLASSNATGRUP VARCHAR(20),
BDDESCTTNAT VARCHAR(20),
BDTITULOGRUPO VARCHAR(20))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wwhere VARCHAR(32700);
DECLARE VARIABLE prquadroant INTEGER;
DECLARE VARIABLE prsalvaquadroant INTEGER;
DECLARE VARIABLE wtit INTEGER;
DECLARE VARIABLE prultimoclassifitit VARCHAR(11);
DECLARE VARIABLE wclassifiprinc VARCHAR(11);
DECLARE VARIABLE wclassifititulo VARCHAR(20);
DECLARE VARIABLE prnumcampo INTEGER;
DECLARE VARIABLE prdescform VARCHAR(150);
DECLARE VARIABLE prclassifiant VARCHAR(11);
DECLARE VARIABLE prnatant INTEGER;
DECLARE VARIABLE waux INTEGER;
DECLARE VARIABLE waux2 INTEGER;
DECLARE VARIABLE prvalor NUMERIC(15,2);
DECLARE VARIABLE prrefant INTEGER;
DECLARE VARIABLE wultimoclassifitit VARCHAR(11);
DECLARE VARIABLE prdescquadroant VARCHAR(80);
DECLARE VARIABLE wtipo INTEGER;
DECLARE VARIABLE wprefixonat INTEGER;
DECLARE VARIABLE wauxcfop INTEGER;
DECLARE VARIABLE wordemttnatcompras INTEGER;
DECLARE VARIABLE wordemttnatvendas INTEGER;
DECLARE VARIABLE wnataux INTEGER;
DECLARE VARIABLE wtitulogrupo VARCHAR(20);
DECLARE VARIABLE wclasstitulo VARCHAR(20);
BEGIN


  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'SELECT T.BDCODEMP, ';
  wsql = wsql || ' empAtual.BDNOMEMP, ';
  wsql = wsql || ' pares.BDCODCONFGIAES, ';
  wsql = wsql || ' T.BDREFERENCIA, ';
  wsql = wsql || ' T.BDCODPERIODO, ';
  wsql = wsql || ' T.BDNUMCAMPO, ';
  wsql = wsql || ' T.BDCODQUADRO, ';
  wsql = wsql || ' GIAESQ.BDCLASSIFICACAO, ';
  wsql = wsql || ' GIAESQ.BDDESCQUADRO, ';
  wsql = wsql || ' GIAESF.BDDESCFORM, ';
  wsql = wsql || ' T.BDVALOR BDVALOR, ';
  wsql = wsql || ' GIAESQ.BDCODTIPO, ';
  wsql = wsql || ' GIAESQ.BDTIPO, ';
  wsql = wsql || ' GIAESF.BDNUMITEM, ';
  wsql = wsql || ' T.BDTIPOAPU, ';
  wsql = wsql || ' T.BDPREFIXONAT BDCodNat, ';
  wsql = wsql || ' T.BDAUXCFOP, ';
  wsql = wsql || ' T.bdordemttnat, ';
  wsql = wsql || ' totaises.bdClassnatgrup, ';
  wsql = wsql || ' totaises.bddescttnat, ';
  wsql = wsql || ' null bdtitulogrupo ';

  wsql = wsql || ' FROM vw_vef_emp_tgiaesgerunion T';
  wsql = wsql || ' left outer join VW_EMPRESAS_REF_ATUAL empAtual on (empAtual.bdcodemp = t.bdcodemp) ';
  wsql = wsql || ' left outer join vef_base_tempparestes pares on (pares.bdCodEmp = empAtual.bdCodEmp and pares.bdrefemp = empAtual.bdempref) ';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIAESQ GIAESQ on (GIAESQ.bdcodquadro = t.bdcodquadro)';
  wsql = wsql || ' left outer join vef_base_ttabtotaisnates TOTAISES on(TOTAISES.bdOrdemttnat = t.bdordemttnat)';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIAESFORM GIAESF on (GIAESF.bdCodConf = pares.BDCODCONFGIAES and GIAESF.bdCODQUADRO = t.bdCODQUADRO and GIAESF.bdNumcampo = t.bdNumcampo)';

  wwhere = '';

   IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

   IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';
       ELSE
          wwhere = wwhere || ' WHERE ';

       wwhere = wwhere || ' t.bdreferencia >= ' || :praNomesInicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || ' t.bdreferencia <= ' || :praNomesFinal;
     END

   IF (:prtipoapu IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';
        ELSE
          wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' T.BDTIPOAPU = ' || :prtipoapu;
      END
   IF (prClassificacao IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' GIAESQ.bdclassificacao LIKE ''' ||:PRCLASSIFICACAO||'%''';
      END
   IF (:prcodperiodo IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' t.bdCODPERIODO ' || ' = ' || :prcodperiodo;
       END
   IF (:prcodquadro IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

      wwhere = wwhere || ' GIAESQ.BDCODQUADRO' || ' = ' ||:prcodquadro;
      END


   wsql = wsql || wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQUADRO,bdcodnat,totaises.bdClassnatgrup,t.bdnumcampo';

   prRefant = 0;
   prquadroant = 0;
   prnatant = 0;
   wTit = 0;
   PRULTIMOCLASSIFITIT = '';
   WCLASSIFIPRINC = '';
   wTIT = 1;
   wordemttnatcompras = NULL;
   wordemttnatvendas = NULL;
   wtitulogrupo = NULL;
   wclasstitulo = '';

   FOR EXECUTE STATEMENT wsql
   INTO
     BDCODEMP,
     BDNOMEMP,
     BDCODCONF,
     BDREFERENCIA,
     BDCODPERIODO,
     BDNUMCAMPO,
     BDCODQUADRO,
     bdclassificacao,
     bddescquadro,
     BDDESCFORM,
     BDVALOR,
     BDCODTIPO,
     BDTIPO,
     BDNUMITEM,
     BDTIPOAPU,
     BDCODNAT,
     BDAUXCFOP,
     bdordemttnat,
     bdclassnatgrup,
     bddescttnat,
     bdtitulogrupo

   DO
   BEGIN
   wnataux = 0;
   wprefixonat = bdcodnat;
   prNumCampo = BDNumcampo;
   prDescForm = BDDESCFORM;
   prValor = bdValor;
   wauxcfop = NULL;

   IF ((wtitulogrupo IS NULL) OR (wtitulogrupo <> bdtitulogrupo) OR (wclasstitulo <> SUBSTRING(bdclassificacao FROM 1 FOR 2)))  THEN
      BEGIN
         wclasstitulo = SUBSTRING(bdclassificacao FROM 1 FOR 2);
         SELECT FIRST 1 bddescquadro FROM VEF_ESTADOS_TCONFGIAESQ tit WHERE tit.bdtipo = 0 AND tit.bdclassificacao = SUBSTRING(:bdclassificacao FROM 1 FOR 2) INTO :wtitulogrupo;
      END

   bdtitulogrupo = wtitulogrupo;

   IF ((prgeral = 1) AND (prRefAnt <> bdReferencia) AND (praNomesInicial <> praNomesFinal)) THEN
      BEGIN
        bdNumCampo = NULL;
        BDDESCFORM = CAST(bdreferencia AS VARCHAR(6));
        bddescform = SUBSTRING(bddescform FROM 5 FOR 2) || '/' ||SUBSTRING(bddescform FROM 1 FOR 4);
        bdvalor = NULL;
        prRefant = bdreferencia;
        SUSPEND;
      END
    IF ((prgeral = 1) AND (bdcodquadro <> prquadroant)) THEN
       BEGIN
         prsalvaquadroant = bdcodquadro;
         prclassifiant = bdclassificacao;
         prdescquadroant = bddescquadro;

         IF (wPrefixoNat IS NULL) THEN
            BEGIN
              SELECT FIRST 1 tPos.BDRPOS FROM rpos('.', :bdclassificacao) tpos INTO :wAUX;

              IF ((wclassifiprinc = '') AND (wAux > 1)) THEN
                 BEGIN
                   wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);
                   wtit = 1;
                 END
              ELSE
                 BEGIN
                   IF (wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1)) THEN
                      BEGIN
                        wtit = 0;
                      END
                   ELSE
                      BEGIN
                        wtit = 1;
                      END
                   IF (waux > 1) THEN
                      BEGIN
                        wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);
                      END
                 END
            END
         ELSE
            BEGIN
              SELECT FIRST 1 tpos.pos FROM pos('.' , :Bdclassificacao) tpos INTO :waux;
              wtit = 1;
              wclassifititulo = '';
            END

         IF (waux > 1) THEN
            BEGIN

              IF (wprefixonat IS NULL) THEN
                 BEGIN
                   SELECT FIRST 1 tpos.pos FROM pos('.' , :bdClassificacao) tpos INTO :waux2;

                   wclassifiprinc = SUBSTRING(bdclassificacao FROM 1 FOR waux2-1);

                   SELECT FIRST 1 tpos.pos FROM pos('.' , :prUltimoClassifiTit) tpos INTO :waux2;

                   IF (waux2 > 0) THEN
                      BEGIN
                        wUltimoClassifiTit = SUBSTRING(prUltimoClassifiTit FROM 1 FOR waux2-1);
                      END
                   ELSE
                      BEGIN
                        wultimoclassifitit = prultimoclassifitit;
                      END
                  IF ((wUltimoclassifitit <> wclassifititulo) AND (wTit = 1)) THEN
                      BEGIN
                        SELECT Q.bdcodquadro, Q.bdDescQuadro FROM VEF_ESTADOS_TCONFGIAESQ Q WHERE Q.bdclassificacao = :wclassifititulo
                        INTO :bdcodquadro, :bddescform;

                        prultimoclassifitit = wClassifiTitulo;
                        bdNUmcampo = NULL;
                        bdValor = NULL;
                        prquadroant = bdCodQuadro;
                        bdclassificacao = wClassifiTitulo;
                        bddescquadro = bddescform;
                        wTipo = BDTipo;
                        bdTipo = 0;
                        bdcodnat = NULL;

                        SUSPEND;
                        bdclassificacao = prClassifiAnt;
                        bdcodquadro = prSalvaQuadroAnt;
                        bdDescQuadro = prDescQuadroAnt;
                        bdTipo = wTipo;
                        bdcodnat = NULL;
                      END
                 END

            wClassifiTitulo = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);

            IF ((prUltimoClassifiTit <> wClassifiTitulo) AND (wTit = 1)) THEN
               BEGIN
                 SELECT Q.bdcodquadro, Q.bdDescQuadro FROM VEF_ESTADOS_TCONFGIAESQ Q WHERE Q.bdclassificacao = :wclassifititulo
                 INTO :bdcodquadro, :bddescform;
                 
                 prultimoclassifitit = wClassifiTitulo;
                 bdNUmcampo = NULL;
                 bdValor = NULL;
                 prquadroant = bdCodQuadro;
                 bdclassificacao = wClassifiTitulo;
                 bddescquadro = bddescform;
                 wTipo = BDTipo;
                 bdTipo = 0;

                 SUSPEND;
                 bdclassificacao = prClassifiAnt;
                 bdcodquadro = prSalvaQuadroAnt;
                 bdDescQuadro = prDescQuadroAnt;
                 bdTipo = wTipo;
               END
            END

         bdNUmcampo = NULL;
         BDDESCFORM = bdclassificacao || ' - ' || bddescquadro;
         bdvalor = NULL;
         prquadroant = bdcodquadro;

         SUSPEND;
       END

     IF (((bdcodtipo = 202) OR (bdcodtipo = 203) OR (bdcodtipo = 204)) AND ((wordemttnatcompras <> bdordemttnat) OR (wordemttnatcompras IS NULL) )) THEN     -- Naturezas de Entrada
        BEGIN
          wauxcfop = 1;
          bdnumcampo = NULL;
          bddescform = bddescttnat || ' ' || bdclassnatgrup ;
          bdclassificacao = bdclassnatgrup;
          bdvalor = NULL;
          bdauxcfop = wauxcfop;
          SUSPEND;
        END

     wordemttnatcompras = bdordemttnat;

     IF (((bdcodtipo = 205) OR (bdcodtipo = 206) OR (bdcodtipo = 207)) AND ((wordemttnatvendas <> bdordemttnat) OR (wordemttnatvendas IS NULL))) THEN   -- Naturezas de saida
        BEGIN
          wauxcfop = 1;
          bdnumcampo = NULL;
          bddescform = bddescttnat || ' ' || bdclassnatgrup ;
          bdclassificacao = bdclassnatgrup;
          bdvalor = NULL;
          bdauxcfop = wauxcfop;
          SUSPEND;
        END

     IF ((bdcodtipo = 202) OR (bdcodtipo = 203) OR (bdcodtipo = 204)) THEN
        wordemttnatvendas = NULL;
     ELSE
        wordemttnatvendas = bdordemttnat;


     IF ((bdcodtipo = 210) AND (prNatAnt <> wprefixonat) OR ((bdCodTipo = 211) AND (prNatAnt <> wprefixonat))) THEN
        BEGIN
          wauxcfop = 1;
          bdNumCampo = NULL;
          bddescForm = SUBSTRING(CAST(wprefixonat AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wprefixonat AS VARCHAR(10)) FROM 2 FOR 3);
          bdValor = NULL;
          prnatAnt = wprefixonat;
          bdauxcfop = wauxcfop;
          SUSPEND;
        END

     IF (wnataux <> 0) THEN
        BEGIN
          SUSPEND;
        END


    bdnumcampo = prnumcampo;
    bddescform = /*'['||cast(BDNUMITEM as varchar(3))||'] - '||*/prdescform;
    bdvalor = prvalor;
    bdauxcfop = NULL;
    prtipoapu = bdtipoapu;
    SUSPEND;

  END

END
^

/* Alter (SP_VEF_TREEVIEW_CONS_GIAMG) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEMORDEM VARCHAR(5),
BDNUMITEM VARCHAR(5))
 AS
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable PRREFANT integer;
declare variable PRQUADROANT integer;
declare variable PRSALVAQUADROANT integer;
declare variable PRNATANT integer;
declare variable PRCLASSIFIANT varchar(11);
declare variable PRDESCQUADROANT varchar(80);
declare variable PRULTIMOCLASSIFITIT varchar(11);
declare variable PRNUMCAMPO integer;
declare variable PRDESCFORM varchar(60);
declare variable PRVALOR numeric(15,6);
declare variable WPREFIXONAT integer;
declare variable WCLASSIFITITULO varchar(11);
declare variable WCLASSIFIPRINC varchar(11);
declare variable WAUX integer;
declare variable WAUX2 integer;
declare variable WTIT integer;
declare variable WTIPO integer;
declare variable WULTIMOCLASSIFITIT varchar(11);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas2.BDNOMEMP, ';
  wsql = wsql || 'parmg.BDCODCONFGIAMG,';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQUADRO,';
  wsql = wsql || 'TCONF.bdclassificacao, ';
  wsql = wsql || 'TCONF.bddescquadro,';
  wsql = wsql || 'TCONFGIAMGFORM.bddescform,';
  wsql = wsql || 'T.BDVALOR BDVALOR, ';
  wsql = wsql || 'TCONF.bdcodtipo, ';
  wsql = wsql || 'T.BDPREFIXONAT BDCODNAT, ';
  wsql = wsql || 'TCONF.bdtipo, ';
  wsql = wsql || 'Lpad(TCONFGIAMGFORM.BDNUMITEM, 3, ''0'')||SUBSTRING(TCONFGIAMGFORM.BDNUMITEM FROM 4 FOR 2 ) BDNUMITEMORDEM, ';
  wsql = wsql || 'TCONFGIAMGFORM.BDNUMITEM';

  wsql = wsql || ' from VW_VEF_EMP_TGIAMGGERUNION T';

--  wsql = wsql||' left outer join VW_EMP_REF_TOTAL empresas on (empresas.bdcodemp = t.bdcodemp ) ';
  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join VEF_BASE_TEMPPARESTMG parmg on (parmg.bdcodemp = empresas2.bdcodemp and parmg.bdrefemp = empresas2.BDEMPREF) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIAMGQ TCONF on (TCONF.bdcodquadro = t.bdcodquadro) ' ;
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIAMGFORM TCONFGIAMGFORM on (TCONFGIAMGFORM.bdcodconf = parmg.BDCODCONFGIAMG and ';
  wsql = wsql||' TCONFGIAMGFORM.bdcodquadro = T.BDCODQUADRO and TCONFGIAMGFORM.bdnumcampo = T.BDNUMCAMPO) ' ;
  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (PRCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       --wwhere = wwhere||'T.BDCODQUADRO  = '||:prcodquadro;
       --wwhere = wwhere||'TCONF.bdclassificacao LIKE ''0'||:prcodquadro||'%''';
       wwhere = wwhere||'TCONF.bdclassificacao LIKE '''||:PRCLASSIFICACAO||'%''';
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODPERIODO' || ' = '||:prcodperiodo;

    END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'TCONF.BDCODQPRINC' || ' = '||:prcodquadro;

    END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQUADRO, BDCODNAT, cast(TCONFGIAMGFORM.BDNUMITEM as numeric(10,2))' ;

  prrefant   = 0;
  prquadroant = 0;
  prnatant = 0;
  PRULTIMOCLASSIFITIT = '';
  WCLASSIFIPRINC = '';
  WTIT = 1;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP ,
    BDCODCONF ,
    BDREFERENCIA ,
    BDCODPERIODO ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCQUADRO ,
    BDDESCFORM ,
    BDVALOR ,
    BDCODTIPO,
    BDCODNAT,
    BDTIPO,
    BDNUMITEMORDEM,
    BDNUMITEM
  DO
  BEGIN

    wPREFIXONAT = BDCODNAT;

    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;

    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal) ) THEN -- mostra a referencia caso esteja consultando varias
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        prrefant = bdreferencia;
        SUSPEND;
      END

    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN   -- mostra o nome do quadro atual na consulta
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        IF (wPREFIXONAT IS NULL) THEN
           BEGIN
             SELECT FIRST 1 tpos.BDRPOS FROM rpos('.',  :bdclassificacao) tpos INTO :waux;

             IF ((WCLASSIFIPRINC = '') AND (waux > 1)) THEN
                BEGIN
                   WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);
                   WTIT = 1;
                END
             ELSE
                BEGIN
                  IF (WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1)) THEN
                     BEGIN
                        WTIT = 0;
                     END
                  ELSE
                     BEGIN
                        WTIT = 1;
                     END
    
                  IF (waux > 1) THEN
                     WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);
                END
           END
        ELSE
           BEGIN
             SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;
             WTIT = 1;
             WCLASSIFIPRINC = '';
           END

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            IF (wPREFIXONAT IS NULL) THEN
               BEGIN
                SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux2;
    
                wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux2-1);
    
                SELECT FIRST 1 tpos.pos FROM pos('.', :prultimoclassifitit) tpos INTO :waux2;

                IF (waux2 > 0) THEN
                   wultimoclassifitit = SUBSTRING(prultimoclassifitit FROM 1 FOR waux2-1);
                ELSE
                   wultimoclassifitit = prultimoclassifitit;
    
                IF ((wultimoclassifitit <> wclassifititulo) AND (WTIT = 1)) THEN
                  BEGIN
    
                    SELECT x.bdcodquadro, x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                        :bdcodquadro,
                        :bddescform;
    
                    prultimoclassifitit = wclassifititulo;
                    bdnumcampo = NULL;
                    BDVALOR = NULL;
                    prquadroant = bdcodquadro;
                    bdclassificacao = wclassifititulo;
                    bddescquadro = bddescform;
                    WTIPO = BDTIPO;
                    BDTIPO = 0;
    
                    SUSPEND;
                    bdclassificacao = prclassifiant;
                    bddescquadro = prdescquadroant;
                    bdcodquadro = prsalvaquadroant;
                    BDTIPO = WTIPO;
                  END
               END

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF ((prultimoclassifitit <> wclassifititulo) AND (WTIT = 1)) THEN
              BEGIN

                SELECT x.bdcodquadro, x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;

                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;
                WTIPO = BDTIPO;
                BDTIPO = 0;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
                BDTIPO = WTIPO;
              END

          END

        bdnumcampo = NULL;
        BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        -- BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        prquadroant = bdcodquadro;

        SUSPEND;

      END

    IF ((bdcodtipo =116) AND (prnatant <> wPREFIXONAT) OR ((bdcodtipo =149) AND (prnatant <> wPREFIXONAT)) ) THEN -- mostra a natureza atual na consuta...
       BEGIN
         bdnumcampo = NULL;
         bddescform =  SUBSTRING(CAST(wPREFIXONAT AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wPREFIXONAT AS VARCHAR(10)) FROM 2 FOR 3);
         BDVALOR = NULL;
         prnatant = wPREFIXONAT;
         SUSPEND;
       END

    bdnumcampo = prnumcampo;
    bddescform = '['||BDNUMITEM||'] - '||prdescform;
    bdvalor = prvalor;

    SUSPEND;


  END

END
^

/* Alter (SP_VEF_TREEVIEW_CONS_GIAPR) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAPR(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRCODNAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER)
 AS
DECLARE VARIABLE wWhereQuadro VARCHAR(1000);
DECLARE VARIABLE wRefBetween VARCHAR(100);
DECLARE VARIABLE wCondicaoNatureza VARCHAR(100);
DECLARE VARIABLE wInnerSelect VARCHAR(1000);
DECLARE VARIABLE wSql BLOB SUB_TYPE 1 SEGMENT SIZE 16384;
DECLARE VARIABLE wRefAnt INTEGER;
DECLARE VARIABLE wCodQuadroAnt INTEGER;
DECLARE VARIABLE wPosPonto INTEGER;
DECLARE VARIABLE wClassificacaoTitulo VARCHAR(10);
DECLARE VARIABLE wClassificacaoTituloAnt VARCHAR(10);
DECLARE VARIABLE wClassificacaoTitulo2 VARCHAR(10);
DECLARE VARIABLE wClassificacaoTitulo2Ant VARCHAR(10);
DECLARE VARIABLE wClassificacaoAnalitica VARCHAR(10);
DECLARE VARIABLE wClassificacaoAnaliticaAnt VARCHAR(10);
DECLARE VARIABLE wQtdPontos INTEGER;
DECLARE VARIABLE wCodQuadroSalvo INTEGER;
DECLARE VARIABLE wCodTipoSalvo INTEGER;
DECLARE VARIABLE wDescQuadroSalvo VARCHAR(80);
DECLARE VARIABLE wClassificacaoSalvo VARCHAR(10);
DECLARE VARIABLE wTipoSalvo INTEGER;
DECLARE VARIABLE wNumCampoSalvo INTEGER;
DECLARE VARIABLE wDescFormSalvo VARCHAR(150);
DECLARE VARIABLE wValorSalvo NUMERIC(15,2);
DECLARE VARIABLE wNumItemSalvo INTEGER;
DECLARE VARIABLE wImprimirNomeQuadroAnalitico INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  /* inicializa com uma string vazia */
  wSql              = '';
  wInnerSelect      = '';
  wRefBetween       = '';
  wWhereQuadro      = '';
  wCondicaoNatureza = '';

  /* adiciona condi??o da empresa */
  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> '')) THEN
    BEGIN
      wInnerSelect = :wInnerSelect || :PRCODEMP;
    END

  /* adiciona a condi??o do c?digo do periodo */
  IF (:PRCODPERIODO > 0) THEN
    BEGIN
      IF (:wInnerSelect <> '') THEN
        BEGIN
          wInnerSelect = :wInnerSelect || ' and ';
        END 

      wInnerSelect = :wInnerSelect || 'bdCodPeriodo = ' || :PRCODPERIODO;
    END 

  /* adiciona a condi??o da referencia */
  IF ((:PRANOMESINICIAL > 0) OR (:PRANOMESFINAL > 0)) THEN
    BEGIN
      wRefBetween = 'bdreferencia between ';

      IF (:PRANOMESINICIAL > 0) THEN
        BEGIN
          wRefBetween = :wRefBetween || :PRANOMESINICIAL;
        END 
      ELSE
        BEGIN
          wRefBetween = :wRefBetween || :PRANOMESFINAL;
        END

      wRefBetween = :wRefBetween || ' and ';

      IF (:PRANOMESFINAL > 0) THEN
        BEGIN
          wRefBetween = :wRefBetween || :PRANOMESFINAL;
        END
      ELSE
        BEGIN
          wRefBetween = :wRefBetween || :PRANOMESINICIAL;
        END

      IF (:wInnerSelect <> '') THEN
        BEGIN
          wInnerSelect = :wInnerSelect || ' and ';
        END 

      wInnerSelect = :wInnerSelect || :wRefBetween;
    END 

  IF (:wInnerSelect <> '') THEN
    BEGIN
      wInnerSelect = ' where ' || :wInnerSelect;
    END 

  wInnerSelect = ' select bdcodemp, bdcodperiodo, bdreferencia from vef_emp_tgiaprger ' || :wInnerSelect;

  /* condi??o classifica??o do quadro (usado no join) */
  IF ((:PRCLASSIFICACAO IS NOT NULL) AND (:PRCLASSIFICACAO <> '')) THEN
    BEGIN
      wWhereQuadro = ' and Q.bdclassificacao like '''|| :PRCLASSIFICACAO ||'%''';
    END 

  IF ((:PRCODQUADRO IS NOT NULL) AND (:PRCODQUADRO > 0))  THEN
    BEGIN
      IF (:wWhereQuadro <> '') THEN
        BEGIN
          wWhereQuadro = :wWhereQuadro || ' and ';
        END 

      wWhereQuadro = :wWhereQuadro || ' Q.bdcodquadro = ' || :PRCODQUADRO;
    END 

  /* condi??o da natureza de opera??o */
  IF ((:PRCODNAT IS NOT NULL) AND (:PRCODNAT > 0)) THEN
    BEGIN
      wCondicaoNatureza = ' and nat.bdprefixonat = ' || :PRCODNAT;
    END 

  wSql = wSql || ' select T.bdcodemp, ';
  wSql = wSql || '        E.bdnomemp, ';
  wSql = wSql || '        P.bdcodconfgiapr, ';
  wSql = wSql || '        T.bdreferencia, ';
  wSql = wSql || '        T.bdcodperiodo, ';
  wSql = wSql || '        T.bdnumcampo, ';
  wSql = wSql || '        T.bdcodquadro, ';
  wSql = wSql || '        Q.bdclassificacao, ';
  wSql = wSql || '        Q.bddescquadro, ';
  wSql = wSql || '        F.bddescform, ';
  wSql = wSql || '        T.bdvalor , ';
  wSql = wSql || '        Q.bdcodtipo, ';
  wSql = wSql || '        T.bdprefixonat BDCODNAT, ';
  wSql = wSql || '        Q.bdtipo, ';
  wSql = wSql || '        F.bdnumitem ';
  wSql = wSql || ' from ';
  wSql = wSql || ' ( ';
  wSql = wSql || '     select ger.bdcodemp   , ger.bdcodperiodo, ger.bdreferencia,  ';
  wSql = wSql || '            nat.bdcodquadro, nat.bdnumcampo  , min(nat.bdprefixonat) BDPREFIXONAT, ';
  wSql = wSql || '            sum(coalesce(nat.bdvalor,  0)) "BDVALOR" ';
  wSql = wSql || '     from (' || :wInnerSelect || ') ger ';
  wSql = wSql || '     left outer join vef_emp_tgiaprgernat nat on nat.bdcodemp = ger.bdcodemp and nat.bdcodperiodo = ger.bdcodperiodo and nat.bdreferencia = ger.bdreferencia ' || :wCondicaoNatureza;
  wSql = wSql || '     group by ger.bdcodemp, ger.bdcodperiodo, ger.bdreferencia, nat.bdcodquadro, nat.bdnumcampo';
  wSql = wSql || '     union ';
  wSql = wSql || '     select ger.bdcodemp   , ger.bdcodperiodo, ger.bdreferencia, ';
  wSql = wSql || '            reg.bdcodquadro, reg.bdnumcampo  , null            , ';
  wSql = wSql || '            reg.bdvalor ';
  wSql = wSql || '     from (' || :wInnerSelect || ') ger ';
  wSql = wSql || '     left outer join vef_emp_tgiaprgerreg reg on reg.bdcodemp = ger.bdcodemp and reg.bdcodperiodo = ger.bdcodperiodo and reg.bdreferencia = ger.bdreferencia ';
  wSql = wSql || ' ) T ';
  wSql = wSql || ' inner join VEF_ESTADOS_TCONFGIAPRQ Q on (Q.bdcodquadro = t.bdcodquadro) ' || :wWhereQuadro;
  wSql = wSql || ' left outer join VW_TEMPRESAS_REF_ATUAL E on (E.bdcodemp = T.bdcodemp) ';
  wSql = wSql || ' left outer join VW_VEF_BASE_TEMPPARESTPR P on (P.bdcodemp = E.bdcodemp) ';
  wSql = wSql || ' left outer join VEF_ESTADOS_TCONFGIAPRFORM F on (F.bdcodconf = P.bdcodconfgiapr) and (F.bdcodquadro = T.BDCODQUADRO) and (F.bdnumcampo = T.bdnumcampo) ';

  /* inicializa variaveis de controle */
  wRefAnt                    = 0;
  wCodQuadroAnt              = 0;
  wClassificacaoTitulo       = '';
  wClassificacaoTituloAnt    = '';
  wClassificacaoTitulo2      = '';
  wClassificacaoTitulo2Ant   = '';
  wClassificacaoAnalitica    = '';
  wClassificacaoAnaliticaAnt = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCONF,
    :BDREFERENCIA,
    :BDCODPERIODO,
    :BDNUMCAMPO,
    :BDCODQUADRO,
    :BDCLASSIFICACAO,
    :BDDESCQUADRO,
    :BDDESCFORM,
    :BDVALOR,
    :BDCODTIPO,
    :BDCODNAT,
    :BDTIPO,
    :BDNUMITEM
  DO
    BEGIN
      /* vari?vel de controle para verificar se precisa ou n?o imprimir o nome do quadro analitico */
      wImprimirNomeQuadroAnalitico = 0;

      /* salva valores dos registro em variaveis para restaurar depois */
      wCodQuadroSalvo     = :BDCODQUADRO;
      wCodTipoSalvo       = :BDCODTIPO;
      wDescQuadroSalvo    = :BDDESCQUADRO;
      wClassificacaoSalvo = :BDCLASSIFICACAO;
      wTipoSalvo          = :BDTIPO;
      wNumCampoSalvo      = :BDNUMCAMPO;
      wDescFormSalvo      = :BDDESCFORM;
      wValorSalvo         = :BDVALOR;
      wNumItemSalvo       = :BDNUMITEM;

--      wPrefixoNat = :bdcodnat;

      /* mostra a referencia na consulta */
      IF ((:PRGERAL = 1) AND (:PRANOMESINICIAL <> :PRANOMESFINAL) AND (:BDREFERENCIA <> :wRefAnt)) THEN
        BEGIN
          BDCODQUADRO = 0; /* para ordena??o das referencias */
          BDVALOR     = NULL;
          BDNUMCAMPO  = NULL;
          BDNUMITEM   = NULL;
          BDDESCFORM  = CAST(:BDREFERENCIA AS VARCHAR(6));
          BDDESCFORM  = SUBSTRING(:BDDESCFORM FROM 5 FOR 2) || '/' || SUBSTRING(:BDDESCFORM FROM 1 FOR 4);

          SUSPEND;

          wRefAnt = :BDREFERENCIA;
          wImprimirNomeQuadroAnalitico = 1;
        END 

      /* mostra o nome do quadro na consulta */
      IF ((:PRGERAL = 1) AND (:BDCODQUADRO <> :wCodQuadroAnt))  THEN
        BEGIN
          SELECT p.pos FROM pos('.', :wClassificacaoSalvo) p INTO :wPosPonto;

          wClassificacaoTitulo = LEFT(:wClassificacaoSalvo, (:wPosPonto - 1));

          /* se mudou o t?tulo, mostra qual o t?tulo atual na consulta */
          IF (:wClassificacaoTitulo <> :wClassificacaoTituloAnt) THEN
            BEGIN
              SELECT q.bdcodquadro, q.bdcodtipo, q.bddescquadro, q.bdclassificacao, q.bdtipo
              FROM vef_estados_tconfgiaprq q WHERE (q.bdclassificacao = :wClassificacaoTitulo) AND (q.bdtipo = 0)
              INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

              BDVALOR    = NULL;
              BDNUMCAMPO = NULL;
              BDNUMITEM  = NULL;
              BDDESCFORM = :wClassificacaoTitulo || ' - ' || :BDDESCQUADRO;

              SUSPEND;

              wClassificacaoTituloAnt = :wClassificacaoTitulo;
              wImprimirNomeQuadroAnalitico = 1;
            END 

          /* verifica agora, se o registro atual possui mais de um t?tulo */
          SELECT cc.contar_char FROM contar_char(:wClassificacaoSalvo, '.') cc INTO :wQtdPontos;

          /* Exemplo: 08.01.01 */
          IF (:wQtdPontos > 1) THEN
            BEGIN
              SELECT (p.pos + :wPosPonto) FROM pos('.', SUBSTRING(:wClassificacaoSalvo FROM (:wPosPonto + 1) FOR (CHAR_LENGTH(:wClassificacaoSalvo)-:wPosPonto))) p INTO :wPosPonto;

              wClassificacaoTitulo2 = LEFT(:wClassificacaoSalvo, (:wPosPonto - 1));

              /* se mudou o t?tulo de segundo n?vel, mostra ele na consulta */
              IF (:wClassificacaoTitulo2 <> :wClassificacaoTitulo2Ant) THEN
                BEGIN
                  SELECT q.bdcodquadro, q.bdcodtipo, q.bddescquadro, q.bdclassificacao, q.bdtipo
                  FROM vef_estados_tconfgiaprq q WHERE (q.bdclassificacao = :wClassificacaoTitulo2) AND (q.bdtipo = 0)
                  INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

                  BDVALOR = NULL;
                  BDNUMCAMPO = NULL;
                  BDNUMITEM  = NULL;
                  BDDESCFORM = :wClassificacaoTitulo2 || ' - ' || :BDDESCQUADRO;

                  SUSPEND;

                  wClassificacaoTitulo2Ant = :wClassificacaoTitulo2;
                  wImprimirNomeQuadroAnalitico = 1;
                END
            END 

          /* quadro analitico */
          SELECT rp.bdrpos FROM rpos('.', :wClassificacaoSalvo) rp INTO :wPosPonto;

          wClassificacaoAnalitica = RIGHT(:wClassificacaoSalvo, (wPosPonto-1));

          IF ((:wImprimirNomeQuadroAnalitico > 0) OR (:wClassificacaoAnalitica <> :wClassificacaoAnaliticaAnt)) THEN
            BEGIN
              SELECT q.bdcodquadro, q.bdcodtipo, q.bddescquadro, q.bdclassificacao, q.bdtipo
              FROM vef_estados_tconfgiaprq q WHERE (q.bdclassificacao = :wClassificacaoSalvo) AND (q.bdtipo = 1)
              INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

              BDVALOR    = NULL;
              BDNUMCAMPO = NULL;
              BDNUMITEM  = NULL;
              BDDESCFORM = :BDCLASSIFICACAO || ' - ' || :BDDESCQUADRO;

              SUSPEND;

              wClassificacaoAnaliticaAnt = :wClassificacaoAnalitica;
            END 

          BDCODQUADRO   = :wCodQuadroSalvo;
          wCodQuadroAnt = :BDCODQUADRO;
        END 

      /* restaura os valores salvos anteriormente */
      BDCODQUADRO     = :wCodQuadroSalvo;
      BDCODTIPO       = :wCodTipoSalvo;
      BDDESCQUADRO    = :wDescQuadroSalvo;
      BDCLASSIFICACAO = :wClassificacaoSalvo;
      BDTIPO          = :wTipoSalvo;
      BDNUMCAMPO      = :wNumCampoSalvo;
      BDDESCFORM      = :wDescFormSalvo;
      BDVALOR         = :wValorSalvo;
      BDNUMITEM       = :wNumItemSalvo;

      SUSPEND;
    END
END
^

/* Alter (SP_VEF_TREEVIEW_CONS_GIARJ) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARJ(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRCODNAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER)
 AS
DECLARE VARIABLE WWHEREQUADRO VARCHAR(1000);
DECLARE VARIABLE WREFBETWEEN VARCHAR(100);
DECLARE VARIABLE WCONDICAONATUREZA VARCHAR(100);
DECLARE VARIABLE WINNERSELECT VARCHAR(1000);
DECLARE VARIABLE WSQL BLOB SUB_TYPE 1 SEGMENT SIZE 16384;
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE WCODQUADROANT INTEGER;
DECLARE VARIABLE WPOSPONTO INTEGER;
DECLARE VARIABLE WCLASSIFICACAOTITULO VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULOANT VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULO2 VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULO2ANT VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOANALITICA VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOANALITICAANT VARCHAR(10);
DECLARE VARIABLE WQTDPONTOS INTEGER;
DECLARE VARIABLE WCODQUADROSALVO INTEGER;
DECLARE VARIABLE WCODTIPOSALVO INTEGER;
DECLARE VARIABLE WDESCQUADROSALVO VARCHAR(80);
DECLARE VARIABLE WCLASSIFICACAOSALVO VARCHAR(10);
DECLARE VARIABLE WTIPOSALVO INTEGER;
DECLARE VARIABLE WNUMCAMPOSALVO INTEGER;
DECLARE VARIABLE WDESCFORMSALVO VARCHAR(150);
DECLARE VARIABLE WVALORSALVO NUMERIC(15,2);
DECLARE VARIABLE WNUMITEMSALVO INTEGER;
DECLARE VARIABLE WIMPRIMIRNOMEQUADROANALITICO INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WCODUFANTERIOR INTEGER;
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE WPREFIXONATANTERIOR INTEGER;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRANOMESFINAL, NULL, NULL);

  /* INICIALIZA COM UMA STRING VAZIA */
  WSQL              = '';
  WINNERSELECT      = '';
  WREFBETWEEN       = '';
  WWHEREQUADRO      = '';
  WCONDICAONATUREZA = '';

  /* ADICIONA CONDI??O DA EMPRESA */
  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> '')) THEN
    BEGIN
      WINNERSELECT = :WINNERSELECT || :PRCODEMP;
    END

  /* ADICIONA A CONDI??O DO C?DIGO DO PERIODO */
  IF (:PRCODPERIODO > 0) THEN
    BEGIN
      IF (:WINNERSELECT <> '') THEN
        BEGIN
          WINNERSELECT = :WINNERSELECT || ' AND ';
        END 

      WINNERSELECT = :WINNERSELECT || 'BDCODPERIODO = ' || :PRCODPERIODO;
    END 

  /* ADICIONA A CONDI??O DA REFERENCIA */
  IF ((:PRANOMESINICIAL > 0) OR (:PRANOMESFINAL > 0)) THEN
    BEGIN
      WREFBETWEEN = 'BDREFERENCIA BETWEEN ';

      IF (:PRANOMESINICIAL > 0) THEN
        BEGIN
          WREFBETWEEN = :WREFBETWEEN || :PRANOMESINICIAL;
        END 
      ELSE
        BEGIN
          WREFBETWEEN = :WREFBETWEEN || :PRANOMESFINAL;
        END

      WREFBETWEEN = :WREFBETWEEN || ' AND ';

      IF (:PRANOMESFINAL > 0) THEN
        BEGIN
          WREFBETWEEN = :WREFBETWEEN || :PRANOMESFINAL;
        END
      ELSE
        BEGIN
          WREFBETWEEN = :WREFBETWEEN || :PRANOMESINICIAL;
        END

      IF (:WINNERSELECT <> '') THEN
        BEGIN
          WINNERSELECT = :WINNERSELECT || ' AND ';
        END 

      WINNERSELECT = :WINNERSELECT || :WREFBETWEEN;
    END 

  IF (:WINNERSELECT <> '') THEN
    BEGIN
      WINNERSELECT = ' WHERE ' || :WINNERSELECT;
    END 

  WINNERSELECT = ' SELECT BDCODEMP, BDCODPERIODO, BDREFERENCIA FROM VEF_EMP_TGIARJGER ' || :WINNERSELECT;

  /* CONDI??O CLASSIFICA??O DO QUADRO (USADO NO JOIN) */
  IF ((:PRCLASSIFICACAO IS NOT NULL) AND (:PRCLASSIFICACAO <> '')) THEN
    BEGIN
      WWHEREQUADRO = ' AND Q.BDCLASSIFICACAO LIKE '''|| :PRCLASSIFICACAO ||'%''';
    END 

  IF ((:PRCODQUADRO IS NOT NULL) AND (:PRCODQUADRO > 0))  THEN
    BEGIN
      IF (:WWHEREQUADRO <> '') THEN
        BEGIN
          WWHEREQUADRO = :WWHEREQUADRO || ' AND ';
        END 

      WWHEREQUADRO = :WWHEREQUADRO || ' Q.BDCODQUADRO = ' || :PRCODQUADRO;
    END 

  /* CONDI??O DA NATUREZA DE OPERA??O */
  IF ((:PRCODNAT IS NOT NULL) AND (:PRCODNAT > 0)) THEN
    BEGIN
      WCONDICAONATUREZA = ' AND NAT.BDPREFIXONAT = ' || :PRCODNAT;
    END 

  WSQL = WSQL || ' SELECT T.BDCODEMP, ';
  WSQL = WSQL || '        E.BDNOMEMP, ';
  WSQL = WSQL || '        P.BDCODCONFGIARJ, ';
  WSQL = WSQL || '        T.BDREFERENCIA, ';
  WSQL = WSQL || '        T.BDCODPERIODO, ';
  WSQL = WSQL || '        T.BDNUMCAMPO, ';
  WSQL = WSQL || '        T.BDCODQUADRO, ';
  WSQL = WSQL || '        Q.BDCLASSIFICACAO, ';
  WSQL = WSQL || '        Q.BDDESCQUADRO, ';
  WSQL = WSQL || '        F.BDDESCFORM, ';
  WSQL = WSQL || '        T.BDVALOR , ';
  WSQL = WSQL || '        Q.BDCODTIPO, ';
  WSQL = WSQL || '        T.BDPREFIXONAT BDCODNAT, ';
  WSQL = WSQL || '        Q.BDTIPO, ';
  WSQL = WSQL || '        F.BDNUMITEM, ';
  WSQL = WSQL || '        T.BDCODUF, ';
  WSQL = WSQL || '        uf.BDSIGLAUF ';
  WSQL = WSQL || ' FROM ( ';
  WSQL = WSQL || '        SELECT GER.BDCODEMP   , GER.BDCODPERIODO, GER.BDREFERENCIA,  ';
  WSQL = WSQL || '               NAT.BDCODQUADRO, NAT.BDNUMCAMPO  , NAT.BDPREFIXONAT, ';
  WSQL = WSQL || '               SUM(COALESCE(NAT.BDVALOR,  0)) "BDVALOR", null as BDCODUF ';
  WSQL = WSQL || '        FROM (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '        LEFT OUTER JOIN VEF_EMP_TGIARJGERNAT NAT ON NAT.BDCODEMP = GER.BDCODEMP AND NAT.BDCODPERIODO = GER.BDCODPERIODO AND NAT.BDREFERENCIA = GER.BDREFERENCIA ' || :WCONDICAONATUREZA;
  WSQL = WSQL || '        GROUP BY GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, NAT.BDCODQUADRO, NAT.BDNUMCAMPO, BDPREFIXONAT ';
  WSQL = WSQL || '        UNION ALL ';
  WSQL = WSQL || '        SELECT GER.BDCODEMP   , GER.BDCODPERIODO, GER.BDREFERENCIA, ';
  WSQL = WSQL || '               REG.BDCODQUADRO, REG.BDNUMCAMPO  , NULL            , ';
  WSQL = WSQL || '               REG.BDVALOR, null as BDCODUF ';
  WSQL = WSQL || '        FROM (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '        LEFT OUTER JOIN VEF_EMP_TGIARJGERREG REG ON REG.BDCODEMP = GER.BDCODEMP AND REG.BDCODPERIODO = GER.BDCODPERIODO AND REG.BDREFERENCIA = GER.BDREFERENCIA ';

  WSQL = WSQL || '       union all ';
  -- // Entradas Interestaduais //
  WSQL = WSQL || '       select GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q21.BDCODQUADRO, q21.BDNUMCAMPO, ';
  WSQL = WSQL || '              null as BDPREFIXONAT, sum(coalesce(q21.BDVALOR, 0)) "BDVALOR", COALESCE(Q21.BDCODUF, 9999) as BDCODUF ';
  WSQL = WSQL || '       from (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '       left outer join VEF_EMP_TGIARJGERQ21 q21 on (q21.BDCODEMP = GER.BDCODEMP and q21.BDCODPERIODO = GER.BDCODPERIODO and q21.BDREFERENCIA = GER.BDREFERENCIA) ';
  WSQL = WSQL || '       group by GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q21.BDCODQUADRO, q21.BDNUMCAMPO, q21.BDCODUF ';
  WSQL = WSQL || '       union all ';
  -- // Sa?das Interestaduais //
  WSQL = WSQL || '       select GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q22.BDCODQUADRO, q22.BDNUMCAMPO, ';
  WSQL = WSQL || '              null as BDPREFIXONAT, sum(coalesce(q22.BDVALOR, 0)) "BDVALOR", COALESCE(Q22.BDCODUF, 9999) as BDCODUF ';
  WSQL = WSQL || '       from (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '       left outer join VEF_EMP_TGIARJGERQ22 q22 on (q22.BDCODEMP = GER.BDCODEMP and q22.BDCODPERIODO = GER.BDCODPERIODO and q22.BDREFERENCIA = GER.BDREFERENCIA) ';
  WSQL = WSQL || '       group by GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q22.BDCODQUADRO, q22.BDNUMCAMPO, q22.BDCODUF ';

  WSQL = WSQL || '       ) T ';
  WSQL = WSQL || ' INNER JOIN VEF_ESTADOS_TCONFGIARJQ Q ON (Q.BDCODQUADRO = T.BDCODQUADRO) ' || :WWHEREQUADRO;
  WSQL = WSQL || ' LEFT OUTER JOIN VW_TEMPRESAS_REF_ATUAL E ON (E.BDCODEMP = T.BDCODEMP) ';
  WSQL = WSQL || ' LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTRJ P ON (P.BDCODEMP = E.BDCODEMP) ';
  WSQL = WSQL || ' LEFT OUTER JOIN VEF_ESTADOS_TCONFGIARJFORM F ON (F.BDCODCONF = P.BDCODCONFGIARJ) AND (F.BDCODQUADRO = T.BDCODQUADRO) AND (F.BDNUMCAMPO = T.BDNUMCAMPO) ';
  WSQL = WSQL || ' left outer join TUF uf on (uf.BDCODUF = T.BDCODUF) ';
  WSQL = WSQL || ' order by BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODQUADRO, BDPREFIXONAT,/*XXX*/ BDCODUF, BDNUMCAMPO, BDDESCFORM ';

  /* INICIALIZA VARIAVEIS DE CONTROLE */
  WREFANT                    = 0;
  WCODQUADROANT              = 0;
  WCLASSIFICACAOTITULO       = '';
  WCLASSIFICACAOTITULOANT    = '';
  WCLASSIFICACAOTITULO2      = '';
  WCLASSIFICACAOTITULO2ANT   = '';
  WCLASSIFICACAOANALITICA    = '';
  WCLASSIFICACAOANALITICAANT = '';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCONF,
    :BDREFERENCIA,
    :BDCODPERIODO,
    :BDNUMCAMPO,
    :BDCODQUADRO,
    :BDCLASSIFICACAO,
    :BDDESCQUADRO,
    :BDDESCFORM,
    :BDVALOR,
    :BDCODTIPO,
    :BDCODNAT,
    :BDTIPO,
    :BDNUMITEM,
    :wCODUF,
    :wSIGLAUF
  DO
    BEGIN
      /* VARI?VEL DE CONTROLE PARA VERIFICAR SE PRECISA OU N?O IMPRIMIR O NOME DO QUADRO ANALITICO */
      WIMPRIMIRNOMEQUADROANALITICO = 0;

      /* SALVA VALORES DOS REGISTRO EM VARIAVEIS PARA RESTAURAR DEPOIS */
      WCODQUADROSALVO     = :BDCODQUADRO;
      WCODTIPOSALVO       = :BDCODTIPO;
      WDESCQUADROSALVO    = :BDDESCQUADRO;
      WCLASSIFICACAOSALVO = :BDCLASSIFICACAO;
      WTIPOSALVO          = :BDTIPO;
      WNUMCAMPOSALVO      = :BDNUMCAMPO;
      WDESCFORMSALVO      = :BDDESCFORM;
      WVALORSALVO         = :BDVALOR;
      WNUMITEMSALVO       = :BDNUMITEM;

      /* MOSTRA A REFERENCIA NA CONSULTA */
      IF ((:PRGERAL = 1) AND (:PRANOMESINICIAL <> :PRANOMESFINAL) AND (:BDREFERENCIA <> :WREFANT)) THEN
        BEGIN
          BDCODQUADRO = 0; /* PARA ORDENA??O DAS REFERENCIAS */
          BDVALOR     = NULL;
          BDNUMCAMPO  = NULL;
          BDNUMITEM   = NULL;
          BDDESCFORM  = CAST(:BDREFERENCIA AS VARCHAR(6));
          BDDESCFORM  = SUBSTRING(:BDDESCFORM FROM 5 FOR 2) || '/' || SUBSTRING(:BDDESCFORM FROM 1 FOR 4);

          SUSPEND;

          WREFANT = :BDREFERENCIA;
          WIMPRIMIRNOMEQUADROANALITICO = 1;
        END 

      /* MOSTRA O NOME DO QUADRO NA CONSULTA */
      IF ((:PRGERAL = 1) AND (:BDCODQUADRO <> :WCODQUADROANT))  THEN
        BEGIN
          SELECT P.POS FROM POS('.', :WCLASSIFICACAOSALVO) P INTO :WPOSPONTO;

          WCLASSIFICACAOTITULO = LEFT(:WCLASSIFICACAOSALVO, (:WPOSPONTO - 1));

          /* SE MUDOU O T?TULO, MOSTRA QUAL O T?TULO ATUAL NA CONSULTA */
          IF (:WCLASSIFICACAOTITULO <> :WCLASSIFICACAOTITULOANT) THEN
            BEGIN
              SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
              FROM VEF_ESTADOS_TCONFGIARJQ Q WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOTITULO) AND (Q.BDTIPO = 0)
              INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

              BDVALOR    = NULL;
              BDNUMCAMPO = NULL;
              BDNUMITEM  = NULL;
              BDDESCFORM = :WCLASSIFICACAOTITULO || ' - ' || :BDDESCQUADRO;

              SUSPEND;

              WCLASSIFICACAOTITULOANT = :WCLASSIFICACAOTITULO;
              WIMPRIMIRNOMEQUADROANALITICO = 1;
            END 

          /* VERIFICA AGORA, SE O REGISTRO ATUAL POSSUI MAIS DE UM T?TULO */
          SELECT CC.CONTAR_CHAR FROM CONTAR_CHAR(:WCLASSIFICACAOSALVO, '.') CC INTO :WQTDPONTOS;

          /* EXEMPLO: 08.01.01 */
          IF (:WQTDPONTOS > 1) THEN
            BEGIN
              SELECT (P.POS + :WPOSPONTO) FROM POS('.', SUBSTRING(:WCLASSIFICACAOSALVO FROM (:WPOSPONTO + 1) FOR (CHAR_LENGTH(:WCLASSIFICACAOSALVO)-:WPOSPONTO))) P INTO :WPOSPONTO;

              WCLASSIFICACAOTITULO2 = LEFT(:WCLASSIFICACAOSALVO, (:WPOSPONTO - 1));

              /* SE MUDOU O T?TULO DE SEGUNDO N?VEL, MOSTRA ELE NA CONSULTA */
              IF (:WCLASSIFICACAOTITULO2 <> :WCLASSIFICACAOTITULO2ANT) THEN
                BEGIN
                  SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
                  FROM VEF_ESTADOS_TCONFGIARJQ Q WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOTITULO2) AND (Q.BDTIPO = 0)
                  INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

                  BDVALOR = NULL;
                  BDNUMCAMPO = NULL;
                  BDNUMITEM  = NULL;
                  BDDESCFORM = :WCLASSIFICACAOTITULO2 || ' - ' || :BDDESCQUADRO;

                  SUSPEND;

                  WCLASSIFICACAOTITULO2ANT = :WCLASSIFICACAOTITULO2;
                  WIMPRIMIRNOMEQUADROANALITICO = 1;
                END
            END 

          /* QUADRO ANALITICO */
          SELECT RP.BDRPOS FROM RPOS('.', :WCLASSIFICACAOSALVO) RP INTO :WPOSPONTO;

          WCLASSIFICACAOANALITICA = RIGHT(:WCLASSIFICACAOSALVO, (WPOSPONTO-1));

          IF ((:WIMPRIMIRNOMEQUADROANALITICO > 0) OR (:WCLASSIFICACAOANALITICA <> :WCLASSIFICACAOANALITICAANT)) THEN
            BEGIN
              SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
              FROM VEF_ESTADOS_TCONFGIARJQ Q WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOSALVO) AND (Q.BDTIPO = 1)
              INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

              BDVALOR    = NULL;
              BDNUMCAMPO = NULL;
              BDNUMITEM  = NULL;
              BDDESCFORM = :BDCLASSIFICACAO || ' - ' || :BDDESCQUADRO;

              SUSPEND;

              WCLASSIFICACAOANALITICAANT = :WCLASSIFICACAOANALITICA;
            END 

          BDCODQUADRO   = :WCODQUADROSALVO;
          WCODQUADROANT = :BDCODQUADRO;
        END 

      /* JOGA OS PREFIXOS DA NATUREZAS */
      IF (WPREFIXONATANTERIOR IS NULL) THEN
        WPREFIXONATANTERIOR = 0; /* Para jogar na primeira linha dos totalizadores */
      IF ((PRGERAL = 1) AND 
          (((BDCODTIPO = 2) AND (WPREFIXONATANTERIOR <> BDCODNAT)) OR  /* Valores entradas */
           ((BDCODTIPO = 3) AND (WPREFIXONATANTERIOR <> BDCODNAT)))) THEN /* Valores sa?das */
         BEGIN
           BDNUMCAMPO = NULL;
           BDNUMITEM  = NULL;
           BDDESCFORM = SUBSTRING(BDCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(BDCODNAT FROM 2 FOR 3);
           BDVALOR    = NULL;
           BDTIPO     = 0;
           WPREFIXONATANTERIOR = BDCODNAT;
           SUSPEND;
         END

      /* JOGA OS ESTADOS NOS QUADROS ESTADUAIS */
      IF (WCODUFANTERIOR IS NULL) THEN
        WCODUFANTERIOR = 0; /* Para jogar na primeira linha dos totalizadores */
      IF ((PRGERAL = 1) AND 
          (((BDCODTIPO = 332) AND (((WCODUF = 9999) AND (WCODUFANTERIOR <> 9999)) OR ((WCODUF <> 9999) AND (WCODUF <> WCODUFANTERIOR)))) OR  /* Entradas Interestaduais */
           ((BDCODTIPO = 333) AND (((WCODUF = 9999) AND (WCODUFANTERIOR <> 9999)) OR ((WCODUF <> 9999) AND (WCODUF <> WCODUFANTERIOR)))))) THEN /* Sa?das Interestaduais */
         BEGIN
           BDNUMCAMPO = NULL;
           BDNUMITEM  = NULL;
           IF (WCODUF = 9999) THEN
             BDDESCFORM = 'Total';
           ELSE
             BDDESCFORM = wSIGLAUF;
           BDVALOR        = NULL;
           WCODUFANTERIOR = WCODUF;
           BDTIPO         = 0;
           SUSPEND;
         END

      /* RESTAURA OS VALORES SALVOS ANTERIORMENTE */
      BDCODQUADRO     = :WCODQUADROSALVO;
      BDCODTIPO       = :WCODTIPOSALVO;
      BDDESCQUADRO    = :WDESCQUADROSALVO;
      BDCLASSIFICACAO = :WCLASSIFICACAOSALVO;
      BDTIPO          = :WTIPOSALVO;
      BDNUMCAMPO      = :WNUMCAMPOSALVO;
      BDDESCFORM      = :WDESCFORMSALVO;
      BDVALOR         = :WVALORSALVO;
      BDNUMITEM       = :WNUMITEMSALVO;

      SUSPEND;
    END
END
^

/* Alter (SP_VEF_TREEVIEW_CONS_GIARO) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARO(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDCODNAT INTEGER,
BDORDEMTTNAT INTEGER,
BDTITULOGRUPO VARCHAR(80))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRSALVAQUADROANT INTEGER;
DECLARE VARIABLE WTIT INTEGER;
DECLARE VARIABLE WCLASSIFIPRINC VARCHAR(20);
DECLARE VARIABLE WCLASSIFITITULO VARCHAR(20);
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(150);
DECLARE VARIABLE PRCLASSIFIANT VARCHAR(11);
DECLARE VARIABLE PRNATANT INTEGER;
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WAUX2 INTEGER;
DECLARE VARIABLE PRVALOR NUMERIC(15,2);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRDESCQUADROANT VARCHAR(80);
DECLARE VARIABLE WTIPO INTEGER;
DECLARE VARIABLE WPREFIXONAT INTEGER;
DECLARE VARIABLE WORDEMTTNATCOMPRAS INTEGER;
DECLARE VARIABLE WORDEMTTNATVENDAS INTEGER;
DECLARE VARIABLE WNATAUX INTEGER;
DECLARE VARIABLE WTITULOGRUPO VARCHAR(80);
DECLARE VARIABLE WCLASSTITULO VARCHAR(20);
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(20);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'SELECT T.BDCODEMP, ';
  wsql = wsql || ' empAtual.BDNOMEMP, ';
  wsql = wsql || ' parro.BDCODCONFGIARO, ';
  wsql = wsql || ' T.BDREFERENCIA, ';
  wsql = wsql || ' T.BDCODPERIODO, ';
  wsql = wsql || ' T.BDNUMCAMPO, ';
  wsql = wsql || ' T.BDCODQUADRO, ';
  wsql = wsql || ' GIAROQ.BDCLASSIFICACAO, ';
  wsql = wsql || ' GIAROQ.BDDESCQUADRO, ';
  wsql = wsql || ' GIAROF.BDDESCFORM, ';
  wsql = wsql || ' T.BDVALOR BDVALOR, ';
  wsql = wsql || ' GIAROQ.BDCODTIPO, ';
  wsql = wsql || ' GIAROQ.BDTIPO, ';
  wsql = wsql || ' GIAROF.BDNUMITEM, ';
  wsql = wsql || ' T.BDPREFIXONAT BDCodNat, ';
  wsql = wsql || ' T.bdordemttnat, ';
  wsql = wsql || ' null bdtitulogrupo ';
  wsql = wsql || ' FROM vw_vef_emp_tGIAROgerunion T';
  wsql = wsql || ' left outer join VW_EMPRESAS_REF_ATUAL empAtual on (empAtual.bdcodemp = t.bdcodemp) ';
  wsql = wsql || ' left outer join vef_base_tempparestro parro on (parro.bdCodEmp = empAtual.bdCodEmp and parro.bdrefemp = empAtual.bdempref) ';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIAROQ GIAROQ on (GIAROQ.bdcodquadro = t.bdcodquadro)';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIAROFORM GIAROF on (GIAROF.bdCodConf = parro.BDCODCONFGIARO and GIAROF.bdCODQUADRO = t.bdCODQUADRO and GIAROF.bdNumcampo = t.bdNumcampo)';

  wwhere = '';

   IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

   IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';
       ELSE
          wwhere = wwhere || ' WHERE ';

       wwhere = wwhere || ' t.bdreferencia >= ' || :praNomesInicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || ' t.bdreferencia <= ' || :praNomesFinal;
     END

   IF (prClassificacao IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' GIAROQ.bdclassificacao LIKE ''' ||:PRCLASSIFICACAO||'%''';
      END
   IF (:prcodperiodo IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' t.bdCODPERIODO ' || ' = ' || :prcodperiodo;
       END
   IF (:prcodquadro IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

      wwhere = wwhere || ' GIAROQ.BDCODQUADRO' || ' = ' ||:prcodquadro;
      END

   wsql = wsql || wwhere || ' order by bdcodemp, bdreferencia desc, bdclassificacao, BDCODQUADRO,bdcodnat,t.bdnumcampo';

   prRefant = 0;
   prquadroant = 0;
   prnatant = 0;
   wTit = 0;
   WCLASSIFIPRINC = '';
   wTIT = 1;
   wtitulogrupo = NULL;
   wclasstitulo = '';
   wClassificacao = '';

   FOR EXECUTE STATEMENT wsql
   INTO
     BDCODEMP,
     BDNOMEMP,
     BDCODCONF,
     BDREFERENCIA,
     BDCODPERIODO,
     BDNUMCAMPO,
     BDCODQUADRO,
     bdclassificacao,
     bddescquadro,
     BDDESCFORM,
     BDVALOR,
     BDCODTIPO,
     BDTIPO,
     BDNUMITEM,
     BDCODNAT,
     bdordemttnat,
     bdtitulogrupo

   DO
   BEGIN
   wnataux = 0;
   wprefixonat = bdcodnat;
   prNumCampo = BDNumcampo;
   prDescForm = BDDESCFORM;
   prValor = bdValor;

   IF ((wtitulogrupo IS NULL) OR (wtitulogrupo <> bdtitulogrupo) OR (wclasstitulo <> SUBSTRING(bdclassificacao FROM 1 FOR 2)))  THEN
      BEGIN
         wclasstitulo = SUBSTRING(bdclassificacao FROM 1 FOR 2);
         SELECT FIRST 1 bddescquadro FROM VEF_ESTADOS_TCONFGIAROQ tit WHERE tit.bdtipo = 0 AND tit.bdclassificacao = SUBSTRING(:bdclassificacao FROM 1 FOR 2) INTO :wtitulogrupo;
      END

   bdtitulogrupo = wtitulogrupo;

   IF ((prgeral = 1) AND (prRefAnt <> bdReferencia) AND (praNomesInicial <> praNomesFinal)) THEN
      BEGIN
        bdNumCampo = NULL;
        BDDESCFORM = CAST(bdreferencia AS VARCHAR(6));
        bddescform = SUBSTRING(bddescform FROM 5 FOR 2) || '/' ||SUBSTRING(bddescform FROM 1 FOR 4);
        bdvalor = NULL;
        prRefant = bdreferencia;
        SUSPEND;
      END
    IF ((prgeral = 1) AND (bdcodquadro <> prquadroant)) THEN
       BEGIN
         prsalvaquadroant = bdcodquadro;
         prclassifiant = bdclassificacao;
         prdescquadroant = bddescquadro;

         IF (wPrefixoNat IS NULL) THEN
            BEGIN
              SELECT FIRST 1 tPos.BDRPOS FROM rpos('.', :bdclassificacao) tpos INTO :wAUX;

              IF ((wclassifiprinc = '') AND (wAux > 1)) THEN
                 BEGIN
                   wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);
                   wtit = 1;
                 END
              ELSE
                 BEGIN
                   IF (wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1)) THEN
                      BEGIN
                        wtit = 0;
                      END
                   ELSE
                      BEGIN
                        wtit = 1;
                      END
                   IF (waux > 1) THEN
                      BEGIN
                        wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);
                      END
                 END
            END
         ELSE
            BEGIN
              SELECT FIRST 1 tpos.pos FROM pos('.' , :Bdclassificacao) tpos INTO :waux;
              wtit = 1;
              wclassifititulo = '';
            END

         IF (waux > 1) THEN
            BEGIN

              IF (wprefixonat IS NULL) THEN
                 BEGIN
                   SELECT FIRST 1 tpos.pos FROM pos('.' , :bdClassificacao) tpos INTO :waux2;
                   wClassifiPrinc = SUBSTRING(bdclassificacao FROM 1 FOR waux2-1);
                 END

          wClassifiTitulo = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);

          IF ((wClassifiPrinc <> wClassifiTitulo) AND (wTit = 1) AND (wClassificacao <> wClassifiPrinc)) THEN
             BEGIN
               SELECT Q.bdcodquadro, Q.bdDescQuadro FROM VEF_ESTADOS_TCONFGIAROQ Q WHERE Q.bdclassificacao = :wClassifiPrinc
               INTO :bdcodquadro, :bddescform;
 
               bdNUmcampo = NULL;
               bdValor = NULL;
               prquadroant = bdCodQuadro;
               bdclassificacao = wClassifiPrinc;
               bddescquadro = bddescform;
               wTipo = BDTipo;
               bdTipo = 0;
               bdcodnat = NULL;
 
               SUSPEND;
               bdclassificacao = prClassifiAnt;
               bdcodquadro = prSalvaQuadroAnt;
               bdDescQuadro = prDescQuadroAnt;
               bdTipo = wTipo;
               bdcodnat = NULL;
               wClassificacao = wClassifiPrinc;
             END
          IF ((wClassifiTitulo <> '') AND (wtit = 1)) THEN
               BEGIN
                 SELECT Q.bdcodquadro, Q.bdDescQuadro FROM VEF_ESTADOS_TCONFGIAROQ Q WHERE Q.bdclassificacao = :wclassifititulo
                 INTO :bdcodquadro, :bddescform;
                 
                 bdNUmcampo = NULL;
                 bdValor = NULL;
                 prquadroant = bdCodQuadro;
                 bdclassificacao = wClassifiTitulo;
                 bddescquadro = bddescform;
                 wTipo = BDTipo;
                 bdTipo = 0;

                 SUSPEND;
                 bdclassificacao = prClassifiAnt;
                 bdcodquadro = prSalvaQuadroAnt;
                 bdDescQuadro = prDescQuadroAnt;
                 bdTipo = wTipo;
               END
            END

         bdNUmcampo = NULL;
         BDDESCFORM = bdclassificacao || ' - ' || bddescquadro;
         bdvalor = NULL;
         prquadroant = bdcodquadro;

         SUSPEND;
       END

     IF ((bdcodtipo = 264) AND (prNatAnt <> wprefixonat) OR ((bdCodTipo = 268) AND (prNatAnt <> wprefixonat))) THEN
        BEGIN
          bdNumCampo = NULL;
          bddescForm = SUBSTRING(CAST(wprefixonat AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wprefixonat AS VARCHAR(10)) FROM 2 FOR 3);
          bdValor = NULL;
          prnatAnt = wprefixonat;
          SUSPEND;
        END

     IF (wnataux <> 0) THEN
        BEGIN
          SUSPEND;
        END

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = prvalor;
    SUSPEND;
  END
END
^

/* Alter (SP_VEF_TREEVIEW_CONS_GIASP) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIASP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(10),
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODTIPO INTEGER,
BDCODNAT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRSALVAQUADROANT INTEGER;
DECLARE VARIABLE PRNATANT INTEGER;
DECLARE VARIABLE PRCLASSIFIANT VARCHAR(10);
DECLARE VARIABLE PRDESCQUADROANT VARCHAR(80);
DECLARE VARIABLE PRULTIMOCLASSIFITIT VARCHAR(10);
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,6);
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODCIDTOT INTEGER;
DECLARE VARIABLE WNOMCID VARCHAR(40);
DECLARE VARIABLE WPREFIXONAT INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE PRUFANT INTEGER;
DECLARE VARIABLE WCLASSIFITITULO VARCHAR(10);
DECLARE VARIABLE WAUX INTEGER;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas2.BDNOMEMP, ';
  wsql = wsql || 'empresas.BDCODCONFGIASP,';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQUADRO,';
  wsql = wsql || 'TCONF.bdclassificacao, ';
  wsql = wsql || 'TCONF.bddescquadro,';
  wsql = wsql || 'TCONFGIASPFORM.bddescform,';
  wsql = wsql || 'T.BDVALOR BDVALOR, ';
  wsql = wsql || 'TCONF.bdcodtipo, ';
  wsql = wsql || 'T.BDPREFIXONAT BDCODNAT ';

  wsql = wsql || ' from VW_VEF_EMP_TGIASPGERUNION T';

  wsql = wsql||' left outer join VW_EMP_REF_TOTAL empresas on (empresas.bdcodemp = t.bdcodemp ) ';
  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIASPQ TCONF on (TCONF.bdcodquadro = t.bdcodquadro) ' ;
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIASPFORM TCONFGIASPFORM on (TCONFGIASPFORM.bdcodconf = empresas.BDCODCONFGIASP and ';
  wsql = wsql||' TCONFGIASPFORM.bdcodquadro = T.BDCODQUADRO and TCONFGIASPFORM.bdnumcampo = T.BDNUMCAMPO) ' ;
  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (PRCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       --wwhere = wwhere||'T.BDCODQUADRO  = '||:prcodquadro;
       --wwhere = wwhere||'TCONF.bdclassificacao LIKE ''0'||:prcodquadro||'%''';
       wwhere = wwhere||'TCONF.bdclassificacao LIKE '''||:PRCLASSIFICACAO||'%''';
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODPERIODO' || ' = '||:prcodperiodo;

    END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQUADRO, BDCODNAT, bdnumcampo' ;

  prrefant   = 0;
  prquadroant = 0;
  prnatant = 0;
  prufant = 0;
  PRULTIMOCLASSIFITIT = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP ,
    BDCODCONF ,
    BDREFERENCIA ,
    BDCODPERIODO ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCQUADRO ,
    BDDESCFORM ,
    BDVALOR ,
    BDCODTIPO,
    BDCODNAT
  DO
  BEGIN

    wPREFIXONAT = BDCODNAT;

    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;

    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal) ) THEN -- mostra a referencia caso esteja consultando varias
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        prrefant = bdreferencia;
        SUSPEND;
      END

    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN   -- mostra o nome do quadro atual na consulta
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF  (prultimoclassifitit <> wclassifititulo) THEN
              BEGIN

                SELECT x.bdcodquadro, x.bddescquadro FROM VEF_ESTADOS_TCONFGIASPQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;


                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                prufant = 0;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
              END

          END

        bdnumcampo = NULL;
        BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        -- BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        prquadroant = bdcodquadro;
        prufant = 0;

        SUSPEND;

      END

    IF ((bdcodtipo =2) AND (prnatant <> wPREFIXONAT) OR ((bdcodtipo =3) AND (prnatant <> wPREFIXONAT)) ) THEN -- mostra a natureza atual na consuta...
       BEGIN
         bdnumcampo = NULL;
         bddescform =  SUBSTRING(CAST(wPREFIXONAT AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wPREFIXONAT AS VARCHAR(10)) FROM 2 FOR 3);
         BDVALOR = NULL;
         prnatant = wPREFIXONAT;
         SUSPEND;
       END

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = prvalor;

    SUSPEND;


  END

END
^

/* Alter (SP_VEF_TREEVIEW_CONS_ICMSSPED) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ICMSSPED(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRUF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(150),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDCODTIPOVALAGRE INTEGER,
BDDESCRICAO VARCHAR(150),
BDCODTIPO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WVALAGRE VARCHAR(32700);
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE WUFANT INTEGER;
DECLARE VARIABLE WTIPOVA INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(150);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  --sol:10913 - juntar os valores agregados
  wsql = 'select BDCODEMP, BDNOMEMP, BDCODCONFICMSSPED, BDREFERENCIA, BDCODPERIODO, BDNUMCAMPO, ';
  wsql = wsql || ' BDCODQICMSSPED, BDDESCQICMSSPED, BDDESCFORMICMSSPED, BDVALOR, ';
  wsql = wsql || ' BDNUMITEM, BDCLASSIFICACAO, BDCODUF, BDSIGLAUF, bdcodtipovalagre, bddescricao, BDCODTIPO from ( ';

  wsql = wsql || 'select T.BDCODEMP, ';
  wsql = wsql || 'emp.BDNOMEMP, ';
  wsql = wsql || 'empresas.bdcodconfICMSSPED, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQICMSSPED, ';
  wsql = wsql || 'TCONF.bddescqICMSSPED,';
  wsql = wsql || 'TCONFICMSSPEDFORM.bddescformICMSSPED,';
  wsql = wsql || 'T.BDVALOR, ';
  wsql = wsql || 'TCONFICMSSPEDFORM.BDNUMITEM, ';
  wsql = wsql || 'TCONF.BDCLASSIFICACAO, ';
  wsql = wsql || 'T.BDCODUF, ';
  wsql = wsql || 'UF.BDSIGLAUF, ';
  wsql = wsql || 'null bdcodtipovalagre, ';
  wsql = wsql || 'null bddescricao, ';
  wsql = wsql || 'TCONF.BDCODTIPO ';


  wsql = wsql || 'from VW_VEF_EMP_TICMSSPEDGERUNION T';


  wsql = wsql||' left outer join VW_VEF_BASE_TEMPPARFED empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join vw_tempresas_ref emp on (emp.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join TUF UF on (UF.bdcodUF = t.bdcodUF ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFICMSSPEDQ TCONF on (TCONF.bdcodqICMSSPED = t.bdcodqICMSSPED ) ' ;

  wsql = wsql||' left outer join VEF_BASE_TCONFICMSSPEDFORM TCONFICMSSPEDFORM on (TCONFICMSSPEDFORM.bdcodconfICMSSPED = empresas.bdcodconfICMSSPED  and TCONFICMSSPEDFORM.bdcodqICMSSPED = T.BDCODQICMSSPED  and TCONFICMSSPEDFORM.bdnumcampoICMSSPED = T.BDNUMCAMPO) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;


  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQICMSSPED = '||:prcodquadro;

    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'('||:prcodperiodo||')';
    END

  IF( (:pruf IS NOT NULL) AND (:pruf <> 0)) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||' T.BDCODUF = '||:prUF;
    END
  ELSE
    BEGIN
      IF (:prgeral = 2) THEN--por estado
        BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||' T.BDCODUF is not null ';
        END
    END

  /* Configura??o 89 e 90 - E310 ? por estado */
  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';
  ELSE
     wwhere = wwhere||' where ';
  wwhere = wWhere||' (((TCONF.BDCODTIPO <> 89) or ((TCONF.BDCODTIPO = 89) and (T.BDCODUF is not null))) and '||
                   '  ((TCONF.BDCODTIPO <> 90) or ((TCONF.BDCODTIPO = 90) and (T.BDCODUF is not null))))  ';


  IF (((:pruf IS NOT NULL) AND (:pruf <> 0)) OR (:prgeral = 2)) THEN
     BEGIN
       --sol:10913 - se tiver UF ent?o nesse momento n?o deve levar os valores agregados
       WVALAGRE = '';
     END
  ELSE
     BEGIN
  --sol:10913 - juntar os valores agregados
  WVALAGRE = ' union all ';
  WVALAGRE = WVALAGRE || ' select t.BDCODEMP, emp.BDNOMEMP, empresas.bdcodconfICMSSPED, t.bdreflan, 999 BDCODPERIODO, t.bdcodcid BDNUMCAMPO, ';
  WVALAGRE = WVALAGRE || ' q.bdcodqicmssped, q.bddescqICMSSPED, cid.bdnomcid bddescformICMSSPED, SUM(t.bdvalor) bdvalor, 1 BDNUMITEM, q.bdclassificacao, ';
  WVALAGRE = WVALAGRE || ' null BDCODUF, null BDSIGLAUF, va.bdcodtipovalagre, va.bddescricao, q.BDCODTIPO from VEF_EMP_TMOVVALAGRE1400 t ';
  WVALAGRE = WVALAGRE || ' left outer join VW_VEF_BASE_TEMPPARFED empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  WVALAGRE = WVALAGRE || ' left outer join vw_tempresas_ref emp on (emp.bdcodemp = t.bdcodemp ) ';
  WVALAGRE = WVALAGRE || ' left outer join vef_base_tconficmsspedq q on (q.bdcodqicmssped = 4) ';
  WVALAGRE = WVALAGRE || ' left outer join tcidade cid on (cid.bdcodcid = t.bdcodcid) ';
  WVALAGRE = WVALAGRE || ' left outer join VEF_BASE_TTABTIPOVALAGRE va on (va.bdcodtipovalagre = t.bdcodtipovalagre) ';
  --WVALAGRE = WVALAGRE || ' where u.bdcodemp = '+wEmpTreeView+' and u.BDREFLAN >= '+wRefTreeView+' and u.BDREFLAN <= '+wRefTreeView;

  IF (:PRCODEMP IS NOT NULL) THEN
     WVALAGRE = WVALAGRE || ' where ' || :PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (WVALAGRE <> '') THEN
          WVALAGRE = WVALAGRE || ' and ';
       ELSE
          WVALAGRE = WVALAGRE || ' where ';

       WVALAGRE = WVALAGRE || 't.BDREFLAN >= ' || :pranomesinicial;

       IF (WVALAGRE <> '') THEN
          WVALAGRE = WVALAGRE || ' and ';

       WVALAGRE = WVALAGRE || 't.BDREFLAN <= ' || :pranomesfinal;
     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (WVALAGRE <> '') THEN
          WVALAGRE = WVALAGRE||' and ';
       ELSE
          WVALAGRE = WVALAGRE||' where ';

       WVALAGRE = WVALAGRE||'q.BDCODQICMSSPED = '||:prcodquadro;
    END

    WVALAGRE = WVALAGRE || 'group by T.BDCODEMP, EMP.BDNOMEMP, EMPRESAS.BDCODCONFICMSSPED, T.BDREFLAN, BDCODPERIODO, BDNUMCAMPO, Q.BDCODQICMSSPED, ';
    WVALAGRE = WVALAGRE || 'Q.BDDESCQICMSSPED, BDDESCFORMICMSSPED, BDNUMITEM, Q.BDCLASSIFICACAO, BDCODUF, BDSIGLAUF, va.bdcodtipovalagre, va.bddescricao, q.BDCODTIPO ';

    END

  WVALAGRE = WVALAGRE || ')';

--  if (:prgeral = 2) then--por estado
--    begin
--      wsql = wsql || ' group by'
      wsql = wsql || wwhere || WVALAGRE || ' order by bdcodemp, bdreferencia desc, bdCODPERIODO,BDCODQICMSSPED, bdcoduf, bdcodtipovalagre, bdnumcampo';
--    end
--  else
---    wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia ,bdCODPERIODO, BDCODQICMSSPED, bdnumcampo' ;


  wREFANT         = 0;
  prquadroant     = 0;
  wufANT          = 0;
  wTIPOVA         = 0;


  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR,
    BDNUMITEM,
    BDCLASSIFICACAO,
    bdcoduf,
    BDSIGLAUF,
    bdcodtipovalagre,
    bddescricao,
    BDCODTIPO
  DO
  BEGIN
    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    wvalor = bdvalor;

    --Refer?ncia
    IF ((prGeral = 1) AND (wREFANT <> bdreferencia) AND (pranomesinicial <> pranomesfinal)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        --wREFANT = bdreferencia;
        SUSPEND;
      END

    --Quadro
    IF (/*(prGeral = 1) AND *Precisa levar a descri??o do quadro nas apura??es por UF tamb?m* */
        (prquadroant <> bdcodquadro)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        --prquadroant = bdcodquadro;
        SUSPEND;
        --estado                   --acho que pode deixar aparecendo o estado
        IF ((bdcoduf IS NOT NULL)/* and (pruf = 0)*/)THEN
          BEGIN
            BDDESCFORM =  bdsiglauf;
            SUSPEND;
          END

        --tipo valor agregado
        IF ((bdcodtipovalagre IS NOT NULL))THEN
          BEGIN
            BDDESCFORM =  bdcodtipovalagre || ' - ' || bddescricao;
            SUSPEND;
          END
      END

    --estado
    IF (((prGeral = 2) OR (BDCODTIPO = 89) OR (BDCODTIPO = 90)) AND (wufant <> bdcoduf) AND (prquadroant = bdcodquadro)) THEN /* AQUI */
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  bdsiglauf;
        BDVALOR = NULL;
        SUSPEND;
      END

    --tipo valor agregado
    IF ((prGeral = 1) AND (wtipova <> bdcodtipovalagre) AND (prquadroant = bdcodquadro)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM = bdcodtipovalagre || ' - ' || bddescricao;
        BDVALOR = NULL;
        SUSPEND;
      END

/*
    --Per?odo
    if (((prcodperiodoant <> bdcodperiodo) or ((prquadroant <> bdcodquadro) and (prcodperiodoant = bdcodperiodo))) and (bdCodperiodo in (2,3,4,5,6))) then
      begin
        bdnumcampo = null;
        if (bdcodperiodo = 2) then
           BDDESCFORM =  '1? dec?ndio';
        else
        if (bdcodperiodo = 3) then
           BDDESCFORM =  '2? dec?ndo';
        else
        if (bdcodperiodo = 4) then
           BDDESCFORM =  '3? dec?ndio';
        else
        if (bdcodperiodo = 5) then
           BDDESCFORM =  '1? quinzena';
        else
        if (bdcodperiodo = 6) then
           BDDESCFORM =  '2? quinzena';

        BDVALOR = null;
        --prcodperiodoant = bdcodperiodo;
        suspend;
      end            */

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = wvalor;

    wREFANT = bdreferencia;
    prquadroant = bdcodquadro;

    wufANT  = bdcoduf;
    wTIPOVA = bdcodtipovalagre;

    SUSPEND;

  END

END
^

/* Alter (SP_VEF_TREEVIEW_CONS_IMPOSTOS) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IMPOSTOS(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRSIGLAIMPOSTO VARCHAR(10))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,8),
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDCLASSIFICACAO VARCHAR(10))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE WQUADROANT INTEGER;
DECLARE VARIABLE WNUMCAMPO INTEGER;
DECLARE VARIABLE WDESCFORM VARCHAR(60);
DECLARE VARIABLE WVALOR NUMERIC(15,8);
DECLARE VARIABLE WCODPERIODOANT INTEGER;
DECLARE VARIABLE WCAMPOQUADRO VARCHAR(20);
DECLARE VARIABLE WCAMPODESCQ VARCHAR(20);
DECLARE VARIABLE WCAMPOCONF VARCHAR(20);
DECLARE VARIABLE WCAMPONUMCAMPO VARCHAR(20);
DECLARE VARIABLE WCAMPODESCF VARCHAR(20);
BEGIN
  /* Procedure Text */

  /* SP Padrao para montar a treeview dos impostos que sao iguais... ex IRLP, COFINS, PIS */

  wCampoQuadro   = 'BDCODQ'||prSiglaImposto||' ';
  wCampoDescQ    = 'BDDESCQ'||prSiglaImposto||' ';
  wCampoConf     = 'BDCODCONF'||prSiglaImposto||' ';
  wCampoNumCampo = 'BDNUMCAMPO'||prSiglaImposto||' ';
  wCampoDescF    = 'BDDESCFORM'||prSiglaImposto||'';

  IF (prSiglaImposto = 'BLOCOM') THEN -- Alt.: 14060 - Campos das tabelas do Bloco M
    BEGIN
      wCampoQuadro   = 'BDCODQUADRO ';
      wCampoDescQ    = 'BDDESCQUADRO ';
      wCampoConf     = 'BDCODCONF ';
      wCampoNumCampo = 'BDNUMCAMPO ';
      wCampoDescF    = 'BDDESCFORM ';
    END

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA (prAnoMesInicial, NULL, NULL);

  wSQL = 'select t.BDCODEMP, ';
  wSQL = wSQL || 'emp.BDNOMEMP, ';
  wSQL = wSQL || 'emp.BDCODCONF'||prSiglaImposto||', ';
  wSQL = wSQL || 't.BDREFERENCIA, ';
  wSQL = wSQL || 't.BDCODPERIODO, ';
  wSQL = wSQL || 'tconf'||prSiglaImposto||'form.BDNUMITEM as BDNUMCAMPO, ';--alt:# 7636 n?o estava ordenando o campo certo
  wSQL = wSQL || 't.'||wCampoQuadro||', ';
  wSQL = wSQL || 'tconf.'||wCampoDescq||',';
  wSQL = wSQL || 'tconf'||prSiglaImposto||'form.'||wCampoDescF||',';
  wSQL = wSQL || 't.BDVALOR ';
  wSQL = wSQL || 'BDQBH, ';
  wSQL = wSQL || 'tconf.BDCLASSIFICACAO ';
  wSQL = wSQL || 'from VEF_EMP_T'||prSiglaImposto||'GERREG t';

  wSQL = wSQL || ' left outer join VW_EMP_REF_TOTAL emp on (emp.BDCODEMP = t.BDCODEMP) ' ;
  wSQL = wSQL || ' left outer join VEF_BASE_TCONF'||prSiglaImposto||'Q tconf on (tconf.'||wCampoQuadro||' = t.'||wCampoQuadro||') ' ;
  wSQL = wSQL || ' left outer join VEF_BASE_TCONF'||prSiglaImposto||'FORM tconf'||prSiglaImposto||'form on (tconf'||prSiglaImposto||'form.'||wCampoConf||' = emp.BDCODCONF'||prSiglaImposto||' and ' ;
  wSQL = wSQL || '                 tconf'||prSiglaImposto||'form.'||wCampoQuadro||' = t.'||wCampoQuadro||' and tconf'||prSiglaImposto||'form.'||wCampoNumCampo||' = t.BDNUMCAMPO) ' ;

  wWhere = '';

  IF (:prCodEmp IS NOT NULL) THEN
     wWhere = ' where '||:prCodEmp;

  IF (:prAnoMesInicial IS NOT NULL) THEN
     BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
       ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'t.BDREFERENCIA >= '||:prAnoMesInicial;

      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';

      wWhere = wWhere||'t.BDREFERENCIA <= '||:prAnoMesFinal;
     END

  IF (:prCodQuadro IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
       ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'t.'||wCampoQuadro||' = '||:prCodQuadro;
    END

  IF (:prCodPeriodo IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
         wWhere = wWhere||' and ';
       ELSE
         wWhere = wWhere||' where ';

      wWhere = wWhere||'('||:prCodPeriodo||')';
    END

  wSQL = wSQL||wWhere || ' order by BDCODEMP, BDREFERENCIA desc, ' ||wCampoQuadro||', BDCODPERIODO, BDNUMITEM ';

  wRefAnt        = 0;
  wQuadroant     = 0;
  wCodPeriodoAnt = 0;

  FOR EXECUTE STATEMENT wSQL
  INTO
    BDCODEMP,
    BDNOMEMP,
    BDCODCONF,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    BDCODQUADRO,
    BDDESCQUADRO,
    BDDESCFORM,
    BDVALOR,
    BDCLASSIFICACAO
  DO
  BEGIN
    BDANOMESFINAL   = prAnoMesFinal;
    BDANOMESINICIAL = prAnoMesInicial;
    wNumCampo       = BDNUMCAMPO;
    wDescForm       = BDDESCFORM;
    wValor          = BDVALOR;

    --Refer?ncia
    IF ((prGeral = 1) AND (wRefAnt <> BDREFERENCIA) AND (prAnoMesInicial <> prAnoMesFinal)) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        BDDESCFORM =  CAST(BDREFERENCIA AS VARCHAR(6));
        BDDESCFORM =  SUBSTRING(BDDESCFORM FROM 5 FOR 2)||'/'||SUBSTRING(BDDESCFORM FROM 1 FOR 4);
        BDVALOR = NULL;
        --wRefAnt  = BDREFERENCIA;
        SUSPEND;
      END

    --Quadro
    IF ((prGeral = 1) AND (wQuadroAnt <> BDCODQUADRO)) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        --wQuadroAnt = BDCODQUADRO;
        SUSPEND;
      END

    --Per?odo
    IF (((wCodPeriodoAnt <> BDCODPERIODO) OR ((wQuadroAnt <> BDCODQUADRO) AND (wCodPeriodoAnt = BDCODPERIODO))) AND (BDCODPERIODO IN (2,3,4,5,6))) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        IF (BDCODPERIODO = 2) THEN
           BDDESCFORM =  '1? dec?ndio';
        ELSE
        IF (BDCODPERIODO = 3) THEN
           BDDESCFORM =  '2? dec?ndo';
        ELSE
        IF (BDCODPERIODO = 4) THEN
           BDDESCFORM =  '3? dec?ndio';
        ELSE
        IF (BDCODPERIODO = 5) THEN
           BDDESCFORM =  '1? quinzena';
        ELSE
        IF (BDCODPERIODO = 6) THEN
           BDDESCFORM =  '2? quinzena';
        ELSE
        BDVALOR = NULL;
        --wCodPeriodoAnt = bdcodperiodo;
        SUSPEND;
      END

    BDNUMCAMPO = wNumCampo;
    BDDESCFORM = wDescForm;
    BDVALOR    = wValor;

    wRefAnt    = BDREFERENCIA;
    wQuadroAnt = BDCODQUADRO;
    wCodPeriodoAnt = BDCODPERIODO;

    SUSPEND;

  END

END
^

/* Alter (SP_VEF_TREEVIEW_CONS_IPI) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,6);
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);
  
    wSql = 'select TIPIGERREG.BDCODEMP, ';
    wSql = wSql ||'temp.BDNOMEMP, ';
    wSql = wSql ||'temp.BDCODCONFIPI, ';
    wSql = wSql ||'TIPIGERREG.BDREFERENCIA, ';
    wSql = wSql ||'TIPIGERREG.BDCODPERIODO, ';
    wSql = wSql ||'TIPIGERREG.BDNUMCAMPO, ';
    wSql = wSql ||'TIPIGERREG.BDCODQIPI, ';
    wSql = wSql ||'TCONFIPIQ.bddescqipi, ';
    wSql = wSql ||'TCONFIPIFORM.bddescformipi, ';
    wSql = wSql ||'TIPIGERREG.BDVALOR ';
    wSql = wSql ||'from VEF_EMP_TIPIGERREG TIPIGERREG ';

    wSql = wsql||'left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', TIPIGERREG.bdcodemp, null) temp on (temp.bdcodemp = TIPIGERREG.bdcodemp ) ' ;
    wSql = wsql||'left outer join VEF_BASE_TCONFIPIQ TCONFIPIQ on (TCONFIPIQ.bdcodqipi = TIPIGERREG.bdcodqipi ) ' ;
    wSql = wsql||'left outer join VEF_BASE_TCONFIPIFORM TCONFIPIFORM on (TCONFIPIFORM.bdcodconfipi = temp.bdcodconfipi and TCONFIPIFORM.bdcodqipi = TIPIGERREG.BDCODQIPI  and TCONFIPIFORM.bdnumcampoipi = TIPIGERREG.BDNUMCAMPO) ' ;

    wwhere = '';
  
    IF (:PRCODEMP IS NOT NULL) THEN
       wwhere = ' where '||:PRCODEMP;

    IF (:pranomesinicial IS NOT NULL) THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         ELSE
            wwhere = wwhere||' where ';
  
         wwhere = wwhere||'TIPIGERREG.BDREFERENCIA >= '||:pranomesinicial;
  
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
  
         wwhere = wwhere||'TIPIGERREG.BDREFERENCIA <= '||:pranomesfinal;
       END

    IF (:prcodquadro IS NOT NULL) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         ELSE
            wwhere = wwhere||' where ';
  
         wwhere = wwhere||'TIPIGERREG.BDCODQIPI = '||:prcodquadro;
      END


    wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, bdnumcampo' ;
  
    prrefant = 0;
  
    FOR EXECUTE STATEMENT wsql
    INTO
      bdcodemp,
      bdnomemp,
      bdcodconf,
      bdreferencia,
      bdcodperiodo,
      bdnumcampo,
      bdcodquadro,
      bddescquadro,
      bddescform,
      bdvalor
    DO
    BEGIN
      prnumcampo = bdnumcampo;
      prdescform = bddescform;
      prvalor = bdvalor;
  
      IF ((prGeral = 1) AND (prrefant <> bdreferencia)) THEN
        BEGIN
          bdnumcampo = 0;
          bddescform = CAST(bdreferencia AS VARCHAR(6));
          bddescform = SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
          bdvalor  = 0;
          prrefant = bdreferencia;
          SUSPEND;
        END
  
      bdnumcampo = prnumcampo;
      bddescform = prdescform;
      bdvalor = prvalor;
  
      SUSPEND;
    END
  END
^

/* Alter (SP_VEF_TREEVIEW_CONS_IRLP) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IRLP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,6);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, '||
                 'empresas.BDNOMEMP, '||
                 'empresas.BDCODCONFIRLP,'||
                'T.BDREFERENCIA, '||
                'T.BDCODPERIODO, '||
                'T.BDNUMCAMPO, '||
                'T.BDCODQIRLP, '||
                'TCONFIRLPQ.bddescqirlp,'||
                'TCONFIRLPFORM.bddescformirlp,'||
                'T.BDVALOR '||
                'BDQBH '||
                'from VEF_EMP_TIRLPGERREG T';


  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFIRLPQ TCONFIRLPQ on (TCONFIRLPQ.bdcodqirlp = t.bdcodqirlp ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFIRLPFORM TCONFIRLPFORM on (TCONFIRLPFORM.bdcodconfirlp = empresas.bdcodconfirlp  and TCONFIRLPFORM.bdcodqirlp = T.BDCODQIRLP  and TCONFIRLPFORM.bdnumcampoirlp = T.BDNUMCAMPO) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;


  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQIRLP = '||:prcodquadro;

    END


  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, bdnumcampo' ;

  prrefant = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR
  DO
  BEGIN

    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;


    IF ((prGeral = 1) AND (prrefant <> bdreferencia)) THEN
      BEGIN
        bdnumcampo = 0;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = 0;
        prrefant = bdreferencia;
        SUSPEND;
      END

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = prvalor;

    SUSPEND;




  END




END
^

/* Alter (SP_VEF_TREEVIEW_CONSUF_GIASP) */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONSUF_GIASP(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRNATENTSAI INTEGER,
PRPREFIXONAT INTEGER,
PRSIGLAUF VARCHAR(2))
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDSIGLAUF VARCHAR(2),
BDPREFIXONAT INTEGER,
BDDESCRICAO VARCHAR(100),
BDVALOR NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WVLRCONTAB NUMERIC(18,6);
DECLARE VARIABLE WBASEICMS NUMERIC(18,6);
DECLARE VARIABLE WVLRICMS NUMERIC(18,6);
DECLARE VARIABLE WOUTRASICMS NUMERIC(18,6);
DECLARE VARIABLE WVLRST NUMERIC(18,6);
DECLARE VARIABLE WOUTROSIMPOSTOS NUMERIC(18,6);
DECLARE VARIABLE WNUMCAMPO INTEGER;
DECLARE VARIABLE WVLRCONTAB2 NUMERIC(18,6);
DECLARE VARIABLE WBASEICMS2 NUMERIC(18,6);
DECLARE VARIABLE WSUFIXO VARCHAR(3);
BEGIN

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA (PRREFERENCIA);

  wSQL =         'SELECT bdCODEMP, bdREFERENCIA, bdSIGLAUF, bdNUMCAMPO, bdPREFIXONAT, bdDESCRICAO, SUM(0) as bdVALOR, ';
  wSQL = wSQL ||       ' SUM(IIF(bdISENTO = '''||'FALSE'||''', bdVLRCONTAB, 0)) as bdVLRCONTAB, ';
  wSQL = wSQL ||       ' SUM(IIF(bdISENTO = '''||'FALSE'||''', bdBASEICMS, 0)) as bdBASEICMS, ';
  wSQL = wSQL ||       ' SUM(bdVLRICMS) as bdVLRICMS, SUM(bdOUTRASICMS) as bdOUTRASICMS, SUM(bdVLRST) as bdVLRST, SUM(bdOUTROSIMPOSTOS) as bdOUTROSIMPOSTOS, ';
  wSQL = wSQL ||       ' SUM(IIF(bdISENTO = '''||'TRUE'||''', bdVLRCONTAB, 0)) as bdVLRCONTAB2, ';
  wSQL = wSQL ||       ' SUM(IIF(bdISENTO = '''||'TRUE'||''', bdBASEICMS, 0)) as bdBASEICMS2 ';
  wSQL = wSQL || 'FROM ( ';

  IF (PRNATENTSAI = 2) THEN
     wSufixo = 'ENT';
  ELSE
     wSufixo = 'SAI';

  wSQL = wSQL ||        'SELECT i.bdCODEMP, mov.bdREFLAN as bdREFERENCIA, NULL as bdNUMCAMPO, NULL as bdDESCRICAO, NULL as bdVALOR, i.bdPREFIXONAT, ';
  wSQL = wSQL ||               'SUM(COALESCE(i.bdVLRCONTAB, 0)) as bdVLRCONTAB, SUM(COALESCE(i.bdBASEICMS, 0)) as bdBASEICMS, ';
  wSQL = wSQL ||               'SUM(COALESCE(i.bdVLRICMS, 0)) as bdVLRICMS, SUM(COALESCE(i.bdOUTRASICMS, 0)) as bdOUTRASICMS, ';
  wSQL = wSQL ||               'SUM(COALESCE(i.bdVLRST, 0)) as bdVLRST, SUM(COALESCE(0, 0)) as bdOUTROSIMPOSTOS, ';
  IF (wSufixo = 'ENT') THEN
    BEGIN
      wSQL = wSQL ||              'uf.bdSIGLAUF, ';
      wSQL = wSQL ||              'IIF(ter.bdIETER = ''ISENTO'', ''TRUE'', ''FALSE'') as bdISENTO ';
    END
  ELSE
  IF (wSufixo = 'SAI') THEN
    BEGIN
      wSQL = wSQL ||              'IIF(uf.bdSIGLAUF <> ''SP'', uf.bdSIGLAUF, COALESCE(ufDest.bdSIGLAUF, uf.bdSIGLAUF)) AS bdSIGLAUF, ';
      wSQL = wSQL ||              'IIF(uf.bdSIGLAUF <> ''SP'', IIF(ter.bdIETER = ''ISENTO'', ''TRUE'', ''FALSE''), ';
      wSQL = wSQL ||              '    IIF(cidDest.bdCODUF > 0, IIF(dest.bdIETER = ''ISENTO'', ''TRUE'', ''FALSE''), ';
      wSQL = wSQL ||              '        IIF(ter.bdIETER = ''ISENTO'', ''TRUE'', ''FALSE'') ) ) AS bdISENTO ';
    END
  wSQL = wSQL ||        'FROM ( ';
  wSQL = wSQL ||               'SELECT m.bdCODEMP, m.bdCHAVE, m.bdREFLAN, m.bdCODTER, m.bdCODSITNF ';
  IF (wSufixo = 'SAI') THEN
   wSQL = wSQL ||                      ', m.bdCODCID ';
  wSQL = wSQL ||               'FROM VEF_EMP_TMOV'||:wSufixo||' m ';
  wSQL = wSQL ||               'WHERE m.bdCODEMP = '||:PRCODEMP;
  wSQL = wSQL ||                 'AND m.bdREFLAN = '||:PRREFERENCIA;
  wSQL = wSQL ||               ') mov ';
  wSQL = wSQL ||        'LEFT OUTER JOIN VEF_EMP_TMOV'||:wSufixo||'ITENS i ON (mov.bdCODEMP = i.bdCODEMP AND mov.bdCHAVE = i.bdCHAVE) ';
  wSQL = wSQL ||        'LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdCODTER = mov.bdCODTER) ';
  if (wSufixo = 'ENT') then
    wSQL = wSQL ||      'LEFT OUTER JOIN TCIDADE cid ON (cid.bdCODCID = ter.bdCODCID) ';
  else
  if (wSufixo = 'SAI') then
    wSQL = wSQL ||      'LEFT OUTER JOIN TCIDADE cid ON (cid.bdCODCID = mov.bdCODCID) ';

  wSQL = wSQL ||        'LEFT OUTER JOIN TUF uf ON (uf.bdCODUF = cid.bdCODUF) ';
  if (wSufixo = 'SAI') then
    begin
      wSQL = wSQL ||    'LEFT OUTER JOIN VEF_EMP_TD160CARGATRANS d160 ON (mov.bdCODEMP = d160.bdCODEMP AND mov.bdCHAVE = d160.bdCHAVE) ';
      wSQL = wSQL ||    'LEFT OUTER JOIN VW_TTERCEIRO dest ON (dest.bdCODTER = d160.bdCODTERDESTINATARIO) ';
      wSQL = wSQL ||    'LEFT OUTER JOIN TCIDADE cidDest ON (cidDest.BDCODCID = d160.bdCODCIDDESTINATARIO) ';
      wSQL = wSQL ||    'LEFT OUTER JOIN TUF ufDest ON (ufDest.bdCODUF = cidDest.bdCODUF) ';
    end
  wSQL = wSQL ||        'WHERE (mov.bdCODSITNF NOT IN (2,3,4,5)) ';
  IF (wSufixo = 'ENT') THEN
    wSQL = wSQL ||        'AND uf.bdSIGLAUF <> ''SP'' ';
  ELSE
  IF (wSufixo = 'SAI') THEN
     wSQL = wSQL ||       'AND ((uf.bdSIGLAUF <> ''SP'') OR (ufDest.bdSIGLAUF <> ''SP'')) ';
  wSQL = wSQL ||          'AND i.bdPREFIXONAT = '||:PRPREFIXONAT;
  wSQL = wSQL ||        'GROUP BY i.bdCODEMP, mov.bdREFLAN, cid.bdCODUF, bdSIGLAUF, i.bdCODNAT, i.bdDIGOPERNAT, i.bdPREFIXONAT, bdISENTO ';
  wSQL = wSQL ||        'ORDER BY i.bdCODEMP, mov.bdREFLAN, cid.bdCODUF, i.bdCODNAT, i.bdDIGOPERNAT, i.bdPREFIXONAT ';

  wSQL = wSQL || ') aux ';
  wSQL = wSQL || 'WHERE bdSIGLAUF = '''||:PRSIGLAUF||'''';
  wSQL = wSQL || '  AND bdPREFIXONAT = '||:PRPREFIXONAT;
  wSQL = wSQL || 'group by BDCODEMP, BDREFERENCIA, BDSIGLAUF, BDNUMCAMPO, BDPREFIXONAT, BDDESCRICAO ';

  WNUMCAMPO = 0;

  FOR EXECUTE STATEMENT wSQL
  INTO
    BDCODEMP ,
    BDREFERENCIA,
    BDSIGLAUF,
    BDNUMCAMPO,
    BDPREFIXONAT,
    BDDESCRICAO,
    BDVALOR,
    wVLRCONTAB,
    wBASEICMS,
    wVLRICMS,
    --wISENTASICMS,
    wOUTRASICMS,
    wVLRST,
    --wICMSRET,
    --wIMPSUBSTITUTO,
    --wIMPSUBSTITUIDO,
    wOUTROSIMPOSTOS,
    wVLRCONTAB2,
    wBASEICMS2
  DO
  BEGIN
    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;
    /*sol:17736
    IF (PRNATENTSAI = 2) THEN
      BEGIN
        BDVALOR = wVLRCONTAB;
        BDDESCRICAO = 'Valor cont?bil de contribuinte';
        SUSPEND;
    
        WNUMCAMPO = WNUMCAMPO + 1;
        bdnumcampo = WNUMCAMPO;

        BDVALOR = wBASEICMS;
        BDDESCRICAO = 'Base de c?lculo de contribuinte';
        SUSPEND;

        WNUMCAMPO = WNUMCAMPO + 1;
        bdnumcampo = WNUMCAMPO;
    
        BDVALOR = 0;
        BDDESCRICAO = 'Valor cont?bil de n?o contribuinte';
        SUSPEND;

        WNUMCAMPO = WNUMCAMPO + 1;
        bdnumcampo = WNUMCAMPO;
    
        BDVALOR = 0;
        BDDESCRICAO = 'Base de c?lculo de n?o contribuinte';
        SUSPEND;
      END
    ELSE
      BEGIN
        BDVALOR = 0;
        BDDESCRICAO = 'Valor cont?bil de contribuinte';
        SUSPEND;
    
        WNUMCAMPO = WNUMCAMPO + 1;
        bdnumcampo = WNUMCAMPO;

        BDVALOR = 0;
        BDDESCRICAO = 'Base de c?lculo de contribuinte';
        SUSPEND;
    
        WNUMCAMPO = WNUMCAMPO + 1;
        bdnumcampo = WNUMCAMPO;

        BDVALOR = wVLRCONTAB;
        BDDESCRICAO = 'Valor cont?bil de n?o contribuinte';
        SUSPEND;

        WNUMCAMPO = WNUMCAMPO + 1;
        bdnumcampo = WNUMCAMPO;
    
        BDVALOR = wBASEICMS;
        BDDESCRICAO = 'Base de c?lculo de n?o contribuinte';
        SUSPEND;
      END*/

    BDVALOR = wVLRCONTAB;
    BDDESCRICAO = 'Valor cont?bil de contribuinte';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wBASEICMS;
    BDDESCRICAO = 'Base de c?lculo de contribuinte';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wVLRCONTAB2;
    BDDESCRICAO = 'Valor cont?bil de n?o contribuinte';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wBASEICMS2;
    BDDESCRICAO = 'Base de c?lculo de n?o contribuinte';
    SUSPEND;

    --

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wVLRICMS;
    BDDESCRICAO = 'Imposto creditado ou debitado';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wOUTRASICMS;
    BDDESCRICAO = 'Outros valores';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wVLRST;
    BDDESCRICAO = 'ICMS cobrado por substitui??o tribut?ria';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    IF (PRNATENTSAI = 2) THEN
      BEGIN
        BDVALOR = wVLRST;
        --BDVALOR = wICMSRET;
        BDDESCRICAO = 'Petr?leo energia / outros';
        SUSPEND;
      END

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wOUTROSIMPOSTOS;
    BDDESCRICAO = 'Outros produtos';
    SUSPEND;

  END

END
^

/* Alter (SP_VERIFICA_NOVO_CODIGO) */
ALTER PROCEDURE SP_VERIFICA_NOVO_CODIGO(PRCODPLAPADRAO INTEGER,
PRCODTPLA INTEGER,
PRCTALON VARCHAR(40))
 RETURNS(BDCODIGO INTEGER)
 AS
DECLARE VARIABLE WNOVACHAVE INTEGER;
DECLARE VARIABLE WCODIGO2 INTEGER;
DECLARE VARIABLE WCODIGO1 INTEGER;
BEGIN
  -- verifica se ja existe aguma conta
  SELECT bdcodtpla FROM planos_tpla
  WHERE (bdcodtpla = :prCodTpla)
  AND (bdcodplapadrao = :prCodPlaPadrao)
  INTO wCodigo1;

  IF (wCodigo1> 0) THEN
     BEGIN
       -- se existir, ent?o deve verificar se a classifica??o tamb?m ? a mesma
       -- como o sistema n?o permite inserir uma nova conta com classifi??o ja existente, ent?o o registro deve estar vindo da importa??o
       SELECT bdcodtpla FROM planos_tpla
       WHERE (bdcodtpla = :prCodTpla)
       AND (bdcodplapadrao = :prCodPlaPadrao)
       AND (bdctalon = :prCtalon)
       INTO wCodigo2;

       IF (wCodigo2 > 0) THEN
          DELETE FROM planos_tpla WHERE bdcodplapadrao = :prcodplapadrao AND bdcodtpla = :prcodtpla;
       ELSE
          BEGIN
             SELECT COALESCE((MAX(bdcodtpla)+1), 1) FROM planos_tpla WHERE bdcodplapadrao = :prcodplapadrao INTO wNovaChave;
             bdcodigo = wNovaChave;
    
             SUSPEND;
          END
    END
END
^

/* Alter (SP_VINCULAR_CST_TNCM) */
ALTER PROCEDURE SP_VINCULAR_CST_TNCM(PRSESSAO INTEGER)
 AS
BEGIN

  /*CST ICMS*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTICMS = (SELECT FIRST 1 ICMS.BDCODCSTICMS FROM VEF_BASE_TTABCSTICMS ICMS WHERE ICMS.BDCSTICMS = N.BDCSTICMS)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTICMS IS NOT NULL) AND (N.BDCSTICMS <> ''));

  /*CST IPI entrada*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTIPIENT = (SELECT FIRST 1 IPI.BDCODCSTIPI FROM VEF_BASE_TTABCSTIPI IPI WHERE IPI.BDCODEXPCSTIPI = N.BDCSTIPIENT AND IPI.BDCODCSTIPI BETWEEN 1 AND 7)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTIPIENT IS NOT NULL) AND (N.BDCSTIPIENT <> ''));

  /*CST IPI sa?da*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTIPISAI = (SELECT FIRST 1 IPI.BDCODCSTIPI FROM VEF_BASE_TTABCSTIPI IPI WHERE IPI.BDCODEXPCSTIPI = N.BDCSTIPISAI AND IPI.BDCODCSTIPI BETWEEN 8 AND 14)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTIPISAI IS NOT NULL) AND (N.BDCSTIPISAI <> ''));

  /*CST PIS entrada*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTPISENT = (SELECT FIRST 1 PIS.BDCODCSTPIS FROM VEF_BASE_TTABCSTPIS PIS WHERE PIS.BDCSTPIS = N.BDCSTPISENT AND PIS.BDCODCSTPIS BETWEEN 50 AND 99)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTPISENT IS NOT NULL) AND (N.BDCSTPISENT <> ''));

  /*CST PIS sa?da*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTPISSAI = (SELECT FIRST 1 PIS.BDCODCSTPIS FROM VEF_BASE_TTABCSTPIS PIS WHERE PIS.BDCSTPIS = N.BDCSTPISSAI AND ((PIS.BDCODCSTPIS BETWEEN 1 AND 49) OR (PIS.BDCODCSTPIS = 99)))
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTPISSAI IS NOT NULL) AND (N.BDCSTPISSAI <> ''));

  /*CST Cofins entrada*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTCOFENT = (SELECT FIRST 1 COF.BDCODCSTCOF FROM VEF_BASE_TTABCSTCOF COF WHERE COF.BDCSTCOF = N.BDCSTCOFENT AND (COF.BDCODCSTCOF BETWEEN 50 AND 99))
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTCOFENT IS NOT NULL) AND (N.BDCSTCOFENT <> ''));

  /*CST Cofins sa?da*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTCOFSAI = (SELECT FIRST 1 COF.BDCODCSTCOF FROM VEF_BASE_TTABCSTCOF COF WHERE COF.BDCSTCOF = N.BDCSTCOFSAI AND ((COF.BDCODCSTCOF BETWEEN 1 AND 49) OR (COF.BDCODCSTCOF = 99)))
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTCOFSAI IS NOT NULL) AND (N.BDCSTCOFSAI <> ''));
END
^

/* Alter (SP_VINCULAR_PRODUTO) */
ALTER PROCEDURE SP_VINCULAR_PRODUTO(PRSESSAO INTEGER,
PRID_TERMINAL INTEGER)
 AS
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WSESSAOATU INTEGER;
DECLARE VARIABLE WSQL VARCHAR(600);
BEGIN
  /*Tabelas de sa?da com produto devem ter o campo BDCODSAIDA para que a sp jogue o BDALTCODPROD(Chave do produto gerada no servidor) no lan?amento*/
  FOR SELECT TRIM(UPPER(T.RDB$RELATION_NAME)) BDTABLE
      FROM RDB$RELATION_FIELDS T
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$FIELD_NAME = 'BDALTCODPROD'
      AND EXISTS(
                 SELECT F.RDB$RELATION_NAME BDTABLE
                 FROM RDB$RELATION_FIELDS F
                 WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
                 AND (RDB$FIELD_NAME = 'BDCODSAIDA')
                 AND T.RDB$RELATION_NAME = F.RDB$RELATION_NAME
                 GROUP BY F.RDB$RELATION_NAME
                )
      INTO :wTable
  DO
    BEGIN
      wSessaoAtu = NULL;

      SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = :wTable INTO :wSessaoAtu;
      IF (:wSessaoAtu IS NOT NULL) THEN
        BEGIN
          /*Desvincula todos os produtos*/
          wSql = 'UPDATE '||:wTable||' T SET T.BDALTCODPROD = NULL, T.BDDESCPROD = NULL WHERE T.BDSESSAO = '||:wSessaoAtu;
          EXECUTE STATEMENT :wSql;
    
          /*1 - Busca os produtos na tabela TEMP, cont?m os registros que est?o sendo importados*/
          wSql = 'UPDATE '||:wTable||' T SET T.BDALTCODPROD = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = '||:PRSESSAO||' AND P.BDCODSAIDA = T.BDCODSAIDA), ';
          wSql = :wSql || 'T.BDDESCPROD = ( ';
          wSql = :wSql || '                SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '''', P.BDDESCRICAOUNICA, P.BDDESCPROD) ';
          wSql = :wSql || '                FROM TMP_TCADPRO_TEMP P ';
          wSql = :wSql || '                WHERE P.BDSESSAO = '||:PRSESSAO;
          wSql = :wSql || '                AND P.BDCODSAIDA = T.BDCODSAIDA ';
          wSql = :wSql || '               ) ';
          wSql = :wSql || 'WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || ' AND ((T.BDCODSAIDA IS NOT NULL) AND (T.BDCODSAIDA <> ''''))';
          EXECUTE STATEMENT :wSql;
    
          /*2 - Busca os produtos na tabela TMP, cont?m todos os registros de produto do banco*/
          wSql =  'UPDATE '||:wTable||' T SET T.BDALTCODPROD = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDA), ';
          wSql = :wSql || 'T.BDDESCPROD = ( ';
          wSql = :wSql || '                SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '''', P.BDDESCRICAOUNICA, P.BDDESCPROD) ';
          wSql = :wSql || '                FROM TMP_TCADPRO P ';
          wSql = :wSql || '                WHERE P.BDCODEMP = T.BDCODEMP ';
          wSql = :wSql || '                AND P.BDCODSAIDA = T.BDCODSAIDA ';
          wSql = :wSql || '               ) ';
          wSql = :wSql || 'WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || 'AND T.BDALTCODPROD IS NULL ';
          wSql = :wSql || 'AND ((T.BDCODSAIDA IS NOT NULL) AND (T.BDCODSAIDA <> ''''))';
          EXECUTE STATEMENT :wSql;
    
          /*Apenas joga o altcodprod para o bdcodprod*/
          wSql =          ' UPDATE '||:wTable||' T SET T.BDCODPROD = T.BDALTCODPROD ';
          wSql = :wSql || ' WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || ' AND T.BDALTCODPROD IS NOT NULL';
          EXECUTE STATEMENT :wSql;
        END
    END

END
^

/* Alter (SP_VRH_APAGACALCULOS) */
ALTER PROCEDURE SP_VRH_APAGACALCULOS(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCODAUT INTEGER,
PRREF INTEGER,
PRREFPAG INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     BEGIN
       /*
          FOLHA COMPLEMENTAR
        */

       wsql = 'delete from VRHF_EMP_TFOLHACOMP where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFFN = '||prref;

       IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
          wsql = wsql||' and BDREFCOMP = '||prrefpag;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA COMPLEMENTAR POR TOMADOR
        */

       wsql = 'delete from VRHF_EMP_TFOLTOMCOMP where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFTOMADOR = '||prref;

       IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
          wsql = wsql||' and BDREFCOMP = '||prrefpag;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA NORMAL
        */

       wsql = 'delete from VRHF_EMP_TFOLHANORMAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFFN = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA NORMAL POR TOMADOR
        */

       wsql = 'delete from VRHF_EMP_TFOLHATOMADOR where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFTOMADOR = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          ADIANTAMENTO SALARIAL
        */

       wsql = 'delete from VRHF_EMP_TADSAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFAD = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          F?RIAS
        */

       wsql = 'delete from VRH_EMP_TFERIAS where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and ((BDREFINIFE = '||prref||') or (BDREFFIMFE = '||prref||'))';

       EXECUTE STATEMENT wsql;


       /*
          COMPLEMENTO DE 13? SAL?RIO
        */

       wsql = 'delete from VRHF_EMP_TC13SAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFC13 = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          13? SAL?RIO
        */

       wsql = 'delete from VRHF_EMP_T13SAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREF13 = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          ADIANTAMENTO DE 13? SAL?RIO
        */

       wsql = 'delete from VRHF_EMP_TA13SAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFA13 = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA DE AUT?NOMOS
        */

       wsql = 'delete from VRHF_BASE_CALC_TERC where BDCODEMP = '||prcodemp;

       IF (prcodaut IS NOT NULL AND prcodaut <> 0) THEN
          wsql = wsql||' and BDCODTER = '||prcodaut;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFINSSSERV = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA AVULSA
        */

       wsql = 'delete from VRHF_EMP_TFOLHAAVULSA where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREF = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          C?LCULO DA PR?VIA DE RESCIS?O
        */

       wsql = 'delete from VRHF_EMP_TFOLHANORMAL_PREV_RESC where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       EXECUTE STATEMENT wsql;

       /*
          LAN?AMENTO DA PR?VIA DE RESCIS?O
        */

       wsql = 'delete from VRH_EMP_TRESCISAO_PREVIA where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       EXECUTE STATEMENT wsql;


       /*
          PLANILHA DA LAN?AMENTOS
        */

       wsql = 'delete from VRHF_EMP_TPLANLANC where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDCOMPLANC = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          PLANILHA DA LAN?AMENTOS ADIANTAMENTO SALARIAL
        */

       wsql = 'delete from VRHF_EMP_TPLANLANC_ADSAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDCOMPLANC = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          PLANILHA DA LAN?AMENTOS FOLHA AVULSA
        */

       wsql = 'delete from VRHF_EMP_TPLANLANC_FA where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDCOMPFA = '||prref;

       EXECUTE STATEMENT wsql;

     END
END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_CONVSAU_DIRF2 for: SP_VRH_CONVSAU_DIRF */
ALTER PROCEDURE SP_VRH_CONVSAU_DIRF2(PREMP VARCHAR(25000),
PRCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDREF INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODDPN INTEGER,
BDNOME /* DM_BDNOMCOL */ VARCHAR(70),
BDCPF VARCHAR(14),
BDVALORMENSALIDADE NUMERIC(18,2),
BDVALORCOPAR NUMERIC(18,2),
BDCODTIPOCONV INTEGER,
BDTIPOFAIXA INTEGER,
BDDESCRICAO VARCHAR(80),
BDCNPJ /* DM_CNPJ_CPF */ VARCHAR(18),
BDREGISTROANS INTEGER,
BDRAZAOSOCIAL VARCHAR(80),
BDPARENESCODPN INTEGER,
BDDATANASCDPN DATE)
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_VRH_CONVSAU_DIRF) */
ALTER PROCEDURE SP_VRH_CONVSAU_DIRF(PREMP INTEGER,
PRCOL INTEGER,
PRREF INTEGER,
PRPLASAUDE INTEGER = 0)
 RETURNS(BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDREF INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODDPN INTEGER,
BDNOME DM_BDNOMCOL,
BDCPF VARCHAR(14),
BDVALORMENSALIDADE NUMERIC(18,2),
BDVALORCOPAR NUMERIC(18,2),
BDCODTIPOCONV INTEGER,
BDTIPOFAIXA INTEGER,
BDDESCRICAO VARCHAR(80),
BDCNPJ DM_CNPJ_CPF,
BDREGISTROANS INTEGER,
BDRAZAOSOCIAL VARCHAR(80),
BDPARENESCODPN INTEGER,
BDDATANASCDPN DATE)
 AS
declare variable WSQL varchar(1000);
begin
  execute procedure sp_seta_competencia(prref);

  if (COALESCE(prplasaude, 0) = 0) then
     begin
       wsql = 'select first 1 BDCODPLACONVSAU from VRHF_BASE_TEMPVINC where BDCODEMP = '||premp||' and BDREFEMP <= '||prref||' order by BDREFEMP DESC';
       execute statement wsql into :prplasaude;
     end

  wsql = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||premp||' and BDCODCOL = '||prcol;
  execute statement wsql into : BDNOME;

  for SELECT x.bdcodplaconvsau,x.bdcodoperadora, x.bdcodconvenio, x.bdrefvcs ,colcon.bdcodemp, colcon.bdcodcol,
             colcon.bdcpfcol bdcpf, COALESCE(x.BDVALORMENSALIDADEFUN,0) bdvalormensalidade, x.bdvalorcoparfun bdvalorcopar, y.bdcodtipoconv, COALESCE(x.bdtipo, 0) bdtipofaixa,
             w.bddescricao, w.bdcnpj, w.bdregistroans, w.bdrazaosocial
      FROM vrh_emp_tcolcon colcon
      LEFT OUTER JOIN VW_VRHM_EMP_VAL_COL_OP_ATU x ON (x.bdcodemp = colcon.bdcodemp AND x.bdcodcol = colcon.bdcodcol)
      LEFT OUTER JOIN VRH_BASE_CONVENIO_OPERADORAS y ON (y.bdcodplaconvsau = x.bdcodplaconvsau AND y.bdcodoperadora = x.bdcodoperadora AND y.bdcodconvenio = x.bdcodconvenio)
      LEFT OUTER JOIN VRH_BASE_TCONVSAUDE w on (w.BDCODCONVENIO = X.BDCODOPERADORA)
      WHERE colcon.bdcodemp = :premp and colcon.bdcodcol = :prcol and x.bdcodplaconvsau = :prplasaude
  into
    :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDREF, :BDCODEMP, :BDCODCOL,
    :BDCPF, :BDVALORMENSALIDADE, :BDVALORCOPAR, :BDCODTIPOCONV, :BDTIPOFAIXA,
    :BDDESCRICAO, :BDCNPJ, :BDREGISTROANS, :BDRAZAOSOCIAL
  do
    begin
      BDTIPO = 0;
      BDCODDPN = NULL;
      BDPARENESCODPN = NULL;
      BDDATANASCDPN = NULL;
      suspend;
    end

  for SELECT CONV.bdcodplaconvsau,CONV.bdcodoperadora, conv.bdcodconvenio, conv.bdrefvcs, dep.bdcodemp, dep.bdcodcol, dep.bdcoddpn,
             conv.bdvalormensalidadedep, conv.bdvalorcopardep, y.bdcodtipoconv, COALESCE(conv.bdtipo, 0) bdtipofaixa,
             w.bddescricao, w.bdcnpj, w.bdregistroans, w.bdrazaosocial
      FROM vrh_emp_tdep dep
      LEFT OUTER JOIN SP_VRHM_EMP_VAL_DEP_OP_ATU(:premp, :prref, :prcol) conv ON (conv.bdcodemp = dep.bdcodemp AND conv.bdcodcol = dep.bdcodcol AND conv.bdcoddpn = dep.bdcoddpn)
      LEFT OUTER JOIN VRH_BASE_CONVENIO_OPERADORAS y ON (y.bdcodplaconvsau = conv.bdcodplaconvsau AND y.bdcodoperadora = conv.bdcodoperadora AND y.bdcodconvenio = conv.bdcodconvenio)
      LEFT OUTER JOIN VRH_BASE_TCONVSAUDE w on (w.BDCODCONVENIO = conv.BDCODOPERADORA)
      WHERE dep.bdcodemp = :premp and dep.bdcodcol = :prcol and CONV.bdcodplaconvsau = :prplasaude
  into
    :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDREF, :BDCODEMP, :BDCODCOL, :BDCODDPN,
    :BDVALORMENSALIDADE, :BDVALORCOPAR, :BDCODTIPOCONV, :BDTIPOFAIXA,
    :BDDESCRICAO, :BDCNPJ, :BDREGISTROANS, :BDRAZAOSOCIAL
  do
    begin
      BDTIPO = 1;

      wsql = 'select first 1 BDNOMEDPN, BDPARENESCODPN, BDDATANASCDPN, BDCPFDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
             ' and BDCODDPN = '||BDCODDPN||' and BDREFDPN <= '||prref||' order by BDREFDPN DESC';

      execute statement wsql into :BDNOME, :BDPARENESCODPN, :BDDATANASCDPN, :BDCPF;
      suspend;
    end        
end
^

/* Alter (SP_VRH_CONVSAU_DIRF2) */
ALTER PROCEDURE SP_VRH_CONVSAU_DIRF2(PREMP VARCHAR(25000),
PRCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDREF INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODDPN INTEGER,
BDNOME DM_BDNOMCOL,
BDCPF VARCHAR(14),
BDVALORMENSALIDADE NUMERIC(18,2),
BDVALORCOPAR NUMERIC(18,2),
BDCODTIPOCONV INTEGER,
BDTIPOFAIXA INTEGER,
BDDESCRICAO VARCHAR(80),
BDCNPJ DM_CNPJ_CPF,
BDREGISTROANS INTEGER,
BDRAZAOSOCIAL VARCHAR(80),
BDPARENESCODPN INTEGER,
BDDATANASCDPN DATE)
 AS
declare variable WSQL varchar(32700);
declare variable WSQL2 varchar(500);
begin
  wsql = 'select dep.BDCODEMP, dep.BDCODCOL from VRH_EMP_TCOLCON dep ';

  if (COALESCE(premp, '') <> '') then
     begin
       wsql = wsql||' where '||premp;

       if (COALESCE(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDCODEMP, :BDCODCOL do
    begin
      wsql2 = 'select first 1 BDCODPLACONVSAU from VRHF_BASE_TEMPVINC where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||prref||' order by BDREFEMP DESC';
      execute statement wsql2 into :BDCODPLACONVSAU;

      for select BDTIPO,BDCODOPERADORA,BDCODCONVENIO,BDREF,BDCODDPN,BDNOME,BDCPF,BDVALORMENSALIDADE,BDVALORCOPAR,BDCODTIPOCONV,BDTIPOFAIXA,
                 BDDESCRICAO,BDCNPJ,BDREGISTROANS,BDRAZAOSOCIAL,BDPARENESCODPN,BDDATANASCDPN
          from SP_VRH_CONVSAU_DIRF(:BDCODEMP, :BDCODCOL, :prref, :BDCODPLACONVSAU)
      into :BDTIPO,:BDCODOPERADORA,:BDCODCONVENIO,:BDREF,:BDCODDPN,:BDNOME,:BDCPF,:BDVALORMENSALIDADE,:BDVALORCOPAR,:BDCODTIPOCONV,:BDTIPOFAIXA,
                 :BDDESCRICAO,:BDCNPJ,:BDREGISTROANS,:BDRAZAOSOCIAL,:BDPARENESCODPN,:BDDATANASCDPN do
        suspend;
    end
end
^

/* Alter (SP_VRH_DEC_REND_7_2) */
ALTER PROCEDURE SP_VRH_DEC_REND_7_2(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODDPN INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDCPF VARCHAR(14),
BDCNPJ VARCHAR(18),
BDRAZAOSOCIAL VARCHAR(80),
BDVALOR NUMERIC(18,6))
 AS
DECLARE VARIABLE WDATA VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQL2 VARCHAR(8000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCODDPN INTEGER;
DECLARE VARIABLE WNOMDPN VARCHAR(70);
DECLARE VARIABLE WCPFDPN VARCHAR(14);
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFIRFIR INTEGER;
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WVALOR1 NUMERIC(18,6);
DECLARE VARIABLE WVALOR2 NUMERIC(18,6);
DECLARE VARIABLE WCNPJ VARCHAR(18);
DECLARE VARIABLE WRS VARCHAR(80);
DECLARE VARIABLE WVALPLANOFFIR NUMERIC(18,6);
DECLARE VARIABLE WUTILIZOUVALOR VARCHAR(5);
DECLARE VARIABLE WEXISTEVINCULO VARCHAR(5);
DECLARE VARIABLE WDESPMEDLANCVALM NUMERIC(18,6);
DECLARE VARIABLE WDESPMEDLANCVALC NUMERIC(18,6);
BEGIN
/*  wsql = 'select distinct INF.BDCODEMP, INF.BDCODCOL, INF.BDREF, INF.BDREFPAG, EMPRH.BDCODPLACONVSAU, sum(INF.BDDESPMED) BDDESPMED '||
         'from SP_VRHF_DADOS_IR_DIRF(';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||''''||prcodemp||''',';
  ELSE
     wsql = wsql||'null,';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||''''||prcodcol||''',';
  ELSE
     wsql = wsql||'null,';

  wsql = wsql||prano||'01,'||prano||'12) INF ';
  wsql = wsql||'join VW_VRHF_BASE_TEMPVINC EMPRH on (EMPRH.BDCODEMP = INF.BDCODEMP) ';

  wsql = wsql||'where (INF.BDDESPMED > 0 and INF.BDTIPO < 9000) ';
  wsql = wsql||'group by INF.BDCODEMP, INF.BDCODCOL, INF.BDREF, INF.BDREFPAG, EMPRH.BDCODPLACONVSAU ';
  wsql = wsql||'order by INF.BDREF,INF.BDCODEMP,INF.BDCODCOL '; */

  wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDREFPAG, EMPRH.BDCODPLACONVSAU, sum(FOL.BDVALVFN) BDDESPMED from ('||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVFN '||
           'from VRHF_EMP_TVERBAFN FOL '||
           'left outer join VRHF_EMP_TFOLHANORMAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFFN = FOL.BDREFFN) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
           'where SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                 '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVFT '||
           'from VRHF_EMP_TVERBATOMADOR FOL '||
           'left outer join VRHF_EMP_TFOLHATOMADOR FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFTOMADOR = FOL.BDREFTOMADOR and FN.BDORDEM = FOL.BDORDEM) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
           'where SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                 '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FN.BDREFCOMP BDREFPAG, FOL.BDVALVFC '||
           'from VRHF_EMP_TVERBAFC FOL '||
           'left outer join VRHF_EMP_TFOLHACOMP FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFFN = FOL.BDREFFN and FN.BDREFFC = FOL.BDREFFC) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
           'where FOL.BDREFCOMP between '||prano||'01 and '||prano||'12 and ((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FN.BDREFCOMP BDREFPAG, FOL.BDVALVFC '||
           'from VRHF_EMP_TVERBAFCTOMADOR FOL '||
           'left outer join VRHF_EMP_TFOLTOMCOMP FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFTOMADOR = FOL.BDREFTOMADOR and FN.BDREFFC = FOL.BDREFFC and FN.BDORDEM = FOL.BDORDEM) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
           'where FOL.BDREFCOMP between '||prano||'01 and '||prano||'12 and ((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FN.BDREFAD, FN.BDREFAD BDREFPAG, FOL.BDVALVAD '||
           'from VRHF_EMP_TVERBAAD FOL '||
           'left outer join VRHF_EMP_TADSAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDDATAAD = FOL.BDDATAAD) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
           'where FN.BDREFAD between '||prano||'01 and '||prano||'12 and ((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) BDREFFE, SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVFE '||
           'from VRHF_EMP_TVERBAFE FOL '||
           'left outer join VRH_EMP_TFERIAS FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDINIPERAQUISFE = FOL.BDINIPERAQUISFE and FN.BDCODFE = FOL.BDCODFE) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
           'where SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, SUBSTRING(CAST(FN.BDDATAPGTO13 AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTO13 AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALV13 '||
           'from VRHF_EMP_TVERBA13 FOL '||
           'left outer join VRHF_EMP_T13SAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREF13 = FOL.BDREF13) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
           'where SUBSTRING(CAST(FN.BDDATAPGTO13 AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTO13 AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFC13, SUBSTRING(CAST(FN.BDDATAPGTOC13 AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOC13 AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVC13 '||
           'from VRHF_EMP_TVERBAC13 FOL '||
           'left outer join VRHF_EMP_TC13SAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREF13 = FOL.BDREF13 and FN.BDREFC13 = FOL.BDREFC13) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
           'where SUBSTRING(CAST(FN.BDDATAPGTOC13 AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOC13 AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and ((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ') FOL '||
         'left outer join VW_VRHF_BASE_TEMPVINC EMPRH on (EMPRH.BDCODEMP = FOL.BDCODEMP) '||
         'group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDREFPAG, EMPRH.BDCODPLACONVSAU '||
         'order by FOL.BDREFFN, FOL.BDCODEMP, FOL.BDCODCOL ';

  wrefatu = 0;
  EXECUTE PROCEDURE sp_seta_competencia(CAST((:prano||'12') AS INTEGER), NULL, NULL);
  FOR EXECUTE STATEMENT wsql
  INTO
    :wcodemp,
    :wcodcol,
    :wref,
    :wrefirfir,
    :wplano,
    :wvalplanoffir
  DO
    BEGIN
      IF (wPlano IS NOT NULL) THEN
         BEGIN
           wutilizouvalor = 'FALSE';
           WEXISTEVINCULO = 'FALSE';

           wsql2 = 'select X.BDCODDPN,X.BDNOME,X.BDCPF,sum(X.BDVALORMENSALIDADE) BDVALORMENSALIDADE ,sum(X.BDVALORCOPAR) BDVALORCOPAR,X.BDCNPJ,X.BDRAZAOSOCIAL '||
                   'from SP_VRH_CONVSAU_DIRF('||wcodemp||','||wcodcol||','||wref||','||wplano||') X '||
                   'where (BDVALORMENSALIDADE) > 0 or (BDVALORCOPAR > 0) '||
                   'group by X.BDCODDPN, X.BDNOME, X.BDCPF, X.BDCNPJ, X.BDRAZAOSOCIAL ';

           IF (wrefatu <> wref) THEN
              BEGIN
                wData = SUBSTRING(''||:wref FROM 5 FOR 2)||'/01/'||SUBSTRING(''||:wref FROM 1 FOR 4);
                EXECUTE PROCEDURE sp_seta_competencia(:wref, :wData, NULL);
                wrefatu = wref;
              END
     
           FOR EXECUTE STATEMENT wsql2 INTO :wcoddpn,:wnomdpn,:wcpfdpn,:wvalor1,:wvalor2,:wcnpj,:wrs DO
             BEGIN
               bdcodemp      = wcodemp;
               bdcodcol      = wcodcol;
               bdcoddpn      = COALESCE(:wcoddpn, 0);
               bdref         = wrefirfir;
               bdnome        = wnomdpn;
               bdcpf         = COALESCE(wcpfdpn, '   .   .   -  ');
               bdcnpj        = wcnpj;
               bdrazaosocial = wrs;
               bdvalor       = COALESCE(:wvalor1, 0) + COALESCE(:wvalor2, 0);

               wexistevinculo = 'TRUE';

               /* Quando bdvalor for zero, significa que n?o tem valores de faixa et?ria dos planos de sa?de lan?ados. 
                  Se tiver valor na ficha de IR, deve levar no primeiro plano de sa?de vinculado ao funcin?rio. */
               IF (bdvalor = 0 AND wvalplanoffir > 0 AND wutilizouvalor = 'FALSE') THEN
                 BEGIN
                   bdvalor = COALESCE(wvalplanoffir, 0);
                   wutilizouvalor = 'TRUE';
                 END

               SUSPEND;
             END

           IF (WEXISTEVINCULO = 'FALSE') THEN
              BEGIN
                wsql2 = 'select first 1 X.BDCODDPN,X.BDNOME,X.BDCPF,X.BDCNPJ,X.BDRAZAOSOCIAL '||
                        ' from SP_VRH_CONVSAU_DIRF('||wcodemp||','||wcodcol||','||wref||') X ';

                FOR EXECUTE STATEMENT wsql2 INTO :wcoddpn,:wnomdpn,:wcpfdpn,:wcnpj,:wrs DO
                  BEGIN
                    bdcodemp      = wcodemp;
                    bdcodcol      = wcodcol;
                    bdcoddpn      = COALESCE(:wcoddpn, 0);
                    bdref         = wrefirfir;
                    bdnome        = wnomdpn;
                    bdcpf         = COALESCE(wcpfdpn, '   .   .   -  ');
                    bdcnpj        = wcnpj;
                    bdrazaosocial = wrs;
     
                    /* Quando bdvalor for zero, significa que n?o tem valores de faixa et?ria dos planos de sa?de lan?ados. 
                       Se tiver valor na ficha de IR, deve levar no primeiro plano de sa?de vinculado ao funcin?rio. */
                    bdvalor = COALESCE(wvalplanoffir, 0);
                    wutilizouvalor = 'TRUE';

                    SUSPEND;
                  END
              END
         END
    END

/*  wsql = 'select distinct INF.BDCODEMP,INF.BDCODCOL,INF.BDREF,INF.BDREFPAG,INF.BDDESPMED,EMPRH.BDCODPLACONVSAU '||
         'from SP_VRHF_DADOS_IR_DIRF(';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||''''||prcodemp||''',';
  ELSE
     wsql = wsql||'null,';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||''''||prcodcol||''',';
  ELSE
     wsql = wsql||'null,';

  wsql = wsql||prano||'01,'||prano||'12) INF ';
  wsql = wsql||'join VW_VRHF_BASE_TEMPVINC EMPRH on (EMPRH.BDCODEMP = INF.BDCODEMP) ';

  wsql = wsql||'where (INF.BDDESPMED > 0 and INF.BDTIPO >= 9000) ';

  wsql = wsql||'order by INF.BDREF,INF.BDCODEMP,INF.BDCODCOL ';
  */

  wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFIR, FOL.BDREFIRFIR, FOL.BDDESPMEDFIR, EMPRH.BDCODPLACONVSAU '||
         'from VRHF_EMP_TFICHAIRRF FOL '||
         'left outer join VW_VRHF_BASE_TEMPVINC EMPRH on (EMPRH.BDCODEMP = FOL.BDCODEMP) '||
         'where FOL.BDREFIRFIR between '||prano||'01 and '||prano||'12 and FOL.BDDESPMEDFIR > 0 ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         'order by FOL.BDREFFIR, FOL.BDCODEMP, FOL.BDCODCOL ';

  wrefatu = 0;
  EXECUTE PROCEDURE sp_seta_competencia(CAST((:prano||'12') AS INTEGER), NULL, NULL);
  FOR EXECUTE STATEMENT wsql
  INTO
    :wcodemp,
    :wcodcol,
    :wref,
    :wrefirfir,
    :wvalplanoffir,
    :wplano
  DO
    BEGIN
      IF (wPlano IS NOT NULL) THEN
         BEGIN
           wutilizouvalor = 'FALSE';
           WEXISTEVINCULO = 'FALSE';

           wsql2 = 'select X.BDCODDPN, X.BDNOME, X.BDCPF, X.BDVALORMENSALIDADE, X.BDVALORCOPAR, Y.BDCNPJ, Y.BDRAZAOSOCIAL '||
                   'from VW_VRHM_EMP_VAL_TOD_OP_ATU X '||
                   'join VRH_BASE_TCONVSAUDE Y on (Y.BDCODCONVENIO = X.bdcodoperadora) '||
                   'where X.BDCODEMP = '||wcodemp||' and X.BDCODPLACONVSAU = '||wplano||' and X.BDCODCOL = '||wcodcol||' and (X.BDVALORMENSALIDADE > 0 or X.BDVALORCOPAR > 0) '||
                   'and not exists (select FN.BDCODEMP, FN.BDCODCOL from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = X.BDCODEMP and FN.BDCODCOL = X.BDCODCOL and FN.BDREFFN = '||wref||') '||
                   'and not exists (select FT.BDCODEMP, FT.BDCODCOL from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = X.BDCODEMP and FT.BDCODCOL = X.BDCODCOL and FT.BDREFTOMADOR = '||wref||') '
                   ;

           IF (wrefatu <> wref) THEN
              BEGIN
                wData = SUBSTRING(''||:wref FROM 5 FOR 2)||'/01/'||SUBSTRING(''||:wref FROM 1 FOR 4);
                EXECUTE PROCEDURE sp_seta_competencia(:wref, :wData, NULL);
                wrefatu = wref;
              END

           wdespmedlancvalm = 0;
           wdespmedlancvalc = 0;
           SELECT SUM(COALESCE(BDVALORMENSALIDADE, 0)) BDVALORMENSALIDADE, SUM(COALESCE(BDVALORCOPAR, 0)) BDVALORCOPAR
           FROM VW_VRHM_EMP_VAL_TOD_OP_ATU WHERE bdcodemp = :wcodemp AND bdcodcol = :wcodcol
           GROUP BY BDCODEMP, BDCODCOL INTO wdespmedlancvalm, wdespmedlancvalc;

/*           wsql2 = 'select X.BDTIPO, X.BDCODDPN,X.BDNOME,X.BDCPF,'||wvalplanoffir||' BDVALORMENSALIDADE ,0 BDVALORCOPAR,Y.BDCNPJ,Y.BDRAZAOSOCIAL '||
                   'from VW_VRHM_EMP_VAL_TOD_OP_ATU X '||
                   'join VRH_BASE_TCONVSAUDE Y on (Y.BDCODCONVENIO = X.bdcodoperadora) '||
                   'where X.BDCODEMP = '||wcodemp||' and X.BDCODPLACONVSAU = '||wplano||' and X.BDCODCOL = '||wcodcol||' and X.BDTIPO = 0';

           IF (wrefatu <> wref) THEN
              BEGIN
                wData = SUBSTRING(''||:wref FROM 5 FOR 2)||'/01/'||SUBSTRING(''||:wref FROM 1 FOR 4);
                EXECUTE PROCEDURE sp_seta_competencia(:wref, :wData, NULL);
                wrefatu = wref;
              END                 */

           IF (wdespmedlancvalm + wdespmedlancvalc = wvalplanoffir) THEN
             BEGIN
               FOR EXECUTE STATEMENT wsql2 INTO :wcoddpn,:wnomdpn,:wcpfdpn,:wvalor1,:wvalor2,:wcnpj,:wrs DO
                 BEGIN
                   bdcodemp      = wcodemp;
                   bdcodcol      = wcodcol;
                   bdcoddpn      = COALESCE(:wcoddpn, 0);
                   bdref         = wrefirfir;
                   bdnome        = wnomdpn;
                   bdcpf         = COALESCE(wcpfdpn, '   .   .   -  ');
                   bdcnpj        = wcnpj;
                   bdrazaosocial = wrs;
                   bdvalor     = COALESCE(:wvalor1, 0) + COALESCE(:wvalor2, 0);
    
                   --wexistevinculo = 'TRUE';
    
                   /* Quando bdvalor for zero, significa que n?o tem valores de faixa et?ria dos planos de sa?de lan?ados. 
                      Se tiver valor na ficha de IR, deve levar no primeiro plano de sa?de vinculado ao funcin?rio. */
                   /*IF (bdvalor = 0 AND wutilizouvalor = 'FALSE') THEN
                     BEGIN
                       bdvalor = COALESCE(wvalplanoffir, 0);
                       wutilizouvalor = 'TRUE';
                     END*/
    
                   SUSPEND;
                 END
             END
           ELSE
             BEGIN
               wsql2 = 'select first 1 X.BDCODDPN,X.BDNOME,X.BDCPF,conv.BDCNPJ,conv.BDRAZAOSOCIAL '||
                       ' from ( '||
                       ' select cast(null as integer) BDCODDPN, colcad.bdnomcol BDNOME, doc.bdcpfcol bdcpf, vc.bdcodoperadora BDCODCONVENIO, vc.bdcodemp,vc.bdcodcol,vc.bdrefini '||
                       ' from VRH_EMP_VINC_COL_CONV vc '||
                       ' join vrh_emp_tcolcon col on (vc.bdcodemp = col.bdcodemp and vc.bdcodcol = col.bdcodcol) '||
                       ' join vrh_emp_tcolcon_doc doc on (vc.bdcodemp = doc.bdcodemp and vc.bdcodcol = doc.bdcodcol) '||
                       ' left outer join vw_vrh_emp_tcolcon_cad colcad on (colcad.bdcodemp = vc.bdcodemp and colcad.bdcodcol = vc.bdcodcol) '||
                       ' where vc.bdcodemp = '||wcodemp||' and vc.bdcodcol = '||wcodcol||' and '||
                       '       vc.bdrefini <= '||:wref||' and (vc.bdreffim >= '||:wref||' or vc.bdreffim is null or vc.bdreffim = 0)'||
                       ' union all '||
                       ' select dep.bdcoddpn, dep.bdnomedpn, dep.bdcpfdpn, dc.bdcodoperadora BDCODCONVENIO, dc.bdcodemp,dc.bdcodcol,dc.bdrefini from VRH_EMP_VINC_DEP_CONV dc '||
                       ' join vw_vrh_emp_tdep_ref dep on (dc.bdcodemp = dep.bdcodemp and dc.bdcodcol = dep.bdcodcol and dc.bdcoddpn = dep.bdcoddpn) '||
                       ' where dc.bdcodemp = '||wcodemp||' and dc.bdcodcol = '||wcodcol||' and '||
                       '       dc.bdrefini <= '||:wref||' and (dc.bdreffim >= '||:wref||' or dc.bdreffim is null or dc.bdreffim = 0) '||
                       ' ) X '||
                       ' join VRH_BASE_TCONVSAUDE conv on (conv.BDCODCONVENIO = x.BDCODCONVENIO) '||
                       'where '||
                       ' not exists (select FN.BDCODEMP, FN.BDCODCOL from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = X.BDCODEMP and FN.BDCODCOL = X.BDCODCOL and FN.BDREFFN = '||wref||') '||
                       'and not exists (select FT.BDCODEMP, FT.BDCODCOL from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = X.BDCODEMP and FT.BDCODCOL = X.BDCODCOL and FT.BDREFTOMADOR = '||wref||') '||
                       ' order by X.BDCODEMP, X.BDCODCOL, X.BDCODDPN, X.BDCODCONVENIO ';

               FOR EXECUTE STATEMENT wsql2 INTO :wcoddpn,:wnomdpn,:wcpfdpn,:wcnpj,:wrs DO
                 BEGIN
                   bdcodemp      = wcodemp;
                   bdcodcol      = wcodcol;
                   bdcoddpn      = COALESCE(:wcoddpn, 0);
                   bdref         = wrefirfir;
                   bdnome        = wnomdpn;
                   bdcpf         = COALESCE(wcpfdpn, '   .   .   -  ');
                   bdcnpj        = wcnpj;
                   bdrazaosocial = wrs;
     
                   /* Quando bdvalor for zero, significa que n?o tem valores de faixa et?ria dos planos de sa?de lan?ados.
                      Se tiver valor na ficha de IR, deve levar no primeiro plano de sa?de vinculado ao funcin?rio. */
                   bdvalor = COALESCE(wvalplanoffir, 0);
                   wutilizouvalor = 'TRUE';

                   SUSPEND;
                 END
             END
         END
    END


  EXECUTE PROCEDURE sp_seta_competencia(CAST((:prano||'12') AS INTEGER), NULL, NULL);
END
^

/* Alter (SP_VRH_DECLARACAO_RENDIMENTOS_7) */
ALTER PROCEDURE SP_VRH_DECLARACAO_RENDIMENTOS_7(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRANO INTEGER,
PREXPORTACAO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODDPN INTEGER,
BDTIPOCALCFIR INTEGER,
BDINFORMACAO VARCHAR(250),
BDVALOR NUMERIC(18,6))
 AS
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODDPN integer;
declare variable WNOMDPN varchar(70);
declare variable WCPFDPN varchar(14);
declare variable WVALDPN numeric(18,6);
declare variable WVALREND numeric(18,6);
declare variable WDESCREND varchar(200);
declare variable WCNPJ varchar(18);
declare variable WRS varchar(80);
declare variable WNRBENEF varchar(20);
declare variable WVALDPN2 numeric(18,6);
declare variable WREFPAG integer;
declare variable WRENDISENTOS numeric(18,6);
declare variable WRENDTRIB numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WTOTRENDISENTOS numeric(18,6);
declare variable WTIPOFIR integer;
declare variable WDESCRENDATU varchar(200);
declare variable WPREVPRIV numeric(18,6);
declare variable WPRIVATU numeric(18,6);
declare variable WDTNASC date;
declare variable WDTNASCS varchar(10);
declare variable WSQL2 varchar(5000);
declare variable WTOTABONO numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WCNPJEMP varchar(18);
declare variable WNOMEMP varchar(100);
BEGIN
  /*
    PENS?O ALIMENT?CIA
  */

  IF (PREXPORTACAO = 0) THEN -- Quando for exporta??o n?o precisa levar a descri??o do plano de sa?de Almir 16/02/2015
    BEGIN
      /* Rendimentos ISENTOS, RENDIMENTOS E PLR */
      wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFPAG, case when COALESCE(FOL.BDTIPO, 0) in (0, 1, 2, 100, 110) then 0 else COALESCE(FOL.BDTIPO, 0) end BDTIPO, SUM(FOL.BDRENDISENTOS), SUM(FOL.BDRENDTRIBUTAVEL), SUM(FOL.BDINSS), MAX(FOL.BDDRENDISENTOS), SUM(FOL.BDPREVPRIV), SUM(FOL.BDVALABO) '||
             'from SP_VRHF_DADOS_IR_DIRF(';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||''''||prcodemp||''',';
      ELSE
         wsql = wsql||'null,';
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         wsql = wsql||''''||prcodcol||''',';
      ELSE
         wsql = wsql||'null,';
    
      wsql = wsql ||prano||'01,'||prano||'12, 0, '''', 0, 1) FOL '||
             'where (COALESCE(FOL.BDRENDISENTOS, 0.00) <> 0) or (COALESCE(FOL.BDRENDTRIBUTAVEL, 0.00) <> 0) or (COALESCE(FOL.BDINSS, 0.00) <> 0) or (COALESCE(FOL.BDVALABO, 0.00) <> 0)  or (COALESCE(FOL.BDPREVPRIV, 0.00) <> 0) '||
             'group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFPAG, BDTIPO '||
             'order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFPAG';

      wempatu         = 0;
      wcolatu         = 0;
      wrefatu         = 0;
      wrendisentos    = 0;
      wrendtrib       = 0;
      winss           = 0;
      wtotrendisentos = 0;
      wvalrend        = 0;
      wdescrendatu    = '';
      wprivatu        = 0;
      wtotabono       = 0;

      FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wrefpag, :wtipofir, :wrendisentos, :wrendtrib, :winss, :wdescrend, :wprevpriv, :wvalabo DO
        BEGIN
          IF (wempatu = 0) THEN
             wempatu = wcodemp;
          IF (wcolatu = 0) THEN
             wcolatu = wcodcol;
          IF (wrefatu = 0) THEN
             wrefatu = wrefpag;

          IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
             BEGIN
               IF (wtotrendisentos <> 0) THEN
                  BEGIN
                    bdcodemp     = wempatu;
                    bdcodcol     = wcolatu;
                    bdinformacao = SUBSTRING('Rendimentos isentos: '||:wdescrendatu FROM 1 FOR 250);
                    bdtipocalcfir= 7;
                    bdvalor      = :wtotrendisentos;
                    bdcoddpn     = 0;
                    SUSPEND;
                  END

               IF (wvalrend > 0) THEN
                  BEGIN
                    bdcodemp     = wempatu;
                    bdcodcol     = wcolatu;
                    bdcoddpn     = 0;
                    bdinformacao = 'Os rendimentos seguintes est?o informados na linha 01, quadro 3 e/ou linha 03, quadro 05:';
                    bdtipocalcfir= 0;
                    bdvalor      = 0;
                    SUSPEND;

                    bdcodemp     = wempatu;
                    bdcodcol     = wcolatu;
                    bdcoddpn     = 0;
                    bdinformacao = ' - Rendimentos do trabalho assalariado: ';
                    bdtipocalcfir= 1;
                    bdvalor      = :wvalrend;
                    SUSPEND;
                  END

               IF (wprivatu <> 0) THEN
                  BEGIN
                    bdcodemp     = wempatu;
                    bdcodcol     = wcolatu;
                    bdcoddpn     = 0;
                    bdinformacao = 'Valor pago a t?tulo de Previd?ncia Complementar'; -- 17110 - Marcelo B. M. - 28/09/2017 - 'Privada' para 'Complementar'
                    bdtipocalcfir= 5;
                    bdvalor      = :wprivatu;
                    SUSPEND;

                    wsql2 = 'select first 1 Y.BDCNPJ, Y.BDDESCPREV from VRH_EMP_TLANCPREVCOMP X '||
                            'join VRH_BASE_TCADPREVCOMP Y on (Y.BDCODCADPREV = X.BDCODCADPREV) '||
                            'where X.BDCODEMP = '||bdcodemp||' and X.BDCODCOL = '||bdcodcol||' and X.BDREFINI <= '||wrefatu||' and ((COALESCE(X.BDREFFIN, 0) = 0) or (X.BDREFFIN >= '||wrefatu||')) '||
                               ' and COALESCE(X.BDVALMENSAL, 0) + COALESCE(X.BDVAL13SAL, 0) > 0 '||
                            'order by X.BDREFINI desc';

                    EXECUTE STATEMENT wsql2 INTO :wcnpjemp, :wnomemp;

                    IF (COALESCE(wnomemp,'') = '') THEN
                       wnomemp = 'Previd?ncia complementar';

                    bdtipocalcfir= 6;
                    bdinformacao = 'CNPJ: '||COALESCE(wcnpjemp,'')||', Entidade: '||COALESCE(wnomemp,'');

                    bdvalor = 0;
                    wcnpjemp = '';
                    wnomemp = '';

                    SUSPEND;
                  END
               -- 17110 - Marcelo B. M. - Alt:16/10/2017 - Fim

               IF (wtotabono <> 0) THEN
                  BEGIN
                    bdcodemp     = wempatu;
                    bdcodcol     = wcolatu;
                    bdcoddpn     = 0;
                    bdinformacao = 'Abono pecuni?rio';
                    bdtipocalcfir= 30;
                    bdvalor      = wtotabono;
                    SUSPEND;
                  END

               wempatu         = wcodemp;
               wcolatu         = wcodcol;
               wrefatu         = wrefpag;
               wtotrendisentos = 0;
               wvalrend        = 0;
               wdescrendatu    = '';
               wprivatu        = 0;
               wtotabono       = 0;
             END

          IF ((TRIM(COALESCE(wdescrend, '')) <> '') OR (COALESCE(wrendisentos, 0.00) <> 0)) THEN
             BEGIN
               IF (wdescrendatu <> '') THEN
                  wdescrendatu = wdescrendatu||', ';

               wdescrendatu = SUBSTRING(wdescrendatu||wdescrend FROM 1 FOR 200);
               wtotrendisentos = wtotrendisentos + COALESCE(wrendisentos, 0.00);
             END

          IF (wvalabo <> 0) THEN
             wtotabono = wtotabono + wvalabo;

          IF (COALESCE(wtipofir,0) NOT IN (9, 10, 11, 101, 111, 9002, 9012, 9099, 9100) AND wrendtrib >= 0) THEN
             BEGIN
               IF (wrendtrib > 0 AND winss < 0) THEN
                  wvalrend = wvalrend + (winss * -1);

               wvalrend = wvalrend + wrendtrib;
             END

           wprivatu = wprivatu + wprevpriv;
        end
    
     IF (wempatu <> 0 AND wcolatu <> 0) THEN
        BEGIN
          IF (wtotrendisentos <> 0) THEN
             BEGIN
               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdinformacao = SUBSTRING('Rendimentos isentos: '||:wdescrendatu FROM 1 FOR 250);
               bdtipocalcfir= 7;
               bdvalor      = :wtotrendisentos;
               bdcoddpn     = 0;
               SUSPEND;
             END

          IF (wvalrend > 0) THEN
             BEGIN
               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdcoddpn     = 0;
               bdinformacao = 'Os rendimentos seguintes est?o informados na linha 01, quadro 3 e/ou linha 03, quadro 05:';
               bdtipocalcfir= 0;
               bdvalor      = 0;
               SUSPEND;

               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdcoddpn     = 0;
               bdinformacao = ' - Rendimentos do trabalho assalariado: ';
               bdtipocalcfir= 1;
               bdvalor      = :wvalrend;
               SUSPEND;
             END

          IF (wprivatu <> 0) THEN
             BEGIN
               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdcoddpn     = 0;
               bdinformacao = 'Valor pago a t?tulo de Previd?ncia Complementar'; -- 17110 - Marcelo B. M. - 28/09/2017 - 'Privada' para 'Complementar'
               bdtipocalcfir= 5;
               bdvalor      = :wprivatu;
               SUSPEND;

               wsql2 = 'select first 1 Y.BDCNPJ, Y.BDDESCPREV from VRH_EMP_TLANCPREVCOMP X '||
                       'join VRH_BASE_TCADPREVCOMP Y on (Y.BDCODCADPREV = X.BDCODCADPREV) '||
                       'where X.BDCODEMP = '||bdcodemp||' and X.BDCODCOL = '||bdcodcol||' and X.BDREFINI <= '||wrefatu||' and ((COALESCE(X.BDREFFIN, 0) = 0) or (X.BDREFFIN >= '||wrefatu||')) '||
                             ' and COALESCE(X.BDVALMENSAL, 0) + COALESCE(X.BDVAL13SAL, 0) > 0 '||
                       'order by X.BDREFINI desc';

               EXECUTE STATEMENT wsql2 INTO :wcnpjemp, :wnomemp;

               IF (COALESCE(wnomemp,'') = '') THEN
                  wnomemp = 'Previd?ncia privada';

               bdtipocalcfir= 6;
               bdinformacao = 'CNPJ: '||COALESCE(wcnpjemp,'')||', Entidade cadastrada: '||COALESCE(wnomemp,'');

               bdvalor = 0;
               wcnpjemp = '';
               wnomemp = '';

               SUSPEND;
             END
          -- 17110 - Marcelo B. M. - Alt:16/10/2017 - Fim

          IF (wtotabono <> 0) THEN
             BEGIN
               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdcoddpn     = 0;
               bdinformacao = 'Abono pecuni?rio';
               bdtipocalcfir= 30;
               bdvalor      = wtotabono;
               SUSPEND;
        END
        END


      wsql = 'select X.BDCODEMP, X.BDCODCOL, SUM(COALESCE(X.BDRENDTRIBUTAVEL,0)) - SUM(COALESCE(X.BDINSS,0)) - SUM(COALESCE(X.BDDESPMED,0)) - SUM(COALESCE(X.BDPENJUD,0)) - '||
             'SUM(COALESCE(X.BDPENALIM,0)) - SUM(COALESCE(X.BDIR,0)) BDLIQUIDO '||
             'from SP_VRHF_DADOS_IR_FA(';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||''''||prcodemp||''',';
      ELSE
         wsql = wsql||'null,';
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         wsql = wsql||''''||prcodcol||''',';
      ELSE
         wsql = wsql||'null,';
    
      wsql = wsql||prano||'01,'||prano||'12,0,null,1,0) X ';
    
      wsql = wsql||'join VRH_BASE_TTIPOCALCAVUL FA on (FA.BDCODTCA = X.BDCODTCA and FA.BDCODCTP = 7) ';
    
      wsql = wsql||' group by X.BDCODEMP,X.BDCODCOL ';
    
      FOR EXECUTE STATEMENT wsql
      INTO
        :bdcodemp,
        :bdcodcol,
        :wvaldpn2
      DO
        BEGIN
          IF (wvaldpn2 > 0) THEN
             BEGIN
               IF (wvaldpn <= 0) THEN
               BEGIN
                 bdcoddpn     = 0;
                 bdinformacao = 'Os rendimentos seguintes est?o informados na linha 01, quadro 3 e/ou linha 03, quadro 05:';
                 bdtipocalcfir= 3;
                 bdvalor      = 0;
                 SUSPEND;
               END
    
               bdcoddpn     = 0;
               bdinformacao = ' - Participa??o nos lucros ou resultados (PLR): ';
               bdtipocalcfir= 4;
               bdvalor      = :wvaldpn2;
               SUSPEND;
            END
        END

    wsql = 'select FOL.BDCODDPN,FOL.BDCODEMP,FOL.BDCODCOL,DEP.BDNOMBENEF BDNOMEDPN,DEP.BDCPFBENEF BDCPFDPN,DEP.BDDATANASCBENEF,SUM(COALESCE(FOL.BDVALPEND, 0)) '||
       'from VWRH_PENSAO_DEP FOL '||
       'join VRH_EMP_TCOLCON_BENEF DEP on (DEP.BDCODEMP = FOL.BDCODEMP and DEP.BDCODCOL = FOL.BDCODCOL and DEP.BDCODBENEF = FOL.BDCODDPN) ';
  
    wsql = wsql||'where FOL.BDTIPO <> 1 and FOL.BDREFPAGPEND >= '||prano||'01 and FOL.BDREFPAGPEND <= '||prano||'12 ';
    
    IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
       wsql = wsql||' and '||prcodemp;
      
    IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
       wsql = wsql||' and '||prcodcol;
      
    wsql = wsql||' group by FOL.BDCODDPN,FOL.BDCODEMP,FOL.BDCODCOL,DEP.BDNOMBENEF,DEP.BDCPFBENEF,DEP.BDDATANASCBENEF ';
    wsql = wsql||'having SUM(COALESCE(FOL.BDVALPEND, 0)) <> 0 ';
    wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,DEP.BDDATANASCBENEF,DEP.BDCPFBENEF,FOL.BDCODDPN ';
  
    wempatu = 0;
    wcolatu = 0;
  
    FOR EXECUTE STATEMENT wsql INTO :wcoddpn, :wcodemp, :wcodcol, :wnomdpn, :wcpfdpn, :wdtnasc, :wvaldpn DO
      BEGIN
        bdcodemp     = :wcodemp;
        bdcodcol     = :wcodcol;
        bdcoddpn     = 0;
        bdtipocalcfir= 9;
        bdinformacao = 'Benefici?rios de pens?o aliment?cia';
        bdvalor      = 0;
        SUSPEND;
  
        bdcodemp     = :wcodemp;
        bdcodcol     = :wcodcol;
        bdcoddpn     = 0;
        bdtipocalcfir= 10;
        bdinformacao = 'CPF               Nascimento    Nome';
  --                            '999.999.999-99    99/99/9999      '
        bdvalor      = 0;
        SUSPEND;
  
        SELECT SUM(COALESCE(fir.bdpenalimfir, 0)) bdpenalimfir
        FROM VRHF_EMP_TFICHAIRRF fir
        WHERE fir.bdcodemp = :wcodemp AND fir.bdcodcol = :wcodcol AND
              fir.bdrefirfir >= :prano||'01' AND fir.bdrefirfir <= :prano||'12' AND fir.bdtipocalcfir >= 9000 AND
              NOT EXISTS (
                 SELECT fpir.bdcodemp FROM VRHF_EMP_TFIPENSAO_DEP fpir
                 WHERE fpir.bdcodemp = fir.bdcodemp AND fpir.bdcodcol = fir.bdcodcol AND fpir.bdrefpagpend = fir.bdrefirfir
              ) INTO :wvaldpn2;
      
        bdcodemp     = :wcodemp;
        bdcodcol     = :wcodcol;
        bdcoddpn     = :wcoddpn;
        bdtipocalcfir= 11;
  
        IF (wdtnasc IS NULL) THEN
           wdtnascs = '  /  /    ';
        ELSE
           wdtnascs = SUBSTRING(CAST(wdtnasc AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(wdtnasc AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdtnasc AS VARCHAR(10)) FROM 1 FOR 4);
  
        IF ((wcpfdpn IS NULL) OR (TRIM(wcpfdpn) = '.   .   -') OR (TRIM(wcpfdpn) = '')) THEN
           wcpfdpn = '              ';
  
        bdinformacao = wcpfdpn||'    '||wdtnascs||'    '||COALESCE(:wnomdpn, '');
        bdvalor      = COALESCE(wvaldpn, 0) + COALESCE(wvaldpn2, 0);
        SUSPEND;
  
      END

    wsql = 'select FOL.BDCODDPN,FOL.BDCODEMP,FOL.BDCODCOL,DEP.BDNOMBENEF BDNOMEDPN,DEP.BDCPFBENEF BDCPFDPN,DEP.BDDATANASCBENEF,SUM(COALESCE(FOL.BDVALPEND, 0)) '||
       'from VWRH_PENSAO_DEP FOL '||
       'join VRH_EMP_TCOLCON_BENEF DEP on (DEP.BDCODEMP = FOL.BDCODEMP and DEP.BDCODCOL = FOL.BDCODCOL and DEP.BDCODBENEF = FOL.BDCODDPN) ';
  
    wsql = wsql||'where FOL.BDTIPO = 1 and FOL.BDREFPAGPEND >= '||prano||'01 and FOL.BDREFPAGPEND <= '||prano||'12 ';
      
    IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
       wsql = wsql||' and '||prcodemp;
      
    IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
       wsql = wsql||' and '||prcodcol;
      
    wsql = wsql||' group by FOL.BDCODDPN,FOL.BDCODEMP,FOL.BDCODCOL,DEP.BDNOMBENEF,DEP.BDCPFBENEF,DEP.BDDATANASCBENEF ';
    wsql = wsql||' having SUM(COALESCE(FOL.BDVALPEND, 0)) <> 0 ';
    wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,DEP.BDDATANASCBENEF,DEP.BDCPFBENEF,FOL.BDCODDPN ';

    FOR EXECUTE STATEMENT wsql INTO :wcoddpn, :wcodemp, :wcodcol, :wnomdpn, :wcpfdpn, :wdtnasc, :wvaldpn DO
      BEGIN
        bdcodemp     = :wcodemp;
        bdcodcol     = :wcodcol;
        bdcoddpn     = 0;
        bdtipocalcfir= 12;
        bdinformacao = '                                (*) 13? sal?rio';
        bdvalor      = COALESCE(wvaldpn, 0);
        SUSPEND;
      END



  END

  /*
    PLANOS DE SA?DE
  */
  IF (PREXPORTACAO = 0) THEN -- Quando for exporta??o n?o precisa levar a descri??o do plano de sa?de Almir 16/02/2015
     BEGIN
       wsql = 'select X.BDCODEMP, X.BDCODCOL, X.BDCODDPN, X.BDNOME, X.BDCPF, X.BDCNPJ, X.BDRAZAOSOCIAL, SUM(X.BDVALOR) BDVALOR '||
              'from SP_VRH_DEC_REND_7_2(';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||''''||prcodemp||''',';
       ELSE
          wsql = wsql||'null,';
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||''''||prcodcol||''',';
       ELSE
          wsql = wsql||'null,';
     
       wsql = wsql||prano||') X ';
       wsql = wsql||'group by X.BDCODEMP,X.BDCODCOL,X.BDCODDPN,X.BDNOME,X.BDCPF,X.BDCNPJ,X.BDRAZAOSOCIAL ';
     
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodemp,
         :bdcodcol,
         :bdcoddpn,
         :wnomdpn,
         :wcpfdpn,
         :wcnpj,
         :wrs, 
         :wvaldpn
       DO
         BEGIN
           IF (bdcoddpn = 0) THEN
              bdinformacao = 'Sa?de: CNPJ: '||TRIM(:wcnpj)||', '||TRIM(:wrs)||', CPF: '||:wcpfdpn||', Benefici?rio: '||TRIM(:wnomdpn);
           ELSE
              bdinformacao = 'Sa?de: CNPJ: '||TRIM(:wcnpj)||', '||TRIM(:wrs)||', CPF: '||:wcpfdpn||', Dependente: '||TRIM(:wnomdpn);
           bdtipocalcfir= 14;
           bdvalor      = :wvaldpn;
           SUSPEND;
         END
     END

  /*

    Lan?amentos anuais para DIRF.

   */

  wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL, FOL.BDPREVPRIVFANO, SUBSTRING(FOL.BDQUADRO3L3 FROM 1 FOR 250) from VRH_EMP_TCOLCON_ANO FOL where FOL.BDANOFUNC = '||prano;
  wsql = wsql||' and FOL.BDPREVPRIVFANO <> 0 ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdvalor, :bdinformacao DO
    BEGIN
      bdcoddpn = 0;
      bdtipocalcfir = 15;
      SUSPEND;
    END

  wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL, FOL.BDOUT13FANO, SUBSTRING(FOL.BDQUADRO5L3 FROM 1 FOR 250) from VRH_EMP_TCOLCON_ANO FOL where FOL.BDANOFUNC = '||prano;
  wsql = wsql||' and FOL.BDOUT13FANO <> 0 ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdvalor, :bdinformacao DO
    BEGIN
      bdcoddpn = 0;
      bdtipocalcfir = 16;
      SUSPEND;
    END

  /*

   Lan?amentos anuais para pens?o da DIRF.

   */

  wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDCODBENEF, FOL.BDVALDIRF, BEN.BDNOMBENEF, BEN.BDCPFBENEF from VRH_EMP_TVALBENEF_DIRF FOL '||
         'join VRH_EMP_TCOLCON_BENEF BEN on (BEN.BDCODEMP = FOL.BDCODEMP and BEN.BDCODCOL = FOL.BDCODCOL and BEN.BDCODBENEF = FOL.BDCODBENEF) '||
         'where FOL.BDANODIRF = '||prano;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wcoddpn, :wvaldpn, :wnomdpn, :wcpfdpn DO
    BEGIN
      bdcodemp = wcodemp;
      bdcodcol = wcodcol;
      bdcoddpn = wcoddpn;
      bdtipocalcfir = 17;
      bdinformacao = 'Pens?o aliment?cia: '||COALESCE(:wnomdpn, '')||', CPF: '||COALESCE(:wcpfdpn, '   .   .   -  ');
      bdvalor      = wvaldpn;
      SUSPEND;
    END

  /*
    Afastamentos com benef?cios
  */

  wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, COALESCE(S.BDNBENEFICIOSIT, '' '') from VRH_EMP_TCOLCON FOL '||
         'join VRH_EMP_TSITCOL S on (S.BDCODEMP = FOL.BDCODEMP and S.BDCODCOL = FOL.BDCODCOL) '||
         'where ((S.BDDATAINISEFIP between '||'''01/01/'||prano||''' and '||'''12/31/'||prano||''') or (s.BDDATAFIMSIT between '||'''01/01/'||prano||''' and '||'''12/31/'||prano||''')) and '||
         ' (coalesce(S.BDNBENEFICIOSIT, ''0'') <> ''0'') and (trim(S.BDNBENEFICIOSIT) <> '''')';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wnrbenef DO
    BEGIN
      bdcodemp = :wcodemp;
      bdcodcol = :wcodcol;
      bdinformacao = 'N?mero do benef?cio: '||:wnrbenef;
      bdvalor = 0;
      bdtipocalcfir = 18;
      SUSPEND;
    END
END
^

/* Alter (SP_VRH_EMP_GERENCIAL_PORFUNCAO) */
ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORFUNCAO(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRDATAATUAL DATE,
PRAGRUPADOR SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMECC DM_BDNOMEMP,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDTEMPO01 INTEGER,
BDTEMPO02 INTEGER,
BDTEMPO03 INTEGER,
BDTEMPO04 INTEGER,
BDTEMPO05 INTEGER,
BDTEMPO06 INTEGER,
BDTEMPO07 INTEGER,
BDTEMPO08 INTEGER,
BDTEMPO09 INTEGER,
BDTEMPO10 INTEGER,
BDTEMPO11 INTEGER,
BDTOTAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQL2 VARCHAR(1000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WDTCOL DATE;
DECLARE VARIABLE WDTCOLANTES DATE;
DECLARE VARIABLE WCODPLAFUC INTEGER;
DECLARE VARIABLE WCODTFUC INTEGER;
DECLARE VARIABLE WDTADM DATE;
DECLARE VARIABLE WDTRESC DATE;
DECLARE VARIABLE WTP INTEGER;
DECLARE VARIABLE WTP01 INTEGER;
DECLARE VARIABLE WTP02 INTEGER;
DECLARE VARIABLE WTP03 INTEGER;
DECLARE VARIABLE WTP04 INTEGER;
DECLARE VARIABLE WTP05 INTEGER;
DECLARE VARIABLE WTP06 INTEGER;
DECLARE VARIABLE WTP07 INTEGER;
DECLARE VARIABLE WTP08 INTEGER;
DECLARE VARIABLE WTP09 INTEGER;
DECLARE VARIABLE WTP10 INTEGER;
DECLARE VARIABLE WTP11 INTEGER;
BEGIN
  /*
    Essa procedure retorna os colaboradores ATIVOS (a partir e/ou at? a data prDataAtual), separados por fun??o/cargo
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos

    Para essa procedure funcionar corretamente deve ser executado o SetaCompentencia do ObjectDAO com a compet?ncia atual.
  */

  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, COL.BDCODCOL, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COL.BDDATACOL, COL.BDCODPLAFUC, COL.BDCODTFUC, COL2.BDDATAADMCOL, RESC.BDDATARESCISAO '||
             'from VW_VRH_EMP_TCOL_VINCDIA COL '||
             'join VRH_EMP_TCOLCON COL2 on (COL2.BDCODEMP = COL.BDCODEMP and COL2.BDCODCOL = COL.BDCODCOL) '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
                '( '||
                  'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                  'from VRHF_EMP_TPREPFN CC '||
                  'where CC.BDDATAENTRADA <= '''||prdataatual||''' '||
                  'group by CC.BDCODEMP, CC.BDCODCOL '||
                ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) '||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) '||
             'where COL2.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, COL.BDCODCOL, null BDCODCENTRO, null BDCODTPCC, COL.BDDATACOL, COL.BDCODPLAFUC, COL.BDCODTFUC, COL2.BDDATAADMCOL, RESC.BDDATARESCISAO '||
             'from VW_VRH_EMP_TCOL_VINCDIA COL '||
             'join VRH_EMP_TCOLCON COL2 on (COL2.BDCODEMP = COL.BDCODEMP and COL2.BDCODCOL = COL.BDCODCOL) '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL2.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP ';
    END

  wempatu = -1;
  wcentroatu = -1;
  wcodtpccatu = -1;

  wtp01 = 0;
  wtp02 = 0;
  wtp03 = 0;
  wtp04 = 0;
  wtp05 = 0;
  wtp06 = 0;
  wtp07 = 0;
  wtp08 = 0;
  wtp09 = 0;
  wtp10 = 0;
  wtp11 = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcol, :wcodcentro, :wcodtpcc, :wdtcol, :wcodplafuc, :wcodtfuc, :wdtadm, :wdtresc DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcentroatu = -1) THEN
        wcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (COALESCE(wcentroatu,-1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          BDCODEMP = wempatu;
          bdcodcentro = wcentroatu;
          bdcodtpcc = wcodtpccatu;
          bdnomecc = wnomeccatu;
          bdtempo01 = wtp01;
          bdtempo02 = wtp02;
          bdtempo03 = wtp03;
          bdtempo04 = wtp04;
          bdtempo05 = wtp05;
          bdtempo06 = wtp06;
          bdtempo07 = wtp07;
          bdtempo08 = wtp08;
          bdtempo09 = wtp09;
          bdtempo10 = wtp10;
          bdtempo11 = wtp11;
          bdtotal   = wtp01 + wtp02 + wtp03 + wtp04 + wtp05 + wtp06 + wtp07 + wtp08 + wtp09 + wtp10 + wtp11;
          SUSPEND;

          wtp01 = 0;
          wtp02 = 0;
          wtp03 = 0;
          wtp04 = 0;
          wtp05 = 0;
          wtp06 = 0;
          wtp07 = 0;
          wtp08 = 0;
          wtp09 = 0;
          wtp10 = 0;
          wtp11 = 0;

          wempatu = wcodemp;
          wcentroatu = wcodcentro;
          wcodtpccatu = wcodtpcc;
        END

      -- Verifica a ?ltima altera??o de cargo
      wsql2 =
            'select MAX(COLV.BDDATACOL) BDDATACOL '||
            'from vrh_emp_tcol_vincdia COLV '||
            'where COLV.BDCODEMP = '||wcodemp||' and COLV.BDCODCOL = '||wcodcol||' and COLV.BDDATACOL < '''||wdtcol||''' and ((COALESCE(COLV.BDCODTFUC,0) <> '||COALESCE(wcodtfuc,0)||') or (COALESCE(COLV.BDCODPLAFUC,0) <> '||COALESCE(wcodplafuc,0)||')) ';

      wdtcolantes = NULL;
      EXECUTE STATEMENT wsql2 INTO :wdtcolantes;

      IF ((wdtcolantes IS NULL) OR (wdtcolantes < wdtadm)) THEN
        wdtcolantes = wdtadm;

      IF (wdtresc IS NOT NULL AND prdataatual > wdtresc) THEN
        wtp = ROUND((wdtresc - wdtcolantes) / 365.24);
      ELSE
        wtp = ROUND((prdataatual - wdtcolantes) / 365.24);

      IF (wtp <= 2) THEN
        wtp01 = wtp01 + 1;
      ELSE
      IF (wtp <= 5) THEN
        wtp02 = wtp02 + 1;
      ELSE
      IF (wtp <= 8) THEN
        wtp03 = wtp03 + 1;
      ELSE
      IF (wtp <= 11) THEN
        wtp04 = wtp04 + 1;
      ELSE
      IF (wtp <= 14) THEN
        wtp05 = wtp05 + 1;
      ELSE
      IF (wtp <= 17) THEN
        wtp06 = wtp06 + 1;
      ELSE
      IF (wtp <= 20) THEN
        wtp07 = wtp07 + 1;
      ELSE
      IF (wtp <= 23) THEN
        wtp08 = wtp08 + 1;
      ELSE
      IF (wtp <= 26) THEN
        wtp09 = wtp09 + 1;
      ELSE
      IF (wtp <= 29) THEN
        wtp10 = wtp10 + 1;
      ELSE
        wtp11 = wtp11 + 1;

      wnomeccatu = wnomecc;
    END

  IF (wempatu <> -1) THEN
    BEGIN
      BDCODEMP = wempatu;
      bdcodcentro = wcentroatu;
      bdcodtpcc = wcodtpccatu;
      bdnomecc = wnomeccatu;
      bdtempo01 = wtp01;
      bdtempo02 = wtp02;
      bdtempo03 = wtp03;
      bdtempo04 = wtp04;
      bdtempo05 = wtp05;
      bdtempo06 = wtp06;
      bdtempo07 = wtp07;
      bdtempo08 = wtp08;
      bdtempo09 = wtp09;
      bdtempo10 = wtp10;
      bdtempo11 = wtp11;
      bdtotal   = wtp01 + wtp02 + wtp03 + wtp04 + wtp05 + wtp06 + wtp07 + wtp08 + wtp09 + wtp10 + wtp11;
      SUSPEND;
    END
END
^

/* Alter (SP_VRH_EMP_GERENCIAL_PORIDADE) */
ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORIDADE(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRDATAATUAL DATE,
PRAGRUPADOR SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMECC DM_BDNOMEMP,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDIDADE01 INTEGER,
BDIDADE02 INTEGER,
BDIDADE03 INTEGER,
BDIDADE04 INTEGER,
BDIDADE05 INTEGER,
BDIDADE06 INTEGER,
BDIDADE07 INTEGER,
BDIDADE08 INTEGER,
BDIDADE09 INTEGER,
BDIDADE10 INTEGER,
BDIDADE11 INTEGER,
BDTOTAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WDATANASC DATE;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WID01 INTEGER;
DECLARE VARIABLE WID02 INTEGER;
DECLARE VARIABLE WID03 INTEGER;
DECLARE VARIABLE WID04 INTEGER;
DECLARE VARIABLE WID05 INTEGER;
DECLARE VARIABLE WID06 INTEGER;
DECLARE VARIABLE WID07 INTEGER;
DECLARE VARIABLE WID08 INTEGER;
DECLARE VARIABLE WID09 INTEGER;
DECLARE VARIABLE WID10 INTEGER;
DECLARE VARIABLE WID11 INTEGER;
DECLARE VARIABLE WID INTEGER;
DECLARE VARIABLE WDTRESC DATE;
BEGIN
  /*
    Essa procedure retorna os colaboradores ATIVOS (a partir e/ou at? a data prDataAtual), separados por idade
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos
  */


  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COL.BDDATANASCCOL, RESC.BDDATARESCISAO '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
               '( '||
                 'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                 'from VRHF_EMP_TPREPFN CC '||
                 'where CC.BDDATAENTRADA <= '''||prdataatual||''' '||
                 'group by CC.BDCODEMP, CC.BDCODCOL '||
               ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, null BDCODCENTRO, null BDCODTPCC, COL.BDDATANASCCOL, RESC.BDDATARESCISAO '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP ';
    END

  wempatu = -1;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wid01 = 0;
  wid02 = 0;
  wid03 = 0;
  wid04 = 0;
  wid05 = 0;
  wid06 = 0;
  wid07 = 0;
  wid08 = 0;
  wid09 = 0;
  wid10 = 0;
  wid11 = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcentro, :wcodtpcc, :wdatanasc, :wdtresc DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcodcentroatu = -1) THEN
        wcodcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (COALESCE(wcodcentroatu, -1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          bdcodemp = wempatu;
          bdnomecc = wnomeccatu;
          bdcodcentro = wcodcentroatu;
          bdcodtpcc   = wcodtpccatu;

          bdidade01 = wid01;
          bdidade02 = wid02;
          bdidade03 = wid03;
          bdidade04 = wid04;
          bdidade05 = wid05;
          bdidade06 = wid06;
          bdidade07 = wid07;
          bdidade08 = wid08;
          bdidade09 = wid09;
          bdidade10 = wid10;
          bdidade11 = wid11;
          bdtotal   = wid01 + wid02 + wid03 + wid04 + wid05 + wid06 + wid07 + wid08 + wid09 + wid10 + wid11;
          SUSPEND;

          wempatu = wcodemp;
          wcodcentroatu = wcodcentro;
          wcodtpccatu   = wcodtpcc;
          wid01 = 0;
          wid02 = 0;
          wid03 = 0;
          wid04 = 0;
          wid05 = 0;
          wid06 = 0;
          wid07 = 0;
          wid08 = 0;
          wid09 = 0;
          wid10 = 0;
          wid11 = 0;
        END

      IF (wdatanasc IS NOT NULL) THEN
        BEGIN
          IF (wdtresc IS NOT NULL AND prdataatual > wdtresc) THEN
            wid = ROUND((wdtresc - wdatanasc) / 365.24);
          ELSE
            wid = ROUND((prdataatual - wdatanasc) / 365.24);

          IF (wid >= 14) THEN
            BEGIN
              IF (wid <= 18) THEN
                wid01 = wid01 + 1;
              ELSE
              IF (wid <= 23) THEN
                wid02 = wid02 + 1;
              ELSE
              IF (wid <= 28) THEN
                wid03 = wid03 + 1;
              ELSE
              IF (wid <= 33) THEN
                wid04 = wid04 + 1;
              ELSE
              IF (wid <= 38) THEN
                wid05 = wid05 + 1;
              ELSE
              IF (wid <= 43) THEN
                wid06 = wid06 + 1;
              ELSE
              IF (wid <= 48) THEN
                wid07 = wid07 + 1;
              ELSE
              IF (wid <= 53) THEN
                wid08 = wid08 + 1;
              ELSE
              IF (wid <= 58) THEN
                wid09 = wid09 + 1;
              ELSE
              IF (wid <= 63) THEN
                wid10 = wid10 + 1;
              ELSE
                wid11 = wid11 + 1;
            END
        END

      wnomeccatu = wnomecc;
    END


  IF (wempatu <> -1) THEN
    BEGIN
      bdcodemp    = wempatu;
      bdnomecc = wnomeccatu;
      bdcodcentro = wcodcentroatu;
      bdcodtpcc   = wcodtpccatu;

      bdidade01 = wid01;
      bdidade02 = wid02;
      bdidade03 = wid03;
      bdidade04 = wid04;
      bdidade05 = wid05;
      bdidade06 = wid06;
      bdidade07 = wid07;
      bdidade08 = wid08;
      bdidade09 = wid09;
      bdidade10 = wid10;
      bdidade11 = wid11;
      bdtotal   = wid01 + wid02 + wid03 + wid04 + wid05 + wid06 + wid07 + wid08 + wid09 + wid10 + wid11;
      SUSPEND;
    END
END
^

/* Alter (SP_VRH_EMP_GERENCIAL_PORINST) */
ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORINST(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRDATAATUAL DATE,
PRGRAUINST SMALLINT = 0,
PRAGRUPADOR SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMECC DM_BDNOMEMP,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDINST01 INTEGER,
BDINST02 INTEGER,
BDINST03 INTEGER,
BDINST04 INTEGER,
BDINST05 INTEGER,
BDINST06 INTEGER,
BDINST07 INTEGER,
BDINST08 INTEGER,
BDINST09 INTEGER,
BDINST10 INTEGER,
BDINST11 INTEGER,
BDINST12 INTEGER,
BDINST13 INTEGER,
BDTOTAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WGRAU INTEGER;
DECLARE VARIABLE WINST01 INTEGER;
DECLARE VARIABLE WINST02 INTEGER;
DECLARE VARIABLE WINST03 INTEGER;
DECLARE VARIABLE WINST04 INTEGER;
DECLARE VARIABLE WINST05 INTEGER;
DECLARE VARIABLE WINST06 INTEGER;
DECLARE VARIABLE WINST07 INTEGER;
DECLARE VARIABLE WINST08 INTEGER;
DECLARE VARIABLE WINST09 INTEGER;
DECLARE VARIABLE WINST10 INTEGER;
DECLARE VARIABLE WINST11 INTEGER;
DECLARE VARIABLE WINST12 INTEGER;
DECLARE VARIABLE WINST13 INTEGER;
BEGIN
  /*
    Essa procedure retorna os colaboradores ATIVOS (a partir e/ou at? a data prDataAtual), separados por grau de instru?ao
    prGrauInst: 0 = Todos; 1 = 1? Grau; 2 = 2? Grau; 3 = 3? Grau
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos
  */


  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COALESCE(COL.BDGRAUINSTCOL,0) '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
               '( '||
                 'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                 'from VRHF_EMP_TPREPFN CC '||
                 'where CC.BDDATAENTRADA <= '''||prdataatual||''' '||
                 'group by CC.BDCODEMP, CC.BDCODCOL '||
               ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prgrauinst = 1) THEN  -- Filtro somente colaboradores com o primeiro grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (0,1,2,3,4) ';
      ELSE
      IF (prgrauinst = 2) THEN  -- Filtro somente colaboradores com o segundo grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (5,6) ';
      ELSE
      IF (prgrauinst = 3) THEN  -- Filtro somente colaboradores com o terceiro grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (7,8,9,10,11,12) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, null BDCODCENTRO, null BDCODTPCC, COL.BDGRAUINSTCOL '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prgrauinst = 1) THEN  -- Filtro somente colaboradores com o primeiro grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (0,1,2,3,4) ';
      ELSE
      IF (prgrauinst = 2) THEN  -- Filtro somente colaboradores com o segundo grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (5,6) ';
      ELSE
      IF (prgrauinst = 3) THEN  -- Filtro somente colaboradores com o terceiro grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (7,8,9,10,11,12) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP ';
    END

  wempatu = -1;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wINST01 = 0;
  wINST02 = 0;
  wINST03 = 0;
  wINST04 = 0;
  wINST05 = 0;
  wINST06 = 0;
  wINST07 = 0;
  wINST08 = 0;
  wINST09 = 0;
  wINST10 = 0;
  wINST11 = 0;
  wINST12 = 0;
  wINST13 = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcentro, :wcodtpcc, :wgrau DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcodcentroatu = -1) THEN
        wcodcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (COALESCE(wcodcentroatu, -1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          bdcodemp = wempatu;
          bdnomecc = wnomeccatu;
          bdcodcentro = wcodcentroatu;
          bdcodtpcc   = wcodtpccatu;

          BDINST01 = wINST01;
          BDINST02 = wINST02;
          BDINST03 = wINST03;
          BDINST04 = wINST04;
          BDINST05 = wINST05;
          BDINST06 = wINST06;
          BDINST07 = wINST07;
          BDINST08 = wINST08;
          BDINST09 = wINST09;
          BDINST10 = wINST10;
          BDINST11 = wINST11;
          BDINST12 = wINST12;
          BDINST13 = wINST13;
          bdtotal   = wINST01 + wINST02 + wINST03 + wINST04 + wINST05 + wINST06 + wINST07 + wINST08 + wINST09 + wINST10 + wINST11 + wINST12 + wINST13;
          SUSPEND;

          wempatu = wcodemp;
          wcodcentroatu = wcodcentro;
          wcodtpccatu   = wcodtpcc;
          wINST01 = 0;
          wINST02 = 0;
          wINST03 = 0;
          wINST04 = 0;
          wINST05 = 0;
          wINST06 = 0;
          wINST07 = 0;
          wINST08 = 0;
          wINST09 = 0;
          wINST10 = 0;
          wINST11 = 0;
          wINST12 = 0;
          wINST13 = 0;
        END

      IF (wGRAU = 1) THEN
        wINST02 = wINST02 + 1;
      ELSE
      IF (wGRAU = 2) THEN
        wINST03 = wINST03 + 1;
      ELSE
      IF (wGRAU = 3) THEN
        wINST04 = wINST04 + 1;
      ELSE
      IF (wGRAU = 4) THEN
        wINST05 = wINST05 + 1;
      ELSE
      IF (wGRAU = 5) THEN
        wINST06 = wINST06 + 1;
      ELSE
      IF (wGRAU = 6) THEN
        wINST07 = wINST07 + 1;
      ELSE
      IF (wGRAU = 7) THEN
        wINST08 = wINST08 + 1;
      ELSE
      IF (wGRAU = 8) THEN
        wINST09 = wINST09 + 1;
      ELSE
      IF (wGRAU = 9) THEN
        wINST10 = wINST10 + 1;
      ELSE
      IF (wGRAU = 10) THEN
        wINST11 = wINST11 + 1;
      ELSE
      IF (wGRAU = 11) THEN
        wINST12 = wINST12 + 1;
      ELSE
      IF (wGRAU = 12) THEN
        wINST13 = wINST13 + 1;
      ELSE
        wINST01 = wINST01 + 1;

      wnomeccatu = wnomecc;
    END


  IF (wempatu <> -1) THEN
    BEGIN
      bdcodemp    = wempatu;
      bdnomecc = wnomeccatu;
      bdcodcentro = wcodcentroatu;
      bdcodtpcc   = wcodtpccatu;

      BDINST01 = wINST01;
      BDINST02 = wINST02;
      BDINST03 = wINST03;
      BDINST04 = wINST04;
      BDINST05 = wINST05;
      BDINST06 = wINST06;
      BDINST07 = wINST07;
      BDINST08 = wINST08;
      BDINST09 = wINST09;
      BDINST10 = wINST10;
      BDINST11 = wINST11;
      BDINST12 = wINST12;
      BDINST13 = wINST13;
      bdtotal   = wINST01 + wINST02 + wINST03 + wINST04 + wINST05 + wINST06 + wINST07 + wINST08 + wINST09 + wINST10 + wINST11 + wINST12 + wINST13;
      SUSPEND;
    END
END
^

/* Alter (SP_VRH_EMP_GERENCIAL_PORRESC) */
ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORRESC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPADOR SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMECC DM_BDNOMEMP,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREFRESCISAO INTEGER,
BDINIEMP INTEGER,
BDINICOL INTEGER,
BDTOTALSAIDAS INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WREFRESC INTEGER;
DECLARE VARIABLE WREFRESCANT INTEGER;
DECLARE VARIABLE WINIC INTEGER;
DECLARE VARIABLE WINIEMP INTEGER;
DECLARE VARIABLE WINICOL INTEGER;
BEGIN
  /*
    Essa procedure retorna os colaboradores DEMITIDO dentro do per?odo prrefini e prreffim
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos
  */


  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COL.BDREFRESCISAO, COALESCE(PRES.BDINIPRES,0) '||
             'from VRH_EMP_TRESCISAO COL '||
             'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = COL.BDCODPRES) '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
               '( '||
                 'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                 'from VRHF_EMP_TPREPFN CC '||
                 'group by CC.BDCODEMP, CC.BDCODCOL '||
               ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) ';

      wsql = wsql||
             'where COL.BDREFRESCISAO >= '||prrefini||' and COL.BDREFRESCISAO <= '||prreffim||' ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, COL.BDREFRESCISAO, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, null BDCODCENTRO, null BDCODTPCC, COL.BDREFRESCISAO, COALESCE(PRES.BDINIPRES,0) '||
             'from VRH_EMP_TRESCISAO COL '||
             'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = COL.BDCODPRES) '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) ';

      wsql = wsql||
             'where COL.BDREFRESCISAO >= '||prrefini||' and COL.BDREFRESCISAO <= '||prreffim||' ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, COL.BDREFRESCISAO ';
    END

  wempatu = -1;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wrefrescant = -1;
  winiemp = 0;
  winicol = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcentro, :wcodtpcc, :wrefresc, :winic DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcodcentroatu = -1) THEN
        wcodcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF (wrefrescant = -1) THEN
        wrefrescant = wrefresc;

      IF ((wempatu <> wcodemp) OR (wrefrescant <> wrefresc) OR (COALESCE(wcodcentroatu, -1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          bdcodemp = wempatu;
          bdnomecc = wnomeccatu;
          bdcodcentro = wcodcentroatu;
          bdcodtpcc   = wcodtpccatu;
          bdrefrescisao = wrefrescant;

          bdinicol = winicol;
          bdiniemp = winiemp;
          bdtotalsaidas = winicol + winiemp;
          SUSPEND;

          wempatu = wcodemp;
          wcodcentroatu = wcodcentro;
          wcodtpccatu   = wcodtpcc;
          wrefrescant = wrefresc;
          winicol = 0;
          winiemp = 0;
        END

      IF (winic = 0) THEN
        winicol = winicol + 1;
      ELSE
        winiemp = winiemp + 1;

      wnomeccatu = wnomecc;
    END


  IF (wempatu <> -1) THEN
    BEGIN
      bdcodemp    = wempatu;
      bdnomecc = wnomeccatu;
      bdcodcentro = wcodcentroatu;
      bdcodtpcc   = wcodtpccatu;
      bdrefrescisao = wrefrescant;
      bdinicol = winicol;
      bdiniemp = winiemp;
      bdtotalsaidas = winicol + winiemp;
      SUSPEND;
    END
END
^

/* Alter (SP_VRH_EMP_GERENCIAL_PORTEMPO) */
ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORTEMPO(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRDATAATUAL DATE,
PRAGRUPADOR SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMECC DM_BDNOMEMP,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDTEMPO01 INTEGER,
BDTEMPO02 INTEGER,
BDTEMPO03 INTEGER,
BDTEMPO04 INTEGER,
BDTEMPO05 INTEGER,
BDTEMPO06 INTEGER,
BDTEMPO07 INTEGER,
BDTEMPO08 INTEGER,
BDTEMPO09 INTEGER,
BDTEMPO10 INTEGER,
BDTEMPO11 INTEGER,
BDTOTAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WDATAADM DATE;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WTP01 INTEGER;
DECLARE VARIABLE WTP02 INTEGER;
DECLARE VARIABLE WTP03 INTEGER;
DECLARE VARIABLE WTP04 INTEGER;
DECLARE VARIABLE WTP05 INTEGER;
DECLARE VARIABLE WTP06 INTEGER;
DECLARE VARIABLE WTP07 INTEGER;
DECLARE VARIABLE WTP08 INTEGER;
DECLARE VARIABLE WTP09 INTEGER;
DECLARE VARIABLE WTP10 INTEGER;
DECLARE VARIABLE WTP11 INTEGER;
DECLARE VARIABLE WTP INTEGER;
DECLARE VARIABLE WDTRESC DATE;
BEGIN
  /*
    Essa procedure retorna os colaboradores ATIVOS (a partir e/ou at? a data prDataAtual), separados por tempo de servi?o
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos
  */


  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COL.BDDATAADMCOL, RESC.BDDATARESCISAO '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
               '( '||
                 'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                 'from VRHF_EMP_TPREPFN CC '||
                 'where CC.BDDATAENTRADA <= '''||prdataatual||''' '||
                 'group by CC.BDCODEMP, CC.BDCODCOL '||
               ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, null BDCODCENTRO, null BDCODTPCC, COL.BDDATAADMCOL, RESC.BDDATARESCISAO '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP ';
    END

  wempatu = -1;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wtp01 = 0;
  wtp02 = 0;
  wtp03 = 0;
  wtp04 = 0;
  wtp05 = 0;
  wtp06 = 0;
  wtp07 = 0;
  wtp08 = 0;
  wtp09 = 0;
  wtp10 = 0;
  wtp11 = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcentro, :wcodtpcc, :wdataadm, :wdtresc DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcodcentroatu = -1) THEN
        wcodcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (COALESCE(wcodcentroatu, -1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          bdcodemp = wempatu;
          bdnomecc = wnomeccatu;
          bdcodcentro = wcodcentroatu;
          bdcodtpcc   = wcodtpccatu;

          bdTEMPO01 = wtp01;
          bdTEMPO02 = wtp02;
          bdTEMPO03 = wtp03;
          bdTEMPO04 = wtp04;
          bdTEMPO05 = wtp05;
          bdTEMPO06 = wtp06;
          bdTEMPO07 = wtp07;
          bdTEMPO08 = wtp08;
          bdTEMPO09 = wtp09;
          bdTEMPO10 = wtp10;
          bdTEMPO11 = wtp11;
          bdtotal   = wtp01 + wtp02 + wtp03 + wtp04 + wtp05 + wtp06 + wtp07 + wtp08 + wtp09 + wtp10 + wtp11;
          SUSPEND;

          wempatu = wcodemp;
          wcodcentroatu = wcodcentro;
          wcodtpccatu   = wcodtpcc;
          wtp01 = 0;
          wtp02 = 0;
          wtp03 = 0;
          wtp04 = 0;
          wtp05 = 0;
          wtp06 = 0;
          wtp07 = 0;
          wtp08 = 0;
          wtp09 = 0;
          wtp10 = 0;
          wtp11 = 0;
        END

      IF (wdataadm IS NOT NULL) THEN
        BEGIN
          IF (wdtresc IS NOT NULL AND prdataatual > wdtresc) THEN
            wtp = ROUND((wdtresc - wdataadm) / 365.24);
          ELSE
            wtp = ROUND((prdataatual - wdataadm) / 365.24);

          IF (wtp <= 2) THEN
            wtp01 = wtp01 + 1;
          ELSE
          IF (wtp <= 5) THEN
            wtp02 = wtp02 + 1;
          ELSE
          IF (wtp <= 8) THEN
            wtp03 = wtp03 + 1;
          ELSE
          IF (wtp <= 11) THEN
            wtp04 = wtp04 + 1;
          ELSE
          IF (wtp <= 14) THEN
            wtp05 = wtp05 + 1;
          ELSE
          IF (wtp <= 17) THEN
            wtp06 = wtp06 + 1;
          ELSE
          IF (wtp <= 20) THEN
            wtp07 = wtp07 + 1;
          ELSE
          IF (wtp <= 23) THEN
            wtp08 = wtp08 + 1;
          ELSE
          IF (wtp <= 26) THEN
            wtp09 = wtp09 + 1;
          ELSE
          IF (wtp <= 29) THEN
            wtp10 = wtp10 + 1;
          ELSE
            wtp11 = wtp11 + 1;
        END

      wnomeccatu = wnomecc;
    END


  IF (wempatu <> -1) THEN
    BEGIN
      bdcodemp    = wempatu;
      bdnomecc = wnomeccatu;
      bdcodcentro = wcodcentroatu;
      bdcodtpcc   = wcodtpccatu;

      bdTEMPO01 = wtp01;
      bdTEMPO02 = wtp02;
      bdTEMPO03 = wtp03;
      bdTEMPO04 = wtp04;
      bdTEMPO05 = wtp05;
      bdTEMPO06 = wtp06;
      bdTEMPO07 = wtp07;
      bdTEMPO08 = wtp08;
      bdTEMPO09 = wtp09;
      bdTEMPO10 = wtp10;
      bdTEMPO11 = wtp11;
      bdtotal   = wtp01 + wtp02 + wtp03 + wtp04 + wtp05 + wtp06 + wtp07 + wtp08 + wtp09 + wtp10 + wtp11;
      SUSPEND;
    END
END
^

/* Alter (SP_VRH_EMP_MULTVINC_PGTO) */
ALTER PROCEDURE SP_VRH_EMP_MULTVINC_PGTO(PREMPRESA VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6))
 AS
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WREF VARCHAR(6);
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  /* Procedure Text */
--  suspend;
  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  wano = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wMes = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);

  IF (wmes = 1) THEN
     BEGIN
       wano = wano - 1;
       wmes = 12;
     END
  ELSE
     BEGIN
       wmes = wmes - 1;
     END

  wref = ''||wano;

  IF (wmes < 10) THEN
     wref = wref||'0'||wmes;
  ELSE
     wref = wref||wmes;

  prref = CAST(wref AS INTEGER);

  -- carrega dados do m?s atual para empresas com pagamento no m?s
  wsql = 'select v.bdcodemp, v.bdcodcol, v.bdrefcol, v.bdbaseinssncol, v.bdvalorinssncol, v.bdbaseirrfncol, '||
                 ' v.bdvalorirrfncol, v.bdbaseinss13col, v.bdvalorinss13col, v.bdbaseirrf13col, '||
                 ' v.bdvalorirrf13col from VW_VRHF_EMP_TCOLCON_MVINC v '||
         ' left outer join vw_vrhf_base_tempcalc emp on (emp.bdcodemp = v.bdcodemp) '||
         ' join VW_VRH_EMP_TCOLCON_VINC colv on (colv.bdcodemp = v.bdcodemp and colv.bdcodcol = v.bdcodcol)'||
         ' join vrh_base_tclasse cla on (cla.bdcodcla = colv.bdcodcla)'||
         ' where ((cla.bdgrupocla <> 2 and coalesce(emp.BDPAGEMP,0) = 1) or (cla.bdgrupocla = 2 and coalesce(emp.BDPAGEMPCONTR,0) = 1))';

  IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
     BEGIN
       wsql = wsql||' and '||prempresa;

       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
          wsql = wsql||' and '||prcol;
     END

  FOR EXECUTE STATEMENT wsql INTO
    bdcodemp,
    bdcodcol,
    bdrefcol,
    bdbaseinssncol,
    bdvalorinssncol,
    bdbaseirrfncol,
    bdvalorirrfncol,
    bdbaseinss13col,
    bdvalorinss13col,
    bdbaseirrf13col,
    bdvalorirrf13col
  DO
   BEGIN
     SUSPEND;
   END

  -- Carrega dados do m?s anterior para empresas com pagamento no m?s seguinte
  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);
  wsql = 'select v.bdcodemp, v.bdcodcol, v.bdrefcol, v.bdbaseinssncol, v.bdvalorinssncol, v.bdbaseirrfncol, '||
                 ' v.bdvalorirrfncol, v.bdbaseinss13col, v.bdvalorinss13col, v.bdbaseirrf13col, '||
                 ' v.bdvalorirrf13col from VW_VRHF_EMP_TCOLCON_MVINC v '||
         ' left outer join vw_vrhf_base_tempcalc emp on (emp.bdcodemp = v.bdcodemp) '||
         ' join VW_VRH_EMP_TCOLCON_VINC colv on (colv.bdcodemp = v.bdcodemp and colv.bdcodcol = v.bdcodcol)'||
         ' join vrh_base_tclasse cla on (cla.bdcodcla = colv.bdcodcla)'||
         ' where ((cla.bdgrupocla <> 2 and coalesce(emp.BDPAGEMP,0) = 0) or (cla.bdgrupocla = 2 and coalesce(emp.BDPAGEMPCONTR,0) = 0))';

  IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
     BEGIN
       wsql = wsql||' and '||prempresa;

       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
          wsql = wsql||' and '||prcol;
     END

  FOR EXECUTE STATEMENT wsql INTO
    bdcodemp,
    bdcodcol,
    bdrefcol,
    bdbaseinssncol,
    bdvalorinssncol,
    bdbaseirrfncol,
    bdvalorirrfncol,
    bdbaseinss13col,
    bdvalorinss13col,
    bdbaseirrf13col,
    bdvalorirrf13col
  DO
   BEGIN
     SUSPEND;
   END
END
^

/* Alter (SP_VRH_FECHAMENTO) */
ALTER PROCEDURE SP_VRH_FECHAMENTO(PREMPRESAS VARCHAR(32000),
PRREF INTEGER = 0,
PRTIPOPER INTEGER = 1)
 RETURNS(BDCODEMP INTEGER,
BDFECHAMENTO INTEGER,
BDDATA DATE)
 AS
declare variable WSQL varchar(32000);
declare variable WDATAINI date;
declare variable WDATFIM date;
declare variable WDIAINI integer;
declare variable WMESINI smallint;
declare variable WANOINI integer;
declare variable WDIAFIM integer;
declare variable WMESFIM smallint;
declare variable WANOFIM integer;
BEGIN
  /* Procedure Text */
  IF ((prref IS NULL) OR (prref = 0))  THEN
     SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database INTO prref;

  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  wSql = 'select bdcodemp,BDFECHAMESEMP from VW_VRHF_BASE_TEMPCALC';

  IF ((prempresas IS NOT NULL) AND (prempresas <> ''))  THEN
     wSql = wSql||' where '||prempresas;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdfechamento DO
    BEGIN
      IF ((bdfechamento >= 28) OR (bdfechamento IS NULL) OR (bdfechamento <= 1) OR (PRTIPOPER = 0)) THEN
         BEGIN
           wdiaini = 1;
           wmesini = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
           wmesfim = wmesini;
           wanoini = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
           wanofim =  wanoini;
           SELECT ULTDIA FROM ultimo_dia_mes(:wmesfim,:wanofim) INTO wdiafim;
         END
      ELSE
         BEGIN
           wdiaini = bdfechamento + 1;
           wdiafim = bdfechamento;
           wmesfim = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
           wanofim = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

           IF (wmesfim = 1) THEN
              BEGIN
                wmesini = 12;
                wanoini = wanofim - 1;
              END
           ELSE
              BEGIN
                 wmesini = wmesfim - 1;
                 wanoini = wanofim;
              END
         END

      wdataini = CAST(''||wmesini||'-'||wdiaini||'-'||wanoini AS DATE);
      wdatfim = CAST(''||wmesfim||'-'||wdiafim||'-'||wanofim AS DATE);

      WHILE (wdataini <= wdatfim) DO
        BEGIN
          bddata = wdataini;
          wdataini = wdataini + 1;

          SUSPEND;
        END
    END
END
^

/* Alter (SP_VRH_RELATORIOABSENTISMO) */
ALTER PROCEDURE SP_VRH_RELATORIOABSENTISMO(PREMP VARCHAR(22000),
PRCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSITCOL INTEGER,
PRFILTROCLA VARCHAR(5000) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREF INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDNOMCOL DM_BDNOMCOL,
BDNOMCOLUPPER DM_BDNOMCOL,
BDNOMTPCC DM_BDNOMEMP,
BDHORASTRABDIA NUMERIC(18,6),
BDDIASTRAB INTEGER,
BDHORASFALTASMES NUMERIC(18,6),
BDHORASTRABMES NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(28000);
DECLARE VARIABLE WSQLAUX VARCHAR(10000);
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WDATAADM DATE;
DECLARE VARIABLE WDIASTRAB INTEGER;
DECLARE VARIABLE WREFRESC INTEGER;
DECLARE VARIABLE WDATARESC DATE;
DECLARE VARIABLE WDATAINI DATE;
DECLARE VARIABLE WDATAFIM DATE;
DECLARE VARIABLE WVAL NUMERIC(18,6);
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOREF INTEGER;
DECLARE VARIABLE WCONVREFEMP DM_BOOLEAN;
DECLARE VARIABLE WTOTFALTAS NUMERIC(18,6);
DECLARE VARIABLE WINTVAL INTEGER;
DECLARE VARIABLE WSQLVER VARCHAR(1500);
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WTIPOCOL INTEGER;
DECLARE VARIABLE WPROPRESC INTEGER;
DECLARE VARIABLE WPROPADM INTEGER;
DECLARE VARIABLE WPROPFER INTEGER;
DECLARE VARIABLE WPROPSIT INTEGER;
DECLARE VARIABLE WDIASDOMES INTEGER;
DECLARE VARIABLE WDIASADM INTEGER;
DECLARE VARIABLE WDIASRESC INTEGER;
DECLARE VARIABLE WDIASSIT INTEGER;
DECLARE VARIABLE WDIASFER INTEGER;
BEGIN
  /* prsitcol
     0 = Somente ativos
     1 = Todos
     2 = Somente os demitidos
     3 = Somente admitidos no m?s
     4 = Somente demitidos no m?s
     5 = Ativos sem os demitidos no m?s
     6 = Ativos sem demitidos com transfer?ncia
     7 = Ativos sem afastados o m?s inteiro
     8 = Afastados o m?s inteiro
   */

  wsql = 'select col.BDCODEMP, col.BDCODCOL, colcad.BDNOMCOL, colcad.BDNOMCOLUPPER, col.BDDATAADMCOL '||
         'from VRH_EMP_TCOLCON col '||
     'left outer join VW_VRH_EMP_TCOLCON_CAD colcad on colcad.BDCODEMP = col.BDCODEMP and colcad.BDCODCOL = col.BDCODCOL ';

  IF (premp IS NOT NULL AND premp <> '') THEN
     BEGIN
       wsql = wsql||' where '||premp;

       IF (prcol IS NOT NULL AND prcol <> '') THEN
          wsql = wsql||' and '||prcol;
     END

  wsql = wsql||' order by col.BDCODEMP, col.BDCODCOL ';
  wrefatu = prrefini;

  WHILE (wrefatu <= prreffim) DO
    BEGIN
      wempatu = 0;
      wconvrefemp = 'FALSE';
      wpropadm = 0;
      wpropfer = 0;
      wpropresc = 0;
      wpropsit = 0;
      wtipocol = 0;
      FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDNOMCOL, :BDNOMCOLUPPER, :wdataadm DO
        BEGIN
          BDREF = wrefatu;
          IF (CAST((SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= wrefatu) THEN
             BEGIN
               wsqlaux = 'select first 1 COL.BDCODCLA, CLA.BDDESCCLA '||
                         'from VRH_EMP_TCOLCON_VINC COL '||
                         'join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COL.BDCODCLA) '||
                         'where COL.BDCODEMP = '||BDCODEMP||' and COL.BDCODCOL = '||BDCODCOL||' and COL.BDREFCOL <= '||wrefatu;

               IF (prfiltrocla IS NOT NULL AND prfiltrocla <> '') THEN
                  wsqlaux = wsqlaux||' and '||prfiltrocla;

               wsqlaux = wsqlaux||' order by COL.BDREFCOL DESC ';

               BDCODCLA = 0;
               BDDESCCLA = NULL;
               EXECUTE STATEMENT wsqlaux INTO :BDCODCLA, :BDDESCCLA;

               IF (BDCODCLA IS NOT NULL AND BDCODCLA > 0) THEN
                  BEGIN
                    IF (wempatu <> BDCODEMP) THEN
                       BEGIN 
                         wempatu = BDCODEMP;
                         wsqlaux = 'select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
                         EXECUTE STATEMENT wsqlaux INTO :wconvrefemp;

                         wsqlaux = 'select first 1     BDPROPADMEMP, BDPROPRESEMP, BDPROPFEREMP, BDPROPSITEMP from VRHF_BASE_TEMPPROP where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
                         EXECUTE STATEMENT wsqlaux INTO :wpropadm, :wpropresc, :wpropfer, :wpropsit;
                       END

                    wdataresc = NULL;
                    wrefresc = 0;
                    SELECT FIRST 1 RESC.BDDATARESCISAO, RESC.BDREFRESCISAO FROM VRH_EMP_TRESCISAO RESC
                    JOIN VRH_BASE_TPREPRESC PRES ON (PRES.BDCODPRES = RESC.BDCODPRES)
                    WHERE RESC.BDCODEMP = :BDCODEMP AND RESC.BDCODCOL = :BDCODCOL AND COALESCE(PRES.BDTIPOMOV, 0) = 0 INTO :wdataresc, :wrefresc;

                    wsqlaux = 'select first 1 BDHORASDIARIASCOL, BDTIPOCOL '||
                              'from VRHF_EMP_TCOL_CALC '||
                              'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||wrefatu||
                              'order by BDREFCOL DESC ';
     
                    EXECUTE STATEMENT wsqlaux INTO :BDHORASTRABDIA, :wtipocol;

                    IF ((BDHORASTRABDIA IS NULL) OR (BDHORASTRABDIA = 0)) THEN
                       BDHORASTRABDIA = 7.3333;

                    IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
                       wdiasdomes = 31;
                    ELSE
                    IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) = 2) THEN
                       BEGIN
                         -- Ano bisexto
                         IF ((MOD(CAST(SUBSTRING(wrefatu FROM 1 FOR 4) AS INTEGER), 4) = 0) AND ((MOD(CAST(SUBSTRING(wrefatu FROM 1 FOR 4) AS INTEGER), 100) <> 0) OR (MOD(CAST(SUBSTRING(wrefatu FROM 1 FOR 4) AS INTEGER), 400) = 0))) THEN
                            wdiasdomes = 29;
                         ELSE
                            wdiasdomes = 28;
                       END
                    ELSE
                       wdiasdomes = 30;

                    -- M?s da admiss?o
                    wdiasadm = 0;
                    IF (wrefatu = CAST((SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)) THEN
                       wdiasadm = CAST((SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER);

                    -- M?s da rescis?o
                    wdiasresc = 0;
                    IF (wrefatu = wrefresc) THEN
                       BEGIN
                         -- Horistas
                         IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                            wdiasresc = (wdiasdomes - CAST((SUBSTRING(CAST(wdataresc AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER));
                         ELSE
                            BEGIN
                              -- Dias do m?s
                              IF (COALESCE(wpropresc,0) = 0) THEN
                                 wdiasresc = (wdiasdomes - CAST((SUBSTRING(CAST(wdataresc AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER));
                              ELSE
                                 wdiasresc = (30 - CAST((SUBSTRING(CAST(wdataresc AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER));
                            END
                       END

                    -- F?rias
                    wdiasfer = 0;
                    FOR SELECT BDINIPERGOZOFE, BDFIMPERGOZOFE FROM VRH_EMP_TFERIAS
                    WHERE BDCODEMP = :BDCODEMP AND BDCODCOL = :BDCODCOL AND ((BDREFINIFE = :wrefatu) OR (BDREFFIMFE = :wrefatu) OR (BDREFINIFE < :wrefatu AND BDREFFIMFE > :wrefatu)) AND BDINIPERGOZOFE IS NOT NULL INTO :wdataini, :wdatafim DO
                      BEGIN
                        -- f?rias dentro do m?s
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)) THEN
                           wdiasfer = wdiasfer + (wdatafim - wdataini) + 1;
                        ELSE
                        -- In?cio das f?rias dentro do m?s
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = wrefatu) THEN
                           wdiasfer = wdiasfer + (wdiasdomes - CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER)) + 1;
                        ELSE
                        -- Final das f?rias dentro do m?s
                        IF (CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = wrefatu) THEN
                           wdiasfer = wdiasfer + CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER);
                        ELSE
                        -- F?rias de janeiro a mar?o. No caso de feveireiro estar o m?s inteiro de f?rias
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) < wrefatu AND CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) > wrefatu) THEN
                           BEGIN
                             IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                                wdiasfer = wdiasdomes;
                             ELSE
                                BEGIN
                                  -- Dias do m?s
                                  IF (COALESCE(wpropfer,0) = 0) THEN
                                     wdiasfer = wdiasdomes;
                                  ELSE
                                     wdiasfer = 30;
                                END
                           END
                      END

                    -- Situa??o
                    wdiassit = 0;
                    FOR SELECT SIT.BDDATAINISIT, SIT.BDDATAFIMSIT FROM VRH_EMP_TSITCOL SIT
                    JOIN VRH_BASE_TPREPSIT PSIT ON (PSIT.BDCODSIT = SIT.BDCODSIT)
                    WHERE SIT.BDCODEMP = :BDCODEMP AND SIT.BDCODCOL = :BDCODCOL AND CAST((SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= :wrefatu AND
                          ((SIT.BDDATAFIMSIT IS NULL) OR (CAST((SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= :wrefatu)) AND
                          PSIT.BDGRUPOSIT IN (0,1,2,3,4,6,7,9,10,11)
                     INTO :wdataini, :wdatafim DO
                      BEGIN
                        -- Situa??o dentro do m?s
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)) THEN
                           wdiassit = wdiassit + (wdatafim - wdataini) + 1;
                        ELSE
                        -- In?cio da situa??o dentro do m?s
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = wrefatu) THEN
                           BEGIN
                             -- Horistas
                             IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                                wdiassit = wdiassit + (wdiasdomes - CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER)) + 1;
                             ELSE
                                BEGIN
                                  -- Dias do m?s
                                  IF (COALESCE(wpropsit,0) = 0) THEN
                                     wdiassit = wdiassit + (wdiasdomes - CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER)) + 1;
                                  ELSE
                                     wdiassit = wdiassit + (30 - CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER)) + 1;

                                END
                           END
                        ELSE
                        -- Final da situa??o dentro do m?s
                        IF (CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = wrefatu) THEN
                           wdiassit = wdiassit + CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER);
                        ELSE
                        -- M?s todo em situa??o
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) < wrefatu AND CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) > wrefatu) THEN
                           BEGIN
                             IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                                wdiassit = wdiasdomes;
                             ELSE
                                BEGIN
                                  -- Dias do m?s
                                  IF (COALESCE(wpropsit,0) = 0) THEN
                                     wdiassit = wdiasdomes;
                                  ELSE
                                     wdiassit = 30;
                                END
                           END
                      END

                    IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                       wdiastrab = wdiasdomes - wdiasadm - wdiasresc - wdiasfer - wdiassit;
                    ELSE
                       BEGIN
                         IF (wdiasresc > 0 AND COALESCE(wpropresc,0) = 0) THEN
                            wdiastrab = wdiasdomes;
                         ELSE
                         IF (wdiasadm > 0 AND COALESCE(wpropadm,0) IN (0,2)) THEN
                            wdiastrab = wdiasdomes;
                         ELSE
                         IF (wdiasfer > 0 AND COALESCE(wpropfer,0) = 0) THEN
                            wdiastrab = wdiasdomes;
                         ELSE
                         IF (wdiassit > 0 AND COALESCE(wpropsit,0) = 0) THEN
                            wdiastrab = wdiasdomes;
                         ELSE
                            wdiastrab = 30;

                         wdiastrab = wdiastrab - wdiasadm - wdiasresc - wdiasfer - wdiassit;
                       END

                    IF ((wdiastrab IS NULL) OR (wdiastrab < 0)) THEN
                       wdiastrab = 0;

                    bddiastrab = wdiastrab;

                    -- Informa??es das faltas horas e dias nas folhas.
                    wsqlaux = 'select FN.BDCODVER, FN.BDREFVFN, VER.BDCLAVER, FN.BDCODCENTRO, FN.BDCODTPCC from ('||
                                 'select BDCODVER, BDREFVFN, CAST(null as integer) BDCODCENTRO, CAST(null as integer) BDCODTPCC from VRHF_EMP_TVERBAFN '||
                                 'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFFN = '||wrefatu||' '||
                                 ' union all '||
                                 'select BDCODVER, BDREFVFC, CAST(null as integer) BDCODCENTRO, CAST(null as integer) BDCODTPCC from VRHF_EMP_TVERBAFC '||
                                 'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOMP = '||wrefatu||' '||
                                 ' union all '||
                                 'select FN.BDCODVER, FN.BDREFVFT, PFN.BDCODCENTRO, PFN.BDCODTPCC from VRHF_EMP_TVERBATOMADOR FN '||
                                 'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FN.BDCODEMP and PFN.BDCODCOL = FN.BDCODCOL and PFN.BDORDEM = FN.BDORDEM) '||
                                 'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFTOMADOR = '||wrefatu||' '||
                                 ' union all '||
                                 'select FN.BDCODVER, FN.BDREFVFC, PFN.BDCODCENTRO, PFN.BDCODTPCC from VRHF_EMP_TVERBAFCTOMADOR FN '||
                                 'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FN.BDCODEMP and PFN.BDCODCOL = FN.BDCODCOL and PFN.BDORDEM = FN.BDORDEM) '||
                                 'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFCOMP = '||wrefatu||
                              ') FN '||
                              'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
--                              'where ((VER.BDCLAVER starting with ''0.007.0'') or (VER.BDCLAVER starting with ''0.460.0.0'') or ((VER.BDCLAVER starting with ''0.715.0''))) '||
                              'order by FN.BDCODCENTRO, FN.BDCODTPCC, FN.BDCODVER ';

                    wcentroatu = -1;
                    wcodtpccatu = -1;
                    wtotfaltas = 0;

                    FOR EXECUTE STATEMENT wsqlaux INTO :wcodver, :wval, :wclaver, :wcodcentro, :wcodtpcc DO
                      BEGIN
                        IF (wcentroatu = -1) THEN
                           wcentroatu = COALESCE(wcodcentro, 0);

                        IF (wcodtpccatu = -1) THEN
                           wcodtpccatu = COALESCE(wcodtpcc, 0);

                       IF ((wcentroatu <> COALESCE(wcodcentro, 0)) OR (wcodtpccatu <> COALESCE(wcodtpcc, 0))) THEN
                          BEGIN
                            IF (wcentroatu = 0) THEN
                               BDCODCENTRO = NULL;
                            ELSE
                               BDCODCENTRO = wcentroatu;

                            IF (wcodtpccatu = 0) THEN
                               BDCODTPCC = NULL;
                            ELSE
                               BDCODTPCC = wcodtpccatu;

                            BDHORASTRABMES = CAST(bddiastrab * bdhorastrabdia AS NUMERIC(18,2));
                            BDHORASFALTASMES = wtotfaltas;
                            SUSPEND;

                            wcentroatu = COALESCE(wcodcentro, 0);
                            wcodtpccatu = COALESCE(wcodtpcc, 0);
                            wtotfaltas = 0;
                          END


                        wsqlver = 'select first 1 BDTIPOREFVER from VRH_BASE_TVERBAS_REF where BDCODVER = '||wcodver||' and BDREFVER <= '||wrefatu||' order by BDREFVER DESC';
                        EXECUTE STATEMENT wsqlver INTO :wtiporef;

                        IF (wval IS NULL) THEN
                           wval = 0;

                        -- Faltas indevidas
                        IF (SUBSTRING(wclaver FROM 1 FOR 7) = '0.715.0') THEN
                           BEGIN
                             IF (wtiporef = 1 AND COALESCE(UPPER(wconvrefemp), 'FALSE') = 'TRUE') THEN  -- Verba com a refer?ncia em horas. Empresa converte refer?ncia em horas
                                BEGIN
                                  wintval = CAST(wval - 0.05 AS INTEGER);
                                  wval = wval - wintval;
     
                                  IF (wval > 0) THEN
                                     BEGIN
                                       wval = CAST(wval / 60 * 100 AS NUMERIC(18, 2)) + wintval;
                                     END
                                END
                             ELSE
                             IF (wtiporef = 2) THEN  -- dia
                                wval = CAST(wval * BDHORASTRABDIA AS NUMERIC(18,2));

                             wval = wval * -1;
                           END
                        ELSE
                        IF ((SUBSTRING(wclaver FROM 1 FOR 7) = '0.007.0') OR (SUBSTRING(wclaver FROM 1 FOR 9) = '0.460.0.0') ) THEN
                           BEGIN
                             IF (wtiporef = 1 AND COALESCE(UPPER(wconvrefemp), 'FALSE') = 'TRUE') THEN  -- Verba com a refer?ncia em horas. Empresa converte refer?ncia em horas
                                BEGIN
                                  wintval = CAST(wval - 0.05 AS INTEGER);
                                  wval = wval - wintval;
     
                                  IF (wval > 0) THEN
                                     BEGIN
                                       wval = CAST(wval / 60 * 100 AS NUMERIC(18, 2)) + wintval;
                                     END
                                END
                             ELSE
                             IF (wtiporef = 2) THEN  -- dia
                                wval = CAST(wval * BDHORASTRABDIA AS NUMERIC(18,2));
                           END
                        ELSE
                           wval = 0;

                        wtotfaltas = wtotfaltas + wval;
                      END

                    IF (wcentroatu <> -1 AND wcodtpccatu <> -1) THEN
                       BEGIN
                         IF (wcentroatu = 0) THEN
                            BDCODCENTRO = NULL;
                         ELSE
                            BDCODCENTRO = wcentroatu;

                         IF (wcodtpccatu = 0) THEN
                            BDCODTPCC = NULL;
                         ELSE
                            BDCODTPCC = wcodtpccatu;

                         BDHORASTRABMES = CAST(bddiastrab * bdhorastrabdia AS NUMERIC(18,2));
                         BDHORASFALTASMES = wtotfaltas;
                         SUSPEND;
                       END
                  END
             END
        END

      IF (SUBSTRING(wrefatu FROM 5 FOR 2) = '12' ) THEN
         wrefatu = CAST((CAST((CAST(SUBSTRING(wrefatu FROM 1 FOR 4) AS INTEGER) + 1) AS VARCHAR(4))||'01') AS INTEGER);
      ELSE
         BEGIN
           IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) < 9) THEN
              wrefatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'0'||CAST((CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) + 1) AS VARCHAR(1))) AS INTEGER);
           ELSE
              wrefatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||CAST((CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) + 1) AS VARCHAR(2))) AS INTEGER);
         END
    END

END
^

/* Alter (SP_VRH_RELATORIOCUSTOCOL) */
ALTER PROCEDURE SP_VRH_RELATORIOCUSTOCOL(PREMP VARCHAR(15000),
PRCOL VARCHAR(30000),
PRAUT VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSITCOL SMALLINT,
PRAGRUPA SMALLINT = 0,
PRCC VARCHAR(10000) = null,
PRAGRUPAFILIAIS SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDTIPOCOL INTEGER,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDNOMCOLUPPER DM_BDNOMCOL,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREMUNERACAO NUMERIC(18,6),
BDENCREMUNERACAO NUMERIC(18,6),
BDINSSPATRONAL NUMERIC(18,6),
BDTERC NUMERIC(18,6),
BDRAT NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDRATAPO NUMERIC(18,6),
BDPROV13 NUMERIC(18,6),
BDENCPROV13 NUMERIC(18,6),
BDPROVFER NUMERIC(18,6),
BDENCPROVFER NUMERIC(18,6),
BDBENIFICIOS NUMERIC(18,6),
BDNOMTPCC DM_BDNOMEMP,
BDTOTAL NUMERIC(18,6),
BDCODSIT INTEGER,
BDDESCSIT VARCHAR(70),
BDCODFILIAL INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WVERBA integer;
declare variable WVALOR numeric(18,6);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WTIPOCOL integer;
declare variable WTIPOCOLATU integer;
declare variable WREF integer;
declare variable WREFATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WBASEINSS integer;
declare variable WTIPOCODVER integer;
declare variable WCLAVER varchar(20);
declare variable WCODTPCC integer;
declare variable WTPCCATU integer;
declare variable WCODCENTRO integer;
declare variable WCENTROATU integer;
declare variable WSQLAUX varchar(1000);
declare variable WCONTRCOL integer;
declare variable WPERCINSS numeric(18,6);
declare variable WCODFPASTERC integer;
declare variable WFAP numeric(18,6);
declare variable WPERCFGTS numeric(18,6);
declare variable WVT numeric(18,6);
declare variable WVR numeric(18,6);
declare variable WRETORNA smallint;
declare variable WRAUX integer;
declare variable WAAUX integer;
declare variable WTAUX integer;
declare variable WPERCAUT numeric(18,6);
declare variable WPERCEMP numeric(18,6);
declare variable WPERCCOL numeric(18,6);
declare variable WPERCFPAS numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WCODCNAE integer;
declare variable WNOMEMP DM_BDNOMEMP;
declare variable WPRIVEZ smallint;
declare variable WCODFILIAL integer;
declare variable WFILIALATU integer;
BEGIN
  /* prsitcol
     0 = Somente ativos
     1 = Todos
     2 = Somente os demitidos
     3 = Somente admitidos no m?s
     4 = Somente demitidos no m?s
     5 = Ativos sem os demitidos no m?s
     6 = Ativos sem demitidos com transfer?ncia
     7 = Ativos sem afastados o m?s inteiro
     8 = Afastados o m?s inteiro
   */

  /* pragrupa
    0 = sem centro de custos (n?o retorna o centro de custos)
    1 = por centro de custos (retorna o centro de custos)
   */

  wsql = '';

  premp = upper(premp);
  prcol = upper(prcol);

  IF (UPPER(COALESCE(prcol, '')) <> 'NENHUM') THEN
     BEGIN
       wsql = wsql||
              'select col.bdcodemp, col.BDCODFILIAL, col.BDREFFN, 0 BDTIPOCOL, col.bdcodcol, col.bdcodver, col.bdvalvfn, col.BDCODCENTRO, col.BDCODTPCC '||
              'from (';

       IF ((prcc IS NULL) OR (prcc = '')) THEN
          BEGIN
            if (coalesce(pragrupafiliais, 0) > 0) then
               begin
                 wsql = wsql||
                          'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.bdcodemp BDCODFILIAL, FN.BDCODCOL, FN.BDREFFN, FN.BDCODVER, FN.BDVALVFN, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFN FN '||
                          'join TEMPRESAS EMP on (EMP.BDCODEMP = FN.BDCODEMP) '||
                          'where FN.BDREFFN between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))' ;

                 wsql = wsql||' union all '||
                          'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.bdcodemp BDCODFILIAL, FC.BDCODCOL, FC.BDREFCOMP, FC.BDCODVER, FC.BDVALVFC, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFC FC '||
                          'join TEMPRESAS EMP on (EMP.BDCODEMP = FC.BDCODEMP) '||
                          'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))' ;

               end
            else
               begin
                 wsql = wsql||
                          'select bdcodemp, bdcodemp BDCODFILIAL, BDCODCOL, BDREFFN, BDCODVER, BDVALVFN, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFN '||
                          'where BDREFFN between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             BEGIN
                               wsql = wsql||' and '||premp;
     
                               IF (prcol IS NOT NULL AND prcol <> '') THEN
                                  wsql = wsql||' and '||prcol;
                             END
          
                 wsql = wsql||' union all '||
                          'select bdcodemp, bdcodemp BDCODFILIAL, BDCODCOL, BDREFCOMP, BDCODVER, BDVALVFC, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFC '||
                          'where BDREFCOMP between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             BEGIN
                               wsql = wsql||' and '||premp;
                   
                               IF (prcol IS NOT NULL AND prcol <> '') THEN
                                  wsql = wsql||' and '||prcol;
                   
                             END
               end

            wsql = wsql||' union all ';
          END

       if (coalesce(pragrupafiliais, 0) > 0) then
          begin
            wsql = wsql||
                     'select FT.bdcodemp, FT.BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR BDREFFN, FT.BDCODVER, FT.BDVALVFT BDVALVFN, ';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsql = wsql||
                     'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, FT.BDCODEMP BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR, FT.BDORDEM, FT.BDCODVER, FT.BDVALVFT from VRHF_EMP_TVERBATOMADOR FT '||
                            'join TEMPRESAS EMP on (EMP.BDCODEMP = FT.BDCODEMP) '||
                            'where FT.BDREFTOMADOR between '||prrefini||' and '||prreffim;
     
                            IF (premp IS NOT NULL AND premp <> '') THEN
                               wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))';
          end
       else
          begin
            wsql = wsql||
                     'select FT.bdcodemp, FT.bdcodemp BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR BDREFFN, FT.BDCODVER, FT.BDVALVFT BDVALVFN, ';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsql = wsql||
                     'from (select * from VRHF_EMP_TVERBATOMADOR '||
                            'where BDREFTOMADOR between '||prrefini||' and '||prreffim;
     
                            IF (premp IS NOT NULL AND premp <> '') THEN
                               BEGIN
                                 wsql = wsql||' and '||premp;
                     
                                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                                    wsql = wsql||' and '||prcol;
                     
                               END
          end

       wsql = wsql||
                ') FT '||
                'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = FT.BDCODEMP and prepft.BDCODCOL = FT.BDCODCOL and prepft.BDORDEM = FT.BDORDEM) ';

       IF (prcc IS NOT NULL AND prcc <> '') THEN
          wsql = wsql||' where '||prcc;


       if (coalesce(pragrupafiliais, 0) > 0) then
          begin
            wsql = wsql||' union all '||
                     'select FT.bdcodemp, FT.BDCODFILIAL, FT.BDCODCOL, FT.BDREFCOMP, FT.BDCODVER, FT.BDVALVFC,';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';
     
            wsql = wsql||
                     'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, FC.BDCODEMP BDCODFILIAL, FC.BDCODCOL, FC.BDREFCOMP, FC.BDCODVER, FC.BDORDEM, FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR FC '||
                            'join TEMPRESAS EMP on (EMP.BDCODEMP = FC.BDCODEMP) '||
                            'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
     
                            IF (premp IS NOT NULL AND premp <> '') THEN
                               wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
          end
       else
          begin
            wsql = wsql||' union all '||
                     'select FT.bdcodemp, FT.bdcodemp BDCODFILIAL, FT.BDCODCOL, FT.BDREFCOMP, FT.BDCODVER, FT.BDVALVFC,';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';
     
            wsql = wsql||
                     'from (select * from VRHF_EMP_TVERBAFCTOMADOR '||
                            'where BDREFCOMP between '||prrefini||' and '||prreffim;
     
                            IF (premp IS NOT NULL AND premp <> '') THEN
                               BEGIN
                                 wsql = wsql||' and '||premp;
                     
                                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                                    wsql = wsql||' and '||prcol;
                     
                               END
          end

       wsql = wsql||
                ') FT '||
                'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = FT.BDCODEMP and prepft.BDCODCOL = FT.BDCODCOL and prepft.BDORDEM = FT.BDORDEM) ';

       IF (prcc IS NOT NULL AND prcc <> '') THEN
          wsql = wsql||' where '||prcc;


      -- adiantamento de 13? sal?rio
      wsql = wsql||
             ' union all ';


      if (coalesce(pragrupafiliais, 0) > 0) then
         begin
           wsql = wsql||
                  'select a13.BDCODEMP, a13.bdcodemp BDCODFILIAL, a13.BDCODCOL, a13.BDREFA13, a13.BDCODVER, a13.BDVALVA13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.BDCODEMP BDCODFILIAL, a13.BDCODCOL, a13.BDREFA13, a13.BDCODVER, a13.BDCHAVE, a13.BDVALVA13 from VRHF_EMP_TVERBAA13_RAT a13 '||
                        'join TEMPRESAS EMP on (EMP.BDCODEMP = a13.BDCODEMP) '||
                        'where a13.BDREFA13 between '||prrefini||' and '||prreffim;
     
                        IF (premp IS NOT NULL AND premp <> '') THEN
                           wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';

           wsql = wsql||
                  ') a13 left outer join VRHF_EMP_TA13SAL_RAT aa13 on (aa13.BDCODEMP = a13.BDCODEMP and aa13.BDCODCOL = a13.bdcodcol and aa13.bdrefa13 = a13.bdrefa13 and aa13.bdchave = a13.bdchave) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = aa13.BDCODEMP and prepft.BDCODCOL = aa13.BDCODCOL and prepft.BDORDEM = aa13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
              wsql = wsql||' where '||prcc;
         end
      else
         begin
           wsql = wsql||
                  'select a13.BDCODEMP, a13.bdcodemp BDCODFILIAL, a13.BDCODCOL, a13.BDREFA13, a13.BDCODVER, a13.BDVALVA13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select * from VRHF_EMP_TVERBAA13_RAT '||
                        'where BDREFA13 between '||prrefini||' and '||prreffim;
     
                        IF (premp IS NOT NULL AND premp <> '') THEN
                           BEGIN
                             wsql = wsql||' and '||premp;
                 
                             IF (prcol IS NOT NULL AND prcol <> '') THEN
                                wsql = wsql||' and '||prcol;
                 
                           END

           wsql = wsql||
                  ') a13 left outer join VRHF_EMP_TA13SAL_RAT aa13 on (aa13.BDCODEMP = a13.BDCODEMP and aa13.BDCODCOL = a13.bdcodcol and aa13.bdrefa13 = a13.bdrefa13 and aa13.bdchave = a13.bdchave) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = aa13.BDCODEMP and prepft.BDCODCOL = aa13.BDCODCOL and prepft.BDORDEM = aa13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
              wsql = wsql||' where '||prcc;
         end

      -- 13? sal?rio
      wsql = wsql||
             ' union all ';

      IF (coalesce(pragrupafiliais, 0) > 0) THEN
         BEGIN
           wsql = wsql||
                  'select S13.BDCODEMP, S13.BDCODFILIAL, S13.BDCODCOL, S13.BDREF13, S13.BDCODVER, S13.BDVALV13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, s13.BDCODEMP BDCODFILIAL, s13.BDCODCOL, s13.BDREF13, s13.BDCHAVE, s13.BDCODVER, s13.BDVALV13 from VRHF_EMP_TVERBA_13_RAT s13 '||
                         'join TEMPRESAS EMP on (EMP.BDCODEMP = s13.BDCODEMP) '||
                         'where s13.BDREF13 between '||prrefini||' and '||prreffim;
             
                         IF (premp IS NOT NULL AND premp <> '') THEN
                            wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';

           wsql = wsql||
                  ') S13 left outer join VRHF_EMP_T13SAL_RAT SS13 on (SS13.BDCODEMP = S13.BDCODEMP and SS13.BDCODCOL = S13.BDCODCOL and SS13.BDREF13 = S13.BDREF13 and SS13.bdchave = S13.BDCHAVE) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = ss13.BDCODEMP and prepft.BDCODCOL = ss13.BDCODCOL and prepft.BDORDEM = ss13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
                  wsql = wsql||' where '||prcc;
         END
      ELSE
         BEGIN
           wsql = wsql||
                  'select S13.BDCODEMP, S13.bdcodemp BDCODFILIAL, S13.BDCODCOL, S13.BDREF13, S13.BDCODVER, S13.BDVALV13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select * from VRHF_EMP_TVERBA_13_RAT '||
                         'where BDREF13 between '||prrefini||' and '||prreffim;
             
                         IF (premp IS NOT NULL AND premp <> '') THEN
                            BEGIN
                              wsql = wsql||' and '||premp;
                   
                              IF (prcol IS NOT NULL AND prcol <> '') THEN
                                 wsql = wsql||' and '||prcol;
                   
                            END
           wsql = wsql||
                  ') S13 left outer join VRHF_EMP_T13SAL_RAT SS13 on (SS13.BDCODEMP = S13.BDCODEMP and SS13.BDCODCOL = S13.BDCODCOL and SS13.BDREF13 = S13.BDREF13 and SS13.bdchave = S13.BDCHAVE) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = ss13.BDCODEMP and prepft.BDCODCOL = ss13.BDCODCOL and prepft.BDORDEM = ss13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
                  wsql = wsql||' where '||prcc;
         END

      -- Complemento de 13? sal?rio
      wsql = wsql||
             ' union all ';

      IF (coalesce(pragrupafiliais, 0) > 0) THEN
         BEGIN
           wsql = wsql||
                  'select C13.BDCODEMP, C13.BDCODFILIAL, C13.BDCODCOL, C13.BDREFC13, C13.BDCODVER, C13.BDVALVC13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.BDCODEMP BDCODFILIAL, c13.BDCODCOL, c13.BDREFC13, c13.BDCODVER, c13.BDVALVC13 from VRHF_EMP_TVERBAC13 c13 '||
                        'join TEMPRESAS EMP on (EMP.BDCODEMP = c13.BDCODEMP) '||
                        'where c13.BDREFC13 between '||prrefini||' and '||prreffim;
           
                        IF (premp IS NOT NULL AND premp <> '') THEN
                           wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';

           wsql = wsql||
                  ') C13 join VRHF_EMP_T13SAL_RAT CC13 on (CC13.BDCODEMP = C13.BDCODEMP and CC13.BDCODCOL = C13.BDCODCOL and CC13.BDREF13 = C13.BDREFC13) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = CC13.BDCODEMP and prepft.BDCODCOL = CC13.BDCODCOL and prepft.BDORDEM = CC13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
              wsql = wsql||' where '||prcc;
         END
      ELSE
         BEGIN
           wsql = wsql||
                  'select C13.BDCODEMP, C13.bdcodemp BDCODFILIAL, C13.BDCODCOL, C13.BDREFC13, C13.BDCODVER, C13.BDVALVC13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select * from VRHF_EMP_TVERBAC13 '||
                        'where BDREFC13 between '||prrefini||' and '||prreffim;
           
                        IF (premp IS NOT NULL AND premp <> '') THEN
                           BEGIN
                             wsql = wsql||' and '||premp;
                 
                             IF (prcol IS NOT NULL AND prcol <> '') THEN
                                wsql = wsql||' and '||prcol;
                 
                           END
           wsql = wsql||
                  ') C13 join VRHF_EMP_T13SAL_RAT CC13 on (CC13.BDCODEMP = C13.BDCODEMP and CC13.BDCODCOL = C13.BDCODCOL and CC13.BDREF13 = C13.BDREFC13) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = CC13.BDCODEMP and prepft.BDCODCOL = CC13.BDCODCOL and prepft.BDORDEM = CC13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
              wsql = wsql||' where '||prcc;
         END

      -- Folha avulsa

      if (coalesce(pragrupafiliais, 0) > 0) then
         begin
           wsql = wsql||
                  ' union all '||
                  'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.BDCODEMP BDCODFILIAL, fa.BDCODCOL, SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) BDREF, fa.BDCODVER, fa.BDVALVFA,';

           if (coalesce(pragrupa, 0) = 0) then
              wsql = wsql||' cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODPTCC ';
           else
              wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from VRHF_EMP_TVERBAFA fa '||
                  'join TEMPRESAS EMP on (EMP.BDCODEMP = fa.BDCODEMP) '||
                  'join VRHF_EMP_TFOLHAAVULSA ffa on (ffa.BDCODEMP = fa.BDCODEMP and ffa.BDCODCOL = fa.BDCODCOL and ffa.BDCODTCA = fa.BDCODTCA and ffa.BDDATAFA = fa.BDDATAFA) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = ffa.BDCODEMP and prepft.BDCODCOL = ffa.BDCODCOL and prepft.BDORDEM = ffa.BDORDEM) '||
                  'where SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) between '||prrefini||' and '||prreffim;
     
                  IF (premp IS NOT NULL AND premp <> '') THEN
                     wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))';

                  if (coalesce(prcc, '') <> '') then
                     wsql = wsql||' and '||prcc;
         end
       else
         begin
           wsql = wsql||
                  ' union all '||
                  'select fa.BDCODEMP, fa.bdcodemp BDCODFILIAL, fa.BDCODCOL, SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) BDREF, fa.BDCODVER, fa.BDVALVFA, ';

           if (coalesce(pragrupa, 0) = 0) then
              wsql = wsql||' cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODPTCC ';
           else
              wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from VRHF_EMP_TVERBAFA fa '||
                  'join VRHF_EMP_TFOLHAAVULSA ffa on (ffa.BDCODEMP = fa.BDCODEMP and ffa.BDCODCOL = fa.BDCODCOL and ffa.BDCODTCA = fa.BDCODTCA and ffa.BDDATAFA = fa.BDDATAFA) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = ffa.BDCODEMP and prepft.BDCODCOL = ffa.BDCODCOL and prepft.BDORDEM = ffa.BDORDEM) '||
                  'where SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) between '||prrefini||' and '||prreffim;
     
                  IF (premp IS NOT NULL AND premp <> '') THEN
                     BEGIN
                       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'fa.BDCODEMP');
           
                       IF (prcol IS NOT NULL AND prcol <> '') THEN
                          wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'fa.BDCODCOL');
                     END

                  if (coalesce(prcc, '') <> '') then
                     wsql = wsql||' and '||prcc;
         end

       wsql = wsql||
              ') col ';
     END

  IF (UPPER(COALESCE(prAut, '')) <> 'NENHUM') THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       if (coalesce(pragrupafiliais, 0) > 0) then
          begin
            wsql = wsql||
                   'select col.BDCODEMP, col.BDCODFILIAL, col.bdrefinssserv BDREFFN, 2 BDTIPOCOL, col.BDCODTER BDCODCOL, FN.BDCODVER, FN.BDVALOR BDVALVFN,';
     
                   IF (pragrupa = 0) THEN
                      wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                   ELSE
                      wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';
     
            wsql = wsql||
                   'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.BDCODEMP BDCODFILIAL, aut.bdrefinssserv, aut.bdcodter, aut.BDCODSERV from VRHF_BASE_CALC_TERC aut '||
                      'join TEMPRESAS EMP on (EMP.BDCODEMP = aut.BDCODEMP) '||
                      'where aut.BDREFINSSSERV between '||prrefini||' and '||prreffim;
     
                      IF (premp IS NOT NULL AND premp <> '') THEN
                         wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
          end
       else
          begin
            wsql = wsql||
                   'select col.BDCODEMP, col.bdcodemp BDCODFILIAL, col.bdrefinssserv BDREFFN, 2 BDTIPOCOL, col.BDCODTER BDCODCOL, FN.BDCODVER, FN.BDVALOR BDVALVFN,';
     
                   IF (pragrupa = 0) THEN
                      wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                   ELSE
                      wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';
     
            wsql = wsql||
                   'from (select * from VRHF_BASE_CALC_TERC '||
                      'where BDREFINSSSERV between '||prrefini||' and '||prreffim;
     
                      IF (premp IS NOT NULL AND premp <> '') THEN
                         BEGIN
                           wsql = wsql||' and '||premp;
               
                           IF (praut IS NOT NULL AND praut <> '') THEN
                              wsql = wsql||' and '||praut;
               
                         END
          end

       wsql = wsql||
              ') col '||
              'join VRHF_BASE_ITEMS_CALCTERC FN on (FN.BDCODTER = COL.BDCODTER and FN.BDCODEMP = COL.BDCODEMP and FN.BDCODSERV = COL.BDCODSERV) ';

       wsql = wsql||'join VRH_BASE_TSERVTERC prepft on (prepft.bdcodter = col.bdcodter and prepft.bdcodemp = col.bdcodemp and prepft.bdcodserv = col.bdcodserv) ';

       IF (prcc IS NOT NULL AND prcc <> '') THEN
          wsql = wsql||' where '||prcc;

     END

  IF (wsql <> '') THEN
     wsql = 'select FOLHA.BDCODEMP, FOLHA.BDREFFN, FOLHA.BDTIPOCOL, FOLHA.BDCODCOL, FOLHA.BDCODVER, FOLHA.BDVALVFN, COALESCE(FOLHA.BDCODCENTRO,0), COALESCE(FOLHA.BDCODTPCC, 0), VER.BDCLAVER, FOLHA.BDCODFILIAL '||
            'from ('||wsql||') FOLHA '||
            'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOLHA.BDCODVER) '||
            'where VER.BDCLAVER not starting with ''0.191'' '||
            'order by FOLHA.BDCODEMP, FOLHA.BDCODFILIAL, FOLHA.BDCODTPCC, FOLHA.BDREFFN, FOLHA.BDCODCOL';

  BDCODCENTRO = NULL;
  BDCODTPCC = NULL;

  wempatu = 0;
  wcolatu = 0;
  wtipocolatu = -1;
  wrefatu = 0;
  wtpccatu = -1;
  wcentroatu = -1;
  BDREMUNERACAO = 0;
  BDENCREMUNERACAO = 0;
  BDPROV13 = 0;
  BDENCPROV13 = 0;
  BDPROVFER = 0;
  BDENCPROVFER = 0;
  BDBENIFICIOS = 0;
  BDTOTAL = 0;
  wvt = 0;
  wvr = 0;
  wpercaut = 0;
  wpercemp = 0;
  wperccol = 0;
  wcodfpasterc = 0;
  wpercfpas = 0;
  wpercrat = 0;
  wprivez = 0;
  BDCODSIT = 0;
  BDDESCSIT = '';
  wfilialatu = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wref, :wtipocol, :wcodcol, :wverba, :wvalor, :wcodcentro, :wcodtpcc, :wclaver, :wcodfilial DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;
      IF (wrefatu = 0) THEN
         wrefatu = wref;
      IF (wtipocolatu = -1) THEN
         wtipocolatu = wtipocol;
      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;
      IF (wtpccatu = -1) THEN
         wtpccatu = wcodtpcc;
      IF (wfilialatu = 0) THEN
         wfilialatu = wcodfilial;

      IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wcolatu <> wcodcol) OR (wtpccatu <> wcodtpcc) or (wfilialatu <> wcodfilial)) THEN
         BEGIN
           BDCODEMP    = wempatu;
           BDREF       = wrefatu;
           BDCODCOL    = wcolatu;
           BDCODCENTRO = wcentroatu;
           BDCODTPCC   = wtpccatu;
           BDCODFILIAL = wfilialatu;
           waaux       = 0;
           wraux       = 0;
           wtaux       = 0;

           IF (wtipocolatu = 2) THEN
              BEGIN
                SELECT FIRST 1 SUBSTRING(BDNOMETER FROM 1 FOR 70), SUBSTRING(UPPER(BDNOMETER) FROM 1 FOR 70) FROM VW_TTERCEIRO WHERE BDCODTER = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER;
                wcontrcol = 2;
              END
           ELSE
              BEGIN
                SELECT CAD.BDNOMCOL, UPPER(CAD.BDNOMCOL), C.BDCONTRCOL, SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2) BDREFADMCOL, R.BDREFRESCISAO, PR.BDTIPOMOV
                FROM VRH_EMP_TCOLCON C
                LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL)
                LEFT OUTER JOIN VRH_EMP_TRESCISAO R ON (R.BDCODEMP = C.BDCODEMP AND R.BDCODCOL = C.BDCODCOL)
                LEFT OUTER JOIN VRH_BASE_TPREPRESC PR ON (PR.BDCODPRES = R.BDCODPRES)
                WHERE C.BDCODEMP = :wfilialatu AND C.BDCODCOL = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER, :wcontrcol, :waaux, :wraux, :wtaux;

                IF (wcontrcol = 1) THEN
                   BEGIN
                     wsqlaux = 'select first 1 X.BDGRUPOCLA from VRH_EMP_TCOLCON_VINC Y '||
                               'join VRH_BASE_TCLASSE X on (X.BDCODCLA = Y.BDCODCLA) '||
                               'where Y.BDCODEMP = '||wfilialatu||' and Y.BDCODCOL = '||wcolatu||' and Y.BDREFCOL <= '||wrefatu||' order by Y.BDREFCOL DESC ';
                     EXECUTE STATEMENT wsqlaux INTO: wcontrcol;

                     IF (wcontrcol = 3) THEN
                        wcontrcol = 2;
                     ELSE
                        wcontrcol = 1;
                   END

              END

           BDTIPOCOL   = wcontrcol;
           wretorna = 0;
           IF (wcontrcol IN (0,1)) THEN
              BEGIN
                IF (prsitcol = 0) THEN   -- somente ativos
                   BEGIN
                     IF (COALESCE(waaux,0) > wrefatu) THEN
                        wretorna = 1;

                     IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu) THEN
                        wretorna = 1;
                   END
                ELSE
                IF (prsitcol = 2) THEN   -- somente os demitidos
                   BEGIN
                     IF (COALESCE(waaux,0) > wrefatu) THEN
                        wretorna = 1;

                     IF ((COALESCE(wraux,0) = 0) OR (COALESCE(wraux,0) > wrefatu)) THEN
                        wretorna = 1;
                   END
                ELSE
                IF (prsitcol = 3) THEN   -- admitidos no m?s
                   BEGIN
                     IF (COALESCE(waaux,0) <> wrefatu) THEN
                        wretorna = 1;
                   END
                ELSE
                IF (prsitcol = 4) THEN   -- somente os demitidos no m?s
                   BEGIN
                     IF (COALESCE(waaux,0) > wrefatu) THEN
                        wretorna = 1;

                     IF (COALESCE(wraux,0) <> wrefatu) THEN
                        wretorna = 1;
                   END
                ELSE
                IF (prsitcol = 5) THEN   -- ativos sem os demitidos no m?s
                   BEGIN
                     IF (COALESCE(waaux,0) > wrefatu) THEN
                        wretorna = 1;

                     IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu) THEN
                        wretorna = 1;
                   END
                ELSE
                IF (prsitcol = 6) THEN   -- ativos sem os demitidos com transfer?ncia
                   BEGIN
                     IF (COALESCE(waaux,0) > wrefatu) THEN
                        wretorna = 1;

                     IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu AND COALESCE(wtaux,0) = 0) THEN
                        wretorna = 1;

                     IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu AND COALESCE(wtaux,0) = 1) THEN
                        wretorna = 1;
                   END
                ELSE
                IF (prsitcol = 7) THEN   -- ativos sem os afastados o m?s inteiro
                   BEGIN
                     IF (COALESCE(waaux,0) > wrefatu) THEN
                        wretorna = 1;

                     IF (wretorna = 0) THEN
                        BEGIN
                          wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                                    ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                    ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                          EXECUTE STATEMENT wsqlaux INTO :wretorna;

                          IF (COALESCE(wretorna,0) > 0) THEN
                             wretorna = 1;
                          ELSE
                             wretorna = 0;
                        END
                   END
                ELSE
                IF (prsitcol = 8) THEN   -- afastados o m?s inteiro
                   BEGIN
                     IF (COALESCE(waaux,0) > wrefatu) THEN
                        wretorna = 1;

                     IF (wretorna = 0) THEN
                        BEGIN
                          wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                                    ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                    ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                          EXECUTE STATEMENT wsqlaux INTO :wretorna;

                          IF (COALESCE(wretorna,0) = 0) THEN
                             wretorna = 1;
                          ELSE
                             wretorna = 0;
                        END
                   END

              END

           IF (wretorna = 0) THEN
              BEGIN
                wpercinss = 0;
                IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wprivez = 0) or (wfilialatu <> wcodfilial)) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDAUTEMP, BDEMPEMP, BDFUNEMP, BDCODFPASTERC, BDFAP from VRHF_BASE_TEMPGPS where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                     EXECUTE STATEMENT wsqlaux INTO :wpercaut, :wpercemp, :wperccol, :wcodfpasterc, :wfap;

                     IF (wcodfpasterc IS NOT NULL AND wcodfpasterc > 0) THEN
                        SELECT BDPERTERC FROM VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;

                     wcodcnae = 0;
                     wsqlaux = 'select first 1 COALESCE(BDCNAEPREP, BDCODCNAE, 0) ';
     
                     IF (pragrupa = 1) THEN
                        wsqlaux = wsqlaux||', BDCODCENTROS ';
                     ELSE
                        wsqlaux = wsqlaux||', 0 BDCODCENTROS ';

                     wsqlaux = wsqlaux||', BDNOMEMP ';
     

                     wsqlaux = wsqlaux||' from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                     EXECUTE STATEMENT wsqlaux INTO :wcodcnae, :BDCODCENTRO, :wnomemp;
          
                     IF (pragrupa = 0) THEN
                        BDCODCENTRO = wcentroatu;
     
                     IF (wcodcnae IS NOT NULL AND wcodcnae > 0) THEN
                        BEGIN
                          wsqlaux = 'select first 1 BDTAXACNAE from TCNAE_REF where BDCODCNAE = '||wcodfpasterc||' and BDREFCNAE <= ' ||wrefatu||' order by BDREFCNAE desc ';
                          EXECUTE STATEMENT wsqlaux INTO :wpercrat;
                        END
                   END

                wprivez = 1;
     
                IF ((wfap IS NULL) OR (wfap = 0)) THEN
                   wfap = 1;

                IF (wcontrcol = 2) THEN
                   wpercinss = wpercaut;
                ELSE
                IF (wcontrcol = 1) THEN
                   wpercinss = wpercemp;
                ELSE
                   wpercinss = wperccol;

                -- INSS Patronal
                BDINSSPATRONAL = 0;
                IF (BDREMUNERACAO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
                   BEGIN
                     BDINSSPATRONAL = CAST(((BDREMUNERACAO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDINSSPATRONAL;
                   END
     
                -- Terceiros
                BDTERC = 0;
                IF (BDREMUNERACAO <> 0 AND wpercfpas IS NOT NULL AND wpercfpas > 0) THEN
                   BEGIN
                     BDTERC = CAST(((BDREMUNERACAO * wpercfpas / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDTERC;
                   END
     
                -- RAT
                BDRAT = 0;
                IF (BDREMUNERACAO <> 0 AND wpercrat IS NOT NULL AND wpercrat > 0) THEN
                   BEGIN
                     wpercrat = CAST((wpercrat * wfap) AS NUMERIC(18, 4));
                     BDRAT = CAST(((BDREMUNERACAO * wpercrat / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDRAT;
                   END
     
                BDFGTS = 0;
                BDRATAPO = 0;
                BDPROV13    = 0;
                BDENCPROV13 = 0;
                BDPROVFER    = 0;
                BDENCPROVFER = 0;
     
                IF (wcontrcol = 0) THEN
                   BEGIN
                     wpercinss = 0;
                     -- FGTS
                     wsqlaux = 'select first 1 BDPERCFGTSCOL, BDPERCRATCOL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFCOL <= '||wrefatu||' order by BDREFCOL DESC ';
                     EXECUTE STATEMENT wsqlaux INTO :wpercfgts, :wpercinss;
     
                     IF (BDREMUNERACAO <> 0 AND wpercfgts IS NOT NULL AND wpercfgts > 0) THEN
                        BEGIN
                          BDFGTS = CAST(((BDREMUNERACAO * wpercfgts / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                          BDENCREMUNERACAO = BDENCREMUNERACAO + BDFGTS;
                        END
     
                     -- RAT APO
                     IF (BDREMUNERACAO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
                        BEGIN
                          BDRATAPO = CAST(((BDREMUNERACAO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                          BDENCREMUNERACAO = BDENCREMUNERACAO + BDRATAPO;
                        END
          
                     -- Provis?o de 13?
                     wsqlaux = 'select SUM(BDVLR13SALP13) BDVALPROV13, SUM(BDFGTSP13 + BDINSSP13 + BDTERCFPASP13 + BDCNAERATP13 + BDRATAPOP13 + BDPISP13) BDENCPROV13 '||
                               'from VRHF_EMP_TPROVISAO13 where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFP13 = '||wrefatu||' and BDLINHAP13 in (6,7,8,9,19) ';

                     EXECUTE STATEMENT wsqlaux INTO :BDPROV13, :BDENCPROV13;
                     IF (BDPROV13 IS NULL) THEN
                        BDPROV13 = 0;
                     IF (BDENCPROV13 IS NULL) THEN
                        BDENCPROV13 = 0;

                     -- Provis?o de F?rias
                     wsqlaux = 'select SUM(BDFERIASPFER + BDUMTERCOPFER) BDVALPROVFER, SUM(BDFGTSPFER + BDINSSPFER + BDTERCFPASPFER + BDCNAERATPFER + BDRATAPOPFER + BDPISPFER) BDENCPROVFER '||
                               'from VRHF_EMP_TPROVISAOFERIAS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFPFER = '||wrefatu||' and BDLINHAPFER in (4,5,6,7,14) ';

                     EXECUTE STATEMENT wsqlaux INTO :BDPROVFER, :BDENCPROVFER;
                     IF (BDPROVFER IS NULL) THEN
                        BDPROVFER = 0;
                     IF (BDENCPROVFER IS NULL) THEN
                        BDENCPROVFER = 0;

                     -- Para apura??o do vale transporte o processo no sistema deve ser modificado para gravar os valores apurados
                     --wsqlaux = 'select * from VRHF_EMP_TAPVALTRANS';
     
     
                     -- Para apura??o do vale refei??o o processo no sistema deve ser modificado para gravar os valores apurados
                     --wsqlaux = 'select * from VRHF_EMP_TAPVALREF';
     
                   END
     
                IF (wtpccatu > 0 AND wcentroatu > 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC '||
                               'left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) '||
                               'where CC.BDCODCENTRO = '||wcentroatu||' and CC.BDCODTPCC = '||wtpccatu;
                     EXECUTE STATEMENT wsqlaux INTO :BDNOMTPCC;
                   END
                ELSE
                   BDNOMTPCC = wnomemp;

                BDCODSIT = 0;
                BDDESCSIT = '';
                if (BDREMUNERACAO + BDENCREMUNERACAO + BDBENIFICIOS + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER <= 0) then
                   begin
                     wsqlaux = 'select first 1 ST.BDCODSIT, PST.BDDESCSIT from VRH_EMP_TSITCOL ST '||
                               'join VRH_BASE_TPREPSIT PST on (PST.BDCODSIT = ST.BDCODSIT) '||
                               'where ST.BDCODEMP = '||wfilialatu||' and ST.BDCODCOL = '||wcolatu||
                               ' and SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                               ' and ((ST.BDDATAFIMSIT is null) or (SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
                     execute statement wsqlaux into :BDCODSIT, :BDDESCSIT;
                   end

                BDTOTAL = BDREMUNERACAO + BDENCREMUNERACAO + BDBENIFICIOS + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER;
                SUSPEND;
              END

           wempatu          = wcodemp;
           wrefatu          = wref;
           wtipocolatu      = wtipocol;
           wcolatu          = wcodcol;
           wtpccatu         = wcodtpcc;
           wfilialatu       = wcodfilial;
           BDREMUNERACAO    = 0;
           BDENCREMUNERACAO = 0;
           BDPROV13         = 0;
           BDENCPROV13      = 0;
           BDPROVFER        = 0;
           BDENCPROVFER     = 0;
           BDBENIFICIOS     = 0;
           wvt              = 0;
           wvr              = 0;
         END

      wcentroatu = wcodcentro;

      wsqlaux = 'select first 1 BDINSSVER, BDTIPOCODVER from VRH_BASE_TVERBAS_REF  '||
                'where BDCODVER = '||wverba||' and BDREFVER <= '||wrefatu||' order by BDREFVER DESC';
      EXECUTE STATEMENT wsqlaux INTO :wbaseinss, :wtipocodver;

      IF (COALESCE(wbaseinss,0) > 0) THEN
         BEGIN
           IF (COALESCE(wtipocodver, 0) = 0) THEN
              BDREMUNERACAO = BDREMUNERACAO + wvalor;
           ELSE
           IF (COALESCE(wtipocodver, 0) = 1) THEN
              BDREMUNERACAO = BDREMUNERACAO - wvalor;
         END

      IF (SUBSTRING(wclaver FROM 1 FOR 9) = '0.008.0.0') THEN   -- Vale transporte
         wvt = wvt + wvalor;

      IF (SUBSTRING(wclaver FROM 1 FOR 9) = '0.008.0.2') THEN   -- Vale refei??o
         wvr = wvr + wvalor;

    END


 IF ((wempatu <> 0) AND (wrefatu <> 0) AND (wcolatu <> 0) AND (wtpccatu <> -1) and (wfilialatu <> 0)) THEN
    BEGIN
      BDCODEMP    = wempatu;
      BDREF       = wrefatu;
      BDTIPOCOL   = wtipocolatu;
      BDCODCOL    = wcolatu;
      BDCODCENTRO = wcentroatu;
      BDCODTPCC   = wtpccatu;
      BDCODFILIAL = wfilialatu;
      waaux       = 0;
      wraux       = 0;
      wtaux       = 0;

      IF (wtipocolatu = 2) THEN
         BEGIN
           SELECT FIRST 1 SUBSTRING(BDNOMETER FROM 1 FOR 70), SUBSTRING(UPPER(BDNOMETER) FROM 1 FOR 70) FROM VW_TTERCEIRO WHERE BDCODTER = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER;
           wcontrcol = 2;
         END
      ELSE
         BEGIN
           SELECT CAD.BDNOMCOL, UPPER(CAD.BDNOMCOL), C.BDCONTRCOL, SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2) BDREFADMCOL, R.BDREFRESCISAO, PR.BDTIPOMOV
           FROM VRH_EMP_TCOLCON C
           LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL)
           LEFT OUTER JOIN VRH_EMP_TRESCISAO R ON (R.BDCODEMP = C.BDCODEMP AND R.BDCODCOL = C.BDCODCOL)
           LEFT OUTER JOIN VRH_BASE_TPREPRESC PR ON (PR.BDCODPRES = R.BDCODPRES)
           WHERE C.BDCODEMP = :wfilialatu AND C.BDCODCOL = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER, :wcontrcol, :waaux, :wraux, :wtaux;

           IF (wcontrcol = 1) THEN
              BEGIN
                wsqlaux = 'select first 1 X.BDGRUPOCLA from VRH_EMP_TCOLCON_VINC Y '||
                          'join VRH_BASE_TCLASSE X on (X.BDCODCLA = Y.BDCODCLA) '||
                          'where Y.BDCODEMP = '||wfilialatu||' and Y.BDCODCOL = '||wcolatu||' and Y.BDREFCOL <= '||wrefatu||' order by Y.BDREFCOL DESC ';
                EXECUTE STATEMENT wsqlaux INTO: wcontrcol;

                IF (wcontrcol = 3) THEN
                   wcontrcol = 2;
                ELSE
                   wcontrcol = 1;
              END

         END

      wretorna = 0;
      IF (wcontrcol IN (0,1)) THEN
         BEGIN
           IF (prsitcol = 0) THEN   -- somente ativos
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 2) THEN   -- somente os demitidos
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF ((COALESCE(wraux,0) = 0) OR (COALESCE(wraux,0) > wrefatu)) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 3) THEN   -- admitidos no m?s
              BEGIN
                IF (COALESCE(waaux,0) <> wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 4) THEN   -- somente os demitidos no m?s
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) <> wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 5) THEN   -- ativos sem os demitidos no m?s
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 6) THEN   -- ativos sem os demitidos com transfer?ncia
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu AND COALESCE(wtaux,0) = 0) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu AND COALESCE(wtaux,0) = 1) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 7) THEN   -- ativos sem os afastados o m?s inteiro
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (wretorna = 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                               ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                               ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                     EXECUTE STATEMENT wsqlaux INTO :wretorna;

                     IF (COALESCE(wretorna,0) > 0) THEN
                        wretorna = 1;
                     ELSE
                        wretorna = 0;
                   END
              END
           ELSE
           IF (prsitcol = 8) THEN   -- afastados o m?s inteiro
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (wretorna = 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                               ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                               ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                     EXECUTE STATEMENT wsqlaux INTO :wretorna;

                     IF (COALESCE(wretorna,0) = 0) THEN
                        wretorna = 1;
                     ELSE
                        wretorna = 0;
                   END
              END

         END

      IF (wretorna = 0) THEN
         BEGIN
           wpercinss = 0;
           IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wprivez = 0) or (wfilialatu <> wcodemp)) THEN
              BEGIN
                wsqlaux = 'select first 1 BDAUTEMP, BDEMPEMP, BDFUNEMP, BDCODFPASTERC, BDFAP from VRHF_BASE_TEMPGPS where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                EXECUTE STATEMENT wsqlaux INTO :wpercaut, :wpercemp, :wperccol, :wcodfpasterc, :wfap;

                IF (wcodfpasterc IS NOT NULL AND wcodfpasterc > 0) THEN
                   SELECT BDPERTERC FROM VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;

                wcodcnae = 0;
                wsqlaux = 'select first 1 COALESCE(BDCNAEPREP, BDCODCNAE, 0) ';

                IF (pragrupa = 1) THEN
                   wsqlaux = wsqlaux||', BDCODCENTROS ';
                ELSE
                   wsqlaux = wsqlaux||', 0 BDCODCENTROS ';

                wsqlaux = wsqlaux||', BDNOMEMP ';


                wsqlaux = wsqlaux||' from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                EXECUTE STATEMENT wsqlaux INTO :wcodcnae, :BDCODCENTRO, :wnomemp;
     
                IF (pragrupa = 0) THEN
                   BDCODCENTRO = wcentroatu;

                IF (wcodcnae IS NOT NULL AND wcodcnae > 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDTAXACNAE from TCNAE_REF where BDCODCNAE = '||wcodfpasterc||' and BDREFCNAE <= ' ||wrefatu||' order by BDREFCNAE desc ';
                     EXECUTE STATEMENT wsqlaux INTO :wpercrat;
                   END
              END

           wprivez = 1;

           IF ((wfap IS NULL) OR (wfap = 0)) THEN
              wfap = 1;

           IF (wcontrcol = 2) THEN
              wpercinss = wpercaut;
           ELSE
           IF (wcontrcol = 1) THEN
              wpercinss = wpercemp;
           ELSE
              wpercinss = wperccol;

           -- INSS Patronal
           BDINSSPATRONAL = 0;
           IF (BDREMUNERACAO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
              BEGIN
                BDINSSPATRONAL = CAST(((BDREMUNERACAO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDINSSPATRONAL;
              END

           -- Terceiros
           BDTERC = 0;
           IF (BDREMUNERACAO <> 0 AND wpercfpas IS NOT NULL AND wpercfpas > 0) THEN
              BEGIN
                BDTERC = CAST(((BDREMUNERACAO * wpercfpas / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDTERC;
              END

           -- RAT
           BDRAT = 0;
           IF (BDREMUNERACAO <> 0 AND wpercrat IS NOT NULL AND wpercrat > 0) THEN
              BEGIN
                wpercrat = CAST((wpercrat * wfap) AS NUMERIC(18, 4));
                BDRAT = CAST(((BDREMUNERACAO * wpercrat / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDRAT;
              END

           BDFGTS = 0;
           BDRATAPO = 0;
           BDPROV13    = 0;
           BDENCPROV13 = 0;
           BDPROVFER    = 0;
           BDENCPROVFER = 0;

           IF (wcontrcol = 0) THEN
              BEGIN
                wpercinss = 0;
                -- FGTS
                wsqlaux = 'select first 1 BDPERCFGTSCOL, BDPERCRATCOL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFCOL <= '||wrefatu||' order by BDREFCOL DESC ';
                EXECUTE STATEMENT wsqlaux INTO :wpercfgts, :wpercinss;

                IF (BDREMUNERACAO <> 0 AND wpercfgts IS NOT NULL AND wpercfgts > 0) THEN
                   BEGIN
                     BDFGTS = CAST(((BDREMUNERACAO * wpercfgts / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDFGTS;
                   END

                -- RAT APO
                IF (BDREMUNERACAO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
                   BEGIN
                     BDRATAPO = CAST(((BDREMUNERACAO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDRATAPO;
                   END
     
                -- Provis?o de 13?
                wsqlaux = 'select SUM(BDVLR13SALP13) BDVALPROV13, SUM(BDFGTSP13 + BDINSSP13 + BDTERCFPASP13 + BDCNAERATP13 + BDRATAPOP13 + BDPISP13) BDENCPROV13 '||
                          'from VRHF_EMP_TPROVISAO13 where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFP13 = '||wrefatu||' and BDLINHAP13 in (6,7,8,9,19) ';

                EXECUTE STATEMENT wsqlaux INTO :BDPROV13, :BDENCPROV13;
                IF (BDPROV13 IS NULL) THEN
                   BDPROV13 = 0;
                IF (BDENCPROV13 IS NULL) THEN
                   BDENCPROV13 = 0;

                -- Provis?o de F?rias
                wsqlaux = 'select SUM(BDFERIASPFER + BDUMTERCOPFER) BDVALPROVFER, SUM(BDFGTSPFER + BDINSSPFER + BDTERCFPASPFER + BDCNAERATPFER + BDRATAPOPFER + BDPISPFER) BDENCPROVFER '||
                          'from VRHF_EMP_TPROVISAOFERIAS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFPFER = '||wrefatu||' and BDLINHAPFER in (4,5,6,7,14) ';

                EXECUTE STATEMENT wsqlaux INTO :BDPROVFER, :BDENCPROVFER;
                IF (BDPROVFER IS NULL) THEN
                   BDPROVFER = 0;
                IF (BDENCPROVFER IS NULL) THEN
                   BDENCPROVFER = 0;

                -- Para apura??o do vale transporte o processo no sistema deve ser modificado para gravar os valores apurados
                --wsqlaux = 'select * from VRHF_EMP_TAPVALTRANS';


                -- Para apura??o do vale refei??o o processo no sistema deve ser modificado para gravar os valores apurados
                --wsqlaux = 'select * from VRHF_EMP_TAPVALREF';

              END

           IF (wtpccatu > 0 AND wcentroatu > 0) THEN
              BEGIN
                wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC '||
                          'left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) '||
                          'where CC.BDCODCENTRO = '||wcentroatu||' and CC.BDCODTPCC = '||wtpccatu;
                EXECUTE STATEMENT wsqlaux INTO :BDNOMTPCC;
              END
           ELSE
              BDNOMTPCC = wnomemp;

           BDCODSIT = 0;
           BDDESCSIT = '';
           if (BDREMUNERACAO + BDENCREMUNERACAO + BDBENIFICIOS + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER <= 0) then
              begin
                wsqlaux = 'select first 1 ST.BDCODSIT, PST.BDDESCSIT from VRH_EMP_TSITCOL ST '||
                          'join VRH_BASE_TPREPSIT PST on (PST.BDCODSIT = ST.BDCODSIT) '||
                          'where ST.BDCODEMP = '||wfilialatu||' and ST.BDCODCOL = '||wcolatu||
                          ' and SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                          ' and ((ST.BDDATAFIMSIT is null) or (SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
                execute statement wsqlaux into :BDCODSIT, :BDDESCSIT;
              end

           BDTOTAL = BDREMUNERACAO + BDENCREMUNERACAO + BDBENIFICIOS + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER;
           SUSPEND;
         END
    END
END
^

/* Alter (SP_VRH_TREEVIEW_CONS_ADSALARIO) */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_ADSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAAD DATE,
BDREF INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select ASAL.BDCODEMP, EMP.BDNOMEMP, '||
                'ASAL.BDCODCOL, COLCAD.BDNOMCOL, '||
                'ASAL.BDDATAAD, '||
                'ASAL.BDREFAD BDREF '||

         'from VRHF_EMP_TADSAL ASAL '||
         'JOIN vw_tempresas_ref_join EMP ON ASAL.BDCODEMP = EMP.BDCODEMP '||
         'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON ASAL.BDCODEMP = COLCAD.BDCODEMP and ASAL.BDCODCOL = COLCAD.BDCODCOL ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
         wwhere = 'where ';
       ELSE
         wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
         wwhere = 'where ';
       ELSE
         wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:prdata IS NOT NULL) THEN
     BEGIN
       /*IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere ||' and ASAL.BDREFAD = ' ||prdata||' ';
       ELSE
          wwhere = wwhere ||' and ASAL.BDREFAD <= ' ||prdata||' ';*/

       IF (:PRMESESANTERIORES = 0) THEN
         BEGIN
           IF (wwhere = '') THEN
             wwhere = 'where ';
           ELSE
             wwhere = wwhere||' and ';

           wwhere = wwhere ||'ASAL.BDREFAD = ' ||prdata||' ';
         END
       ELSE
         BEGIN
           IF (:PRMESESANTERIORES = 1) THEN
             BEGIN
               IF (wwhere = '') THEN
                 wwhere = 'where ';
               ELSE
                 wwhere = wwhere||' and ';

               wwhere = wwhere ||'substring(ASAL.BDREFAD from 1 for 4) = ' ||SUBSTRING(prdata FROM 1 FOR 4)||' ';
             END
         END
     END

  wsql = wsql||wwhere;

  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDDATAAD,
    :BDREF
  DO
  SUSPEND;
END
^

/* Alter (SP_VRH_TREEVIEW_CONS_CALCAUT) */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCAUT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FOL.BDCODEMP, EMP.BDNOMEMP, '||
                'FOL.BDCODTER, COL.BDNOMTER, '||
                'FOL.BDREFINSSSERV '||
         'from VRHF_BASE_CALC_TERC FOL, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VRH_BASE_TTERC COL ';


  wwhere = 'where EMP.BDCODEMP = FOL.BDCODEMP and COL.BDCODTER = FOL.BDCODTER ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  IF (:PRREFERENCIA IS NOT NULL AND :PRREFERENCIA <> 0)  THEN
     BEGIN
       /*IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere||' and FOL.BDREFINSSSERV = '||:PRREFERENCIA;
       ELSE
          wwhere = wwhere||'and FOL.BDREFINSSSERV <= '||:PRREFERENCIA;*/

       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere||' and FOL.BDREFINSSSERV = '||:PRREFERENCIA;
       ELSE
       IF (:PRMESESANTERIORES = 1) THEN
          wwhere = wwhere||' and substring(FOL.BDREFINSSSERV from 1 for 4) = '||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4);
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFFN
  DO
  SUSPEND;
END
^

/* Alter (SP_VRH_TREEVIEW_CONS_CALCINT) */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCINT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRPORCONTRATO SMALLINT,
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER,
BDCODCONTTI INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WPORCONTRATO varchar(100);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wporcontrato = ', CAST(null as INTEGER) BDCODCONTTI ';

  if (COALESCE(prporcontrato, 0) = 1) then
     wporcontrato = ',FOL.BDCODCONTTI ';

  wsql = 'select distinct FOL.BDCODEMP, EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, COLCAD.BDNOMCOL, '||
                'FOL.BDREFFN '||wporcontrato||
         'from ('||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN '||wporcontrato||
                'from VRHF_EMP_TFOLHAINT FOL ';

  wwhere = '';
  if (COALESCE(prcodemp,'') <> '') then
     begin
       wwhere = wwhere||prcodemp;

       if (COALESCE(prcodcol, '') <> '') then
          wwhere = wwhere||' and '||prcodcol;
     end

  if (COALESCE(prreferencia, 0) <> 0) then
     begin
       IF (:PRMESESANTERIORES = 0) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            wwhere = wwhere ||'FOL.BDREFFN = ' ||:PRREFERENCIA||' ';
          end
       ELSE
       IF (:PRMESESANTERIORES = 1) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
             wwhere = wwhere ||'substring(FOL.BDREFFN from 1 for 4) = ' ||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)||' ';
          end
     end

  if (wwhere <> '') then
     wsql = wsql||' where '||wwhere;

                wsql = wsql||
                'union all select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR '||wporcontrato||
                'from VRHF_EMP_TFOLHATOMINT FOL ';

  wwhere = '';
  if (COALESCE(prcodemp,'') <> '') then
     begin
       wwhere = wwhere||prcodemp;

       if (COALESCE(prcodcol, '') <> '') then
          wwhere = wwhere||' and '||prcodcol;
     end

  if (COALESCE(prreferencia, 0) <> 0) then
     begin
       IF (:PRMESESANTERIORES = 0) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            wwhere = wwhere ||'FOL.BDREFTOMADOR = ' ||:PRREFERENCIA||' ';
          end
       ELSE
       IF (:PRMESESANTERIORES = 1) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            wwhere = wwhere ||'substring(FOL.BDREFTOMADOR from 1 for 4) = ' ||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)||' ';
          end
     end

  if (wwhere <> '') then
     wsql = wsql||' where '||wwhere;

  wsql = wsql||
         ') FOL '||
         'left outer join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';


  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFFN,
    :BDCODCONTTI
  DO
  SUSPEND;
END
^

/* Alter (SP_VRH_TREEVIEW_CONS_CALCULO) */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FOL.BDCODEMP, EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, COLCAD.BDNOMCOL, '||
                'FOL.BDREFFN '||
         'from VW_UNION_FN_TOMADOR_REF FOL, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COLCAD ';


  wwhere = 'where EMP.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  IF (:PRREFERENCIA IS NOT NULL AND :PRREFERENCIA <> 0)  THEN
     BEGIN
       /*IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere||' and FOL.BDREFFN = '||:PRREFERENCIA;
       ELSE
          wwhere = wwhere||' and FOL.BDREFFN <= '||:PRREFERENCIA;*/

       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere ||' and FOL.BDREFFN = ' ||:PRREFERENCIA||' ';
       ELSE
          IF (:PRMESESANTERIORES = 1) THEN
             wwhere = wwhere ||' and substring(FOL.BDREFFN from 1 for 4) = ' ||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)||' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFFN
  DO
  SUSPEND;
END
^

/* Alter (SP_VRH_TREEVIEW_CONS_FOLAVUL) */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_FOLAVUL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAFA DATE,
BDREF INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select FA.BDCODEMP, EMP.BDNOMEMP, '||
                'FA.BDCODCOL, COLCAD.BDNOMCOL, '||
                'FA.BDDATAFA, '||
                'FA.BDREF '||

         'from VRHF_EMP_TFOLHAAVULSA FA, '||
         'vw_tempresas_ref_join EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COLCAD ';

  wwhere = ' where FA.BDCODEMP = EMP.BDCODEMP and FA.BDCODEMP = COLCAD.BDCODEMP and FA.BDCODCOL = COLCAD.BDCODCOL ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' and '||:PRCODCOL;
     END

  IF (:prdata IS NOT NULL) THEN
     BEGIN
       /*IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere ||' and FA.BDREF = ' ||prdata||' ';
       ELSE
          wwhere = wwhere ||' and FA.BDREF <= ' ||prdata||' '; */

       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere ||' and FA.BDREF = ' ||prdata||' ';
       ELSE
          IF (:PRMESESANTERIORES = 1) THEN
             wwhere = wwhere ||' and substring(FA.BDREF from 1 for 4) = ' ||SUBSTRING(prdata FROM 1 FOR 4)||' ';
     END

  wsql = wsql||wwhere;

  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDDATAFA,
    :BDREF
  DO
  SUSPEND;
END
^

/* Alter (SP_VRH_VAL_RAIS_FF) */
ALTER PROCEDURE SP_VRH_VAL_RAIS_FF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQLCOL VARCHAR(32000);
DECLARE VARIABLE WSQLFF VARCHAR(32000);
DECLARE VARIABLE WCOL INTEGER;
DECLARE VARIABLE WEMP INTEGER;
BEGIN
  /* Procedure Text */
--  suspend;
--  wsqlcol = 'select bdcodemp,bdcodcol from sp_somente_ativos('||''''||'01/01/'||prano||''''||','||''''||'12/31/'||prano||''''||')';
  wsqlcol = 'select col.bdcodemp,col.bdcodcol from vrh_emp_tcolcon col '||
            ' join sp_somente_ativos('||''''||'01/01/'||prano||''''||','||''''||'12/31/'||prano||''''||') filtro on (filtro.bdcodemp = col.bdcodemp and filtro.bdcodcol = col.bdcodcol)';

  IF ((premp <> '') AND (premp IS NOT NULL)) THEN
     BEGIN
       wsqlcol = wsqlcol||' where '||premp;

       IF ((prcol <> '') AND (prcol IS NOT NULL)) THEN
          wsqlcol = wsqlcol||' and '||prcol;
     END

  FOR EXECUTE STATEMENT wsqlcol INTO wemp,wcol DO
    BEGIN
      FOR SELECT BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade FROM sp_val_rais_ff(:wemp,:wcol,:prano)
          INTO BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade DO
          SUSPEND;
    END

END
^

/* Alter (SP_VRH_VERBAS) */
ALTER PROCEDURE SP_VRH_VERBAS(PRANOMES INTEGER,
PRNIVELCLASSIFICACAO SMALLINT = 0)
 RETURNS(BDCODVER INTEGER NOT NULL,
BDREFVER INTEGER NOT NULL,
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(5000),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDRENDISENTOIRVER VARCHAR(5),
BDFORMINTVER VARCHAR(5000),
BDSIMPLESNACIONAL VARCHAR(5),
BDBASE13HN VARCHAR(5),
BDBASEFERHN VARCHAR(5),
BDBASEAVHN VARCHAR(5),
BDPAGAESTOUROVER VARCHAR(5),
BDGARANTIAMINVER VARCHAR(5),
BDINDRESC VARCHAR(5),
BDNAOCONVHORASVER DM_BOOLEAN,
BDAPEVER VARCHAR(20) NOT NULL,
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDREADONLY VARCHAR(5),
BDORDEMVER INTEGER,
BDINATIVAVER VARCHAR(5),
BDSITVER INTEGER,
BDBASESALRAIS VARCHAR(5),
BDSITMATVER VARCHAR(5),
BDSITDOEVER VARCHAR(5),
BDSITACITRABVER VARCHAR(5),
BDSITMILITARVER VARCHAR(5),
BDSITMATEMPVER VARCHAR(5),
BDSITACITRAB15VER VARCHAR(5),
BDSITDOETRABVER VARCHAR(5),
BDSITLICVENCVER VARCHAR(5),
BDSITDOE15VER VARCHAR(5),
BDSITSINDICALVER VARCHAR(5),
BDSITAPOINVVER VARCHAR(5),
BDSITOUTRASVER VARCHAR(5),
BDTIPOVER INTEGER,
BDORDEMTIPOCODVER INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN
  wsql = 'select '||
           'VERREF.BDCODVER,'||
           'VERREF.BDREFVER,'||
           'VERREF.BDTIPOCODVER,'||
           'VERREF.BDINSSVER,'||
           'VERREF.BDFGTSVER,'||
           'VERREF.BDIRVER,'||
           'VERREF.BDTIPOREFVER,'||
           'VERREF.BDBASESFVER,'||
           'VERREF.BDPISVER,'||
           'VERREF.BDBASEHEVER,'||
           'VERREF.BDBASEMAIORVER,'||
           'VERREF.BDRAISVER,'||
           'VERREF.BDBASEGPSVER,'||
           'VERREF.BDMENORESVER,'||
           'VERREF.BDPROPVER,'||
           'VERREF.BDBASEVTVER,'||
           'VERREF.BDREEMBGPSVER,'||
           'VERREF.BDHEVER,'||
           'VERREF.BDGRAVAFICHAHNVER,'||
           'VERREF.BDCCPRINCIPALVER,'||
           'VERREF.BDFORMREFVER,'||
           'VERREF.BDFORMVALVER,'||
           'VERREF.BDBASEDSRHEVER,'||
           'VERREF.BDBASEDSRRVVER,'||
           'VERREF.BDFORMREFAUXVER,'||
           'VERREF.BDDEDFORMREFAUXVER,'||
           'VERREF.BDDEDFORMREFVER,'||
           'VERREF.BDDEDFORMVALVER,'||
           'VERREF.BDRENDISENTOIRVER,'||
           'VERREF.BDFORMINTVER,'||
           'VERREF.BDSIMPLESNACIONAL,'||
           'VERREF.BDBASE13HN,'||
           'VERREF.BDBASEFERHN,'||
           'VERREF.BDBASEAVHN,'||
           'VERREF.BDPAGAESTOUROVER,'||
           'VERREF.BDGARANTIAMINVER,'||
           'VERREF.BDINDRESC,'||
           'VERREF.BDNAOCONVHORASVER,'||
           'VER.BDAPEVER,'||
           'VER.BDDESCVER,'||
           'VER.BDDESCREDVER,'||
           'VER.BDCLAVER,'||
           'VER.BDREADONLY,'||
           'VER.BDORDEMVER,'||
           'VER.BDINATIVAVER,'||
           'VER.BDSITVER,'||
           'VER.BDBASESALRAIS,'||
           'VER.BDSITMATVER,'||
           'VER.BDSITDOEVER,'||
           'VER.BDSITACITRABVER,'||
           'VER.BDSITMILITARVER,'||
           'VER.BDSITMATEMPVER,'||
           'VER.BDSITACITRAB15VER,'||
           'VER.BDSITDOETRABVER,'||
           'VER.BDSITLICVENCVER,'||
           'VER.BDSITDOE15VER,'||
           'VER.BDSITSINDICALVER,'||
           'VER.BDSITAPOINVVER,'||
           'VER.BDSITOUTRASVER,'||
           'VER.BDTIPOVER,'||
           'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else COALESCE(VERREF.BDTIPOCODVER, 0) END BDORDEMTIPOCODVER '||
         'from VRH_BASE_TVERBAS_REF VERREF '||
         'join(select BDCODVER, max(BDREFVER) BDREFVER '||
              'from VRH_BASE_TVERBAS_REF '||
              'where BDREFVER <= '||:pranomes||' '||
              'group by BDCODVER) REF on (REF.BDCODVER = VERREF.BDCODVER and REF.BDREFVER = VERREF.BDREFVER) '||
         'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = VERREF.BDCODVER)';

  --  Somente anal?ticas
  IF (prnivelclassificacao = 1) THEN
    wsql = wsql||' where STRLEN(VER.BDCLAVER) > 9';
  ELSE
  -- Somente t?tulo
  IF (prnivelclassificacao = 2) THEN
    wsql = wsql||' where STRLEN(VER.BDCLAVER) <= 9';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODVER,
    :BDREFVER,
    :BDTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDMENORESVER,
    :BDPROPVER,
    :BDBASEVTVER,
    :BDREEMBGPSVER,
    :BDHEVER,
    :BDGRAVAFICHAHNVER,
    :BDCCPRINCIPALVER,
    :BDFORMREFVER,
    :BDFORMVALVER,
    :BDBASEDSRHEVER,
    :BDBASEDSRRVVER,
    :BDFORMREFAUXVER,
    :BDDEDFORMREFAUXVER,
    :BDDEDFORMREFVER,
    :BDDEDFORMVALVER,
    :BDRENDISENTOIRVER,
    :BDFORMINTVER,
    :BDSIMPLESNACIONAL,
    :BDBASE13HN,
    :BDBASEFERHN,
    :BDBASEAVHN,
    :BDPAGAESTOUROVER,
    :BDGARANTIAMINVER,
    :BDINDRESC,
    :BDNAOCONVHORASVER,
    :BDAPEVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDCLAVER,
    :BDREADONLY,
    :BDORDEMVER,
    :BDINATIVAVER,
    :BDSITVER,
    :BDBASESALRAIS,
    :BDSITMATVER,
    :BDSITDOEVER,
    :BDSITACITRABVER,
    :BDSITMILITARVER,
    :BDSITMATEMPVER,
    :BDSITACITRAB15VER,
    :BDSITDOETRABVER,
    :BDSITLICVENCVER,
    :BDSITDOE15VER,
    :BDSITSINDICALVER,
    :BDSITAPOINVVER,
    :BDSITOUTRASVER,
    :BDTIPOVER,
    :BDORDEMTIPOCODVER
  DO
    SUSPEND;
END
^

/* Alter (SP_VRHF_13SALARIO_ANO_RESC) */
ALTER PROCEDURE SP_VRHF_13SALARIO_ANO_RESC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRMES INTEGER,
PRANO INTEGER,
PRPREVIA SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDVAL13 NUMERIC(15,6),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDVALORIR13 NUMERIC(15,6),
BDBRAIS13 NUMERIC(15,6),
BDDEP13 NUMERIC(15,6),
BDSALBASE13 NUMERIC(15,6),
BDARREPROV13 NUMERIC(15,6),
BDARREDESC13 NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDVALORINSS13 NUMERIC(15,6),
BDANO13 INTEGER,
BDESTPROV13 NUMERIC(15,6),
BDSALMATEMP13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WANOANT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQLTRANS VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  --Sol. 17607 - Bruno L. R. - 12/07/2017 - In?cio
  wsqltrans = 'select X.BDCODEMP, '||
                'X.BDCODCOL, '||
                'Z.BDREF13, '||
                'Z.BDVAL13, '||
                'Z.BDMESESPROP13, '||
                'Z.BDBASEIR13, '||
                'Z.BDFGTS13, '||
                'Z.BDFGTSCS13, '||
                'Z.BDBASEFGTS13, '||
                'Z.BDDATABAIXA13, '||
                'Z.BDREFBAIXA13, '||
                'Z.BDPERCIR13, '||
                'Z.BDVALORIR13, '||
                'Z.BDBRAIS13, '||
                'Z.BDDEP13, '||
                'Z.BDSALBASE13, '||
                'Z.BDARREPROV13, '||
                'Z.BDARREDESC13, '||
                'Z.BDBASEINSS13, '||
                'Z.BDPERCINSS13, '||
                'Z.BDVALORINSS13, '||
                'Z.BDANO13, '||
                'Z.BDESTPROV13, '||
                'Z.BDSALMATEMP13 '||
         'from VRHF_EMP_T13SAL Z '||
         'join (select trans.bdcodemporig, trans.bdcodcolorig, trans.bdcodempdest bdcodemp, trans.bdcodcoldest bdcodcol '||
         'from vrh_emp_ttranscol trans ) x on (z.bdcodemp = x.BDCODEMPORIG and z.bdcodcol = x.BDCODCOLORIG) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wwhere = wwhere||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wwhere = wwhere||' and '||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'Z.BDANO13 = '||prano;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsqltrans = wsqltrans||wwhere;

  --Sol. 17607 - Bruno L. R. - 12/07/2017 - Fim

  wwhere = '';

  wsql = 'select X.BDCODEMP, '||
                'X.BDCODCOL, '||
                'X.BDREF13, '||
                'X.BDVAL13, '||
                'X.BDMESESPROP13, '||
                'X.BDBASEIR13, '||
                'X.BDFGTS13, '||
                'X.BDFGTSCS13, '||
                'X.BDBASEFGTS13, '||
                'X.BDDATABAIXA13, '||
                'X.BDREFBAIXA13, '||
                'X.BDPERCIR13, '||
                'X.BDVALORIR13, '||
                'X.BDBRAIS13, '||
                'X.BDDEP13, '||
                'X.BDSALBASE13, '||
                'X.BDARREPROV13, '||
                'X.BDARREDESC13, '||
                'X.BDBASEINSS13, '||
                'X.BDPERCINSS13, '||
                'X.BDVALORINSS13, '||
                'X.BDANO13, '||
                'X.BDESTPROV13, '||
                'X.BDSALMATEMP13 '||
         'from VRHF_EMP_T13SAL X ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       IF (prmes IS NOT NULL AND prmes <> 0) THEN
          BEGIN
            IF (prmes = 1) THEN
               BEGIN
                 wanoant = prano - 1;
                 IF (prprevia = 1) THEN
                    wwhere = wwhere||'(X.BDANO13 = '||wanoant||' or '||
                                      '(X.BDANO13 = '||prano||
                                      ' and exists('||
                                                   'select Y.BDCODEMP, Y.BDCODCOL '||
                                                   'from VRH_EMP_TRESCISAO_PREVIA Y '||
                                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and EXTRACT(MONTH from Y.BDDATARESCISAOPREV) = '||prmes||
                                                      ' and EXTRACT(YEAR from Y.BDDATARESCISAOPREV) = '||prano||')) '||
                                     ') ';
                 ELSE
                    wwhere = wwhere||'(X.BDANO13 = '||wanoant||' or '||
                                      '(X.BDANO13 = '||prano||
                                      ' and exists('||
                                                   'select Y.BDCODEMP, Y.BDCODCOL '||
                                                   'from VRH_EMP_TRESCISAO Y '||
                                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((EXTRACT(MONTH from Y.BDDATARESCISAO) = '||prmes||
                                                   ' and EXTRACT(YEAR from Y.BDDATARESCISAO) = '||prano||') or (EXTRACT(MONTH from Y.BDPROJECAOAVISO) = '||prmes||
                                                   ' and EXTRACT(YEAR from Y.BDPROJECAOAVISO) = '||prano||'))))) ';
               END
            ELSE
               BEGIN
                 IF (prprevia = 1) THEN
                    wwhere = wwhere||'(X.BDANO13 = '||prano||
                             ' and exists('||
                                          'select Y.BDCODEMP, Y.BDCODCOL '||
                                          'from VRH_EMP_TRESCISAO_PREVIA Y '||
                                          'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and EXTRACT(MONTH from Y.BDDATARESCISAOPREV) = '||prmes||
                                          ' and EXTRACT(YEAR from Y.BDDATARESCISAOPREV) = '||prano||')) ';
                 ELSE
                    wwhere = wwhere||'(X.BDANO13 = '||prano||
                             ' and exists('||
                                          'select Y.BDCODEMP, Y.BDCODCOL '||
                                          'from VRH_EMP_TRESCISAO Y '||
                                          'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((EXTRACT(MONTH from Y.BDDATARESCISAO) = '||prmes||
                                          ' and EXTRACT(YEAR from Y.BDDATARESCISAO) = '||prano||') or (EXTRACT(MONTH from Y.BDPROJECAOAVISO) = '||prmes||
                                          ' and EXTRACT(YEAR from Y.BDPROJECAOAVISO) = '||prano||')))) ';
               END
          END
       ELSE
          BEGIN
            IF (prprevia = 1) THEN
               wwhere = wwhere||'(X.BDANO13 = '||prano||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO_PREVIA Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and EXTRACT(YEAR from Y.BDDATARESCISAOPREV) = '||prano||')) ';
            ELSE
               wwhere = wwhere||'(X.BDANO13 = '||prano||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and EXTRACT(YEAR from Y.BDDATARESCISAO) = '||prano||')) ';
          END
     END
  ELSE
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       IF (prprevia = 1) THEN
          wwhere = wwhere||'(exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO_PREVIA Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)) ';
       ELSE
          wwhere = wwhere||'(exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)) ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  --Sol. 17607 - Bruno L. R. - 12/07/2017 - In?cio
  wsql = wsql||wwhere;
  wsql = wsql||' union all ';
  wsql = wsql||WSQLTRANS;
  --Sol. 17607 - Bruno L. R. - 12/07/2017 - Fim

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :BDCODCOL,
    :BDREF13,
    :BDVAL13,
    :BDMESESPROP13,
    :BDBASEIR13,
    :BDFGTS13,
    :BDFGTSCS13,
    :BDBASEFGTS13,
    :BDDATABAIXA13,
    :BDREFBAIXA13,
    :BDPERCIR13,
    :BDVALORIR13,
    :BDBRAIS13,
    :BDDEP13,
    :BDSALBASE13,
    :BDARREPROV13,
    :BDARREDESC13,
    :BDBASEINSS13,
    :BDPERCINSS13,
    :BDVALORINSS13,
    :BDANO13,
    :BDESTPROV13,
    :BDSALMATEMP13
  DO
  SUSPEND;
END
^

/* Alter (SP_VRHF_13SALARIO_ANO_SIT) */
ALTER PROCEDURE SP_VRHF_13SALARIO_ANO_SIT(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDANO13 INTEGER,
BDBSALMAT13 NUMERIC(18,6),
BDBACITRAB13 NUMERIC(18,6),
BDBAUXDOE13 NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF13 INTEGER;
DECLARE VARIABLE WVALVER NUMERIC(18,6);
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WBSALMAT NUMERIC(18,6);
DECLARE VARIABLE WBACITRA NUMERIC(18,6);
DECLARE VARIABLE WBAUXDOE NUMERIC(18,6);
BEGIN
  wsql = 'select S13.BDCODEMP, '||
                'S13.BDCODCOL, '||
                'S13.BDREF13, '||
                'S13.BDVALV13, '||
                'VER.BDCLAVER, '||
                'VER.BDTIPOCODVER '||
         'from VRHF_EMP_TVERBA13 S13 '||
         'join VW_TVERBAS_REF VER on (VER.BDCODVER = S13.BDCODVER) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SUBSTRING(S13.BDREF13 FROM 1 FOR 4) = '||prano;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wempatu = 0;
  wcolatu = 0;
  wbsalmat = 0;
  wbacitra = 0;
  wbauxdoe = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    :wcodemp,
    :wcodcol,
    :wref13,
    :wvalver,
    :wclaver,
    :wtipocodver
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol))  THEN
         BEGIN
           BDCODEMP = wempatu;
           BDCODCOL = wcolatu;
           BDREF13 = wref13;
           BDANO13 = CAST((SUBSTRING(:wref13 FROM 1 FOR 4)) AS INTEGER);
           BDBSALMAT13 = wbsalmat;
           BDBACITRAB13 = wbacitra;
           BDBAUXDOE13 = wbauxdoe;

           SUSPEND;

           wempatu = wcodemp;
           wcolatu = wcodcol;
           wbsalmat = 0;
           wbacitra = 0;
           wbauxdoe = 0;
         END

      -- Sal?rio maternidade no 13?
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '5.010') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbsalmat = wbsalmat + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbsalmat = wbsalmat - wvalver;
         END

      -- Acidente de trabalho no 13?
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '5.012') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbacitra = wbacitra + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbacitra = wbacitra - wvalver;
         END

      -- Aux?lio doen?a
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '5.014') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbauxdoe = wbauxdoe + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbauxdoe = wbauxdoe - wvalver;
         END
    END

  IF ((wempatu <> 0) AND (wcolatu <> 0))  THEN
     BEGIN
       BDCODEMP = wempatu;
       BDCODCOL = wcolatu;
       BDREF13 = wref13;
       BDANO13 = CAST((SUBSTRING(:wref13 FROM 1 FOR 4)) AS INTEGER);
       BDBSALMAT13 = wbsalmat;
       BDBACITRAB13 = wbacitra;
       BDBAUXDOE13 = wbauxdoe;

       SUSPEND;

     END
END
^

/* Alter (SP_VRHF_AGRUPA_VERBAS_FT) */
ALTER PROCEDURE SP_VRHF_AGRUPA_VERBAS_FT(PRAGRUPADOR INTEGER,
PRFILTRO VARCHAR(32700) = null,
PRFILTROCC VARCHAR(20000) = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFTOMADOR INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCODVER INTEGER,
BDREFVFT_SUM NUMERIC(15,6),
BDREFVFT_MAX NUMERIC(15,6),
BDREFAUXVFT NUMERIC(15,6),
BDVALVFT NUMERIC(15,6),
BDIGNREFVFT DM_BOOLEAN,
BDIGNREFAVFT DM_BOOLEAN,
BDIGNVALVFT DM_BOOLEAN,
BDTIPOREFVER INTEGER,
BDCODCONTTI INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFTOMADOR integer;
declare variable WORDEM integer;
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
declare variable WCODVER integer;
declare variable WREFVFT numeric(15,6);
declare variable WREFAUXVFT numeric(15,6);
declare variable WVALVFT numeric(15,6);
declare variable WIGNREFFT DM_BOOLEAN;
declare variable WIGNREFAFT DM_BOOLEAN;
declare variable WIGNVALFT DM_BOOLEAN;
declare variable WHOREMP DM_BOOLEAN;
declare variable WTIPOREFVER integer;
declare variable WVERATU integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WCENTROATU integer;
declare variable WTPCCATU integer;
declare variable WREFVTFANT_MAX numeric(15,6);
declare variable WREFVTFANT_SUM numeric(15,6);
declare variable WREFAUXVFTANT numeric(15,6);
declare variable WVALVFTANT numeric(15,6);
declare variable WIGNREFFTANT DM_BOOLEAN;
declare variable WIGNREFAFTANT DM_BOOLEAN;
declare variable WIGNVALFTANT DM_BOOLEAN;
declare variable WFRACAO numeric(15,6);
declare variable WSQLVER varchar(1000);
declare variable WCODCONTTI integer;
declare variable WCONTTIATU integer;
BEGIN
  IF (pragrupador IS NOT NULL AND pragrupador IN (2,3,4)) THEN
     BEGIN
       wordem = NULL;
       wsql = 'select BDCODVER, BDCODEMP, BDCODCOL, BDREFTOMADOR, BDREFVFT, BDREFAUXVFT, BDVALVFT, BDIGNREFVFT, BDIGNREFAVFT, BDIGNVALVFT, BDCODCENTRO, BDCODTPCC, BDREFHOREMP, BDCODCONTTI '||
              ' from (select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT,'||
              'COLCON.BDVALVFT, COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT,';

       IF (pragrupador = 2) THEN
          wsql = wsql||'case when COALESCE(pf.bdCODTPCC,0) = 0 then 0 else COALESCE(pf.bdCodCentro,0) end BDCODCENTRO, COALESCE(pf.bdCODTPCC,0) BDCODTPCC, ';
       ELSE
          wsql = wsql||'case when COALESCE(toma.bdCODTPCC,0) = 0 then 0 else COALESCE(toma.bdCodCentro,0) end BDCODCENTRO, COALESCE(toma.bdCODTPCC,0) BDCODTPCC, ';

       wsql = wsql||
              'EMPCALC.BDREFHOREMP, 0 BDCODCONTTI '||
              'from vrhf_emp_tverbatomador COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) ';

       IF (pragrupador = 3) THEN
          wsql = wsql||'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';
       ELSE
       IF (pragrupador = 4) THEN
          wsql = wsql||'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';

       wsql = wsql||
              'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = COLCON.BDCODEMP) ';

       IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
          wsql = wsql||prfiltro;

       wsql = wsql||' union all select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT,'||
              'COLCON.BDVALVFT, COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT,';

       IF (pragrupador = 2) THEN
          wsql = wsql||'case when COALESCE(pf.bdCODTPCC,0) = 0 then 0 else COALESCE(pf.bdCodCentro,0) end BDCODCENTRO, COALESCE(pf.bdCODTPCC,0) BDCODTPCC, ';
       ELSE
          wsql = wsql||'case when COALESCE(toma.bdCODTPCC,0) = 0 then 0 else COALESCE(toma.bdCodCentro,0) end BDCODCENTRO, COALESCE(toma.bdCODTPCC,0) BDCODTPCC, ';

       wsql = wsql||
              'EMPCALC.BDREFHOREMP, COLCON.BDCODCONTTI '||
              'from vrhf_emp_tverbatomint COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) ';

       IF (pragrupador = 3) THEN
          wsql = wsql||'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';
       ELSE
       IF (pragrupador = 4) THEN
          wsql = wsql||'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';

       wsql = wsql||
              'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = COLCON.BDCODEMP) ';

       IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
          wsql = wsql||prfiltro;


       wsql = wsql||') COLCON ';
       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||' where '||prfiltrocc;

       wsql = wsql||' order by BDCODEMP,BDCODCOL,BDREFTOMADOR,BDCODCONTTI,BDCODCENTRO,BDCODTPCC,BDCODVER ';

       wveratu        = 0;
       wempatu        = 0;
       wcolatu        = 0;
       wrefatu        = 0;
       wcentroatu     = -1;
       wtpccatu       = -1;
       wrefvtfant_sum = 0;
       wrefvtfant_max = 0;
       wrefauxvftant  = 0;
       wvalvftant     = 0;
       wignrefaftant  = '';
       wignrefftant   = '';
       wignvalftant   = '';
       wconttiatu     = -1;

       FOR EXECUTE STATEMENT wsql INTO :wcodver,:wcodemp,:wcodcol,:wreftomador,:wrefvft,:wrefauxvft,:wvalvft,:wignrefft,:wignrefaft,:wignvalft,:wcodcentro,:wcodtpcc,:whoremp,:wcodcontti DO
         BEGIN
           IF (wveratu = 0) THEN
              wveratu = wcodver;
           IF (wempatu = 0) THEN
              wempatu = wcodemp;
           IF (wcolatu = 0) THEN
              wcolatu = wcodcol;
           IF (wrefatu = 0) THEN
              wrefatu = wreftomador;
           IF (wcentroatu = -1) THEN
              wcentroatu = wcodcentro;
           IF (wtpccatu = -1) THEN
              wtpccatu = wcodtpcc;
           IF (wconttiatu = -1) THEN
              wconttiatu = wcodcontti;

           IF ((wveratu <> wcodver) OR (wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreftomador) OR (wcentroatu <> wcodcentro) OR (wtpccatu <> wcodtpcc) OR (wconttiatu <> wcodcontti)) THEN
              BEGIN
                BDCODVER     = wveratu;
                BDCODEMP     = wempatu;
                BDCODCOL     = wcolatu;
                BDREFTOMADOR = wrefatu;

                if (wconttiatu = 0) then
                   BDCODCONTTI = NULL;
                else
                   BDCODCONTTI = wconttiatu;

                IF (wcentroatu = 0) THEN
                   BDCODCENTRO = NULL;
                ELSE
                   BDCODCENTRO  = wcentroatu;

                IF (wtpccatu = 0) THEN
                   BDCODTPCC = NULL;
                ELSE
                   BDCODTPCC    = wtpccatu;

                BDORDEM      = wordem;
                BDREFVFT_SUM = wrefvtfant_sum;
                BDREFVFT_MAX = wrefvtfant_max;
                BDREFAUXVFT  = wrefauxvftant;
                BDVALVFT     = wvalvftant;
                BDIGNREFAVFT = wignrefaftant;
                BDIGNREFVFT  = wignrefftant;
                BDIGNVALVFT  = wignvalftant;
                BDTIPOREFVER = wtiporefver;
                SUSPEND;
                wveratu        = wcodver;
                wempatu        = wcodemp;
                wcolatu        = wcodcol;
                wrefatu        = wreftomador;
                wcentroatu     = wcodcentro;
                wtpccatu       = wcodtpcc;
                wconttiatu     = wcodcontti;
                wrefvtfant_sum = 0;
                wrefvtfant_max = 0;
                wrefauxvftant  = 0;
                wvalvftant     = 0;
                wignrefaftant  = '';
                wignrefftant   = '';
                wignvalftant   = '';
              END

           wignrefaftant = wignrefaft;
           wignrefftant  = wignrefft;
           wignvalftant  = wignvalft;

           wvalvftant    = wvalvftant + wvalvft;
           wrefauxvftant = wrefauxvftant + wrefauxvft;

           IF (wrefvtfant_max < wrefvft) THEN
              wrefvtfant_max = wrefvft;

           wsqlver = 'select first 1 COALESCE(BDTIPOREFVER,0) from VRH_BASE_TVERBAS_REF where BDCODVER = '||wveratu||' and BDREFVER <= '||wrefatu||' order by BDREFVER DESC';
           EXECUTE STATEMENT wsqlver INTO :wtiporefver;
           -- Converte horas e tipo de refer?ncia da verba ? Horas
           IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvft > 0) THEN
              BEGIN
                -- Converte a referencia atual de Horas para Valor
                wfracao      = wrefvft - CAST((wrefvft - 0.5) AS INTEGER);
                IF (wrefvft > 0) THEN
                   BEGIN
                     wrefvft = wrefvft - wfracao;
                     wfracao = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                     wrefvft = wrefvft + wfracao;
                   END
     
                -- Converte a soma atual de Horas para Valor
                wfracao  = wrefvtfant_sum - CAST((wrefvtfant_sum - 0.5) AS INTEGER);
                IF (wrefvtfant_sum > 0) THEN
                   BEGIN
                     wrefvtfant_sum = wrefvtfant_sum - wfracao;
                     wfracao        = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                     wrefvtfant_sum = wrefvtfant_sum + wfracao;
                   END
     
                -- Soma os VALORES
                wrefvtfant_sum = wrefvtfant_sum +  wrefvft;
     
                -- Converte o resultado novamente em Horas
                wfracao  = wrefvtfant_sum - CAST((wrefvtfant_sum - 0.5) AS INTEGER);
                IF (wrefvtfant_sum > 0) THEN
                   BEGIN
                     wrefvtfant_sum = wrefvtfant_sum - wfracao;
                     wfracao        = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                     wrefvtfant_sum = wrefvtfant_sum + wfracao;
                   END
              END
           ELSE
              wrefvtfant_sum = wrefvtfant_sum + wrefvft;

         END

       IF ((wveratu <> 0) AND (wempatu <> 0) AND (wcolatu <> 0) AND (wrefatu <> 0) AND (wcentroatu <> -1) AND (wtpccatu <> -1) AND (wconttiatu <> -1)) THEN
          BEGIN
            BDCODVER     = wveratu;
            BDCODEMP     = wempatu;
            BDCODCOL     = wcolatu;
            BDREFTOMADOR = wrefatu;

            if (wconttiatu = 0) then
               BDCODCONTTI  = NULL;
            else
               BDCODCONTTI  = wconttiatu;

            IF (wcentroatu = 0) THEN
               BDCODCENTRO = NULL;
            ELSE
               BDCODCENTRO  = wcentroatu;

            IF (wtpccatu = 0) THEN
               BDCODTPCC = NULL;
            ELSE
               BDCODTPCC    = wtpccatu;

            BDORDEM      = NULL;
            BDREFVFT_SUM = wrefvtfant_sum;
            BDREFVFT_MAX = wrefvtfant_max;
            BDREFAUXVFT  = wrefauxvftant;
            BDVALVFT     = wvalvftant;
            BDIGNREFAVFT = wignrefaftant;
            BDIGNREFVFT  = wignrefftant;
            BDIGNVALVFT  = wignvalftant;
            BDTIPOREFVER = wtiporefver;
            SUSPEND;
          END
     END
  ELSE
  IF (pragrupador IS NOT NULL AND pragrupador = 1) THEN
     BEGIN
       wordem = NULL;
       wsql = 'select * from (select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT,'||
              'COLCON.BDVALVFT, COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT,';

       wsql = wsql||
              'EMPCALC.BDREFHOREMP, 0 BDCODCONTTI ';

       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||',COALESCE(pf.bdCodCentro,0) BDCODCENTRO, COALESCE(pf.bdCODTPCC,0) BDCODTPCC ';
       ELSE
          wsql = wsql||',cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';

       wsql = wsql||
              'from vrhf_emp_tverbatomador COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';

       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) ';

       wsql = wsql||
              'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = COLCON.BDCODEMP) ';

       IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
          wsql = wsql||prfiltro;


       wsql = wsql||' union all select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT,'||
              'COLCON.BDVALVFT, COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT,';

       wsql = wsql||
              'EMPCALC.BDREFHOREMP, COLCON.BDCODCONTTI ';

       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||',COALESCE(pf.bdCodCentro,0) BDCODCENTRO, COALESCE(pf.bdCODTPCC,0) BDCODTPCC ';
       ELSE
          wsql = wsql||',cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';

       wsql = wsql||
              'from vrhf_emp_tverbatomint COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';

       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) ';

       wsql = wsql||
              'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = COLCON.BDCODEMP) ';

       IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
          wsql = wsql||prfiltro;

       wsql = wsql||') COLCON ';
       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||' where '||prfiltrocc;

       wsql = wsql||' order by BDCODEMP,BDCODCOL,BDREFTOMADOR,BDCODCONTTI,BDCODVER ';

       wveratu        = 0;
       wempatu        = 0;
       wcolatu        = 0;
       wrefatu        = 0;
       wrefvtfant_sum = 0;
       wrefvtfant_max = 0;
       wrefauxvftant  = 0;
       wvalvftant     = 0;
       wignrefaftant  = '';
       wignrefftant   = '';
       wignvalftant   = '';
       wconttiatu     = -1;

       FOR EXECUTE STATEMENT wsql INTO :wcodver,:wcodemp,:wcodcol,:wreftomador,:wrefvft,:wrefauxvft,:wvalvft,:wignrefft,:wignrefaft,:wignvalft,:whoremp,:wcodcontti, :wcodcentro, :wcodtpcc DO
         BEGIN
           IF (wveratu = 0) THEN
              wveratu = wcodver;
           IF (wempatu = 0) THEN
              wempatu = wcodemp;
           IF (wcolatu = 0) THEN
              wcolatu = wcodcol;
           IF (wrefatu = 0) THEN
              wrefatu = wreftomador;
           if (wconttiatu = -1) then
              wconttiatu = wcodcontti;

           IF ((wveratu <> wcodver) OR (wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreftomador) OR (wconttiatu <> wcodcontti)) THEN
              BEGIN
                BDCODVER     = wveratu;
                BDCODEMP     = wempatu;
                BDCODCOL     = wcolatu;
                BDREFTOMADOR = wrefatu;

                if (wconttiatu = 0) then
                   BDCODCONTTI = null;
                else
                   BDCODCONTTI = wconttiatu;

                BDCODCENTRO  = NULL;
                BDCODTPCC    = NULL;
                BDORDEM      = wordem;
                BDREFVFT_SUM = wrefvtfant_sum;
                BDREFVFT_MAX = wrefvtfant_max;
                BDREFAUXVFT  = wrefauxvftant;
                BDVALVFT     = wvalvftant;
                BDIGNREFAVFT = wignrefaftant;
                BDIGNREFVFT  = wignrefftant;
                BDIGNVALVFT  = wignvalftant;
                BDTIPOREFVER = wtiporefver;
                SUSPEND;
                wveratu        = wcodver;
                wempatu        = wcodemp;
                wcolatu        = wcodcol;
                wrefatu        = wreftomador;
                wconttiatu     = wcodcontti;
                wrefvtfant_sum = 0;
                wrefvtfant_max = 0;
                wrefauxvftant  = 0;
                wvalvftant     = 0;
                wignrefaftant  = '';
                wignrefftant   = '';
                wignvalftant   = '';
              END

           wignrefaftant = wignrefaft;
           wignrefftant  = wignrefft;
           wignvalftant  = wignvalft;

           wvalvftant    = wvalvftant + wvalvft;
           wrefauxvftant = wrefauxvftant + wrefauxvft;

           IF (wrefvtfant_max < wrefvft) THEN
              wrefvtfant_max = wrefvft;

           wsqlver = 'select first 1 COALESCE(BDTIPOREFVER,0) from VRH_BASE_TVERBAS_REF where BDCODVER = '||wveratu||' and BDREFVER <= '||wrefatu||' order by BDREFVER DESC';
           EXECUTE STATEMENT wsqlver INTO :wtiporefver;
           -- Converte horas e tipo de refer?ncia da verba ? Horas
           IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvft > 0) THEN
              BEGIN
                -- Converte a referencia atual de Horas para Valor
                wfracao      = wrefvft - CAST((wrefvft - 0.5) AS INTEGER);
                IF (wrefvft > 0) THEN
                   BEGIN
                     wrefvft = wrefvft - wfracao;
                     wfracao = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                     wrefvft = wrefvft + wfracao;
                   END
     
                -- Converte a soma atual de Horas para Valor
                wfracao  = wrefvtfant_sum - CAST((wrefvtfant_sum - 0.5) AS INTEGER);
                IF (wrefvtfant_sum > 0) THEN
                   BEGIN
                     wrefvtfant_sum = wrefvtfant_sum - wfracao;
                     wfracao        = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                     wrefvtfant_sum = wrefvtfant_sum + wfracao;
                   END
     
                -- Soma os VALORES
                wrefvtfant_sum = wrefvtfant_sum +  wrefvft;
     
                -- Converte o resultado novamente em Horas
                wfracao  = wrefvtfant_sum - CAST((wrefvtfant_sum - 0.5) AS INTEGER);
                IF (wrefvtfant_sum > 0) THEN
                   BEGIN
                     wrefvtfant_sum = wrefvtfant_sum - wfracao;
                     wfracao        = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                     wrefvtfant_sum = wrefvtfant_sum + wfracao;
                   END
              END
           ELSE
              wrefvtfant_sum = wrefvtfant_sum + wrefvft;

         END

       IF ((wveratu <> 0) AND (wempatu <> 0) AND (wcolatu <> 0) AND (wrefatu <> 0) AND (wconttiatu <> -1)) THEN
          BEGIN
            BDCODVER     = wveratu;
            BDCODEMP     = wempatu;
            BDCODCOL     = wcolatu;
            BDREFTOMADOR = wrefatu;

            if (wconttiatu = 0) then
               BDCODCONTTI = null;
            else
               BDCODCONTTI = wconttiatu;

            BDCODCENTRO  = NULL;
            BDCODTPCC    = NULL;
            BDORDEM      = wordem;
            BDREFVFT_SUM = wrefvtfant_sum;
            BDREFVFT_MAX = wrefvtfant_max;
            BDREFAUXVFT  = wrefauxvftant;
            BDVALVFT     = wvalvftant;
            BDIGNREFAVFT = wignrefaftant;
            BDIGNREFVFT  = wignrefftant;
            BDIGNVALVFT  = wignvalftant;
            BDTIPOREFVER = wtiporefver;
            SUSPEND;
          END
     END
END
^

/* Alter (SP_VRHF_BASE_TVERBASEMP_CONS) */
ALTER PROCEDURE SP_VRHF_BASE_TVERBASEMP_CONS(PRCODEMP INTEGER,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODIGOVEREMP INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDTIPOCOLVEREMP INTEGER,
BDCLASSECOLVEREMP INTEGER,
BDCOMFGTS VARCHAR(5),
BDCODTCA INTEGER,
BDDESCTCA VARCHAR(50),
BDINTERMITENTE DM_BOOLEAN)
 AS
declare variable WSQL varchar(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomes, NULL, NULL);

  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODIGOVEREMP, '||
                'X.BDCODVER, '||
                'VERBA.BDDESCVER, '||
                'X.BDTIPOCOLVEREMP, '||
                'X.BDCLASSECOLVEREMP, '||
                'X.BDCOMFGTS, '||
                'X.BDCODTCA, '||
                'TCA.BDDESCTCA, '||
                'X.BDINTERMITENTE '||
  'from VRHF_BASE_TVERBASEMP X '||
  'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
     'on (EMP.BDCODEMP = X.BDCODEMP) '||
  'left outer join VRH_BASE_TVERBAS VERBA '||
     'on (VERBA.BDCODVER = X.BDCODVER) '||
  'left outer join VRH_BASE_TTIPOCALCAVUL TCA '||
     'on (TCA.BDCODTCA = X.BDCODTCA) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||'where X.BDCODEMP = '||:prcodemp;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODIGOVEREMP,
    :BDCODVER,
    :BDDESCVER,
    :BDTIPOCOLVEREMP,
    :BDCLASSECOLVEREMP,
    :BDCOMFGTS,
    :BDCODTCA,
    :BDDESCTCA,
    :BDINTERMITENTE
  DO
  SUSPEND;
END
^

/* Alter (SP_VRHF_DADOS_INSS_13) */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_13(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRANOTODO SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDVALORINSS13 NUMERIC(18,6),
BDBASEINSS13 NUMERIC(18,6),
BDSALFAM13 NUMERIC(18,6),
BDSALMATEMP13 NUMERIC(18,6),
BDBINSSMV13 NUMERIC(18,6),
BDCHAVE INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCODTOMADOR INTEGER,
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBRATAPO13 NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(30000);
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCHAVEATU INTEGER;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WCODTOMADORATU INTEGER;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCODTOMADOR INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WINSSVER INTEGER;
DECLARE VARIABLE WBASEGPSVER VARCHAR(5);
DECLARE VARIABLE WREEMBGPSVER VARCHAR(5);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WINSS13 NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS13 NUMERIC(18,6);
DECLARE VARIABLE WSALFAM NUMERIC(18,6);
DECLARE VARIABLE WSALMATEMP NUMERIC(18,6);
DECLARE VARIABLE WBASEMV13 NUMERIC(18,6);
DECLARE VARIABLE WREEMB NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDO NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDOSF NUMERIC(18,6);
DECLARE VARIABLE WPERCRAT NUMERIC(18,6);
BEGIN
  wsql = 'select FN.BDCHAVE,FN.BDCODCENTRO,coalesce(FN.BDCODTPCC,0),coalesce(toma.bdcodtpcc,0), FN.BDCODEMP, FN.BDCODCOL, FN.BDVALV13, FOLN.BDBINSSMV13, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER ';
  wsql = wsql||'from (select * from VW_VRHF_EMP_TVERBA_13_rat_CC ';
  wwhere  = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wwhere = wwhere||prcodemp;
     END

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       IF (pranotodo = 1) THEN
          wwhere = wwhere||'BDREF13 >= '||SUBSTRING(:prref FROM 1 FOR 4)||'01 and BDREF13 <= '||prref||' ';
       ELSE
          wwhere = wwhere||'BDREF13 = '||prref||' ';
     END


  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||') FN ';
  wsql = wsql||'join VW_VRHF_EMP_T13SAL_rat_CC FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREF13 = FN.BDREF13 and FOLN.BDCHAVE = FN.BDCHAVE) ';
--  wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||' left outer join VRHF_SP_TIPO_TOMADOR_GPS(FOLN.bdcodtpcc,FOLN.bdcodcentro,1) toma on (toma.bdcodcencus = FOLN.bdcodtpcc and toma.bdcodcentro = FOLN.bdcodcentro) ';
  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL,FN.BDCHAVE ';

  wChaveatu = 0;
  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss13     = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv13   = 0;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wcodtomadoratu = -1;
  wvindevido = 0;
  wvindevidosf = 0;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wChave, :wcodcentro, :wcodtpcc, :wcodtomador, :wcodemp, :wcodcol, :wvalor, :wbasemv13, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wChaveatu = 0) THEN
       wChaveatu = wChave;

    IF (wcodcentroatu = -1) THEN
       wcodcentroatu = wcodcentro;

    IF (wcodtpccatu = -1) THEN
       wcodtpccatu = wcodtpcc;

    IF (wcodtomadoratu = -1) THEN
       wcodtomadoratu = wcodtomador;


    /*
      Retorna bases de INSS
    */


    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wChaveatu <> wChave)) THEN
       BEGIN
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREF13        = prref;
         BDVALORINSS13  = winss13;
         BDBASEINSS13   = wbaseinss13;
         BDSALFAM13     = wsalfam;
         BDSALMATEMP13  = wsalmatemp;
         BDBINSSMV13    = wbasemv13;
         BDCHAVE = wchaveatu;
         BDCODCENTRO = wcodcentroatu;
         BDCODTPCC = wcodtpccatu;
         BDCODTOMADOR = wcodtomadoratu;
         BDVALINDEVIDO = wvindevido;
         BDVALINDEVIDOSF = wvindevidosf;

         wpercrat = 0;
         SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BDBRATAPO13   = BDBASEINSS13;
         ELSE
            BDBRATAPO13   = 0;

         SUSPEND;

         winss13     = 0;
         wbaseinss13 = 0;
         wsalfam     = 0;
         wsalmatemp  = 0;
         wbasemv13   = 0;
         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wChaveatu = wChave;
         wcodcentroatu = wcodcentro;
         wcodtpccatu = wcodtpcc;
         wcodtomadoratu = wcodtomador;
         wvindevido = 0;
         wvindevidosf = 0;
       END

    -- INSS 13o. rescis?o descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.3') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS 13o. sal?rio descontado na rescis?o
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END
    ELSE
    IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (5, 6) AND UPPER(wbasegpsver) = 'TRUE')  THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de sal?rio fam?lia
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.1.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Base de sal?rio maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END


  END

  IF ((wempatu <> 0) AND (wcolatu <> 0)) THEN
     BEGIN
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREF13        = prref;
       BDVALORINSS13  = winss13;
       BDBASEINSS13   = wbaseinss13;
       BDSALFAM13     = wsalfam;
       BDSALMATEMP13  = wsalmatemp;
       BDBINSSMV13    = wbasemv13;
       BDCHAVE = wchaveatu;
       BDCODCENTRO = wcodcentroatu;
       BDCODTPCC = wcodtpccatu;
       BDCODTOMADOR = wcodtomadoratu;
       BDVALINDEVIDO = wvindevido;
       BDVALINDEVIDOSF = wvindevidosf;

       wpercrat = 0;
       SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BDBRATAPO13   = BDBASEINSS13;
       ELSE
          BDBRATAPO13   = 0;
       SUSPEND;
     END
END
^

/* Alter (SP_VRHF_DADOS_INSS_FC) */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRREFPAG INTEGER,
PRGPSSEFIP SMALLINT = 0)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFCOMP INTEGER,
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBINSSMVFN NUMERIC(18,6),
BDBINSSMV13FN NUMERIC(18,6),
BDCODTIPOFC INTEGER,
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDBINSS13INDFN NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(30000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WINSSVER INTEGER;
DECLARE VARIABLE WBASEGPSVER VARCHAR(5);
DECLARE VARIABLE WREEMBGPSVER VARCHAR(5);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WINSS NUMERIC(18,6);
DECLARE VARIABLE WINSSFE NUMERIC(18,6);
DECLARE VARIABLE WINSS13 NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS NUMERIC(18,6);
DECLARE VARIABLE WBASEINSSFE NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS13 NUMERIC(18,6);
DECLARE VARIABLE WSALFAM NUMERIC(18,6);
DECLARE VARIABLE WSALMATEMP NUMERIC(18,6);
DECLARE VARIABLE WBASEMV NUMERIC(18,6);
DECLARE VARIABLE WBASEMV13 NUMERIC(18,6);
DECLARE VARIABLE WPERCRAT NUMERIC(18,6);
DECLARE VARIABLE WCODTIPOFC INTEGER;
DECLARE VARIABLE WCODFCATU INTEGER;
DECLARE VARIABLE WBINSSAP NUMERIC(18,6);
DECLARE VARIABLE WBINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WINSSAP NUMERIC(18,6);
DECLARE VARIABLE WINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WAINSSAP NUMERIC(18,6);
DECLARE VARIABLE WAINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WABASEMV NUMERIC(18,6);
DECLARE VARIABLE WABASEMV13 NUMERIC(18,6);
DECLARE VARIABLE WEMPAP INTEGER;
DECLARE VARIABLE WSOMAAP NUMERIC(18,6);
DECLARE VARIABLE WCODSIND INTEGER;
DECLARE VARIABLE WLIMSIND INTEGER;
DECLARE VARIABLE WLIMEMP INTEGER;
DECLARE VARIABLE WREEMB NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDO NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDOSF NUMERIC(18,6);
DECLARE VARIABLE WBAVPREV NUMERIC(18,6);
DECLARE VARIABLE WTEMVALOR SMALLINT;
DECLARE VARIABLE WREFFCA INTEGER;
DECLARE VARIABLE WREFFC INTEGER;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, VER.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, FOLN.BDCODTIPOFC ';
  wsql = wsql||'from (select * from VRHF_EMP_TVERBAFC ';
  wwhere  = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wwhere = wwhere||prcodemp;
     END

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFFN = '||prref||' ';
     END

  IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFFC >= '||prrefpag||'01 and BDREFFC <= '||prrefpag||'31 ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||') FN ';
  wsql = wsql||'join VRHF_EMP_TFOLHACOMP FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN and FOLN.BDREFFC = FN.BDREFFC) ';
  wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFC ';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor   = 0;
  wreffca = 0;
  wreffca = 0;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wreffc, :wvalor, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver, :wcodtipofc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wreffca = 0) THEN
       wreffca = wreffc;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wreffca <> wreffc)) THEN
       BEGIN
         wcodsind = NULL;
         wlimemp = NULL;
         wlimsind = NULL;
         SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
            BEGIN
              SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
            END

         IF (wlimsind IS NULL) THEN
            wlimsind = 0;             -- n?o possui liminar

         IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
            SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

         IF (wlimemp IS NULL) THEN
            wlimemp = 0;    -- n?o possui liminar

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = prref;
         BDREFCOMP      = CAST((SUBSTRING(prrefpag FROM 1 FOR 6)) AS INTEGER);
         BDCODTIPOFC    = wcodfcatu;
         BDCODCENTROS   = NULL;
         BDCODTPCC      = NULL;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         IF (bdbinssfn < 0) THEN
            bdbinssfn = 0;

         wpercrat = 0;
         SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN     = wsalfam;
         BDSALMATEMPFN  = wsalmatemp;
         BDBINSSMVFN    = wabasemv;
         BDBINSSMV13FN  = wabasemv13;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDVALREEMBOLSO = wreemb;
         BDVALINDEVIDO  = wvindevido;
         BDVALINDEVIDOSF = wvindevidosf;
         BDBAVPREV       = 0;

         SUSPEND;

         IF (prrefpag >= 200903 AND prGPSSEFIP = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = prref;
              BDREFCOMP      = CAST((SUBSTRING(prrefpag FROM 1 FOR 6)) AS INTEGER);
              BDCODTIPOFC    = wcodfcatu;
              BDCODCENTROS   = NULL;
              BDCODTPCC      = NULL;
              BDBAVPREV      = wbavprev;

              IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                   BDINSSFN  = wainssap;
                   BDBINSSFN = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFN  = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDINSSFEFOLFN  = winssfe;
              BDINSS13FN     = winss13;
              BDBINSSFEFOLFN = wbaseinssfe;
              BDBINSS13FN    = wbaseinss13;
              BDBINSS13INDFN = wbinss13ap;

              IF (bdbinssfn < 0) THEN
                 bdbinssfn = 0;
     
              wpercrat = 0;
              SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;
     
              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END
     
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDBINSSAPFN    = wbinssap;
              BDBINSS13APFN  = wbinss13ap;
              BDINSSAPFN     = wainssap;
              BDINSS13APFN   = wainss13ap;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;
              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wreffca     = wreffc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainss13ap  = 0;
         wainssap    = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
       END

    wcodfcatu  = wcodtipofc;
    wainss13ap = winss13ap;
    wainssap   = winssap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    IF (prrefpag >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref AND X.bdrefcomp = :prrefpag
           UNION ALL
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafctomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref AND X.bdrefcomp = :prrefpag
           UNION ALL
           SELECT X.bdvalvfn BDSOMA
           FROM vrhf_emp_tverbafn X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref
           UNION ALL
           SELECT X.bdvalvft BDSOMA
           FROM vrhf_emp_tverbatomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS f?rias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. complemento de 13? na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
       winss13 = winss13 + wvalor;

    -- INSS 13o. rescis?o descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --n?o incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS f?rias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN

         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    -- Base de INSS f?rias demonstrativo na folha
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. sal?rio descontado na rescis?o
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de sal?rio fam?lia
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido na GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido na GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de sal?rio maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base de INSS sem o aviso pr?vio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --n?o incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --n?o incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso pr?vio indenizado do 13? sal?rio
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END
  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND (wreffca <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- n?o possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- n?o possui liminar

       BDGPSSEFIP = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = prref;
       BDREFCOMP      = CAST((SUBSTRING(prrefpag FROM 1 FOR 6)) AS INTEGER);
       BDCODTIPOFC    = wcodfcatu;
       BDCODCENTROS   = NULL;
       BDCODTPCC      = NULL;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDBAVPREV      = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       IF (bdbinssfn < 0) THEN
          bdbinssfn = 0;

       wpercrat = 0;
       SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;
 
       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN     = wsalfam;
       BDSALMATEMPFN  = wsalmatemp;

       BDBINSSMVFN    = wabasemv;
       BDBINSSMV13FN  = wabasemv13;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDVALREEMBOLSO = wreemb;
       BDVALINDEVIDO  = wvindevido;
       BDVALINDEVIDOSF = wvindevidosf;
       SUSPEND;

    IF (prrefpag >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDREFCOMP      = CAST((SUBSTRING(prrefpag FROM 1 FOR 6)) AS INTEGER);
            BDCODTIPOFC    = wcodfcatu;
            BDCODCENTROS   = NULL;
            BDCODTPCC      = NULL;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                 BDINSSFN  = wainssap;
                 BDBINSSFN = wbinssap;
               END
             ELSE
               BEGIN
                 BDINSSFN  = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN  = winssfe;
            BDINSS13FN     = winss13;
            BDBINSSFEFOLFN = wbaseinssfe;
            BDBINSS13FN    = wbaseinss13;
            BDBINSSAPFN    = wbinssap;
            BDBINSS13APFN  = wbinss13ap;

            IF (bdbinssfn < 0) THEN
               bdbinssfn = 0;
     
            wpercrat = 0;
            SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;
      
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDINSSAPFN     = wainssap;
            BDINSS13APFN   = wainss13ap;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;
            BDBINSS13INDFN = wbinss13ap;
            SUSPEND;
          END
     END
END
^

/* Alter (SP_VRHF_DADOS_INSS_FN) */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FN(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRGPSSEFIP SMALLINT = 0,
PRFILIAIS VARCHAR(15000) = null,
PRCONTRATO INTEGER = 0)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBINSSMVFN NUMERIC(18,6),
BDBINSSMV13FN NUMERIC(18,6),
BDBINSS13INDFN NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDPERCRATCOL NUMERIC(18,6),
BDPERCDESCFPASCOL NUMERIC(18,6))
 AS
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WTABINSS integer;
declare variable WSQLINSS varchar(1500);
declare variable WALIQINSS numeric(18,6);
declare variable WFAIXAINSS numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WCONTRCOL integer;
declare variable WREEMB numeric(18,6);
declare variable WREFRESC integer;
declare variable WBMULTVINC numeric(18,6);
declare variable WVMULTVINC numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WPERCDESCFPAS numeric(18,6);
declare variable WSINDATU integer;
declare variable WBASEINSSCONTR numeric(18,6);
declare variable WBASEINSSCONTRATU numeric(18,6);
declare variable WINTERMITENTE DM_BOOLEAN;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDBINSSMVFN, FN.BDBINSSMV13FN, FN.BDINSSAPFN, FN.BDINSS13APFN, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, FN.BDBINSSFN, '||
                'case when COALESCE(FGTSGPS.BDCATEGORIACOL,0) = 4 and COALESCE(FGTSGPS.BDCATEGORIAESOCIAL,0) = 111 then ''TRUE'' else ''FALSE'' end BDINTERM from (';
     
  if (coalesce(prcontrato, 0) = 0) then
     begin
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDCODVER, FOLN.BDBINSSMVFN, FOLN.BDBINSSMV13FN, FOLN.BDINSSAPFN, FOLN.BDINSS13APFN, FOLN.BDBINSSFN from (';
     
  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';
     
       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAFN FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';
     
      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFFN = '||prref;
     
      wsql = wsql||') ';
     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBAFN ';
     
      wwhere  = '';
     
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         BEGIN
           wwhere = wwhere||prcodemp;
    
           IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
              BEGIN
                IF (wwhere <> '') THEN
                   wwhere = wwhere||' and ';
         
                wwhere = wwhere||prcodcol;
              END
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFFN = '||prref||' ';
         END
    
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END
     
  wsql = wsql||'join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN) ';
     
     
       wsql = wsql||' union all ';
     end

  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDCODVER, FOLN.BDBINSSMVFN, FOLN.BDBINSSMV13FN, FOLN.BDINSSAPFN, FOLN.BDINSS13APFN, FOLN.BDBINSSFN from (';

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';

       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAINT FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';

      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFFN = '||prref;

      wsql = wsql||') ';

      if (coalesce(prcontrato, 0) > 0) then
         wsql = wsql||' where FN.BDCODCONTTI = '||prcontrato||' ';


     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBAINT ';

      wwhere  = '';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         BEGIN
           wwhere = wwhere||prcodemp;
    
           IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
              BEGIN
                IF (wwhere <> '') THEN
                   wwhere = wwhere||' and ';
         
                wwhere = wwhere||prcodcol;
              END
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFFN = '||prref||' ';
         END
    
      IF (coalesce(prcontrato,0) > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDCODCONTTI = '||prcontrato||' ';
         END
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END

  wsql = wsql||'join VRHF_EMP_TFOLHAINT FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';

  wsql = wsql||') FN ';


  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  ELSE
     wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';

  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FN.BDCODEMP and FGTSGPS.BDCODCOL = FN.BDCODCOL) ';

  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL ';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor = 0;
  wsindatu = 0;
  wcodsind = -1;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver,
                                  :wreembgpsver, :wbaseinsscontr, :wintermitente DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- n?o possui liminar
      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    /*
      Retorna bases de INSS
    */


    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
         wcodsind = NULL;
         SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;

         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
                SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- n?o possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- n?o possui liminar
           END

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = prref;
         BDCODCENTROS   = NULL;
         BDCODTPCC      = NULL;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBAVPREV      = 0;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         BDBINSSFEFOLFN = wbaseinssfe;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
            BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

         IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
            BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

         wpercrat = 0;
         wpercdescfpas = 0;
         wcontrcol = NULL;
         SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat, :wpercdescfpas, :wcontrcol;
         IF (wcontrcol IS NULL) THEN
            wcontrcol = 0;

         IF (wcontrcol = 1) THEN
            bdbinssfn = wbaseinsscontratu - wabasemv;

         IF (bdbinssfn < 0) THEN
            bdbinssfn = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;     --+ BDBINSSFEFOLFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN        = wsalfam;
         BDSALMATEMPFN     = wsalmatemp;
         BDBINSSMVFN       = wabasemv;
         BDBINSSMV13FN     = wabasemv13;
         BDINSSAPFN        = wainssap;
         BDINSS13APFN      = wainss13ap;
         BDVALREEMBOLSO    = wreemb;
         BDVALINDEVIDO     = wvindevido;
         BDVALINDEVIDOSF   = wvindevidosf;
         BDPERCRATCOL      = wpercrat;
         BDPERCDESCFPASCOL = wpercdescfpas;

         SUSPEND;

         IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = prref;
              BDCODCENTROS   = NULL;
              BDCODTPCC      = NULL;
              BDBAVPREV      = wbavprev;

              wrefresc = NULL;
              SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFRESCISAO = :prref INTO :wrefresc;

              IF (wcontrcol = 0 AND wrefresc = prref) THEN
                 BEGIN
                   IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                      BEGIN
                        BDINSSFN  = wainssap;
                        BDBINSSFN = wbinssap;
                      END
                   ELSE
                      BEGIN
                        IF ((wbinssap <> 0) OR (wtemvalor = 1)) THEN
                           BEGIN
                             IF (wbinssap < 0) THEN
                               wbinssap = 0;

                             BDBINSSFN = wbinssap;
                             wbinssap = wbinssap + wbaseinssfe;
                             wbmultvinc = 0;
                             wvmultvinc = 0;
                             SELECT BDBASEINSSNCOL, BDVALORINSSNCOL FROM VW_VRHF_EMP_TCOLCON_MVINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wbmultvinc, :wvmultvinc;
                             BDBINSSFN = BDBINSSFN + wbmultvinc;

                             SELECT COALESCE(BDCODINSS, 0) FROM VW_VRHF_BASE_TEMPVINC WHERE BDCODEMP = :wempatu INTO :wtabinss;
                             IF (wtabinss = 0) THEN
                                wtabinss = 1;
     
                             waliqinss = 0;
                             wsqlinss = 'select first 1 COALESCE(X.BDALIQINSS, 0) '||
                                        'from VRHF_TABELAS_TINSSFAIXAS X '||
                                        'join ('||
                                          'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                          'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                          'group by BDCODINSS '||
                                        ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                        'where X.BDFAIXAINSS >= '||wbinssap||' order by X.BDFAIXAINSS ';
     
                             EXECUTE STATEMENT wsqlinss INTO :waliqinss;
     
                             IF ((waliqinss = 0) OR (waliqinss IS NULL)) THEN
                                BEGIN
                                  wsqlinss = 'select MAX(X.BDFAIXAINSS), MAX(X.BDALIQINSS) '||
                                             'from VRHF_TABELAS_TINSSFAIXAS X '||
                                             'join ('||
                                               'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                               'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                               'group by BDCODINSS '||
                                             ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                             'group by X.BDCODINSS, X.BDREFINSS ';
     
                                  wfaixainss = 0;
                                  waliqinss  = 0;
                                  EXECUTE STATEMENT wsqlinss INTO :wfaixainss, :waliqinss;
     
                                  IF (wfaixainss IS NULL) THEN
                                     wfaixainss = 0;
     
                                  IF (waliqinss IS NULL) THEN
                                     waliqinss = 0;
     
                                  BDINSSFN = wfaixainss * waliqinss / 100;
                                END
                             ELSE
                                BDINSSFN = wbinssap * waliqinss / 100;
     
                             BDBINSSFN = BDBINSSFN - wbmultvinc;
                             BDINSSFN = CAST(BDINSSFN - 0.005 AS NUMERIC(15,2)); /* cortar */
                             BDINSSFN = BDINSSFN - winssfe - wvmultvinc;
                           END
                        ELSE
                           BEGIN
                             BDINSSFN = winss;
                             BDBINSSFN = wbaseinss;
                           END
                      END
                 END
              ELSE
                 BEGIN
                   BDINSSFN = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDINSSFEFOLFN     = winssfe;
              BDINSS13FN        = wainss13ap;
              BDBINSSFEFOLFN    = wbaseinssfe;
              BDBINSSAPFN       = wbinssap;
              BDBINSS13FN       = wbaseinss13;
              BDBINSS13APFN     = wbinss13ap;
              BDBINSS13INDFN    = wbinss13ap;
              BDPERCRATCOL      = wpercrat;
              BDPERCDESCFPASCOL = wpercdescfpas;

              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSFN;   -- + BDBINSSFEFOLFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END
     
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDINSSAPFN     = wainssap;
              BDINSS13APFN   = wainss13ap;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF  = wvindevidosf;

              IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
                 BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;
              IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
                 BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;
              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;
    wbaseinsscontratu = wbaseinsscontr;

    IF (prref >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;

         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfn BDSOMA FROM vrhf_emp_tverbafn X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref
           UNION ALL
           SELECT X.bdvalvft BDSOMA FROM vrhf_emp_tverbatomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    if (wintermitente = 'TRUE') then
       begin
         -- INSS 13o. descontado na folha normal
         IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
            winss13 = winss13 + wvalor;
       end

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050' AND wtipocodver = 0) THEN
       wsalfam = wsalfam + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN  --  Valores indevidos da GPS
       wvindevido = wvindevido + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN  --  Valores SF indevidos da GPS
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base INSS sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END
 
       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar
 
       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
 
       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       BDGPSSEFIP     = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = prref;
       BDCODCENTROS   = NULL;
       BDCODTPCC      = NULL;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
          BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;
       IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
          BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

       wpercrat = 0;
       wpercdescfpas = 0;
       wcontrcol = NULL;
       SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat, :wpercdescfpas, :wcontrcol;
       IF (wcontrcol IS NULL) THEN
          wcontrcol = 0;
 
       IF (wcontrcol = 1) THEN
          bdbinssfn = wbaseinsscontratu - wabasemv;

       IF (bdbinssfn < 0) THEN
          bdbinssfn = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;   -- + wbaseinssfe;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN        = wsalfam;
       BDSALMATEMPFN     = wsalmatemp;
       BDBINSSMVFN       = wabasemv;
       BDBINSSMV13FN     = wabasemv13;
       BDVALREEMBOLSO    = wreemb;
       BDVALINDEVIDO     = wvindevido;
       BDPERCRATCOL      = wpercrat;
       BDPERCDESCFPASCOL = wpercdescfpas;
       SUSPEND;

       IF (prRef >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDCODCENTROS   = NULL;
            BDCODTPCC      = NULL;
            BDBAVPREV      = wbavprev;

            wrefresc = NULL;
            SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFRESCISAO = :prref INTO :wrefresc;
            IF (wcontrcol = 0 AND wrefresc = prref) THEN
               BEGIN
                 IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                    BEGIN
                      BDINSSFN  = wainssap;
                      BDBINSSFN = wbinssap;
                    END
                 ELSE
                    BEGIN
                      IF ((wbinssap <> 0) OR (wtemvalor = 1)) THEN
                         BEGIN
                           IF (wbinssap < 0) THEN
                             wbinssap = 0;

                           BDBINSSFN = wbinssap;
                           wbinssap = wbinssap + wbaseinssfe;
     
                           wbmultvinc = 0;
                           wvmultvinc = 0;
                           SELECT BDBASEINSSNCOL, BDVALORINSSNCOL FROM VW_VRHF_EMP_TCOLCON_MVINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wbmultvinc, :wvmultvinc;
                           BDBINSSFN = BDBINSSFN + wbmultvinc;

                           SELECT COALESCE(BDCODINSS, 0) FROM VW_VRHF_BASE_TEMPVINC WHERE BDCODEMP = :wempatu INTO :wtabinss;
                           IF (wtabinss = 0) THEN
                              wtabinss = 1;
     
                           waliqinss = 0;
                           wsqlinss = 'select first 1 COALESCE(X.BDALIQINSS, 0) '||
                                      'from VRHF_TABELAS_TINSSFAIXAS X '||
                                      'join ('||
                                        'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                        'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                        'group by BDCODINSS '||
                                      ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                      'where X.BDFAIXAINSS >= '||wbinssap||' order by X.BDFAIXAINSS ';
     
                           EXECUTE STATEMENT wsqlinss INTO :waliqinss;
     
                           IF ((waliqinss = 0) OR (waliqinss IS NULL)) THEN
                              BEGIN
                                wsqlinss = 'select MAX(X.BDFAIXAINSS), MAX(X.BDALIQINSS) '||
                                           'from VRHF_TABELAS_TINSSFAIXAS X '||
                                           'join ('||
                                             'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                             'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                             'group by BDCODINSS '||
                                           ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                           'group by X.BDCODINSS, X.BDREFINSS ';
     
                                wfaixainss = 0;
                                waliqinss  = 0;
                                EXECUTE STATEMENT wsqlinss INTO :wfaixainss, :waliqinss;
     
                                IF (wfaixainss IS NULL) THEN
                                   wfaixainss = 0;
     
                                IF (waliqinss IS NULL) THEN
                                   waliqinss = 0;
     
                                BDINSSFN = wfaixainss * waliqinss / 100;
                              END
                           ELSE
                              BDINSSFN = wbinssap * waliqinss / 100;
     
                           BDBINSSFN = BDBINSSFN - wbmultvinc;
                           BDINSSFN = CAST(BDINSSFN - 0.005 AS NUMERIC(15,2)); /* cortar */
                           BDINSSFN = BDINSSFN - winssfe - wvmultvinc;
     
                         END
                      ELSE
                         BEGIN
                           BDINSSFN = winss;
                           BDBINSSFN = wbaseinss;
                         END
                    END
               END
            ELSE
               BEGIN
                 BDINSSFN = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN     = winssfe;
            BDINSS13FN        = wainss13ap;
            BDBINSSFEFOLFN    = wbaseinssfe;
            BDBINSS13FN       = wbaseinss13;
            BDBINSSAPFN       = wbinssap;
            BDBINSS13APFN     = wbinss13ap;
            BDBINSS13INDFN    = wbinss13ap;
            BDINSSAPFN        = wainssap;
            BDINSS13APFN      = wainss13ap;
            BDPERCRATCOL      = wpercrat;
            BDPERCDESCFPASCOL = wpercdescfpas;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;    -- + BDBINSSFEFOLFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
               BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;
            IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
               BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;
            SUSPEND;
          END
     END
END
^

/* Alter (SP_VRHF_DADOS_INSS_FN_PREV_RESC) */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FN_PREV_RESC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRGPSSEFIP SMALLINT = 0,
PRFILIAIS VARCHAR(15000) = NULL)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDINSSFNPR NUMERIC(18,6),
BDINSSFEFOLFNPR NUMERIC(18,6),
BDINSS13FNPR NUMERIC(18,6),
BDBINSSFNPR NUMERIC(18,6),
BDBINSSFEFOLFNPR NUMERIC(18,6),
BDBINSS13FNPR NUMERIC(18,6),
BDBRATAPOFNPR NUMERIC(18,6),
BDBRATAPOFEFNPR NUMERIC(18,6),
BDBRATAPO13FNPR NUMERIC(18,6),
BDSALFAMFNPR NUMERIC(18,6),
BDSALMATEMPFNPR NUMERIC(18,6),
BDBINSS13INDFNPR NUMERIC(18,6),
BDBINSSAPFNPR NUMERIC(18,6),
BDBINSS13APFNPR NUMERIC(18,6),
BDINSSAPFNPR NUMERIC(18,6),
BDINSS13APFNPR NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDPERCRATCOL NUMERIC(18,6),
BDPERCDESCFPASCOL NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(30000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WINSSVER INTEGER;
DECLARE VARIABLE WBASEGPSVER VARCHAR(5);
DECLARE VARIABLE WREEMBGPSVER VARCHAR(5);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WINSS NUMERIC(18,6);
DECLARE VARIABLE WINSSFE NUMERIC(18,6);
DECLARE VARIABLE WINSS13 NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS NUMERIC(18,6);
DECLARE VARIABLE WBASEINSSFE NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS13 NUMERIC(18,6);
DECLARE VARIABLE WSALFAM NUMERIC(18,6);
DECLARE VARIABLE WSALMATEMP NUMERIC(18,6);
DECLARE VARIABLE WPERCRAT NUMERIC(18,6);
DECLARE VARIABLE WBINSSAP NUMERIC(18,6);
DECLARE VARIABLE WBINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WINSSAP NUMERIC(18,6);
DECLARE VARIABLE WINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WAINSSAP NUMERIC(18,6);
DECLARE VARIABLE WAINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WEMPAP INTEGER;
DECLARE VARIABLE WSOMAAP NUMERIC(18,6);
DECLARE VARIABLE WTABINSS INTEGER;
DECLARE VARIABLE WSQLINSS VARCHAR(1500);
DECLARE VARIABLE WALIQINSS NUMERIC(18,6);
DECLARE VARIABLE WFAIXAINSS NUMERIC(18,6);
DECLARE VARIABLE WCODSIND INTEGER;
DECLARE VARIABLE WLIMSIND INTEGER;
DECLARE VARIABLE WLIMEMP INTEGER;
DECLARE VARIABLE WCONTRCOL INTEGER;
DECLARE VARIABLE WREEMB NUMERIC(18,6);
DECLARE VARIABLE WREFRESC INTEGER;
DECLARE VARIABLE WBMULTVINC NUMERIC(18,6);
DECLARE VARIABLE WVMULTVINC NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDO NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDOSF NUMERIC(18,6);
DECLARE VARIABLE WBAVPREV NUMERIC(18,6);
DECLARE VARIABLE WTEMVALOR SMALLINT;
DECLARE VARIABLE WPERCDESCFPAS NUMERIC(18,6);
DECLARE VARIABLE WSINDATU INTEGER;
DECLARE VARIABLE WBASEINSSCONTR NUMERIC(18,6);
DECLARE VARIABLE WBASEINSSCONTRATU NUMERIC(18,6);
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFNPR, FNPR.BDINSSAPFNPR, FNPR.BDINSS13APFNPR, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, FNPR.BDBINSSFNPR from (';

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';

       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAFN_PREV_RESC FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';

      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFFN = '||prref;

      wsql = wsql||') ';
     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBAFN_PREV_RESC ';

      wwhere  = '';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         BEGIN
           wwhere = wwhere||prcodemp;
    
           IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
              BEGIN
                IF (wwhere <> '') THEN
                   wwhere = wwhere||' and ';
         
                wwhere = wwhere||prcodcol;
              END
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFFN = '||prref||' ';
         END
    
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END

  wsql = wsql||'join VRHF_EMP_TFOLHANORMAL_PREV_RESC FNPR on (FNPR.BDCODEMP = FN.BDCODEMP and FNPR.BDCODCOL = FN.BDCODCOL) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  ELSE
     wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';

  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL ';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor = 0;
  wsindatu = 0;
  wcodsind = -1;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver, :wbaseinsscontr DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- n?o possui liminar
      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    /*
      Retorna bases de INSS
    */


    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
         SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
                SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- n?o possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- n?o possui liminar
           END

         BDGPSSEFIP       = 0;
         BDCODEMP         = wempatu;
         BDCODCOL         = wcolatu;
         BDREFFN          = prref;
         BDCODCENTROS     = NULL;
         BDCODTPCC        = NULL;
         BDINSSFNPR       = winss;
         BDINSSFEFOLFNPR  = winssfe;
         BDINSS13FNPR     = winss13;
         BDBAVPREV        = 0;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFNPR = wbinssap;
         ELSE
            BDBINSSFNPR = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FNPR = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FNPR = wbaseinss13;

         BDBINSSFEFOLFNPR = wbaseinssfe;
         BDBINSSAPFNPR    = wbinssap;
         BDBINSS13APFNPR  = wbinss13ap;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFNPR = 0;
         ELSE
            BDBINSS13INDFNPR = wbinss13ap;

         IF (BDBINSSFEFOLFNPR > 0 AND BDINSSFNPR < 0) THEN
            BDINSSFEFOLFNPR = bdinssfefolfnpr + bdinssfnpr;

         IF (BDBINSSFNPR < 0 AND BDBINSSFEFOLFNPR > 0) THEN
            BDBINSSFEFOLFNPR = BDBINSSFEFOLFNPR + BDBINSSFNPR;

         wpercrat = 0;
         wpercdescfpas = 0;
         wcontrcol = NULL;
         SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat, :wpercdescfpas, :wcontrcol;
         IF (wcontrcol IS NULL) THEN
            wcontrcol = 0;

         IF (wcontrcol = 1) THEN
            bdbinssfnpr = wbaseinsscontratu;

         IF (bdbinssfnpr < 0) THEN
            bdbinssfnpr = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFNPR   = BDBINSSFNPR;     --+ BDBINSSFEFOLFN;
              BDBRATAPOFEFNPR = BDBINSSFEFOLFNPR;
              BDBRATAPO13FNPR = BDBINSS13FNPR;
            END
         ELSE
            BEGIN
              BDBRATAPOFNPR   = 0;
              BDBRATAPOFEFNPR = 0;
              BDBRATAPO13FNPR = 0;
            END

         BDSALFAMFNPR        = wsalfam;
         BDSALMATEMPFNPR     = wsalmatemp;
         BDINSSAPFNPR        = wainssap;
         BDINSS13APFNPR      = wainss13ap;
         BDVALREEMBOLSO      = wreemb;
         BDVALINDEVIDO       = wvindevido;
         BDVALINDEVIDOSF     = wvindevidosf;
         BDPERCRATCOL        = wpercrat;
         BDPERCDESCFPASCOL   = wpercdescfpas;

         SUSPEND;

         IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = prref;
              BDCODCENTROS   = NULL;
              BDCODTPCC      = NULL;
              BDBAVPREV      = wbavprev;

              wrefresc = NULL;
              SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFRESCISAO = :prref INTO :wrefresc;

              IF (wcontrcol = 0 AND wrefresc = prref) THEN
                 BEGIN
                   IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                      BEGIN
                        BDINSSFNPR  = wainssap;
                        BDBINSSFNPR = wbinssap;
                      END
                   ELSE
                      BEGIN
                        IF ((wbinssap <> 0) OR (wtemvalor = 1)) THEN
                           BEGIN
                             IF (wbinssap < 0) THEN
                               wbinssap = 0;

                             BDBINSSFNPR = wbinssap;
                             wbinssap = wbinssap + wbaseinssfe;
                             wbmultvinc = 0;
                             wvmultvinc = 0;
                             SELECT BDBASEINSSNCOL, BDVALORINSSNCOL FROM VW_VRHF_EMP_TCOLCON_MVINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wbmultvinc, :wvmultvinc;
                             BDBINSSFNPR = BDBINSSFNPR + wbmultvinc;

                             SELECT COALESCE(BDCODINSS, 0) FROM VW_VRHF_BASE_TEMPVINC WHERE BDCODEMP = :wempatu INTO :wtabinss;
                             IF (wtabinss = 0) THEN
                                wtabinss = 1;
     
                             waliqinss = 0;
                             wsqlinss = 'select first 1 COALESCE(X.BDALIQINSS, 0) '||
                                        'from VRHF_TABELAS_TINSSFAIXAS X '||
                                        'join ('||
                                          'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                          'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                          'group by BDCODINSS '||
                                        ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                        'where X.BDFAIXAINSS >= '||wbinssap||' order by X.BDFAIXAINSS ';
     
                             EXECUTE STATEMENT wsqlinss INTO :waliqinss;
     
                             IF ((waliqinss = 0) OR (waliqinss IS NULL)) THEN
                                BEGIN
                                  wsqlinss = 'select MAX(X.BDFAIXAINSS), MAX(X.BDALIQINSS) '||
                                             'from VRHF_TABELAS_TINSSFAIXAS X '||
                                             'join ('||
                                               'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                               'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                               'group by BDCODINSS '||
                                             ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                             'group by X.BDCODINSS, X.BDREFINSS ';
     
                                  wfaixainss = 0;
                                  waliqinss  = 0;
                                  EXECUTE STATEMENT wsqlinss INTO :wfaixainss, :waliqinss;
     
                                  IF (wfaixainss IS NULL) THEN
                                     wfaixainss = 0;
     
                                  IF (waliqinss IS NULL) THEN
                                     waliqinss = 0;
     
                                  BDINSSFNPR = wfaixainss * waliqinss / 100;
                                END
                             ELSE
                                BDINSSFNPR = wbinssap * waliqinss / 100;
     
                             BDBINSSFNPR = BDBINSSFNPR - wbmultvinc;
                             BDINSSFNPR = CAST(BDINSSFNPR - 0.005 AS NUMERIC(15,2)); /* cortar */
                             BDINSSFNPR = BDINSSFNPR - winssfe - wvmultvinc;
                           END
                        ELSE
                           BEGIN
                             BDINSSFNPR = winss;
                             BDBINSSFNPR = wbaseinss;
                           END
                      END
                 END
              ELSE
                 BEGIN
                   BDINSSFNPR = winss;
                   BDBINSSFNPR = wbaseinss;
                 END

              BDINSSFEFOLFNPR     = winssfe;
              BDINSS13FNPR        = wainss13ap;
              BDBINSSFEFOLFNPR    = wbaseinssfe;
              BDBINSSAPFNPR       = wbinssap;
              BDBINSS13FNPR       = wbaseinss13;
              BDBINSS13APFNPR     = wbinss13ap;
              BDBINSS13INDFNPR    = wbinss13ap;
              BDPERCRATCOL        = wpercrat;
              BDPERCDESCFPASCOL   = wpercdescfpas;

              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFNPR   = BDBINSSFNPR;   -- + BDBINSSFEFOLFN;
                   BDBRATAPOFEFNPR = BDBINSSFEFOLFNPR;
                   BDBRATAPO13FNPR = BDBINSS13FNPR;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFNPR   = 0;
                   BDBRATAPOFEFNPR = 0;
                   BDBRATAPO13FNPR = 0;
                 END
     
              BDSALFAMFNPR     = wsalfam;
              BDSALMATEMPFNPR  = wsalmatemp;
              BDINSSAPFNPR     = wainssap;
              BDINSS13APFNPR   = wainss13ap;
              BDVALREEMBOLSO   = wreemb;
              BDVALINDEVIDO    = wvindevido;
              BDVALINDEVIDOSF  = wvindevidosf;

              IF (BDBINSSFEFOLFNPR > 0 AND BDINSSFNPR < 0) THEN
                 BDINSSFEFOLFNPR = bdinssfefolfnpr + bdinssfnpr;
              IF (BDBINSSFNPR < 0 AND BDBINSSFEFOLFNPR > 0) THEN
                 BDBINSSFEFOLFNPR = BDBINSSFEFOLFNPR + BDBINSSFNPR;
              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wbaseinsscontratu = wbaseinsscontr;

    IF (prref >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;

         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfnpr BDSOMA FROM vrhf_emp_tverbafn_prev_resc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp
           UNION ALL
           SELECT X.bdvalvftpr BDSOMA FROM vrhf_emp_tverbaft_prev_resc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS f?rias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescis?o descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --n?o incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS f?rias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    -- Base de INSS f?rias demonstrativo na folha
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. sal?rio descontado na rescis?o
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de sal?rio fam?lia
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050' AND wtipocodver = 0) THEN
       wsalfam = wsalfam + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN  --  Valores indevidos da GPS
       wvindevido = wvindevido + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN  --  Valores SF indevidos da GPS
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de sal?rio maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base INSS sem o aviso pr?vio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --n?o incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --n?o incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso pr?vio indenizado do 13? sal?rio
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END
 
       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- n?o possui liminar
 
       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
 
       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       BDGPSSEFIP       = 0;
       BDCODEMP         = wempatu;
       BDCODCOL         = wcolatu;
       BDREFFN          = prref;
       BDCODCENTROS     = NULL;
       BDCODTPCC        = NULL;
       BDINSSFNPR       = winss;
       BDINSSFEFOLFNPR  = winssfe;
       BDINSS13FNPR     = winss13;
       BDBINSSFEFOLFNPR = wbaseinssfe;
       BDBINSSAPFNPR    = wbinssap;
       BDBINSS13APFNPR  = wbinss13ap;
       BDINSSAPFNPR     = wainssap;
       BDINSS13APFNPR   = wainss13ap;
       BDBAVPREV        = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFNPR = wbinssap;
       ELSE
          BDBINSSFNPR = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FNPR = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FNPR = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFNPR = 0;
       ELSE
          BDBINSS13INDFNPR = wbinss13ap;

       IF (BDBINSSFEFOLFNPR > 0 AND BDINSSFNPR < 0) THEN
          BDINSSFEFOLFNPR = bdinssfefolfnpr + bdinssfnpr;
       IF (BDBINSSFNPR < 0 AND BDBINSSFEFOLFNPR > 0) THEN
          BDBINSSFEFOLFNPR = BDBINSSFEFOLFNPR + BDBINSSFNPR;

       wpercrat = 0;
       wpercdescfpas = 0;
       wcontrcol = NULL;
       SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat, :wpercdescfpas, :wcontrcol;
       IF (wcontrcol IS NULL) THEN
          wcontrcol = 0;
 
       IF (wcontrcol = 1) THEN
          bdbinssfnpr = wbaseinsscontratu;

       IF (bdbinssfnpr < 0) THEN
          bdbinssfnpr = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFNPR   = wbaseinss;   -- + wbaseinssfe;
            BDBRATAPOFEFNPR = wbaseinssfe;
            BDBRATAPO13FNPR = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFNPR   = 0;
            BDBRATAPOFEFNPR = 0;
            BDBRATAPO13FNPR = 0;
          END

       BDSALFAMFNPR        = wsalfam;
       BDSALMATEMPFNPR     = wsalmatemp;
       BDVALREEMBOLSO      = wreemb;
       BDVALINDEVIDO       = wvindevido;
       BDPERCRATCOL        = wpercrat;
       BDPERCDESCFPASCOL   = wpercdescfpas;
       SUSPEND;

       IF (prRef >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDCODCENTROS   = NULL;
            BDCODTPCC      = NULL;
            BDBAVPREV      = wbavprev;

            wrefresc = NULL;
            SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFRESCISAO = :prref INTO :wrefresc;
            IF (wcontrcol = 0 AND wrefresc = prref) THEN
               BEGIN
                 IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                    BEGIN
                      BDINSSFNPR  = wainssap;
                      BDBINSSFNPR = wbinssap;
                    END
                 ELSE
                    BEGIN
                      IF ((wbinssap <> 0) OR (wtemvalor = 1)) THEN
                         BEGIN
                           IF (wbinssap < 0) THEN
                             wbinssap = 0;

                           BDBINSSFNPR = wbinssap;
                           wbinssap = wbinssap + wbaseinssfe;
     
                           wbmultvinc = 0;
                           wvmultvinc = 0;
                           SELECT BDBASEINSSNCOL, BDVALORINSSNCOL FROM VW_VRHF_EMP_TCOLCON_MVINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wbmultvinc, :wvmultvinc;
                           BDBINSSFNPR = BDBINSSFNPR + wbmultvinc;

                           SELECT COALESCE(BDCODINSS, 0) FROM VW_VRHF_BASE_TEMPVINC WHERE BDCODEMP = :wempatu INTO :wtabinss;
                           IF (wtabinss = 0) THEN
                              wtabinss = 1;
     
                           waliqinss = 0;
                           wsqlinss = 'select first 1 COALESCE(X.BDALIQINSS, 0) '||
                                      'from VRHF_TABELAS_TINSSFAIXAS X '||
                                      'join ('||
                                        'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                        'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                        'group by BDCODINSS '||
                                      ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                      'where X.BDFAIXAINSS >= '||wbinssap||' order by X.BDFAIXAINSS ';
     
                           EXECUTE STATEMENT wsqlinss INTO :waliqinss;
     
                           IF ((waliqinss = 0) OR (waliqinss IS NULL)) THEN
                              BEGIN
                                wsqlinss = 'select MAX(X.BDFAIXAINSS), MAX(X.BDALIQINSS) '||
                                           'from VRHF_TABELAS_TINSSFAIXAS X '||
                                           'join ('||
                                             'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                             'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                             'group by BDCODINSS '||
                                           ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                           'group by X.BDCODINSS, X.BDREFINSS ';
     
                                wfaixainss = 0;
                                waliqinss  = 0;
                                EXECUTE STATEMENT wsqlinss INTO :wfaixainss, :waliqinss;
     
                                IF (wfaixainss IS NULL) THEN
                                   wfaixainss = 0;
     
                                IF (waliqinss IS NULL) THEN
                                   waliqinss = 0;
     
                                BDINSSFNPR = wfaixainss * waliqinss / 100;
                              END
                           ELSE
                              BDINSSFNPR = wbinssap * waliqinss / 100;
     
                           BDBINSSFNPR = BDBINSSFNPR - wbmultvinc;
                           BDINSSFNPR = CAST(BDINSSFNPR - 0.005 AS NUMERIC(15,2)); /* cortar */
                           BDINSSFNPR = BDINSSFNPR - winssfe - wvmultvinc;
     
                         END
                      ELSE
                         BEGIN
                           BDINSSFNPR = winss;
                           BDBINSSFNPR = wbaseinss;
                         END
                    END
               END
            ELSE
               BEGIN
                 BDINSSFNPR = winss;
                 BDBINSSFNPR = wbaseinss;
               END

            BDINSSFEFOLFNPR     = winssfe;
            BDINSS13FNPR        = wainss13ap;
            BDBINSSFEFOLFNPR    = wbaseinssfe;
            BDBINSS13FNPR       = wbaseinss13;
            BDBINSSAPFNPR       = wbinssap;
            BDBINSS13APFNPR     = wbinss13ap;
            BDBINSS13INDFNPR    = wbinss13ap;
            BDINSSAPFNPR        = wainssap;
            BDINSS13APFNPR      = wainss13ap;
            BDPERCRATCOL        = wpercrat;
            BDPERCDESCFPASCOL   = wpercdescfpas;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFNPR   = BDBINSSFNPR;    -- + BDBINSSFEFOLFN;
                 BDBRATAPOFEFNPR = BDBINSSFEFOLFNPR;
                 BDBRATAPO13FNPR = BDBINSS13FNPR;
               END
            ELSE
               BEGIN
                 BDBRATAPOFNPR   = 0;
                 BDBRATAPOFEFNPR = 0;
                 BDBRATAPO13FNPR = 0;
               END
     
            BDSALFAMFNPR     = wsalfam;
            BDSALMATEMPFNPR  = wsalmatemp;

            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            IF (BDBINSSFEFOLFNPR > 0 AND BDINSSFNPR < 0) THEN
               BDINSSFEFOLFNPR = bdinssfefolfnpr + bdinssfnpr;
            IF (BDBINSSFNPR < 0 AND BDBINSSFEFOLFNPR > 0) THEN
               BDBINSSFEFOLFNPR = BDBINSSFEFOLFNPR + BDBINSSFNPR;
            SUSPEND;
          END
     END
END
^

/* Alter (SP_VRHF_DADOS_INSS_FT) */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FT(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRGPSSEFIP SMALLINT = 0,
PRFILIAIS VARCHAR(15000) = null,
PRCONTRATO INTEGER = 0,
PRORDEM INTEGER = 0)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBINSSMVFN NUMERIC(18,6),
BDBINSSMV13FN NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13INDFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDPERCRATCOL NUMERIC(18,6),
BDPERCDESCFPASCOL NUMERIC(18,6))
 AS
declare variable WCCNULL integer;
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCENTROS integer;
declare variable WCENTROSATU integer;
declare variable WCC integer;
declare variable WCCATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WPERCDEDFPAS numeric(18,6);
declare variable WSINDATU integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WCONTRCOL integer;
declare variable WBASEINSSCONTRATU numeric(18,6);
declare variable WINTERMITENTE DM_BOOLEAN;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDBINSSMVFT, FN.BDBINSSMV13FT, FN.BDINSSAPFT, FN.BDINSS13APFT, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, PREP.BDORDEM, PREP.BDCODCENTRO, PREP.BDCODTPCC,'||
                'case when COALESCE(FGTSGPS.BDCATEGORIACOL, 0) = 4 and COALESCE(FGTSGPS.BDCATEGORIAESOCIAL, 0) = 111 then ''TRUE'' else ''FALSE'' end BDINTERM from (';

  if (coalesce(prcontrato, 0) = 0) then
     begin
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDCODVER, FN.BDORDEM, FOLN.BDBINSSMVFT, FOLN.BDBINSSMV13FT, FOLN.BDINSSAPFT, FOLN.BDINSS13APFT from (';
     
  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';
     
       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBATOMADOR FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';
     
      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFTOMADOR = '||prref;
     
      wsql = wsql||') ';
     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBATOMADOR ';
      wwhere  = '';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wwhere = wwhere||prcodemp;
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||prcodcol;
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFTOMADOR = '||prref||' ';
         END
    
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END
     
  wsql = wsql||'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDORDEM = FN.BDORDEM) ';
     
     
       wsql = wsql||' union all ';
    end

  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDCODVER, FN.BDORDEM, FOLN.BDBINSSMVFT, FOLN.BDBINSSMV13FT, FOLN.BDINSSAPFT, FOLN.BDINSS13APFT from (';

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';

       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBATOMINT FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';

      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFTOMADOR = '||prref;

      wsql = wsql||') ';

      if (coalesce(prcontrato, 0) > 0) then
         wsql = wsql||' where FN.BDCODCONTTI = '||prcontrato||' ';

      if (coalesce(prordem, 0) > 0) then
         wsql = wsql||' where FN.BDORDEM = '||prordem||' ';

     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBATOMINT ';
      wwhere  = '';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wwhere = wwhere||prcodemp;
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||prcodcol;
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFTOMADOR = '||prref||' ';
         END
    
      IF (coalesce(prcontrato, 0) > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDCODCONTTI = '||prcontrato||' ';
         END

      IF (coalesce(prordem, 0) > 0) THEN
         BEGIN
      IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDORDEM = '||prordem||' ';
         END

      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END

  wsql = wsql||'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDORDEM = FN.BDORDEM and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';


  wsql = wsql||') FN ';

  wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FN.bdcodemp = prep.bdcodemp and FN.bdcodcol = prep.bdcodcol and FN.bdordem = prep.bdordem) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  ELSE
     wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';

  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FN.BDCODEMP and FGTSGPS.BDCODCOL = FN.BDCODCOL) ';

  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL,PREP.BDCODCENTRO,PREP.BDCODTPCC ';

  wempatu     = 0;
  wcolatu     = 0;
  wordematu   = 0;
  wcentrosatu = 0;
  wccatu      = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor = 0;
  wsindatu = 0;
  wcodsind = -1;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver,
                                  :wordem, :wcentros, :wcc, :wintermitente DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- não possui liminar
      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    IF (wordematu = 0) THEN
       wordematu = wordem;

    wCCNull = 0;
    IF ((wccatu IS NULL) AND (wcc IS NOT NULL)) THEN
       wccnull = 1;
    IF ((wccatu IS NOT NULL) AND (wcc IS NULL)) THEN
       wccnull = 1;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
         wcodsind = NULL;
         wwhere = 'select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFCOL <= '||prref||' order by BDREFCOL DESC';

         EXECUTE STATEMENT wwhere INTO :wcodsind;

         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wsindatu IS NOT NULL AND wsindatu <> 0) THEN
               SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- não possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- não possui liminar
           END

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = prref;
         BDORDEM        = wordematu;
         BDCODCENTRO    = wcentrosatu;
         BDCODTPCC      = wccatu;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13INDFN = wbinss13ap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDBAVPREV      = 0;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;


         IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
            BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

         IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
            BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

         wpercrat = 0;
         wpercdedfpas = 0;
         SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat, :wpercdedfpas, :wcontrcol;

         IF (wcontrcol = 1) THEN
            begin
              wwhere = 'select SUM(FT.BDBINSSFT) from (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,BDBINSSFT from VRHF_EMP_TFOLHATOMADOR '||
                                                      'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                                                      ' union all '||
                                                      'select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,BDBINSSFT from VRHF_EMP_TFOLHATOMINT '||
                                                      'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                       ') FT '||
                       'left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
                       'where FT.BDCODEMP = '||wempatu||' and FT.BDCODCOL = '||wcolatu||' and FT.BDREFTOMADOR = '||prref||' and COALESCE(PFN.BDCODCENTRO, 0) = '||COALESCE(:wcentrosatu, 0)||
                       case when COALESCE(:wccatu, 0) = 0 then ' and PFN.BDCODTPCC is null ' else ' and PFN.BDCODTPCC = '||COALESCE(:wccatu, 0) end;
              execute statement wwhere into :wbaseinsscontratu;
              wbaseinsscontratu = COALESCE(:wbaseinsscontratu, 0);
              BDBINSSFN = wbaseinsscontratu - wabasemv;
            end

         IF (BDBINSSFN < 0) THEN
            BDBINSSFN = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;   -- + BDBINSSFEFOLFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN        = wsalfam;
         BDSALMATEMPFN     = wsalmatemp;
         BDBINSSMVFN       = wabasemv;
         BDBINSSMV13FN     = wabasemv13;
         BDVALREEMBOLSO    = wreemb;
         BDVALINDEVIDO     = wvindevido;
         BDVALINDEVIDOSF   = wvindevidosf;
         BDPERCRATCOL      = wpercrat;
         BDPERCDESCFPASCOL = wpercdedfpas;
         SUSPEND;

         IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = prref;
              BDORDEM        = wordematu;
              BDCODCENTRO    = wcentrosatu;
              BDCODTPCC      = wccatu;
              BDINSSFN       = wainssap;
              BDINSSFEFOLFN  = winssfe;
              BDINSS13FN     = wainss13ap;
              BDBAVPREV      = wbavprev;

              --if (wainssap <> 0) then
              IF ((wbavprev <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbaseinssfe + wbinssap < 0) THEN
                      BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                      END

                   BDINSSFN  = wainssap;
                   BDBINSSFN = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFN  = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDBINSSFEFOLFN    = wbaseinssfe;
              BDBINSS13FN       = wbaseinss13;
              BDBINSS13APFN     = wbinss13ap;
              BDINSSAPFN        = wainssap;
              BDINSS13APFN      = wainss13ap;
              BDPERCRATCOL      = wpercrat;
              BDPERCDESCFPASCOL = wpercdedfpas;

              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSAPFN;   -- + BDBINSSFEFOLFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END
     
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
     
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;

              IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
                 BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

              IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
                 BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;
              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wordematu   = wordem;
         wcentrosatu = wcentros;
         wccatu      = wcc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    IF (prref >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfn BDSOMA FROM vrhf_emp_tverbafn X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref
           UNION ALL
           SELECT X.bdvalvft BDSOMA FROM vrhf_emp_tverbatomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    if (wintermitente = 'TRUE') then
       begin
         -- INSS 13o. descontado na folha normal
         IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
            winss13 = winss13 + wvalor;
       end

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base de INSS folha normal sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND ((wccatu <> 0) OR (wccatu IS NULL))) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       BDGPSSEFIP     = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = prref;
       BDORDEM        = wordematu;
       BDCODCENTRO    = wcentrosatu;
       BDCODTPCC      = wccatu;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF (BDBINSSFN+BDBINSSFEFOLFN < 0) THEN
          BEGIN
            BDBINSSFEFOLFN = 0;
            BDBINSSFN = 0;
          END

       IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
          BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

       IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
          BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

       wpercrat = 0;
       wpercdedfpas = 0;
       SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat, :wpercdedfpas, :wcontrcol;

       IF (wcontrcol = 1) THEN
          begin
            wwhere = 'select SUM(FT.BDBINSSFT) from VRHF_EMP_TFOLHATOMADOR FT '||
                     'left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
                     'where FT.BDCODEMP = '||wempatu||' and FT.BDCODCOL = '||wcolatu||' and FT.BDREFTOMADOR = '||prref||' and COALESCE(PFN.BDCODCENTRO, 0) = '||COALESCE(:wcentrosatu, 0)||
                     case when COALESCE(:wccatu, 0) = 0 then ' and PFN.BDCODTPCC is null ' else ' and PFN.BDCODTPCC = '||COALESCE(:wccatu, 0) end;
            execute statement wwhere into :wbaseinsscontratu;
            wbaseinsscontratu = COALESCE(:wbaseinsscontratu, 0);
            BDBINSSFN = wbaseinsscontratu - wabasemv;
          end

       IF (BDBINSSFN < 0) THEN
          BDBINSSFN = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;    -- + wbaseinssfe;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN        = wsalfam;
       BDSALMATEMPFN     = wsalmatemp;
       BDBINSSMVFN       = wabasemv;
       BDBINSSMV13FN     = wabasemv13;
       BDVALREEMBOLSO    = wreemb;
       BDVALINDEVIDO     = wvindevido;
       BDVALINDEVIDOSF   = wvindevidosf;
       BDPERCRATCOL      = wpercrat;
       BDPERCDESCFPASCOL = wpercdedfpas;
       SUSPEND;

    IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDORDEM        = wordematu;
            BDCODCENTRO    = wcentrosatu;
            BDCODTPCC      = wccatu;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbaseinssfe + wbinssap < 0) THEN
                    BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                    END

                 BDINSSFN  = wainssap;
                 BDBINSSFN = wbinssap;
               END
            ELSE
               BEGIN
                 BDINSSFN  = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN     = winssfe;
            BDINSS13FN        = wainss13ap;
            BDBINSSFEFOLFN    = wbaseinssfe;
            BDBINSS13FN       = wbaseinss13;
            BDBINSSAPFN       = wbinssap;
            BDBINSS13INDFN    = wbinss13ap;
            BDBINSS13APFN     = wbinss13ap;
            BDINSSAPFN        = wainssap;
            BDINSS13APFN      = wainss13ap;
            BDPERCRATCOL      = wpercrat;
            BDPERCDESCFPASCOL = wpercdedfpas;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;    -- + BDBINSSFEFOLFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;

            IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
               BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;
            IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
               BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

            SUSPEND;
         END
     END
END
^

/* Alter (SP_VRHF_DADOS_INSS_FT_PREV_RESC) */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FT_PREV_RESC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(30000),
PRREF INTEGER,
PRGPSSEFIP SMALLINT = 0,
PRFILIAIS VARCHAR(15000) = NULL)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDINSSFTPR NUMERIC(18,6),
BDINSSFEFOLFTPR NUMERIC(18,6),
BDINSS13FTPR NUMERIC(18,6),
BDBINSSFTPR NUMERIC(18,6),
BDBINSSFEFOLFTPR NUMERIC(18,6),
BDBINSS13FTPR NUMERIC(18,6),
BDBRATAPOFTPR NUMERIC(18,6),
BDBRATAPOFEFTPR NUMERIC(18,6),
BDBRATAPO13FTPR NUMERIC(18,6),
BDSALFAMFTPR NUMERIC(18,6),
BDSALMATEMPFTPR NUMERIC(18,6),
BDBINSSAPFTPR NUMERIC(18,6),
BDBINSS13INDFTPR NUMERIC(18,6),
BDBINSS13APFTPR NUMERIC(18,6),
BDINSSAPFTPR NUMERIC(18,6),
BDINSS13APFTPR NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDPERCRATCOL NUMERIC(18,6),
BDPERCDESCFPASCOL NUMERIC(18,6))
 AS
DECLARE VARIABLE WCCNULL INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WWHERE VARCHAR(32000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WCENTROS INTEGER;
DECLARE VARIABLE WCENTROSATU INTEGER;
DECLARE VARIABLE WCC INTEGER;
DECLARE VARIABLE WCCATU INTEGER;
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WINSSVER INTEGER;
DECLARE VARIABLE WBASEGPSVER VARCHAR(5);
DECLARE VARIABLE WREEMBGPSVER VARCHAR(5);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WINSS NUMERIC(18,6);
DECLARE VARIABLE WINSSFE NUMERIC(18,6);
DECLARE VARIABLE WINSS13 NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS NUMERIC(18,6);
DECLARE VARIABLE WBASEINSSFE NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS13 NUMERIC(18,6);
DECLARE VARIABLE WSALFAM NUMERIC(18,6);
DECLARE VARIABLE WSALMATEMP NUMERIC(18,6);
DECLARE VARIABLE WPERCRAT NUMERIC(18,6);
DECLARE VARIABLE WBINSSAP NUMERIC(18,6);
DECLARE VARIABLE WBINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WINSSAP NUMERIC(18,6);
DECLARE VARIABLE WINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WAINSSAP NUMERIC(18,6);
DECLARE VARIABLE WAINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WEMPAP INTEGER;
DECLARE VARIABLE WSOMAAP NUMERIC(18,6);
DECLARE VARIABLE WCODSIND INTEGER;
DECLARE VARIABLE WLIMSIND INTEGER;
DECLARE VARIABLE WLIMEMP INTEGER;
DECLARE VARIABLE WREEMB NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDO NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDOSF NUMERIC(18,6);
DECLARE VARIABLE WBAVPREV NUMERIC(18,6);
DECLARE VARIABLE WTEMVALOR SMALLINT;
DECLARE VARIABLE WPERCDEDFPAS NUMERIC(18,6);
DECLARE VARIABLE WSINDATU INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WORDEMATU INTEGER;
DECLARE VARIABLE WCONTRCOL INTEGER;
DECLARE VARIABLE WBASEINSSCONTR NUMERIC(18,6);
DECLARE VARIABLE WBASEINSSCONTRATU NUMERIC(18,6);
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFTPR, FTPR.BDINSSAPFTPR, FTPR.BDINSS13APFTPR, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, PREP.BDORDEM, PREP.BDCODCENTRO, PREP.BDCODTPCC, FTPR.BDBINSSFTPR from (';

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';

       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAFT_PREV_RESC FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';

      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFTOMADOR = '||prref;

      wsql = wsql||') ';
     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBAFT_PREV_RESC ';
      wwhere  = '';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wwhere = wwhere||prcodemp;
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||prcodcol;
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFTOMADOR = '||prref||' ';
         END
    
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END

  wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FN.bdcodemp = prep.bdcodemp and FN.bdcodcol = prep.bdcodcol and FN.bdordem = prep.bdordem) ';
  wsql = wsql||'join VRHF_EMP_TFOLTOM_PREV_RESC FTPR on (FTPR.BDCODEMP = FN.BDCODEMP and FTPR.BDCODCOL = FN.BDCODCOL and FTPR.BDORDEM = FN.BDORDEM) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  ELSE
     wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL,PREP.BDCODCENTRO,PREP.BDCODTPCC ';

  wempatu     = 0;
  wcolatu     = 0;
  wordematu   = 0;
  wcentrosatu = 0;
  wccatu      = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor = 0;
  wsindatu = 0;
  wcodsind = -1;
  wbaseinsscontratu = 0;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver,
                                  :wordem, :wcentros, :wcc, :wbaseinsscontr DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- n?o possui liminar
      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    IF (wordematu = 0) THEN
       wordematu = wordem;

    wCCNull = 0;
    IF ((wccatu IS NULL) AND (wcc IS NOT NULL)) THEN
       wccnull = 1;
    IF ((wccatu IS NOT NULL) AND (wcc IS NULL)) THEN
       wccnull = 1;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
         wcodsind = NULL;

         SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wsindatu IS NOT NULL AND wsindatu <> 0) THEN
               SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- não possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- n?o possui liminar
           END

         BDGPSSEFIP       = 0;
         BDCODEMP         = wempatu;
         BDCODCOL         = wcolatu;
         BDREFFN          = prref;
         BDORDEM          = wordematu;
         BDCODCENTRO      = wcentrosatu;
         BDCODTPCC        = wccatu;
         BDINSSFTPR       = winss;
         BDINSSFEFOLFTPR  = winssfe;
         BDINSS13FTPR     = winss13;
         BDBINSSFEFOLFTPR = wbaseinssfe;
         BDBINSSAPFTPR    = wbinssap;
         BDBINSS13INDFTPR = wbinss13ap;
         BDBINSS13APFTPR  = wbinss13ap;
         BDINSSAPFTPR     = wainssap;
         BDINSS13APFTPR   = wainss13ap;
         BDBAVPREV      = 0;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSS13INDFTPR = 0;
         ELSE
            BDBINSS13INDFTPR = wbinss13ap;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFTPR = wbinssap;
         ELSE
            BDBINSSFTPR = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FTPR = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FTPR = wbaseinss13;


         IF (BDBINSSFEFOLFTPR > 0 AND BDINSSFTPR < 0) THEN
            BDINSSFEFOLFTPR = bdinssfefolftpr + bdinssftpr;

         IF (BDBINSSFTPR < 0 AND BDBINSSFEFOLFTPR > 0) THEN
            BDBINSSFEFOLFTPR = BDBINSSFEFOLFTPR + BDBINSSFTPR;

         wpercrat = 0;
         wpercdedfpas = 0;
         SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat, :wpercdedfpas, :wcontrcol;

         IF (wcontrcol = 1) THEN
            BDBINSSFTPR = wbaseinsscontratu;

         IF (BDBINSSFTPR < 0) THEN
            BDBINSSFTPR = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFTPR   = BDBINSSFTPR;   -- + BDBINSSFEFOLFN;
              BDBRATAPOFEFTPR = BDBINSSFEFOLFTPR;
              BDBRATAPO13FTPR = BDBINSS13FTPR;
            END
         ELSE
            BEGIN
              BDBRATAPOFTPR   = 0;
              BDBRATAPOFEFTPR = 0;
              BDBRATAPO13FTPR = 0;
            END

         BDSALFAMFTPR        = wsalfam;
         BDSALMATEMPFTPR     = wsalmatemp;
         BDVALREEMBOLSO      = wreemb;
         BDVALINDEVIDO       = wvindevido;
         BDVALINDEVIDOSF     = wvindevidosf;
         BDPERCRATCOL        = wpercrat;
         BDPERCDESCFPASCOL   = wpercdedfpas;
         SUSPEND;

         IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP       = 1;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREFFN          = prref;
              BDORDEM          = wordematu;
              BDCODCENTRO      = wcentrosatu;
              BDCODTPCC        = wccatu;
              BDINSSFTPR       = wainssap;
              BDINSSFEFOLFTPR  = winssfe;
              BDINSS13FTPR     = wainss13ap;
              BDBAVPREV        = wbavprev;

              --if (wainssap <> 0) then
              IF ((wbavprev <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbaseinssfe + wbinssap < 0) THEN
                      BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                      END

                   BDINSSFTPR  = wainssap;
                   BDBINSSFTPR = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFTPR  = winss;
                   BDBINSSFTPR = wbaseinss;
                 END

              BDBINSSFEFOLFTPR    = wbaseinssfe;
              BDBINSS13FTPR       = wbaseinss13;
              BDBINSS13APFTPR     = wbinss13ap;
              BDINSSAPFTPR        = wainssap;
              BDINSS13APFTPR      = wainss13ap;
              BDPERCRATCOL        = wpercrat;
              BDPERCDESCFPASCOL   = wpercdedfpas;

              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFTPR   = BDBINSSAPFTPR;   -- + BDBINSSFEFOLFN;
                   BDBRATAPOFEFTPR = BDBINSSFEFOLFTPR;
                   BDBRATAPO13FTPR = BDBINSS13FTPR;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFTPR   = 0;
                   BDBRATAPOFEFTPR = 0;
                   BDBRATAPO13FTPR = 0;
                 END
     
              BDSALFAMFTPR     = wsalfam;
              BDSALMATEMPFTPR  = wsalmatemp;

              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;

              IF (BDBINSSFEFOLFTPR > 0 AND BDINSSFTPR < 0) THEN
                 BDINSSFEFOLFTPR = bdinssfefolftpr + bdinssftpr;

              IF (BDBINSSFTPR < 0 AND BDBINSSFEFOLFTPR > 0) THEN
                 BDBINSSFEFOLFTPR = BDBINSSFEFOLFTPR + BDBINSSFTPR;
              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wordematu   = wordem;
         wcentrosatu = wcentros;
         wccatu      = wcc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wbaseinsscontratu = wbaseinsscontr;

    IF (prref >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfnpr BDSOMA FROM vrhf_emp_tverbafn_prev_resc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp
           UNION ALL
           SELECT X.bdvalvftpr BDSOMA FROM vrhf_emp_tverbaft_prev_resc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS f?rias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescis?o descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --n?o incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS f?rias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de sal?rio fam?lia
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de sal?rio maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base de INSS folha normal sem o aviso pr?vio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --n?o incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --n?o incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso pr?vio indenizado do 13? sal?rio
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND ((wccatu <> 0) OR (wccatu IS NULL))) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- n?o possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- n?o possui liminar

       BDGPSSEFIP       = 0;
       BDCODEMP         = wempatu;
       BDCODCOL         = wcolatu;
       BDREFFN          = prref;
       BDORDEM          = wordematu;
       BDCODCENTRO      = wcentrosatu;
       BDCODTPCC        = wccatu;
       BDINSSFTPR       = winss;
       BDINSSFEFOLFTPR  = winssfe;
       BDINSS13FTPR     = winss13;
       BDBINSSFEFOLFTPR = wbaseinssfe;
       BDBINSSAPFTPR    = wbinssap;
       BDBINSS13APFTPR  = wbinss13ap;
       BDINSSAPFTPR     = wainssap;
       BDINSS13APFTPR   = wainss13ap;
       BDBAVPREV        = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFTPR = wbinssap;
       ELSE
          BDBINSSFTPR = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFTPR = 0;
       ELSE
          BDBINSS13INDFTPR = wbinss13ap;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FTPR = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FTPR = wbaseinss13;

       IF (BDBINSSFTPR+BDBINSSFEFOLFTPR < 0) THEN
          BEGIN
            BDBINSSFEFOLFTPR = 0;
            BDBINSSFTPR = 0;
          END

       IF (BDBINSSFEFOLFTPR > 0 AND BDINSSFTPR < 0) THEN
          BDINSSFEFOLFTPR = bdinssfefolftpr + bdinssftpr;

       IF (BDBINSSFTPR < 0 AND BDBINSSFEFOLFTPR > 0) THEN
          BDBINSSFEFOLFTPR = BDBINSSFEFOLFTPR + BDBINSSFTPR;

       wpercrat = 0;
       wpercdedfpas = 0;
       SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat, :wpercdedfpas, :wcontrcol;

       IF (wcontrcol = 1) THEN
          BDBINSSFTPR = wbaseinsscontratu;

       IF (BDBINSSFTPR < 0) THEN
          BDBINSSFTPR = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFTPR   = wbaseinss;    -- + wbaseinssfe;
            BDBRATAPOFEFTPR = wbaseinssfe;
            BDBRATAPO13FTPR = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFTPR   = 0;
            BDBRATAPOFEFTPR = 0;
            BDBRATAPO13FTPR = 0;
          END

       BDSALFAMFTPR        = wsalfam;
       BDSALMATEMPFTPR     = wsalmatemp;
       BDVALREEMBOLSO      = wreemb;
       BDVALINDEVIDO       = wvindevido;
       BDVALINDEVIDOSF     = wvindevidosf;
       BDPERCRATCOL        = wpercrat;
       BDPERCDESCFPASCOL   = wpercdedfpas;
       SUSPEND;

    IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDORDEM        = wordematu;
            BDCODCENTRO    = wcentrosatu;
            BDCODTPCC      = wccatu;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbaseinssfe + wbinssap < 0) THEN
                    BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                    END

                 BDINSSFTPR  = wainssap;
                 BDBINSSFTPR = wbinssap;
               END
            ELSE
               BEGIN
                 BDINSSFTPR  = winss;
                 BDBINSSFTPR = wbaseinss;
               END

            BDINSSFEFOLFTPR     = winssfe;
            BDINSS13FTPR        = wainss13ap;
            BDBINSSFEFOLFTPR    = wbaseinssfe;
            BDBINSS13FTPR       = wbaseinss13;
            BDBINSSAPFTPR       = wbinssap;
            BDBINSS13INDFTPR    = wbinss13ap;
            BDBINSS13APFTPR     = wbinss13ap;
            BDINSSAPFTPR        = wainssap;
            BDINSS13APFTPR      = wainss13ap;
            BDPERCRATCOL        = wpercrat;
            BDPERCDESCFPASCOL   = wpercdedfpas;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFTPR   = BDBINSSFTPR;    -- + BDBINSSFEFOLFN;
                 BDBRATAPOFEFTPR = BDBINSSFEFOLFTPR;
                 BDBRATAPO13FTPR = BDBINSS13FTPR;
               END
            ELSE
               BEGIN
                 BDBRATAPOFTPR   = 0;
                 BDBRATAPOFEFTPR = 0;
                 BDBRATAPO13FTPR = 0;
               END
     
            BDSALFAMFTPR     = wsalfam;
            BDSALMATEMPFTPR  = wsalmatemp;

            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;

            IF (BDBINSSFEFOLFTPR > 0 AND BDINSSFTPR < 0) THEN
               BDINSSFEFOLFTPR = bdinssfefolftpr + bdinssftpr;
            IF (BDBINSSFTPR < 0 AND BDBINSSFEFOLFTPR > 0) THEN
               BDBINSSFEFOLFTPR = BDBINSSFEFOLFTPR + BDBINSSFTPR;

            SUSPEND;
         END
     END
END
^

/* Alter (SP_VRHF_DADOS_INSS_FTC) */
ALTER PROCEDURE SP_VRHF_DADOS_INSS_FTC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32000),
PRREF INTEGER,
PRREFPAG INTEGER,
PRGPSSEFIP SMALLINT = 0)
 RETURNS(BDGPSSEFIP INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFCOMP INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDINSSFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBINSSMVFN NUMERIC(18,6),
BDBINSSMV13FN NUMERIC(18,6),
BDCODTIPOFC INTEGER,
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDVALREEMBOLSO NUMERIC(18,6),
BDVALINDEVIDO NUMERIC(18,6),
BDVALINDEVIDOSF NUMERIC(18,6),
BDBAVPREV NUMERIC(18,6),
BDBINSS13INDFN NUMERIC(18,6))
 AS
DECLARE VARIABLE WCCNULL INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WWHERE VARCHAR(32000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WCENTROS INTEGER;
DECLARE VARIABLE WCENTROSATU INTEGER;
DECLARE VARIABLE WCC INTEGER;
DECLARE VARIABLE WCCATU INTEGER;
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WINSSVER INTEGER;
DECLARE VARIABLE WBASEGPSVER VARCHAR(5);
DECLARE VARIABLE WREEMBGPSVER VARCHAR(5);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WINSS NUMERIC(18,6);
DECLARE VARIABLE WINSSFE NUMERIC(18,6);
DECLARE VARIABLE WINSS13 NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS NUMERIC(18,6);
DECLARE VARIABLE WBASEINSSFE NUMERIC(18,6);
DECLARE VARIABLE WBASEINSS13 NUMERIC(18,6);
DECLARE VARIABLE WSALFAM NUMERIC(18,6);
DECLARE VARIABLE WSALMATEMP NUMERIC(18,6);
DECLARE VARIABLE WBASEMV NUMERIC(18,6);
DECLARE VARIABLE WBASEMV13 NUMERIC(18,6);
DECLARE VARIABLE WPERCRAT NUMERIC(18,6);
DECLARE VARIABLE WCODTIPOFC INTEGER;
DECLARE VARIABLE WCODFCATU INTEGER;
DECLARE VARIABLE WBINSSAP NUMERIC(18,6);
DECLARE VARIABLE WBINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WINSSAP NUMERIC(18,6);
DECLARE VARIABLE WINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WAINSSAP NUMERIC(18,6);
DECLARE VARIABLE WAINSS13AP NUMERIC(18,6);
DECLARE VARIABLE WABASEMV NUMERIC(18,6);
DECLARE VARIABLE WABASEMV13 NUMERIC(18,6);
DECLARE VARIABLE WEMPAP INTEGER;
DECLARE VARIABLE WSOMAAP NUMERIC(18,6);
DECLARE VARIABLE WCODSIND INTEGER;
DECLARE VARIABLE WLIMSIND INTEGER;
DECLARE VARIABLE WLIMEMP INTEGER;
DECLARE VARIABLE WREEMB NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDO NUMERIC(18,6);
DECLARE VARIABLE WVINDEVIDOSF NUMERIC(18,6);
DECLARE VARIABLE WBAVPREV NUMERIC(18,6);
DECLARE VARIABLE WTEMVALOR SMALLINT;
DECLARE VARIABLE WREFFCA INTEGER;
DECLARE VARIABLE WREFFC INTEGER;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, VER.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, PREP.BDCODCENTRO, PREP.BDCODTPCC, FOLN.BDCODTIPOFC ';
  wsql = wsql||'from (select * from VRHF_EMP_TVERBAFCTOMADOR ';
  wwhere  = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFTOMADOR = '||prref||' ';
     END

  IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFFC >= '||prrefpag||'01 and BDREFFC <= '||prrefpag||'31 ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||') FN ';
  wsql = wsql||'join VRHF_EMP_TFOLTOMCOMP FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDREFFC = FN.BDREFFC and FOLN.BDORDEM = FN.BDORDEM) ';
  wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FN.bdcodemp = prep.bdcodemp and FN.bdcodcol = prep.bdcodcol and FN.bdordem = prep.bdordem) ';
  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFC,PREP.BDCODCENTRO,PREP.BDCODTPCC ';

  wempatu     = 0;
  wcolatu     = 0;
  wcentrosatu = 0;
  wccatu      = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor   = 0;
  wreffca     = 0;
  wreffca     = 0;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wreffc, :wvalor, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver, :wcentros, :wcc, :wcodtipofc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wreffca = 0) THEN
       wreffca = wreffc;

    IF (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    wCCNull = 0;
    IF ((wccatu IS NULL) AND (wcc IS NOT NULL)) THEN
       wccnull = 1;
    IF ((wccatu IS NOT NULL) AND (wcc IS NULL)) THEN
       wccnull = 1;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1) OR (wreffca <> wreffc)) THEN
       BEGIN
         wcodsind = NULL;
         wlimemp = NULL;
         wlimsind = NULL;
         SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
            BEGIN
              SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
            END

         IF (wlimsind IS NULL) THEN
            wlimsind = 0;             -- n?o possui liminar

         IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
            SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

         IF (wlimemp IS NULL) THEN
            wlimemp = 0;    -- n?o possui liminar

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = prref;
         BDREFCOMP      = prrefpag;
         BDCODCENTRO    = wcentrosatu;
         BDCODTPCC      = wccatu;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;
         BDCODTIPOFC    = wcodfcatu;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDBAVPREV      = 0;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         wpercrat = 0;
         SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN     = wsalfam;
         BDSALMATEMPFN  = wsalmatemp;

         BDBINSSMVFN    = wabasemv;
         BDBINSSMV13FN  = wabasemv13;
         BDVALREEMBOLSO = wreemb;
         BDVALINDEVIDO  = wvindevido;
         BDVALINDEVIDOSF  = wvindevidosf;

         SUSPEND;

         IF (prrefpag >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = prref;
              BDREFCOMP      = prrefpag;
              BDCODCENTRO    = wcentrosatu;
              BDCODTPCC      = wccatu;
              BDBAVPREV      = wbavprev;

              IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                   BDINSSFN  = wainssap;
                   BDBINSSFN = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFN  = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDINSSFEFOLFN  = winssfe;
              BDINSS13FN     = winss13;
              BDBINSSFEFOLFN = wbaseinssfe;
              BDBINSS13FN    = wbaseinss13;
              BDCODTIPOFC    = wcodfcatu;
              BDBINSSAPFN    = wbinssap;
              BDBINSS13APFN  = wbinss13ap;
              BDINSSAPFN     = wainssap;
              BDINSS13APFN   = wainss13ap;
              BDBINSS13INDFN = wbinss13ap;
     
              wpercrat = 0;
              SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;
     
              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END
     
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
     
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;
              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wcentrosatu = wcentros;
         wccatu      = wcc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainss13ap  = 0;
         wainssap    = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor   = 0;
         wreffca     = wreffc;
         wreffca     = wreffc;
       END

    wcodfcatu  = wcodtipofc;
    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    IF (prrefpag >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref AND X.bdrefcomp = :prrefpag
           UNION ALL
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafctomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref AND X.bdrefcomp = :prrefpag
           UNION ALL
           SELECT X.bdvalvfn BDSOMA
           FROM vrhf_emp_tverbafn X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref
           UNION ALL
           SELECT X.bdvalvft BDSOMA
           FROM vrhf_emp_tverbatomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS f?rias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. complemento de 13? na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
       winss13 = winss13 + wvalor;

    -- INSS 13o. rescis?o descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --n?o incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS f?rias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. sal?rio descontado na rescis?o
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de sal?rio fam?lia
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de sal?rio maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base INSS sem o aviso pr?vio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --n?o incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --n?o incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso pr?vio indenizado do 13? sal?rio
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND ((wccatu <> 0) OR (wccatu IS NULL)) AND (wreffca <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- n?o possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- n?o possui liminar

       BDGPSSEFIP     = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = prref;
       BDREFCOMP      = prrefpag;
       BDCODCENTRO    = wcentrosatu;
       BDCODTPCC      = wccatu;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDCODTIPOFC    = wcodfcatu;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;
 
       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       wpercrat = 0;
       SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN     = wsalfam;
       BDSALMATEMPFN  = wsalmatemp;

       BDBINSSMVFN    = wabasemv;
       BDBINSSMV13FN  = wabasemv13;
       BDVALREEMBOLSO = wreemb;
       BDVALINDEVIDO  = wvindevido;
       BDVALINDEVIDOSF = wvindevidosf;
       SUSPEND;

       IF (prrefpag >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDREFCOMP      = prrefpag;
            BDCODCENTRO    = wcentrosatu;
            BDCODTPCC      = wccatu;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                 BDINSSFN  = wainssap;
                 BDBINSSFN = wbinssap;
               END
            ELSE
               BEGIN
                 BDINSSFN  = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN  = winssfe;
            BDINSS13FN     = winss13;
            BDBINSSFEFOLFN = wbaseinssfe;
            BDBINSS13FN    = wbaseinss13;
            BDCODTIPOFC    = wcodfcatu;
            BDBINSSAPFN    = wbinssap;
            BDBINSS13APFN  = wbinss13ap;
            BDINSSAPFN     = wainssap;
            BDINSS13APFN   = wainss13ap;
            BDBINSS13INDFN = wbinss13ap;
     
            wpercrat = 0;
            SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;
            SUSPEND;
          END
     END
END
^

/* Alter (SP_VRHF_DADOS_IR_13) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
declare variable WULTDIAMES integer;
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(200);
declare variable WREFINI integer;
declare variable WDATARESC date;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDATAPGTO date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WSQLAUX varchar(1000);
declare variable WEXISTE13MES integer;
declare variable WUSARTMP_EMP_SELECT smallint;
BEGIN
  /* 13? SAL?RIO */
  WUSARTMP_EMP_SELECT = 0;
  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDCODVER,FOL.BDVALV13,FOLN.BDDEP13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROC13,FOLN.BDHORAPROC13 ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREF13, VFN.bdcodver, VFN.BDVALV13 FROM vrhf_emp_tverba13 VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverba13 FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) join vrhf_emp_t13sal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREF13 = FOL.BDREF13) ';
       wsql = wsql||'where FOL.BDREF13 >= '||prrefini||' and FOL.BDREF13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13 ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDCODVER,FO.BDVALV13,FOLN.BDDEP13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROC13,FOLN.BDHORAPROC13 ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREF13, VFN.BDCODVER,VFN.BDVALV13 FROM vrhf_emp_tverba13 VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverba13 FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) join vrhf_emp_t13sal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREF13 = FO.BDREF13) ';
       wsql = wsql||'where FO.BDREF13 >= '||prrefini||' and FO.BDREF13 <= '||prreffim||' ';
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
     
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREF13 ';
     END

  wempatu = 0;
  wcolatu = 0;
  wrefatu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  BDVALABO   = 0;
  BDLUCROPJ  = 0;
  BDAJCUSTOS = 0;
  BDDESPMED  = 0;
  BDINDRESC  = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wcodver,:wvalor,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu)) THEN
       BEGIN
         IF (SUBSTRING(CAST(wrefatu AS VARCHAR(6)) FROM 5 FOR 2) = '12') THEN
            BEGIN
              wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-12-20') AS DATE);
              wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
            END
         ELSE
            BEGIN
              wrefpagto = wrefatu;
              wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||SUBSTRING(CAST(wrefatu AS VARCHAR(6)) FROM 5 FOR 2)||'-20') AS DATE);
              wultdiames = EXTRACT(DAY FROM (wdataatu - EXTRACT(DAY FROM wdataatu) +
                         32 - EXTRACT(DAY FROM wdataatu - EXTRACT(DAY FROM wdataatu) + 32)));
              wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||SUBSTRING(CAST(wrefatu AS VARCHAR(6)) FROM 5 FOR 2)||'-'||wultdiames) AS DATE);
            END

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                        ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
              EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = wdepatu;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;

              if (wprepri <> 0) then
                 BDPREVPRIV = wprepri;
              else
                 BDPREVPRIV = wprevprivcad;

              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 10;    -- 13? sal?rio
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              SUSPEND;
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         wrendis    = 0;
         wdrendis   = '';
       END

    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;
    IF (wirver = 3) THEN -- 13? sal?rio
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir13 = wbaseir13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 7) <> '5.001.8') THEN
                 wbaseir13 = wbaseir13 - wvalor;
            END
       END
    --                                     INSS
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.0') THEN
       winss13 = winss13 + wvalor;
    --                                     IR
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.1') THEN
       wir13 = wir13 + wvalor;
    wdepatu  = wdep;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '5.001.8.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '5.001.8.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '5.001.8.2') THEN
       wprepri = wprepri + wvalor;
    -- Rendimentos isentos
    IF (UPPER(wrendisentover) = 'TRUE') THEN
       BEGIN
         wrendis = wrendis + wvalor;
         wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 200);
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0) THEN
     BEGIN
       IF (SUBSTRING(CAST(wrefatu AS VARCHAR(6)) FROM 5 FOR 2) = '12') THEN
          BEGIN
            wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-12-20') AS DATE);
            wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
          END
       ELSE
          BEGIN
            wrefpagto = wrefatu;
            wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||SUBSTRING(CAST(wrefatu AS VARCHAR(6)) FROM 5 FOR 2)||'-20') AS DATE);
            wultdiames = EXTRACT(DAY FROM (wdataatu - EXTRACT(DAY FROM wdataatu) +
                       32 - EXTRACT(DAY FROM wdataatu - EXTRACT(DAY FROM wdataatu) + 32)));
            wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||SUBSTRING(CAST(wrefatu AS VARCHAR(6)) FROM 5 FOR 2)||'-'||wultdiames) AS DATE);
          END

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;

            if (wprepri <> 0) then
               BDPREVPRIV = wprepri;
            else
               BDPREVPRIV = wprevprivcad;

            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 10;    -- 13? sal?rio
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
          END
     END

  /* 13? RESCISAO DA FOLHA NORMAL */
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,RESC.BDDATAPAGRESCISAO,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.bdcodver, VFN.BDVALVFN FROM vrhf_emp_tverbafn VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbafn FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN) ';
       wsql = wsql||'join vrh_emp_trescisao RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL and RESC.BDREFRESCISAO = FOL.BDREFFN) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.bdcodpres = RESC.BDCODPRES) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and ((FOL.BDREFFN >= '||wrefini||' and FOL.BDREFFN <= '||prreffim||') or ';
       wsql = wsql||'       (FOL.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,RESC.BDDATAPAGRESCISAO,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDCODVER,VFN.BDVALVFN FROM vrhf_emp_tverbafn VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbafn FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFFN = FO.BDREFFN) ';
       wsql = wsql||'join vrh_emp_trescisao RESC on (RESC.BDCODEMP = FO.BDCODEMP and RESC.BDCODCOL = FO.BDCODCOL and RESC.BDREFRESCISAO = FO.BDREFFN) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.bdcodpres = RESC.BDCODPRES) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FO.BDCODEMP and COL.BDCODCOL = FO.BDCODCOL) ';
       wsql = wsql||'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and ((FO.BDREFFN >= '||wrefini||' and FO.BDREFFN <= '||prreffim||') or ';
       wsql = wsql||'       (FO.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||') ';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN ';
     END

  wempatu = 0;
  wcolatu = 0;
  wrefatu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wcodver,:wvalor,:wdep,:wclassif,:wdescver,:wdataresc,:wdataproc,:whoraproc,:wtipomov,:wdatapgto DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                        ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 '||
                        ' order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
              EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

              if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
                 begin
                   /*Se tiver 13? no m?s da rescis?o n?o deve considerar o dependente novamente*/
                   wsqlaux = 'select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = '||wempatu||' and dt.bdcodcol = '||wcolatu||' and dt.bdref13 ='||wrefpagto;
                   wexiste13mes = NULL;
                   EXECUTE STATEMENT wsqlaux INTO :wexiste13mes;
                   IF (wexiste13mes IS NOT NULL) THEN
                      wdepatu = 0;
          
                   BDCODEMP         = wempatu;
                   BDCODCOL         = wcolatu;
                   BDREF            = wrefatu;
                   BDREFPAG         = wrefpagto;
                   BDRENDTRIBUTAVEL = wbaseir13;
                   BDINSS           = winss13;
                   BDIR             = wir13;
          
                   IF (wbaseir13 <= 0 AND winss13 <= 0) THEN
                      wdepatu = 0;
          
                   BDDEP            = wdepatu;
                   BDLUCROPJ        = 0;
                   BDDESPMED        = 0;
                   BDAJCUSTOS       = 0;
                   BDPENJUD         = 0;
                   BDPENALIM        = 0;
     
                   if (wprepri <> 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;
     
                   BDVALABO         = 0;
                   BDRENDISENTOS    = 0;
                   BDDRENDISENTOS   = '';
                   BDDATAPGTO       = wdataatu;
                   BDTIPO           = 101;    -- 13? rescis?o
                   BDINFADIC        = '';
                   BDDATAPROC       = wdataproca;
                   BDHORAPROC       = whoraproca;
                   SUSPEND;
                 end
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         wrendis    = 0;
         wdrendis   = '';
       END

    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;
    IF (wirver = 3) THEN -- 13? sal?rio
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir13 = wbaseir13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir13 = wbaseir13 - wvalor;
            END
       END
    --                                     INSS 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;
    --                                     IR 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.7') THEN
       wir13 = wir13 + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.601.8.2') THEN
       wprepri = wprepri + wvalor;

    wdepatu = wdep;
    IF (wtipomov < 1 ) THEN
       wdataatu = wdataresc;
    ELSE
       wdataatu = wdatapgto;

    wdataproca = wdataproc;
    whoraproca = whoraproc;

  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;
            if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
               begin
            /*Se tiver 13? no m?s da rescis?o n?o deve considerar o dependente novamente*/
            wsqlaux = 'select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = '||wempatu||' and dt.bdcodcol = '||wcolatu||' and dt.bdref13 ='||wrefpagto;
            wexiste13mes = NULL;
            EXECUTE STATEMENT wsqlaux INTO :wexiste13mes;
            IF (wexiste13mes IS NOT NULL) THEN
               wdepatu = 0;
     
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;

            if (wprepri <> 0) then
               BDPREVPRIV = wprepri;
            else
               BDPREVPRIV = wprevprivcad;

            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 101;    -- 13? rescis?o
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
               end
          END
     END

  /*  13? RESCISAO FOLHA TOMADOR  */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,RESC.BDDATAPAGRESCISAO,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFT ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFTOMADOR, VFN.BDORDEM, VFN.bdcodver, VFN.BDVALVFT FROM vrhf_emp_tverbatomador VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbatomador FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and FOLN.BDORDEM = FOL.BDORDEM) ';
       wsql = wsql||'join vrh_emp_trescisao RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL and RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and ((FOL.BDREFTOMADOR >= '||wrefini||' and FOL.BDREFTOMADOR <= '||prreffim||') or ';
       wsql = wsql||'       (FOL.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,RESC.BDDATAPAGRESCISAO,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFT ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFTOMADOR, VFN.BDORDEM, VFN.BDCODVER,VFN.BDVALVFT FROM vrhf_emp_tverbatomador VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbatomador FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and FOLN.BDORDEM = FO.BDORDEM) ';
       wsql = wsql||'join vrh_emp_trescisao RESC on (RESC.BDCODEMP = FO.BDCODEMP and RESC.BDCODCOL = FO.BDCODCOL and RESC.BDREFRESCISAO = FO.BDREFTOMADOR) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FO.BDCODEMP and COL.BDCODCOL = FO.BDCODCOL) ';
       wsql = wsql||'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and ((FO.BDREFTOMADOR >= '||wrefini||' and FO.BDREFTOMADOR <= '||prreffim||') or ';
       wsql = wsql||'       (FO.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM ';
     END

  wempatu   = 0;
  wcolatu   = 0;
  wrefatu   = 0;
  wordematu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wordem,:wcodver,:wvalor,:wdep,:wclassif,:wdescver,:wdataresc,:wdataproc,:whoraproc,:wtipomov,:wdatapgto DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF (wordematu = 0) THEN
       wordematu = wordem;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordem <> wordematu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
                   wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                             ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 '||
                             ' order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
                   EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

              if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
                 begin
                   /*Se tiver 13? no m?s da rescis?o n?o deve considerar o dependente novamente*/
                   wsqlaux = 'select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = '||wempatu||' and dt.bdcodcol = '||wcolatu||' and dt.bdref13 ='||wrefpagto;
                   wexiste13mes = NULL;
                   EXECUTE STATEMENT wsqlaux INTO :wexiste13mes;
                   IF (wexiste13mes IS NOT NULL) THEN
                      wdepatu = 0;
          
                   BDCODEMP         = wempatu;
                   BDCODCOL         = wcolatu;
                   BDREF            = wrefatu;
                   BDREFPAG         = wrefpagto;
                   bdordem          = wordematu;
                   BDRENDTRIBUTAVEL = wbaseir13;
                   BDINSS           = winss13;
                   BDIR             = wir13;
                   BDDEP            = wdepatu;
                   BDLUCROPJ        = 0;
                   BDDESPMED        = 0;
                   BDAJCUSTOS       = 0;
                   BDPENJUD         = 0;
                   BDPENALIM        = 0;

                   if (wprepri <> 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;

                   BDVALABO         = 0;
                   BDRENDISENTOS    = 0;
                   BDDRENDISENTOS   = '';
                   BDDATAPGTO       = wdataatu;
                   BDTIPO           = 101;    -- 13? rescis?o
                   BDINFADIC        = '';
                   BDDATAPROC       = wdataproca;
                   BDHORAPROC       = whoraproca;
                   SUSPEND;
                 end
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;
         wordematu = wordem;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         wrendis    = 0;
         wdrendis   = '';
       END

    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

    IF (wirver = 3) THEN -- 13? sal?rio
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir13 = wbaseir13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir13 = wbaseir13 - wvalor;
            END
       END
    --                                     INSS 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;
    --                                     IR 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.7') THEN
       wir13 = wir13 + wvalor;

    wdepatu = wdep;
    IF (wtipomov < 1) THEN
       wdataatu = wdataresc;
    ELSE
       wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wordematu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 '||
                      ' order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;
            if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
               begin
            /*Se tiver 13? no m?s da rescis?o n?o deve considerar o dependente novamente*/
            wsqlaux = 'select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = '||wempatu||' and dt.bdcodcol = '||wcolatu||' and dt.bdref13 ='||wrefpagto;
            wexiste13mes = NULL;
            EXECUTE STATEMENT wsqlaux INTO :wexiste13mes;
            IF (wexiste13mes IS NOT NULL) THEN
               wdepatu = 0;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            bdordem          = wordematu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;

            if (wprepri <> 0) then
               BDPREVPRIV = wprepri;
            else
               BDPREVPRIV = wprevprivcad;

            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 101;    -- 13? rescis?o
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
               end
          END
     END

  /*  13? RESCISAO FOLHA COMPLEMENTAR NORMAL E TOMADOR  */
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,BDRENDISENTOS,'||
                'BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM from SP_VRHF_DADOS_IR_13FC(';

  if (coalesce(prcodemp, '') = '') then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||prcodemp||''',';

  if (coalesce(prcodcol, '') = '') then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||prcodcol||''',';

  wsql = wsql||prrefini||','||prreffim||','||prpuxarfiliais||',';

  if (coalesce(prcodmatriz, '') = '') then
     wsql = wsql||'null)';
  else
     wsql = wsql||''''||prcodmatriz||''')';

  FOR EXECUTE STATEMENT wsql INTO :BDCODEMP,:BDCODCOL,:BDREF,:BDREFPAG,:BDTIPO,:BDRENDTRIBUTAVEL,:BDINSS,:BDIR,:BDDEP,:BDLUCROPJ,:BDDESPMED,:BDAJCUSTOS,:BDPENJUD,:BDPENALIM,:BDPREVPRIV,
                                  :BDINDRESC,:BDVALABO,:BDRENDISENTOS,:BDDRENDISENTOS,:BDDATAPGTO,:BDINFADIC,:BDDATAPROC,:BDHORAPROC,:BDORDEM
  DO
    SUSPEND;

  /*  DADOS IMPORTADOS OU CADASTRADOS NA FICHA  */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9002,9012,9099,9100) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select S13.BDCODEMP,S13.BDCODCOL,S13.BDREF13 from VRHF_EMP_T13SAL S13 where S13.BDCODEMP = FOL.BDCODEMP and S13.BDCODCOL = FOL.BDCODCOL and '||
                                'S13.BDREF13 = FOL.BDREFFIR) and '||
                    'not exists (select A13.BDCODEMP,A13.BDCODCOL,A13.BDREFA13 from VRHF_EMP_TA13SAL A13 where A13.BDCODEMP = FOL.BDCODEMP and A13.BDCODCOL = FOL.BDCODCOL and '||
                                'A13.BDREFA13 = FOL.BDREFFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'from tmp_empresas_select FOL ';
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9002,9012,9099,9100) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select S13.BDCODEMP,S13.BDCODCOL,S13.BDREF13 from VRHF_EMP_T13SAL S13 where S13.BDCODEMP = FO.BDCODEMP and S13.BDCODCOL = FO.BDCODCOL and '||
                                'S13.BDREF13 = FO.BDREFFIR) and '||
                    'not exists (select A13.BDCODEMP,A13.BDCODCOL,A13.BDREFA13 from VRHF_EMP_TA13SAL A13 where A13.BDCODEMP = FO.BDCODEMP and A13.BDCODCOL = FO.BDCODCOL and '||
                                'A13.BDREFA13 = FO.BDREFFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO :BDCODEMP,:BDCODCOL,:BDREF,:BDREFPAG,:BDTIPO,:BDRENDTRIBUTAVEL,:BDINSS,:BDIR,:BDDEP,:BDLUCROPJ,:BDDESPMED,:BDAJCUSTOS,:BDPENJUD,:BDPENALIM,
                                  :BDPREVPRIV,:BDINDRESC,:BDVALABO,:BDRENDISENTOS,:BDDRENDISENTOS,:BDDATAPGTO,:BDINFADIC
  DO
  BEGIN
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    SUSPEND;
  END

  /*  PENS?ES DO ADIANTAMENTO DE 13? SAL?RIO  */
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,BDRENDISENTOS,'||
                'BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM from SP_VRHF_DADOS_IR_AD13(';

  if (coalesce(prcodemp, '') = '') then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||prcodemp||''',';

  if (coalesce(prcodcol, '') = '') then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||prcodcol||''',';

  wsql = wsql||prrefini||','||prreffim||','||prpuxarfiliais||',';

  if (coalesce(prcodmatriz, '') = '') then
     wsql = wsql||'null)';
  else
     wsql = wsql||''''||prcodmatriz||''')';


  FOR EXECUTE STATEMENT wsql INTO :BDCODEMP,:BDCODCOL,:BDREF,:BDREFPAG,:BDTIPO,:BDRENDTRIBUTAVEL,:BDINSS,:BDIR,:BDDEP,:BDLUCROPJ,:BDDESPMED,:BDAJCUSTOS,:BDPENJUD,:BDPENALIM,:BDPREVPRIV,
                                  :BDINDRESC,:BDVALABO,:BDRENDISENTOS,:BDDRENDISENTOS,:BDDATAPGTO,:BDINFADIC,:BDDATAPROC,:BDHORAPROC,:BDORDEM
  DO
    SUSPEND;
END
^

/* Alter (SP_VRHF_DADOS_IR_13FC) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_13FC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WREFAUX integer;
declare variable WREFAUXATU integer;
declare variable WDATAPGTO date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
BEGIN
  WUSARTMP_EMP_SELECT = 0;
  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  /*  13? RESCISAO FOLHA COMPLEMENTAR NORMAL  */

  BDINDRESC = 0;
  BDORDEM = null;

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDREFFC, VFN.bdcodver, VFN.BDVALVFC FROM vrhf_emp_tverbafc VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbafc FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN and FOLN.BDREFFC = FOL.BDREFFC) ';
       wsql = wsql||'join vrh_emp_trescisao RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL and RESC.BDREFRESCISAO = FOL.BDREFFN) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       wsql = wsql||'where ((FOLN.BDREFCOMP >= '||prrefini||' and FOLN.BDREFCOMP <= '||prreffim||') or ';
       wsql = wsql||'       (FOLN.BDREFCOMP <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||prrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDREFFC ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
             wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDREFFC, VFN.BDCODVER,VFN.BDVALVFC FROM vrhf_emp_tverbafc VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbafc FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFFN = FO.BDREFFN and FOLN.BDREFFC = FO.BDREFFC) ';
       wsql = wsql||'join vrh_emp_trescisao RESC on (RESC.BDCODEMP = FO.BDCODEMP and RESC.BDCODCOL = FO.BDCODCOL and RESC.BDREFRESCISAO = FO.BDREFFN) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       wsql = wsql||'where ((FOLN.BDREFCOMP >= '||prrefini||' and FOLN.BDREFCOMP <= '||prreffim||') or ';
       wsql = wsql||'       (FOLN.BDREFCOMP <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||prrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDREFFC ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefauxatu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdataatu   = NULL;
  wprepri    = 0;
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wrefaux,:wcodver,:wvalor,:wdatapgto,:wclassif,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF (wrefauxatu = 0) THEN
       wrefauxatu = wrefaux;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefaux <> wrefauxatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = 0;
              BDLUCROPJ        = 0;
              BDDESPMED        = 0;
              BDAJCUSTOS       = 0;
              BDPENJUD         = 0;
              BDPENALIM        = 0;
              BDPREVPRIV       = wprepri;
              BDVALABO         = 0;
              BDRENDISENTOS    = 0;
              BDDRENDISENTOS   = '';
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 111;    -- 13? rescis?o
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefauxatu = wrefaux;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdataatu   = NULL;
         wprepri    = 0;
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver;
    IF (wirver = 3) THEN -- 13? sal?rio
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir13 = wbaseir13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir13 = wbaseir13 - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;
    --                                     IR 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.7') THEN
       wir13 = wir13 + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.601.8.2') THEN
       wprepri = wprepri + wvalor;

    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefauxatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = 0;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;
            BDPREVPRIV       = wprepri;
            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 111;    -- 13? rescis?o complementar
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
          END
     END

  /*  FOLHA COMPLEMENTAR TOMADOR  */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFTOMADOR, VFN.BDREFFC, VFN.BDORDEM, VFN.bdcodver, VFN.BDVALVFC FROM vrhf_emp_tverbafctomador VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbafctomador FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfoltomcomp FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and FOLN.BDORDEM = FOL.BDORDEM and FOLN.BDREFFC = FOL.BDREFFC) ';
       wsql = wsql||'join vrh_emp_trescisao RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL and RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       wsql = wsql||'where FOL.BDREFFC >= '||prrefini||'01 and FOL.BDREFFC <= '||prreffim||'31 ';
       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDREFFC ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFTOMADOR, VFN.BDREFFC, VFN.BDORDEM, VFN.BDCODVER,VFN.BDVALVFC FROM vrhf_emp_tverbafctomador VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbafctomador FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfoltomcomp FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and FOLN.BDORDEM = FO.BDORDEM and FOLN.BDREFFC = FO.BDREFFC) ';
       wsql = wsql||'join vrh_emp_trescisao RESC on (RESC.BDCODEMP = FO.BDCODEMP and RESC.BDCODCOL = FO.BDCODCOL and RESC.BDREFRESCISAO = FO.BDREFTOMADOR) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       wsql = wsql||'where FO.BDREFFC >= '||prrefini||'01 and FO.BDREFFC <= '||prreffim||'31 ';
       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDREFFC ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefauxatu = 0;
  wordematu  = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdataatu   = NULL;
  wprepri    = 0;
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wordem,:wrefaux,:wcodver,:wvalor,:wdatapgto,:wclassif,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF (wrefauxatu = 0) THEN
       wrefauxatu = wrefaux;
    IF (wordematu = 0) THEN
       wordematu = wordem;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordem <> wordematu) OR (wrefaux <> wrefauxatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = 0;
              BDLUCROPJ        = 0;
              BDDESPMED        = 0;
              BDAJCUSTOS       = 0;
              BDPENJUD         = 0;
              BDPENALIM        = 0;
              BDPREVPRIV       = wprepri;
              BDVALABO         = 0;
              BDRENDISENTOS    = 0;
              BDDRENDISENTOS   = '';
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 111;    -- 13? rescis?o
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefauxatu = wrefaux;
         wordematu  = wordem;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdataatu   = NULL;
         wprepri    = 0;
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver;
    IF (wirver = 3) THEN -- 13? sal?rio
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir13 = wbaseir13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir13 = wbaseir13 - wvalor;
            END
       END
    --                                     INSS 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;
    --                                     IR 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.7') THEN
       wir13 = wir13 + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.601.8.2') THEN
       wprepri = wprepri + wvalor;

    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wordematu <> 0 AND wrefauxatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = 0;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;
            BDPREVPRIV       = wprepri;
            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 111;    -- 13? rescis?o complementar
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
          END
     END
END
^

/* Alter (SP_VRHF_DADOS_IR_AD) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_AD(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WCLASSIF VARCHAR(20);
DECLARE VARIABLE WDESCVER VARCHAR(40);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WDATAATU DATE;
DECLARE VARIABLE WBASEIR NUMERIC(18,6);
DECLARE VARIABLE WREFPAGTO INTEGER;
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WIRVER INTEGER;
DECLARE VARIABLE WRENDISENTOVER VARCHAR(5);
DECLARE VARIABLE WINSSN NUMERIC(18,6);
DECLARE VARIABLE WIR NUMERIC(18,6);
DECLARE VARIABLE WDEP NUMERIC(18,6);
DECLARE VARIABLE WDEPATU NUMERIC(18,6);
DECLARE VARIABLE WLUCROPJ NUMERIC(18,6);
DECLARE VARIABLE WDESPMED NUMERIC(18,6);
DECLARE VARIABLE WAJCUS NUMERIC(18,6);
DECLARE VARIABLE WPENJUD NUMERIC(18,6);
DECLARE VARIABLE WPENALIM NUMERIC(18,6);
DECLARE VARIABLE WPREPRI NUMERIC(18,6);
DECLARE VARIABLE WINDRESC NUMERIC(18,6);
DECLARE VARIABLE WVALABO NUMERIC(18,6);
DECLARE VARIABLE WRENDIS NUMERIC(18,6);
DECLARE VARIABLE WDRENDIS VARCHAR(200);
DECLARE VARIABLE WDATAPROC DATE;
DECLARE VARIABLE WHORAPROC TIME;
DECLARE VARIABLE WDATAPROCA DATE;
DECLARE VARIABLE WHORAPROCA TIME;
DECLARE VARIABLE WUSARTMP_EMP_SELECT SMALLINT;
BEGIN
  /*
      ADIANTAMENTO SALARIAL
  */

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDDATAAD,FOL.BDCODVER,FOL.BDVALVAD,FOLN.BDDEPIRAD,FOLN.BDREFAD,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCAD,FOLN.BDHORAPROCAD ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDDATAAD, VFN.bdcodver,  VFN.BDVALVAD FROM vrhf_emp_tverbaad VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbaad FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tadsal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDDATAAD = FOL.BDDATAAD) ';
       wsql = wsql||'where FOLN.BDREFAD >= '||prrefini||' and FOLN.BDREFAD <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDDATAAD ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDDATAAD,FO.BDCODVER,FO.BDVALVAD,FOLN.BDDEPIRAD,FOLN.BDREFAD,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCAD,FOLN.BDHORAPROCAD ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL ';

             wsql = wsql||'INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDDATAAD, VFN.BDCODVER, VFN.BDVALVAD FROM vrhf_emp_tverbaad VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END
       ELSE
          BEGIN
             wSQL = wSQL ||'from TEMPRESAS FOL ';
             wsql = wsql||'join vrhf_emp_tverbaad FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tadsal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDDATAAD = FO.BDDATAAD) ';
       wsql = wsql||'where FOLN.BDREFAD >= '||prrefini||' and FOLN.BDREFAD <= '||prreffim||' ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDDATAAD ';
     END


  wempatu  = 0;
  wcolatu  = 0;
  wdataatu = NULL;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wdata,:wcodver,:wvalor,:wdep,:wref,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wdataatu IS NULL) THEN
       wdataatu = wdata;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wdata <> wdataatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefpagto;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 2;    -- Adiantamento salarial
              BDINFADIC        = 'Data: '||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4);
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              SUSPEND;
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wdataatu  = wdata;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     IR
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.1') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataproca = wdataproc;
    whoraproca = whoraproc;

    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1') THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;
    -- Rendimentos isentos
    IF (UPPER(wrendisentover) = 'TRUE') THEN
       BEGIN
         wrendis = wrendis + wvalor;
         wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 200);
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wdataatu IS NOT NULL) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefpagto;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 2;    -- Adiantamento salarial
            BDINFADIC        = 'Data: '||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4);
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
          END
     END

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';


       wsql = wsql||'where FOL.BDTIPOCALCFIR = 9020 and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select AD.BDCODEMP,AD.BDCODCOL,AD.BDDATAAD from VRHF_EMP_TADSAL AD where AD.BDCODEMP = FOL.BDCODEMP and AD.BDCODCOL = FOL.BDCODCOL and '||
                                'AD.BDDATAAD = FOL.BDDATAFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wsql = wsql||'from tmp_empresas_select FOL ';
          END
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR = 9020 and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select AD.BDCODEMP,AD.BDCODCOL,AD.BDDATAAD from VRHF_EMP_TADSAL AD where AD.BDCODEMP = FO.BDCODEMP and AD.BDCODCOL = FO.BDCODCOL and '||
                                'AD.BDDATAAD = FO.BDDATAFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';
    SUSPEND;
  END
END
^

/* Alter (SP_VRHF_DADOS_IR_AD13) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_AD13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WDATAPGTO date;
declare variable WUSARTMP_EMP_SELECT smallint;
BEGIN
  /*  PENS?ES DO ADIANTAMENTO DE 13? SAL?RIO  */
  WUSARTMP_EMP_SELECT = 0;
  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDVALVA13, VER.BDCLAVER ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFA13, VFN.bdcodver, VFN.BDVALVA13 FROM vrhf_emp_tverbaa13 VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbaa13 FOL ';

       wsql = wsql||
              'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
              'where VER.BDCLAVER starting with '||'''4.001.8'''||' and FOL.BDREFA13 >= '||prrefini||' and FOL.BDREFA13 <= '||prreffim;

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFA13 ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP, FO.BDCODCOL, FO.BDREFA13, FO.BDVALVA13, VER.BDCLAVER ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFA13, VFN.BDCODVER,VFN.BDVALVA13 FROM vrhf_emp_tverbaa13 VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbaa13 FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||
              'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FO.BDCODVER) '||
              'where VER.BDCLAVER starting with '||'''4.001.8'''||' and FO.BDREFA13 >= '||prrefini||' and FO.BDREFA13 <= '||prreffim;

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFA13 ';
     END

  wempatu = 0;
  wcolatu = 0;
  wrefatu = 0;
  BDRENDTRIBUTAVEL = 0;
  BDINSS           = 0;
  BDIR             = 0;
  BDDEP            = 0;
  BDPREVPRIV       = 0;
  BDINDRESC        = 0;
  BDVALABO         = 0;
  BDRENDISENTOS    = 0;
  BDDRENDISENTOS   = '';
  BDINFADIC        = '';
  BDLUCROPJ        = 0;
  BDDESPMED        = 0;
  BDAJCUSTOS       = 0;
  BDDATAPROC       = null;
  BDHORAPROC       = null;
  BDORDEM          = null;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wvalor, :wclassif DO
  BEGIN
    IF (wempatu = 0) THEN
      wempatu = wcodemp;
    IF (wcolatu = 0) THEN
      wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
      wrefatu = wref;

    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wref)) THEN
      BEGIN
        IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
          wdatapgto = CAST((SUBSTRING(wrefatu FROM 5 FOR 2)||'-31-'||SUBSTRING(wrefatu FROM 1 FOR 4)) AS DATE);
        ELSE
        IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) IN (4,6,9,11)) THEN
          wdatapgto = CAST((SUBSTRING(wrefatu FROM 5 FOR 2)||'-30-'||SUBSTRING(wrefatu FROM 1 FOR 4)) AS DATE);
        ELSE
          wdatapgto = CAST((SUBSTRING(wrefatu FROM 5 FOR 2)||'-28-'||SUBSTRING(wrefatu FROM 1 FOR 4)) AS DATE);

        BDCODEMP         = wempatu;
        BDCODCOL         = wcolatu;
        BDREF            = wrefatu;
        BDREFPAG         = wrefatu;
        BDTIPO           = 9;    -- Adiantamento de 13?
        BDPENJUD         = wpenjud;
        BDPENALIM        = wpenalim;
        BDDATAPGTO       = wdatapgto;
        SUSPEND;
        wempatu  = wcodemp;
        wcolatu  = wcodcol;
        wrefatu  = wref;
        wpenjud  = 0;
        wpenalim = 0;
      END

   IF (SUBSTRING(wclassif FROM 1 FOR 9) = '4.001.8.0') THEN
     wpenjud = wpenjud + wvalor;
   IF (SUBSTRING(wclassif FROM 1 FOR 9) = '4.001.8.1') THEN
     wpenalim = wpenalim + wvalor;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0) THEN
    BEGIN
      IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
        wdatapgto = CAST((SUBSTRING(wrefatu FROM 5 FOR 2)||'-31-'||SUBSTRING(wrefatu FROM 1 FOR 4)) AS DATE);
      ELSE
      IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) IN (4,6,9,11)) THEN
        wdatapgto = CAST((SUBSTRING(wrefatu FROM 5 FOR 2)||'-30-'||SUBSTRING(wrefatu FROM 1 FOR 4)) AS DATE);
      ELSE
        wdatapgto = CAST((SUBSTRING(wrefatu FROM 5 FOR 2)||'-28-'||SUBSTRING(wrefatu FROM 1 FOR 4)) AS DATE);

      BDCODEMP         = wempatu;
      BDCODCOL         = wcolatu;
      BDREF            = wrefatu;
      BDREFPAG         = wrefatu;
      BDTIPO           = 9;    -- Adiantamento de 13?
      BDPENJUD         = wpenjud;
      BDPENALIM        = wpenalim;
      BDDATAPGTO       = wdatapgto;
      SUSPEND;
    END
END
^

/* Alter (SP_VRHF_DADOS_IR_C13) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_C13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC13 numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(200);
declare variable WREFC13 integer;
declare variable WREFC13ATU integer;
declare variable WREFINI integer;
declare variable WDATA date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
BEGIN
  /*
      COMPLEMENTO DE 13? SAL?RIO
  */
  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDREFC13,FOL.BDCODVER,FOL.BDVALVC13,0 BDDEP13,FOLN.BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13 ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREF13, VFN.BDREFC13, VFN.bdcodver, VFN.BDVALVC13 FROM vrhf_emp_tverbac13 VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbac13 FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tc13sal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREF13 = FOL.BDREF13 and FOLN.BDREFC13 = FOL.BDREFC13) ';
       wsql = wsql||'where FOL.BDREFC13 >= '||wrefini||' and FOL.BDREFC13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDREFC13 ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDREFC13,FO.BDCODVER,FO.BDVALVC13,0 BDDEP13,FOLN.BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13 ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREF13, VFN.BDREFC13, VFN.BDCODVER,VFN.BDVALVC13 FROM vrhf_emp_tverbac13 VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbac13 FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tc13sal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREF13 = FO.BDREF13 and FOLN.BDREFC13 = FO.BDREFC13) ';
       wsql = wsql||'where FO.BDREFC13 >= '||wrefini||' and FO.BDREFC13 <= '||prreffim||' ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDREFC13 ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefc13atu = 0;

  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc13 = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wrefc13,:wcodver,:wvalor,:wdep,:wdata,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wrefc13atu = 0) THEN
       wrefc13atu = wrefc13;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefc13 <> wrefc13atu)) THEN
       BEGIN
         EXECUTE PROCEDURE sp_seta_competencia(:wrefc13atu, NULL, NULL);

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc13;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 11;    -- Complemento 13? sal?rio
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefc13atu = wrefc13;

         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc13 = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

    IF (wirver = 3) THEN -- 13? sal?rio
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir13 = wbaseir13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 7) <> '6.001.8') THEN
                 wbaseir13 = wbaseir13 - wvalor;
            END
       END

    -- Desconto de 13? sal?rio
    IF (SUBSTRING(wclassif FROM 1 FOR 5) = '6.080') THEN
       wbaseir13 = wbaseir13 - wvalor;

    --                                     INSS
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.0') THEN
       winss13 = winss13 + wvalor;
    --                                     IR
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.1') THEN
       wir13 = wir13 + wvalor;

    wdepatu = wdep;
    wdataatu = wdata;
    wdataproca = wdataproc;
    whoraproca = whoraproc;

    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.2') THEN
       wprepri = wprepri + wvalor;

    -- Rendimentos isentos
    IF (UPPER(wrendisentover) = 'TRUE') THEN
       BEGIN
         wrendis = wrendis + wvalor;
         wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 200);
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefc13atu <> 0) THEN
     BEGIN
       EXECUTE PROCEDURE sp_seta_competencia(:wrefc13atu, NULL, NULL);

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc13;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 11;    -- Complemento 13? sal?rio
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
          END
     END

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR = 9110 and CAST((SUBSTRING(CAST(FOL.BDDATAFIR AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FOL.BDDATAFIR AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prrefini||
              ' and CAST((SUBSTRING(CAST(FOL.BDDATAFIR AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FOL.BDDATAFIR AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prreffim||' and '||
                    'not exists (select C13.BDCODEMP,C13.BDCODCOL,C13.BDREF13,C13.BDREFC13 from VRHF_EMP_TC13SAL C13 where C13.BDCODEMP = FOL.BDCODEMP and C13.BDCODCOL = FOL.BDCODCOL and '||
                                'C13.BDREF13 = FOL.BDREFFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'from tmp_empresas_select FOL ';
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR = 9110 and CAST((SUBSTRING(CAST(FO.BDDATAFIR AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FO.BDDATAFIR AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prrefini||
              ' and CAST((SUBSTRING(CAST(FO.BDDATAFIR AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FO.BDDATAFIR AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prreffim||' and '||
                    'not exists (select C13.BDCODEMP,C13.BDCODCOL,C13.BDREF13,C13.BDREFC13 from VRHF_EMP_TC13SAL C13 where C13.BDCODEMP = FO.BDCODEMP and C13.BDCODCOL = FO.BDCODCOL and '||
                                'C13.BDREF13 = FO.BDREFFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';
    SUSPEND;
  END

  EXECUTE PROCEDURE sp_seta_competencia(:prreffim, NULL, NULL);

END
^

/* Alter (SP_VRHF_DADOS_IR_DARF) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_DARF(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPORCC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFIR INTEGER,
BDREFIRFIR INTEGER,
BDTIPOCALCFIR INTEGER,
BDCCFIR INTEGER,
BDCODFERFIR INTEGER,
BDCODTCA INTEGER,
BDBASEIRFIR NUMERIC(18,6),
BDVALINSSFIR NUMERIC(18,6),
BDVALIRFIR NUMERIC(18,6),
BDVALDEPFIR NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDDATAFIR DATE)
 AS
declare variable WEMP varchar(20000);
declare variable WCOL varchar(30000);
declare variable WMAT varchar(15000);
declare variable WSQL varchar(10000);
declare variable WREF integer;
BEGIN
  SELECT CAST(TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) AS INTEGER) FROM rdb$database INTO wref;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wemp = ''''||prcodemp||'''';
  ELSE
     wemp = 'null';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wcol = ''''||prcodcol||'''';
  ELSE
     wcol = 'null';

  IF (prpuxarfiliais = 1) THEN
     wmat = ''''||prcodmatriz||'''';
  ELSE
     wmat = 'null';

  -- Folha normal
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem,0),0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_FN('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,0,'||prporcc||') ' ;

  -- Folha complementar
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem,0),0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_FC('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,0,'||prporcc||') ' ;

  -- Adiantamento salarial
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0,0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_AD('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') ' ;

  -- Férias
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0,BDCODFE,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_FE('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') ' ;

  -- 13º salário
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem,0),0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') ' ;

  -- Complemento de 13º salário
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0,0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_C13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') ' ;

  -- Folha avulsa
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0,0,BDCODTCA,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_FA('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') ' ;

  -- Folha intermitente
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem, 0) bdordem,0,0,SUM(BDRENDTRIBUTAVEL),SUM(BDINSS),SUM(BDIR),MAX(BDDEP),SUM(BDPENJUD),SUM(BDPENALIM),MAX(BDDATAPGTO) '||
                'from SP_VRHF_DADOS_IR_INT('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') '||
                'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,bdordem ';

  -- Folha intermitente 13?
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem, 0) bdordem,0,0,SUM(BDRENDTRIBUTAVEL),SUM(BDINSS),SUM(BDIR),MAX(BDDEP),SUM(BDPENJUD),SUM(BDPENALIM),MAX(BDDATAPGTO) '||
                'from SP_VRHF_DADOS_IR_INT13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') '||
                'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,bdordem ';

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFIR,
    :BDREFIRFIR,
    :BDTIPOCALCFIR,
    :BDCCFIR,
    :BDCODFERFIR,
    :BDCODTCA,
    :BDBASEIRFIR,
    :BDVALINSSFIR,
    :BDVALIRFIR,
    :BDVALDEPFIR,
    :BDPENJUD,
    :BDPENALIM,
    :BDDATAFIR
  DO
    SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
END
^

/* Alter (SP_VRHF_DADOS_IR_DIRF) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_DIRF(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PREXPORTACAO INTEGER = 0,
PRSEMPLR SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDCODTCA INTEGER)
 AS
DECLARE VARIABLE WEMP VARCHAR(20000);
DECLARE VARIABLE WCOL VARCHAR(30000);
DECLARE VARIABLE WMAT VARCHAR(15000);
DECLARE VARIABLE WSQL VARCHAR(30000);
BEGIN
  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wemp = ''''||prcodemp||'''';
  ELSE
     wemp = 'null';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wcol = ''''||prcodcol||'''';
  ELSE
     wcol = 'null';

  IF (prpuxarfiliais = 1) THEN
     wmat = ''''||prcodmatriz||'''';
  ELSE
     wmat = 'null';

  -- Folha normal
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,SUM(BDRENDTRIBUTAVEL) BDRENDTRIBUTAVEL,SUM(BDINSS) BDINSS,SUM(BDIR) BDIR,SUM(BDDEP) BDDEP,SUM(BDLUCROPJ) BDLUCROPJ,'||
                'SUM(BDDESPMED) BDDESPMED,SUM(BDAJCUSTOS) BDAJCUSTOS,SUM(BDPENJUD) BDPENJUD,SUM(BDPENALIM) BDPENALIM,SUM(BDPREVPRIV) BDPREVPRIV,SUM(BDINDRESC) BDINDRESC,'||
                'SUM(BDVALABO) BDVALABO,SUM(BDRENDISENTOS) BDRENDISENTOS,MAX(BDDRENDISENTOS) BDDRENDISENTOS,MAX(BDDATAPGTO) BDDATAPGTO, MAX(BDINFADIC) BDINFADIC,'||
                'CAST(0 as INTEGER) BDCODTCA from SP_VRHF_DADOS_IR_FN('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,'||prexportacao||') '||
                'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO ' ;

  -- Folha complementar
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA from SP_VRHF_DADOS_IR_FC('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,'||prexportacao||') ' ;

  -- Adiantamento salarial
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA from SP_VRHF_DADOS_IR_AD('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') ' ;

  -- F?rias
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA from SP_VRHF_DADOS_IR_FE('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||','||prexportacao||') ' ;

  -- 13? sal?rio
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA from SP_VRHF_DADOS_IR_13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') ' ;

  -- Complemento de 13? sal?rio
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA from SP_VRHF_DADOS_IR_C13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||') ' ;

  -- Folha avulsa
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDCODTCA from SP_VRHF_DADOS_IR_FA('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,'||prsemplr||') ' ;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDCODTCA
  DO
    SUSPEND;
END
^

/* Alter (SP_VRHF_DADOS_IR_FA) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FA(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRSOMENTEPLR SMALLINT = 0,
PRSEMPLR SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDCODTCA INTEGER,
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
DECLARE VARIABLE WCONTROL INTEGER;
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WCLASSIF VARCHAR(20);
DECLARE VARIABLE WDESCVER VARCHAR(40);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WDATAATU DATE;
DECLARE VARIABLE WBASEIR NUMERIC(18,6);
DECLARE VARIABLE WREFPAGTO INTEGER;
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WIRVER INTEGER;
DECLARE VARIABLE WRENDISENTOVER VARCHAR(5);
DECLARE VARIABLE WINSSN NUMERIC(18,6);
DECLARE VARIABLE WIR NUMERIC(18,6);
DECLARE VARIABLE WDEP NUMERIC(18,6);
DECLARE VARIABLE WDEPATU NUMERIC(18,6);
DECLARE VARIABLE WLUCROPJ NUMERIC(18,6);
DECLARE VARIABLE WDESPMED NUMERIC(18,6);
DECLARE VARIABLE WAJCUS NUMERIC(18,6);
DECLARE VARIABLE WPENJUD NUMERIC(18,6);
DECLARE VARIABLE WPENALIM NUMERIC(18,6);
DECLARE VARIABLE WPREPRI NUMERIC(18,6);
DECLARE VARIABLE WINDRESC NUMERIC(18,6);
DECLARE VARIABLE WVALABO NUMERIC(18,6);
DECLARE VARIABLE WRENDIS NUMERIC(18,6);
DECLARE VARIABLE WDRENDIS VARCHAR(200);
DECLARE VARIABLE WCODTCA INTEGER;
DECLARE VARIABLE WCODTCAATU INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WDESCTCA VARCHAR(70);
DECLARE VARIABLE WDATAPROC DATE;
DECLARE VARIABLE WHORAPROC TIME;
DECLARE VARIABLE WDATAPROCA DATE;
DECLARE VARIABLE WHORAPROCA TIME;
DECLARE VARIABLE WUSARTMP_EMP_SELECT SMALLINT;
BEGIN
  /*
      FOLHA AVULSA
  */

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDCODTCA,FOL.BDDATAFA,FOL.BDCODVER,FOL.BDVALVFA,FOLN.BDDEPFA,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFA,FOLN.BDHORAPROCFA ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDDATAFA, VFN.BDCODTCA, VFN.bdcodver, VFN.BDVALVFA FROM vrhf_emp_tverbafa VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbafa FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhaavulsa FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDCODTCA = FOL.BDCODTCA and FOLN.BDDATAFA = FOL.BDDATAFA) ';

       IF (prsomenteplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOL.BDCODTCA and CALCAVUL.BDCODCTP = 7) ';
       ELSE
       IF (prsemplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOL.BDCODTCA and CALCAVUL.BDCODCTP <> 7) ';

       wsql = wsql||'where FOLN.BDREF >= '||prrefini||' and FOLN.BDREF <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDCODTCA,FOL.BDDATAFA ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDCODTCA,FO.BDDATAFA,FO.BDCODVER,FO.BDVALVFA,FOLN.BDDEPFA,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFA,FOLN.BDHORAPROCFA ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDDATAFA, VFN.BDCODTCA, VFN.BDCODVER,VFN.BDVALVFA FROM vrhf_emp_tverbafa VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbafa FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhaavulsa FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDCODTCA = FO.BDCODTCA and FOLN.BDDATAFA = FO.BDDATAFA) ';

       IF (prsomenteplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FO.BDCODTCA and CALCAVUL.BDCODCTP = 7) ';
       ELSE
       IF (prsemplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FO.BDCODTCA and CALCAVUL.BDCODCTP <> 7) ';

       wsql = wsql||'where FOLN.BDREF >= '||prrefini||' and FOLN.BDREF <= '||prreffim||' ';
     
       wcontrol = 0;
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               BEGIN
                 wsql = wsql||' and (('||prcodemp||')';
                 wcontrol = 1;
               END
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               BEGIN
                 wsql = wsql||' or ('||prcodmatriz||')';
                 wcontrol = 1;
               END
          
            IF (wcontrol = 1) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDCODTCA,FO.BDDATAFA ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wcodtcaatu = 0;
  wdataatu   = NULL;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wcodtca,:wdata,:wcodver,:wvalor,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wcodtcaatu = 0) THEN
       wcodtcaatu = wcodtca;

    IF (wdataatu IS NULL) THEN
       wdataatu = wdata;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wcodtca <> wcodtcaatu) OR (wdata <> wdataatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         SELECT BDDESCTCA FROM VRH_BASE_TTIPOCALCAVUL WHERE BDCODTCA = :wcodtcaatu INTO :wdesctca;

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefpagto;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDDEP            = 0;
              IF (wbaseir <> 0) THEN
                 BDDEP            = wdepatu; -- Apenas incluir os dependentes se tiver base IR #11034
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 50;    -- Folha avulsa
              BDINFADIC        = wcodtcaatu||' - '||wdesctca;
              BDCODTCA         = wcodtcaatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wcodtcaatu = wcodtca;
         wdataatu   = wdata;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
       END

    -- soma as bases
    wref = CAST((SUBSTRING(CAST(wdata AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdata AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

    IF (wirver > 0) THEN -- IR
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '1.040') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.0') THEN
       winssn = winssn + wvalor;
    --                                     IR
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.1') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataproca = wdataproc;
    whoraproca = whoraproc;

    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1') THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '1.040.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '1.040.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;
    --                                      Abono pec.                                      1/3 abono pec.                                  Abono pec. dobro                                1/3 abono pec.
    IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '3.003') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.004') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.007') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.008')) THEN
       wvalabo = wvalabo + wvalor;
    -- Rendimentos isentos
    IF (UPPER(wrendisentover) = 'TRUE') THEN
       BEGIN
         wrendis = wrendis + wvalor;
         wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 200);
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wcodtcaatu <> 0 AND wdataatu IS NOT NULL) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       SELECT BDDESCTCA FROM VRH_BASE_TTIPOCALCAVUL WHERE BDCODTCA = :wcodtcaatu INTO :wdesctca;

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefpagto;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDDEP            = 0;
            IF (wbaseir <> 0) THEN
               BDDEP            = wdepatu; -- Apenas incluir os dependentes se tiver base IR #11034
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 50;    -- Folha avulsa
            BDINFADIC        = wcodtcaatu||' - '||wdesctca;
            BDCODTCA         = wcodtcaatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
          END
     END

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX, FOL.BDCODTCA ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       IF (prsomenteplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOL.BDCODTCA and CALCAVUL.BDCODCTP = 7) ';
       ELSE
       IF (prsemplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOL.BDCODTCA and CALCAVUL.BDCODCTP <> 7) ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR = 9500 and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FA.BDCODEMP,FA.BDCODCOL,FA.BDCODTCA,FA.BDDATAFA from VRHF_EMP_TFOLHAAVULSA FA where FA.BDCODEMP = FOL.BDCODEMP and FA.BDCODCOL = FOL.BDCODCOL and '||
                                'FA.BDCODTCA = FOL.BDCODTCA and FA.BDDATAFA = FOL.BDDATAFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX, FO.BDCODTCA ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'from tmp_empresas_select FOL ';
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       IF (prsomenteplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FO.BDCODTCA and CALCAVUL.BDCODCTP = 7) ';
       ELSE
       IF (prsemplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FO.BDCODTCA and CALCAVUL.BDCODCTP <> 7) ';

       wsql = wsql||'where FO.BDTIPOCALCFIR = 9500 and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FA.BDCODEMP,FA.BDCODCOL,FA.BDCODTCA,FA.BDDATAFA from VRHF_EMP_TFOLHAAVULSA FA where FA.BDCODEMP = FO.BDCODEMP and FA.BDCODCOL = FO.BDCODCOL and '||
                                'FA.BDCODTCA = FO.BDCODTCA and FA.BDDATAFA = FO.BDDATAFIR) ';
     
       wcontrol = 0;
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               BEGIN
                 wcontrol = 1;
                 wsql = wsql||' and (('||prcodemp||')';
               END
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               BEGIN
                 wcontrol = 1;
                 wsql = wsql||' or ('||prcodmatriz||')';
               END
     
            IF (wcontrol = 1) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDCODTCA
  DO
  BEGIN
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    SUSPEND;
  END
END
^

/* Alter (SP_VRHF_DADOS_IR_FC) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPREVIARESC SMALLINT = 0,
PREXPORTACAO INTEGER = 0,
PRPORCC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
WGCLASS VARCHAR(1000),
WDESCVER2 VARCHAR(70),
WI INTEGER,
BDORDEM INTEGER)
 AS
DECLARE VARIABLE WEHINDRESC VARCHAR(5);
DECLARE VARIABLE WISENTOABONO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WDATAPGTO DATE;
DECLARE VARIABLE WCLASSIF VARCHAR(20);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WDATAATU DATE;
DECLARE VARIABLE WBASEIR NUMERIC(18,6);
DECLARE VARIABLE WREFPAGTO INTEGER;
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WIRVER INTEGER;
DECLARE VARIABLE WRENDISENTOVER VARCHAR(5);
DECLARE VARIABLE WINSSN NUMERIC(18,6);
DECLARE VARIABLE WIR NUMERIC(18,6);
DECLARE VARIABLE WDEP NUMERIC(18,6);
DECLARE VARIABLE WDEPATU NUMERIC(18,6);
DECLARE VARIABLE WLUCROPJ NUMERIC(18,6);
DECLARE VARIABLE WDESPMED NUMERIC(18,6);
DECLARE VARIABLE WAJCUS NUMERIC(18,6);
DECLARE VARIABLE WPENJUD NUMERIC(18,6);
DECLARE VARIABLE WPENALIM NUMERIC(18,6);
DECLARE VARIABLE WPREPRI NUMERIC(18,6);
DECLARE VARIABLE WINDRESC NUMERIC(18,6);
DECLARE VARIABLE WVALABO NUMERIC(18,6);
DECLARE VARIABLE WRENDIS NUMERIC(18,6);
DECLARE VARIABLE WDRENDIS VARCHAR(200);
DECLARE VARIABLE WDATARESC DATE;
DECLARE VARIABLE WCODPRES INTEGER;
DECLARE VARIABLE WDESCPRES VARCHAR(110);
DECLARE VARIABLE WREFAUX INTEGER;
DECLARE VARIABLE WREFAUXATU INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WORDEMATU INTEGER;
DECLARE VARIABLE WDESCCC VARCHAR(100);
DECLARE VARIABLE WDATAPROC DATE;
DECLARE VARIABLE WHORAPROC TIME;
DECLARE VARIABLE WDATAPROCA DATE;
DECLARE VARIABLE WHORAPROCA TIME;
DECLARE VARIABLE WUSARTMP_EMP_SELECT SMALLINT;
BEGIN
  /*
      FOLHA COMPLEMENTAR NORMAL
  */

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDREFFC, VFN.bdcodver, VFN.BDVALVFC FROM vrhf_emp_tverbafc VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
         wsql = wsql||'from vrhf_emp_tverbafc FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN and FOLN.BDREFFC = FOL.BDREFFC) ';
       wsql = wsql||'where FOLN.BDREFCOMP >= '||prrefini||' and FOLN.BDREFCOMP <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDREFFC ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL ';
             wsql = wsql||'INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDREFFC, VFN.BDCODVER, VFN.BDVALVFC FROM vrhf_emp_tverbafc VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END
       ELSE
          BEGIN
             wSQL = wSQL ||'from TEMPRESAS FOL ';
             wsql = wsql||'join vrhf_emp_tverbafc FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFFN = FO.BDREFFN and FOLN.BDREFFC = FO.BDREFFC) ';
       wsql = wsql||'where FOLN.BDREFCOMP >= '||prrefini||' and FOLN.BDREFCOMP <= '||prreffim||' ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDREFFC ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefauxatu = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wrefaux,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wrefauxatu = 0) THEN
       wrefauxatu = wrefaux;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefaux <> wrefauxatu)) THEN
       BEGIN
         wcodpres     = NULL;
         wdescpres    = NULL;
         wdataresc    = NULL;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
            END

         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 110;    -- Folha complementar rescis?o
                   BDINFADIC = wcodpres||' - '||wdescpres;
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 1;    -- Folha complementar normal
                   BDINFADIC = '';
                 END

              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefauxatu = wrefaux;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover, wehindresc;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
       winssn = winssn + wvalor;
    --                                     IR folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Di?rias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;

    IF (UPPER(wehindresc) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN   -- Provento
            windresc = windresc + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- Desconto
            windresc = windresc - wvalor;
       END

    WISENTOABONO = 0;
    --                                      Complemento de abono pecuni?rio                  Compl. 1/3 abono pecuni?rio
    IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
       BEGIN
         wvalabo = wvalabo + wvalor;
                 END
    ELSE
             -- Rendimentos isentos
    IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefauxatu <> 0) THEN
     BEGIN
       wcodpres     = NULL;
       wdescpres    = NULL;
       wdataresc    = NULL;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
          END

       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 110;    -- Folha complementar rescis?o
                 BDINFADIC = wcodpres||' - '||wdescpres;
               END
            ELSE
               BEGIN
                 BDTIPO    = 1;    -- Folha complementar normal
                 BDINFADIC = '';
               END
            SUSPEND;
          END
     END


  /*
      FOLHA COMPLEMENTAR TOMADOR
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC '||
              'from vrhf_emp_tverbafctomador FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfoltomcomp FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and FOLN.BDORDEM = FOL.BDORDEM and FOLN.BDREFFC = FOL.BDREFFC) ';
       wsql = wsql||'where FOL.BDREFFC >= '||prrefini||'01 and FOL.BDREFFC <= '||prreffim||'31 ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDREFFC ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' from tmp_empresas_select FOL ';
       ELSE
          wSQL = wSQL ||' from TEMPRESAS FOL ';

       wsql = wsql||'join vrhf_emp_tverbafctomador FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfoltomcomp FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and FOLN.BDORDEM = FO.BDORDEM and FOLN.BDREFFC = FO.BDREFFC) ';
       wsql = wsql||'where FO.BDREFFC >= '||prrefini||'01 and FO.BDREFFC <= '||prreffim||'31 ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDREFFC ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefauxatu = 0;
  wordematu  = -1;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wordem,:wrefaux,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wrefauxatu = 0) THEN
       wrefauxatu = wrefaux;

    IF (prporcc = 0) THEN
       wordematu = COALESCE(wordem, 0);
    ELSE
    IF (wordematu = 0) THEN
       wordematu = COALESCE(wordem, 0);

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefaux <> wrefauxatu) OR (wordematu <> COALESCE(wordem, 0))) THEN
       BEGIN
         wcodpres     = NULL;
         wdescpres    = NULL;
         wdataresc    = NULL;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
            END

         SELECT
         CASE
           WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
           WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
           WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
           ELSE CC.BDAPECTA END BDNOMCC
         FROM (
           SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
           FROM vrhf_emp_tprepfn X
           JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
           LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
           LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
           WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
         ) CC INTO :wdesccc;

         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDORDEM          = wordematu;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 110;    -- Folha complementar rescis?o
                   BDINFADIC = wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres;
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 1;    -- Folha complementar normal
                   BDINFADIC = wordematu||' - '||wdesccc;
                 END

              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefauxatu = wrefaux;
         wordematu  = wordem;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover, :wehindresc;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
       winssn = winssn + wvalor;
    --                                     IR folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;

    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Di?rias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;

    IF (UPPER(wehindresc) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN   -- Provento
            windresc = windresc + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- Desconto
            windresc = windresc - wvalor;
       END

    WISENTOABONO = 0;
    --                                      Complemento de abono pecuni?rio                  Compl. 1/3 abono pecuni?rio
    IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
       BEGIN
         wvalabo = wvalabo + wvalor;
                 END
    ELSE
    -- Rendimentos isentos
    IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefauxatu <> 0) THEN
     BEGIN
       wcodpres     = NULL;
       wdescpres    = NULL;
       wdataresc    = NULL;
       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
          END

       SELECT
       CASE
         WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
         WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
         WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
         ELSE CC.BDAPECTA END BDNOMCC
       FROM (
         SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
         FROM vrhf_emp_tprepfn X
         JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
         LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
         LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
       ) CC INTO :wdesccc;

       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDORDEM          = wordematu;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 110;    -- Folha complementar rescis?o
                 BDINFADIC = wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres;
               END
            ELSE
               BEGIN
                 BDTIPO    = 1;    -- Folha complementar normal
                 BDINFADIC = wordematu||' - '||wdesccc;
               END
            SUSPEND;
          END
     END

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9010,9011) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FC.BDCODEMP,FC.BDCODCOL,FC.BDREFFN,FC.BDDATAPAGFC from VRHF_EMP_TFOLHACOMP FC where FC.BDCODEMP = FOL.BDCODEMP and FC.BDCODCOL = FOL.BDCODCOL and '||
                                'FC.BDREFFN = FOL.BDREFFIR and FC.BDDATAPAGFC = FOL.BDDATAFIR) and '||
                    'not exists (select FCT.BDCODEMP,FCT.BDCODCOL,FCT.BDREFTOMADOR, FCT.BDDATAPAGFC from VRHF_EMP_TFOLTOMCOMP FCT where FCT.BDCODEMP = FOL.BDCODEMP and FCT.BDCODCOL = FOL.BDCODCOL and '||
                                'FCT.BDREFTOMADOR = FOL.BDREFFIR and FCT.BDDATAPAGFC = FOL.BDDATAFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'from tmp_empresas_select FOL ';
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9010,9011) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FC.BDCODEMP,FC.BDCODCOL,FC.BDREFFN,FC.BDDATAPAGFC from VRHF_EMP_TFOLHACOMP FC where FC.BDCODEMP = FO.BDCODEMP and FC.BDCODCOL = FO.BDCODCOL and '||
                                'FC.BDREFFN = FO.BDREFFIR and FC.BDDATAPAGFC = FO.BDDATAFIR) and '||
                    'not exists (select FCT.BDCODEMP,FCT.BDCODCOL,FCT.BDREFTOMADOR, FCT.BDDATAPAGFC from VRHF_EMP_TFOLTOMCOMP FCT where FCT.BDCODEMP = FO.BDCODEMP and FCT.BDCODCOL = FO.BDCODCOL and '||
                                'FCT.BDREFTOMADOR = FO.BDREFFIR and FCT.BDDATAPAGFC = FO.BDDATAFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC
  DO
  BEGIN
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    SUSPEND;
  END
END
^

/* Alter (SP_VRHF_DADOS_IR_FE) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FE(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PREXPORTACAO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDCODFE INTEGER,
BDINIPERAQUIS DATE,
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WCODFE INTEGER;
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WCLASSIF VARCHAR(20);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WDATAATU DATE;
DECLARE VARIABLE WCODFEATU INTEGER;
DECLARE VARIABLE WBASEIR NUMERIC(18,6);
DECLARE VARIABLE WREFPAGTO INTEGER;
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WIRVER INTEGER;
DECLARE VARIABLE WRENDISENTOVER VARCHAR(5);
DECLARE VARIABLE WINSSN NUMERIC(18,6);
DECLARE VARIABLE WIR NUMERIC(18,6);
DECLARE VARIABLE WDEP NUMERIC(18,6);
DECLARE VARIABLE WDEPATU NUMERIC(18,6);
DECLARE VARIABLE WLUCROPJ NUMERIC(18,6);
DECLARE VARIABLE WDESPMED NUMERIC(18,6);
DECLARE VARIABLE WAJCUS NUMERIC(18,6);
DECLARE VARIABLE WPENJUD NUMERIC(18,6);
DECLARE VARIABLE WPENALIM NUMERIC(18,6);
DECLARE VARIABLE WPREPRI NUMERIC(18,6);
DECLARE VARIABLE WINDRESC NUMERIC(18,6);
DECLARE VARIABLE WVALABO NUMERIC(18,6);
DECLARE VARIABLE WRENDIS NUMERIC(18,6);
DECLARE VARIABLE WDRENDIS VARCHAR(200);
DECLARE VARIABLE WINIAQUIS DATE;
DECLARE VARIABLE WINIAQUISATU DATE;
DECLARE VARIABLE WDATAFE DATE;
DECLARE VARIABLE WDATAFEATU DATE;
DECLARE VARIABLE WREFABO INTEGER;
DECLARE VARIABLE WREFABOATU INTEGER;
DECLARE VARIABLE WDATAFEFIM DATE;
DECLARE VARIABLE WDATAFEFIMATU DATE;
DECLARE VARIABLE WDATAPROCA DATE;
DECLARE VARIABLE WHORAPROCA TIME;
DECLARE VARIABLE WDATAPROC DATE;
DECLARE VARIABLE WHORAPROC TIME;
DECLARE VARIABLE WGCLASS VARCHAR(1000);
DECLARE VARIABLE WDESCVER2 VARCHAR(70);
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WISENTOABONO INTEGER;
DECLARE VARIABLE WUSARTMP_EMP_SELECT SMALLINT;
BEGIN
  /*
      FERIAS
  */
  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDINIPERAQUISFE,FOL.BDCODFE,FOL.BDCODVER,FOL.BDVALVFE,FOLN.BDDATAPAGFE,FOLN.BDDEPFE,FOLN.BDINIPERGOZOFE,'||
              'COALESCE(FOLN.BDREFPAGABOFE, 0) BDREFPAGABOFE,FOLN.BDFIMPERGOZOFE,VER.BDCLAVER,FOLN.BDDATAPROCFE,FOLN.BDHORAPROCFE ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDINIPERAQUISFE, VFN.BDCODFE, VFN.bdcodver, VFN.BDVALVFE FROM vrhf_emp_tverbafe VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbafe FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrh_emp_tferias FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDINIPERAQUISFE = FOL.BDINIPERAQUISFE and FOLN.BDCODFE = FOL.BDCODFE) ';
       wsql = wsql||'where ((CAST((SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 1 for 4)|| SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 6 for 2)) AS INTEGER) >= '||prrefini||
                    ' and CAST((SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 1 for 4)|| SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 6 for 2)) AS INTEGER) <= '||prreffim||')) ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDINIPERAQUISFE,FOL.BDCODFE ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDINIPERAQUISFE,FO.BDCODFE,FO.BDCODVER,FO.BDVALVFE,FOLN.BDDATAPAGFE,FOLN.BDDEPFE,FOLN.BDINIPERGOZOFE,'||
              'COALESCE(FOLN.BDREFPAGABOFE, 0) BDREFPAGABOFE,FOLN.BDFIMPERGOZOFE,VER.BDCLAVER,FOLN.BDDATAPROCFE,FOLN.BDHORAPROCFE ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL ';

             wsql = wsql||'INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDINIPERAQUISFE, VFN.BDCODFE, VFN.BDCODVER,VFN.BDVALVFE FROM vrhf_emp_tverbafe VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END
       ELSE
          BEGIN
             wSQL = wSQL ||'from TEMPRESAS FOL ';
             wsql = wsql||'join vrhf_emp_tverbafe FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrh_emp_tferias FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDINIPERAQUISFE = FO.BDINIPERAQUISFE and FOLN.BDCODFE = FO.BDCODFE) ';
       wsql = wsql||'where ((CAST((SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 1 for 4)|| SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 6 for 2)) AS INTEGER) >= '||prrefini||
                    ' and CAST((SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 1 for 4)|| SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 6 for 2)) AS INTEGER) <= '||prreffim||')) ';


       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDINIPERAQUISFE,FO.BDCODFE ';
     END

  wempatu       = 0;
  wcolatu       = 0;
  wdataatu      = NULL;
  winiaquisatu  = NULL;
  wdatafeatu    = NULL;
  wdatafefimatu = NULL;
  wrefaboatu    = 0;
  wcodfeatu     = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:winiaquis,:wcodfe,:wcodver,:wvalor,:wdata,:wdep,:wdatafe,:wrefabo,:wdatafefim,:wclassif,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (winiaquisatu IS NULL) THEN
       winiaquisatu = winiaquis;

    IF (wcodfeatu = 0) THEN
       wcodfeatu = wcodfe;

    IF (wdataatu IS NULL) THEN
       wdataatu = wdata;

    IF (wdatafeatu IS NULL) THEN
       wdatafeatu = wdatafe;

    IF (wrefaboatu = 0) THEN
       wrefaboatu = wrefabo;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (winiaquis <> winiaquisatu) OR (wcodfe <> wcodfeatu)) THEN
       BEGIN
         IF (wdataatu IS NULL) THEN
            BEGIN
              IF (wdatafeatu IS NULL) THEN
                 wdataatu = CAST((SUBSTRING(wrefaboatu FROM 1 FOR 4)||'-'||SUBSTRING(wrefaboatu FROM 5 FOR 2)||'-01') AS DATE);
              ELSE
                 wdataatu = wdatafeatu;
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefpagto;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wValAbo;

              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 3;    -- F?rias
              BDINFADIC        = '';
              BDCODFE          = wcodfeatu;
              BDINIPERAQUIS    = winiaquisatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdatafeatu IS NOT NULL) THEN
                 BDINFADIC = BDINFADIC||'Per?odo de gozo: '||SUBSTRING(CAST(wdatafeatu AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(wdatafeatu AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdatafeatu AS VARCHAR(10)) FROM 1 FOR 4)||' at? '||
                             SUBSTRING(CAST(wdatafefimatu AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(wdatafefimatu AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdatafefimatu AS VARCHAR(10)) FROM 1 FOR 4);

              IF (BDINFADIC <> '') THEN
                 BDINFADIC = BDINFADIC||'; ';

              BDINFADIC = BDINFADIC||'C?digo: '||wcodfeatu;

              IF (BDVALABO > 0) THEN
                 BEGIN
                    IF (BDINFADIC <> '') THEN
                       BDINFADIC = BDINFADIC||'; ';
      
                    BDINFADIC = BDINFADIC||'Abono: '||SUBSTRING(wrefaboatu FROM 5 FOR 2)||'/'||SUBSTRING(wrefaboatu FROM 1 FOR 4);
                 END

              SUSPEND;

            END

         wempatu      = wcodemp;
         wcolatu      = wcodcol;
         wdataatu     = wdata;
         winiaquisatu = winiaquis;
         wcodfeatu    = wcodfe;
         wdatafeatu   = wdatafe;
         wrefaboatu   = wrefabo;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    IF (wdatafe IS NULL) THEN
       wref = wrefabo;
    ELSE
       wref = CAST((SUBSTRING(CAST(wdatafe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

    IF (wirver = 2) THEN -- IR F?rias
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 7) <> '3.001.8') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     IR
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.1') THEN
       wir = wir + wvalor;
    --                                     INSS
    IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.0') THEN
       winssn = winssn + wvalor;

    wdepatu = wdep;
    wdatafefimatu = wdatafefim;
    wdataproca = wdataproc;
    whoraproca = whoraproc;

    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1') THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '3.001.8.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '3.001.8.1') THEN
       wpenalim = wpenalim + wvalor;
    WISENTOABONO = 0;
    --                                      Abono pecuni?rio                                1/3 de abono pecuni?rio
    IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '3.003') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.004')) THEN
       BEGIN
         wvalabo = wvalabo + wvalor;
                 END
    ELSE
    -- Rendimentos isentos
    IF ((UPPER(wrendisentover) = 'TRUE') AND (WISENTOABONO = 0)) THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND winiaquisatu IS NOT NULL AND wcodfeatu <> 0) THEN
     BEGIN
       IF (wdataatu IS NULL) THEN
          BEGIN
            IF (wdatafeatu IS NULL) THEN
               wdataatu = CAST((SUBSTRING(wrefaboatu FROM 1 FOR 4)||'-'||SUBSTRING(wrefaboatu FROM 5 FOR 2)||'-01') AS DATE);
            ELSE
               wdataatu = wdatafeatu;
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefpagto;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 3;    -- F?rias
            BDINFADIC        = '';
            BDCODFE          = wcodfeatu;
            BDINIPERAQUIS    = winiaquisatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdatafeatu IS NOT NULL) THEN
               BDINFADIC = BDINFADIC||'Per?odo de gozo: '||SUBSTRING(CAST(wdatafeatu AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(wdatafeatu AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdatafeatu AS VARCHAR(10)) FROM 1 FOR 4)||' at? '||
                           SUBSTRING(CAST(wdatafefimatu AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(wdatafefimatu AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdatafefimatu AS VARCHAR(10)) FROM 1 FOR 4);

            IF (BDINFADIC <> '') THEN
               BDINFADIC = BDINFADIC||'; ';
            BDINFADIC = BDINFADIC||'C?digo: '||wcodfeatu;

            BDVALABO = wValAbo;

            IF (BDVALABO > 0) THEN
               BEGIN
                  IF (BDINFADIC <> '') THEN
                     BDINFADIC = BDINFADIC||'; ';
    
                  BDINFADIC = BDINFADIC||'Abono: '||SUBSTRING(wrefaboatu FROM 5 FOR 2)||'/'||SUBSTRING(wrefaboatu FROM 1 FOR 4);
               END

            SUSPEND;
          END

     END

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX, FOL.BDCODFERFIR, FOL.BDINIPERAQUISFIR ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR = 9030 and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FE.BDCODEMP,FE.BDCODCOL,FE.BDINIPERAQUISFE,FE.BDCODFE from VRHF_EMP_TVERBAFE FE where FE.BDCODEMP = FOL.BDCODEMP and FE.BDCODCOL = FOL.BDCODCOL and '||
                                'FE.BDINIPERAQUISFE = FOL.BDINIPERAQUISFIR and FE.BDCODFE = FOL.BDCODFERFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX, FO.BDCODFERFIR, FO.BDINIPERAQUISFIR ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wsql = wsql||'from tmp_empresas_select FOL ';
          END
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR = 9030 and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FE.BDCODEMP,FE.BDCODCOL,FE.BDINIPERAQUISFE,FE.BDCODFE from VRHF_EMP_TVERBAFE FE where FE.BDCODEMP = FO.BDCODEMP and FE.BDCODCOL = FO.BDCODCOL and '||
                                'FE.BDINIPERAQUISFE = FO.BDINIPERAQUISFIR and FE.BDCODFE = FO.BDCODFERFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDCODFE,
    :BDINIPERAQUIS
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';
    SUSPEND;
  END
END
^

/* Alter (SP_VRHF_DADOS_IR_FN) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FN(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPREVIARESC SMALLINT = 0,
PREXPORTACAO INTEGER = 0,
PRPORCC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
declare variable WEHINDRESC varchar(5);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WPAGEMP integer;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(200);
declare variable WDATARESC date;
declare variable WDATAPAGRESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDESCCC varchar(100);
declare variable WREFINI integer;
declare variable WSIND integer;
declare variable WFERIADO varchar(5);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WTIPOCLASSECOL integer;
declare variable WGCLASS varchar(1000);
declare variable WDESCVER2 varchar(70);
declare variable WI integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WSQLAUX varchar(1000);
declare variable WISENTOABONO integer;
BEGIN
  /*
      FOLHA NORMAL
  */

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.bdcodver,  VFN.BDVALVFN FROM vrhf_emp_tverbafn VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbafn FOL ';

       wsql = wsql||'left outer join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'left outer join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN) ';
       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';

       wsql = wsql||'where ((FOL.BDREFFN >= '||wrefini||' and FOL.BDREFFN <= '||prreffim||') or ';
       wsql = wsql||'       (FOL.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
     
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

/*       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VRHF_EMP_TVERBAFN Y '||
              'where Y.BDCODEMP = FOL.BDCODEMP and Y.BDCODCOL = FOL.BDCODCOL and Y.BDREFFN = FOL.BDREFFN '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02) ';   */

     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN ';
     END
  ELSE
     BEGIN

       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL ';

             wsql = wsql||'INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDCODVER, VFN.BDVALVFN FROM vrhf_emp_tverbafn VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END
       ELSE
          BEGIN
             wSQL = wSQL ||'from TEMPRESAS FOL ';
             wsql = wsql||'join vrhf_emp_tverbafn FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END

       wsql = wsql||'left outer join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'left outer join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFFN = FO.BDREFFN) ';
       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';
       wsql = wsql||'where ((FO.BDREFFN >= '||wrefini||' and FO.BDREFFN <= '||prreffim||') or ';
       wsql = wsql||'       (FO.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
             IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                wsql = wsql||' and (('||prcodemp||')';

             IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
                wsql = wsql||' or ('||prcodmatriz||')';
        
             IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
                wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';


     /*  wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VRHF_EMP_TVERBAFN Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFN '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02) '; */

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wpagemp    = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';
  wehindresc = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu)) THEN
       BEGIN
         wpagemp        = 0;
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;
         wtipoclassecol = 0;
         EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

         SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
         JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
         INTO :wtipoclassecol;

         IF (wtipoclassecol = 2) THEN   -- pro-labore
            SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
         ELSE
            SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              wsqlaux = 'select SUM(COALESCE(BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                        ' and ((COALESCE(BDREFFIN,0) >= '||wrefatu||') or (COALESCE(BDREFFIN,0) = 0)) ';
              EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;

              IF (wbaseir + winssn + wir > 0)  THEN
                 BDDEP = wdepatu;
              ELSE
                 BDDEP = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;

              if (COALESCE(:wprevprivcad, 0) > 0) then
                 begin
                   if (COALESCE(:wprepri, 0) > 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;
                 end
              else
                 BDPREVPRIV = 0;

              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescis?o
                   BDINFADIC = SUBSTRING(wcodpres||' - '||wdescpres FROM 1 FOR 300);
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = '';
                 END

              SUSPEND;
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover, :wehindresc;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
       winssn = winssn + wvalor;
    --                                     IR folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;

    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Di?rias/Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;

--    if ((substring(wclassif from 1 for 7) = '7.001.3') or (substring(wclassif from 1 for 5) = '7.020') or (substring(wclassif from 1 for 5) = '7.021')) then
    IF (UPPER(wehindresc) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN   -- Provento
            windresc = windresc + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- Desconto
            windresc = windresc - wvalor;
       END

    wisentoabono = 0;
    --                                      Complemento de abono pecuni?rio                  Compl. 1/3 abono pecuni?rio
    IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
       BEGIN
         wvalabo = wvalabo + wvalor;
                 END
    ELSE
    -- Rendimentos isentos
    IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0) THEN
     BEGIN
       wpagemp        = 0;
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;
       wtipoclassecol = 0;
       EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

       SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
       JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
       WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
       INTO :wtipoclassecol;

       IF (wtipoclassecol = 2) THEN  -- pro-labore
          SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
       ELSE
          SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select SUM(COALESCE(BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) ';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;

            IF (wbaseir + winssn + wir > 0)  THEN
               BDDEP = wdepatu;
            ELSE
               BDDEP = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;

            if (COALESCE(:wprevprivcad, 0) > 0) then
               begin
                 if (COALESCE(:wprepri, 0) > 0) then
                    BDPREVPRIV = wprepri;
                 else
                    BDPREVPRIV = wprevprivcad;
               end
            else
               BDPREVPRIV = 0;

            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescis?o
                 BDINFADIC = SUBSTRING(wcodpres||' - '||wdescpres FROM 1 FOR 300);
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = '';
               END
            SUSPEND;
          END
     END

  /*
      FOLHA TOMADOR
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT '||
              'from vrhf_emp_tverbatomador FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'left outer join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';

--       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and FOLN.BDORDEM = FOL.BDORDEM) ';

       wsql = wsql||'left outer join ('||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, MAX(FOL.BDDATAPGTOFT) BDDATAPGTOFT, MAX(FOL.BDDATAPROCFT) BDDATAPROCFT, MAX(FOL.BDHORAPROCFT) BDHORAPROCFT, SUM(FOL.BDDEPFT) BDDEPFT '||
                        'from VRHF_EMP_TFOLHATOMADOR FOL '||
                        'where FOL.BDREFTOMADOR >= '||wrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
            
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||'group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR) FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR) ';

       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';
       wsql = wsql||'where ((FOL.BDREFTOMADOR >= '||wrefini||' and FOL.BDREFTOMADOR <= '||prreffim||') or ';
       wsql = wsql||'       (FOL.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       /*wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFTOMADOR, COUNT(*) BDTOT, SUM(Y.BDVALVFT) BDSOMA from VRHF_EMP_TVERBATOMADOR Y '||
              'where Y.BDCODEMP = FOL.BDCODEMP and Y.BDCODCOL = FOL.BDCODCOL and Y.BDREFTOMADOR = FOL.BDREFTOMADOR and Y.BDORDEM = FOL.BDORDEM '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFTOMADOR having COUNT(*) = 2 and SUM(Y.BDVALVFT) = 0.02) ';*/

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wSQL = wSQL ||' from tmp_empresas_select FOL ';
          END
       ELSE
          wSQL = wSQL ||' from TEMPRESAS FOL ';

       wsql = wsql||'left outer join vrhf_emp_tverbatomador FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'left outer join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';

--       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and FOLN.BDORDEM = FO.BDORDEM) ';

       wsql = wsql||'left outer join ('||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, MAX(FOL.BDDATAPGTOFT) BDDATAPGTOFT, MAX(FOL.BDDATAPROCFT) BDDATAPROCFT, MAX(FOL.BDHORAPROCFT) BDHORAPROCFT, SUM(FOL.BDDEPFT) BDDEPFT '||
                        'from VRHF_EMP_TFOLHATOMADOR FOL '||
                        'where FOL.BDREFTOMADOR >= '||wrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (prpuxarfiliais = 0) AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR) FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR) ';


       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';
       wsql = wsql||'where ((FO.BDREFTOMADOR >= '||wrefini||' and FO.BDREFTOMADOR <= '||prreffim||') or ';
       wsql = wsql||'       (FO.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
             IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                wsql = wsql||' and (('||prcodemp||')';
         
             IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
                wsql = wsql||' or ('||prcodmatriz||')';
         
             IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
                wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       /*wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFTOMADOR, COUNT(*) BDTOT, SUM(Y.BDVALVFT) BDSOMA from VRHF_EMP_TVERBATOMADOR Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFTOMADOR = FO.BDREFTOMADOR and Y.BDORDEM = FO.BDORDEM '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFTOMADOR having COUNT(*) = 2 and SUM(Y.BDVALVFT) = 0.02) ';*/

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM ';
     END

  wempatu   = 0;
  wcolatu   = 0;
  wrefatu   = 0;
  wordematu = -1;
  wpagemp   = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wordem,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (prporcc = 0) THEN
       wordematu = COALESCE(wordem,0);
    ELSE
    IF (wordematu = -1) THEN
       wordematu = COALESCE(wordem,0);

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordematu <> COALESCE(wordem, 0))) THEN
       BEGIN
         wpagemp        = 0;
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;
         wtipoclassecol = 0;
         EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

         SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
         JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
         INTO :wtipoclassecol;

         IF (wtipoclassecol = 2) THEN   -- pro-labore
            SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
         ELSE
            SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         SELECT
         CASE
           WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
           WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
           WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
           ELSE CC.BDAPECTA END BDNOMCC
         FROM (
           SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
           FROM vrhf_emp_tprepfn X
           JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
           LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
           LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
           WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
         ) CC INTO :wdesccc;

         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordematu <> COALESCE(wordem, 0))) THEN
                 BEGIN
                   wsqlaux = 'select SUM(COALESCE(BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                             ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||'))';
                   EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;
                 END

              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              bdordem          = wordematu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;

              IF (wbaseir + winssn + wir > 0)  THEN
                 BDDEP = wdepatu;
              ELSE
                 BDDEP = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;

              if (COALESCE(:wprevprivcad, 0) > 0) then
                 begin
                   if (COALESCE(:wprepri, 0) > 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;
                 end
              else
                 BDPREVPRIV = 0;

              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescis?o
                   BDINFADIC = SUBSTRING(wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres FROM 1 FOR 300);
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = SUBSTRING(wordematu||' - '||wdesccc FROM 1 FOR 300);
                 END

              SUSPEND;
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;
         wordematu = wordem;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover, wehindresc;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
       winssn = winssn + wvalor;
    --                                     IR folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Di?rias/Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;

--    if ((substring(wclassif from 1 for 7) = '7.001.3') or (substring(wclassif from 1 for 5) = '7.020') or (substring(wclassif from 1 for 5) = '7.021')) then
    IF (UPPER(wehindresc) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN   -- Provento
            windresc = windresc + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- Desconto
            windresc = windresc - wvalor;
       END

    wisentoabono = 0;
    --                                      Complemento de abono pecuni?rio                  Compl. 1/3 abono pecuni?rio
    IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
       BEGIN
         wvalabo = wvalabo + wvalor;
                 END
    ELSE
    -- Rendimentos isentos
    IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0) THEN
     BEGIN
       wpagemp        = 0;
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;
       wtipoclassecol = 0;
       EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

       SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
       JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
       WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
       INTO :wtipoclassecol;

       IF (wtipoclassecol = 2) THEN    -- pro-labore
          SELECT COALESCE(BDPAGEMPCONTR,0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
       ELSE
          SELECT COALESCE(BDPAGEMP,0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       SELECT
       CASE
         WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
         WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
         WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
         ELSE CC.BDAPECTA END BDNOMCC
       FROM (
         SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
         FROM vrhf_emp_tprepfn X
         JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
         LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
         LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
       ) CC INTO :wdesccc;

       IF ((wtipomov = 0) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select SUM(COALESCE(BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||'))';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            bdordem          = wordematu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;

            IF (wbaseir + winssn + wir > 0)  THEN
               BDDEP = wdepatu;
            ELSE
               BDDEP = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;

            if (COALESCE(:wprevprivcad, 0) > 0) then
               begin
                 if (COALESCE(:wprepri, 0) > 0) then
                    BDPREVPRIV = wprepri;
                 else
                    BDPREVPRIV = wprevprivcad;
               end
            else
               BDPREVPRIV = 0;

            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescis?o
                 BDINFADIC = SUBSTRING(wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres FROM 1 FOR 300);
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = SUBSTRING(wordematu||' - '||wdesccc FROM 1 FOR 300);
               END
            SUSPEND;
          END
     END


  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9000,9001) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and '||
                                  'FN.BDREFFN = FOL.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FOL.BDREFFIR)) or ( ';

       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FOL.BDCODEMP and Y.BDCODCOL = FOL.BDCODCOL and Y.BDREFFN = FOL.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';
     
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';


       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wsql = wsql||'from tmp_empresas_select FOL ';
          END
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and '||
                                  'FN.BDREFFN = FO.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FO.BDREFFIR)) or ( ';
     
       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
             IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                wsql = wsql||' and (('||prcodemp||')';
             
             IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
                wsql = wsql||' or ('||prcodmatriz||')';
             
             IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
                wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';
    SUSPEND;
  END
END
^

/* Alter (SP_VRHF_DADOS_IR_FN2) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_FN2(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPREVIARESC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WDATAPGTO DATE;
DECLARE VARIABLE WCLASSIF VARCHAR(20);
DECLARE VARIABLE WDESCVER VARCHAR(40);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WDATAATU DATE;
DECLARE VARIABLE WPAGEMP INTEGER;
DECLARE VARIABLE WBASEIR NUMERIC(18,6);
DECLARE VARIABLE WREFPAGTO INTEGER;
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WIRVER INTEGER;
DECLARE VARIABLE WRENDISENTOVER VARCHAR(5);
DECLARE VARIABLE WINSSN NUMERIC(18,6);
DECLARE VARIABLE WIR NUMERIC(18,6);
DECLARE VARIABLE WDEP NUMERIC(18,6);
DECLARE VARIABLE WDEPATU NUMERIC(18,6);
DECLARE VARIABLE WLUCROPJ NUMERIC(18,6);
DECLARE VARIABLE WDESPMED NUMERIC(18,6);
DECLARE VARIABLE WAJCUS NUMERIC(18,6);
DECLARE VARIABLE WPENJUD NUMERIC(18,6);
DECLARE VARIABLE WPENALIM NUMERIC(18,6);
DECLARE VARIABLE WPREPRI NUMERIC(18,6);
DECLARE VARIABLE WINDRESC NUMERIC(18,6);
DECLARE VARIABLE WVALABO NUMERIC(18,6);
DECLARE VARIABLE WRENDIS NUMERIC(18,6);
DECLARE VARIABLE WDRENDIS VARCHAR(200);
DECLARE VARIABLE WDATARESC DATE;
DECLARE VARIABLE WDATAPAGRESC DATE;
DECLARE VARIABLE WCODPRES INTEGER;
DECLARE VARIABLE WDESCPRES VARCHAR(110);
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WORDEMATU INTEGER;
DECLARE VARIABLE WDESCCC VARCHAR(100);
DECLARE VARIABLE WREFINI INTEGER;
DECLARE VARIABLE WSIND INTEGER;
DECLARE VARIABLE WFERIADO VARCHAR(5);
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WDATAPROC DATE;
DECLARE VARIABLE WHORAPROC TIME;
DECLARE VARIABLE WDATAPROCA DATE;
DECLARE VARIABLE WHORAPROCA TIME;
DECLARE VARIABLE WTIPOMOV INTEGER;
DECLARE VARIABLE WTIPOCLASSECOL INTEGER;
DECLARE VARIABLE WGCLASS VARCHAR(1000);
DECLARE VARIABLE WDESCVER2 VARCHAR(70);
BEGIN
  /*
      FOLHA NORMAL
  */

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOt.BDREFFN,FOt.BDCODVER,FOt.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN '||
              'from (select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST BDCODEMP, BDCODCOLDEST BDCODCOL from VRH_EMP_TTRANSCOL) FOL ';
       wsql = wsql||'join vrhf_emp_tverbafn FOt on (FOt.BDCODEMP = FOL.BDCODEMPORIG and FOt.BDCODCOL = FOL.BDCODCOLORIG) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOt.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FOt.BDCODEMP and FOLN.BDCODCOL = FOt.BDCODCOL and FOLN.BDREFFN = FOt.BDREFFN) ';
       wsql = wsql||'left outer join TEMPRESAS TEMP_DEST on (TEMP_DEST.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FOt.BDREFFN >= '||wrefini||' and FOt.BDREFFN <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' and TEMP_DEST.BDCODMATRIZ = FOL.BDCODEMPORIG ';

       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VRHF_EMP_TVERBAFN Y '||
              'where Y.BDCODEMP = FOL.BDCODEMPORIG and Y.BDCODCOL = FOL.BDCODCOLORIG and Y.BDREFFN = FOt.BDREFFN '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02) ';

     
       wsql = wsql||' order by FOL.BDCODEMPORIG,FOL.BDCODCOLORIG,FOt.BDREFFN ';
     END
  ELSE
     BEGIN
       wsql = 'select fot.BDCODEMPDEST,fot.BDCODCOLDEST,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN '||
              'from TEMPRESAS FOL ';
       wsql = wsql||'join vrhf_emp_tverbafn FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'join VRH_EMP_TTRANSCOL fot on (fot.BDCODEMPDEST = FO.BDCODEMP and fot.BDCODCOLDEST = FO.BDCODCOL) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFFN = FO.BDREFFN) ';
       wsql = wsql||'where FO.BDREFFN >= '||wrefini||' and FO.BDREFFN <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       wsql = wsql||' and FOL.BDCODMATRIZ = fot.BDCODEMPORIG ';

       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VRHF_EMP_TVERBAFN Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFN '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02) ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFFN ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wpagemp    = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu)) THEN
       BEGIN
         wpagemp        = 0;
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;
         wtipoclassecol = 0;
         EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

         SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
         JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
         INTO :wtipoclassecol;

         IF (wtipoclassecol = 2) THEN   -- pro-labore
            SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
         ELSE
            SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END
         ELSE
            BEGIN
              IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) = 12) THEN
                 wdataatu = CAST((CAST((CAST((SUBSTRING(wrefatu FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'-01-01') AS DATE);
              ELSE
              IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) < 9) THEN
                 wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-0'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1))||'-01') AS DATE);
              ELSE
                 wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2))||'-01') AS DATE);
     
              IF (wpagemp = 0) THEN -- m?s seguinte
                 BEGIN
                   wsind = NULL;
                   wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                   SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wsind;
     
                   wi = 1;
                   WHILE (wi <= 5) DO
                     BEGIN
                       SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefpagto, :wsind) INTO wferiado;
                       IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                          wi = wi + 1;
     
                       IF (wi <= 5) THEN
                          wdataatu = wdataatu + 1;
                     END
                 END
              ELSE
                 BEGIN
                   wdataatu = wdataatu - 1;
                   wi = 1;
                   WHILE (wi = 1) DO
                     BEGIN
                       SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefatu, :wsind) INTO wferiado;
                       IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                          wi = 0;
     
                       IF (wi = 1) THEN
                          wdataatu = wdataatu - 1;
                     END
                 END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;

              IF (wbaseir + winssn + wir > 0)  THEN
                 BDDEP = wdepatu;
              ELSE
                 BDDEP = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescis?o
                   BDINFADIC = wcodpres||' - '||wdescpres;
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = '';
                 END

              SUSPEND;
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
       winssn = winssn + wvalor;
    --                                     IR folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;

    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Di?rias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;

    IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '7.001.3') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '7.020') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '7.021')) THEN
       BEGIN
         IF (wtipocodver = 0) THEN   -- Provento
            windresc = windresc + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- Desconto
            windresc = windresc - wvalor;
       END

    --                                      Abono pec.                                      1/3 abono pec.                                  Abono pec. dobro                                1/3 abono pec.
    IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '3.003') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.004') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.007') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.008') OR
    --                                      Complemento de abono pecuni?rio                  Compl. 1/3 abono pecuni?rio
        (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
       wvalabo = wvalabo + wvalor;
    -- Rendimentos isentos
    IF (UPPER(wrendisentover) = 'TRUE') THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0) THEN
     BEGIN
       wpagemp        = 0;
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;
       wtipoclassecol = 0;
       EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

       SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
       JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
       WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
       INTO :wtipoclassecol;

       IF (wtipoclassecol = 2) THEN  -- pro-labore
          SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
       ELSE
          SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END
       ELSE
          BEGIN
            IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) = 12) THEN
               wdataatu = CAST((CAST((CAST((SUBSTRING(wrefatu FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'-01-01') AS DATE);
            ELSE
            IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) < 9) THEN
               wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-0'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1))||'-01') AS DATE);
            ELSE
               wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2))||'-01') AS DATE);
   
            IF (wpagemp = 0) THEN -- m?s seguinte
               BEGIN
                 wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                 wsind = NULL;
                 SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wsind;
   
                 wi = 1;
                 WHILE (wi <= 5) DO
                   BEGIN
                     SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefpagto, :wsind) INTO wferiado;
                     IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                        wi = wi + 1;
   
                     IF (wi <= 5) THEN
                        wdataatu = wdataatu + 1;
                   END
               END
            ELSE
               BEGIN
                 wdataatu = wdataatu - 1;
                 wi = 1;
                 WHILE (wi = 1) DO
                   BEGIN
                     SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefatu, :wsind) INTO wferiado;
                     IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                        wi = 0;
   
                     IF (wi = 1) THEN
                        wdataatu = wdataatu - 1;
                   END
               END
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;

            IF (wbaseir + winssn + wir > 0)  THEN
               BDDEP = wdepatu;
            ELSE
               BDDEP = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescis?o
                 BDINFADIC = wcodpres||' - '||wdescpres;
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = '';
               END
            SUSPEND;
          END
     END

  /*
      FOLHA TOMADOR
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOt.BDREFTOMADOR,FOt.BDORDEM,FOt.BDCODVER,FOt.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT '||
              'from (select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST BDCODEMP, BDCODCOLDEST BDCODCOL from VRH_EMP_TTRANSCOL) FOL ';

       wsql = wsql||'join vrhf_emp_tverbatomador FOt on (FOt.BDCODEMP = FOL.BDCODEMPORIG and FOt.BDCODCOL = BDCODCOLORIG) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOt.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FOt.BDCODEMP and FOLN.BDCODCOL = FOt.BDCODCOL and FOLN.BDREFTOMADOR = FOt.BDREFTOMADOR and FOLN.BDORDEM = FOt.BDORDEM) ';
       wsql = wsql||'left outer join TEMPRESAS TEMP_DEST on (TEMP_DEST.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FOt.BDREFTOMADOR >= '||wrefini||' and FOt.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' and TEMP_DEST.BDCODMATRIZ = FOL.BDCODEMPORIG ';

       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFTOMADOR, COUNT(*) BDTOT, SUM(Y.BDVALVFT) BDSOMA from VRHF_EMP_TVERBATOMADOR Y '||
              'where Y.BDCODEMP = FOL.BDCODEMPORIG and Y.BDCODCOL = FOL.BDCODCOLORIG and Y.BDREFTOMADOR = FOt.BDREFTOMADOR and Y.BDORDEM = FOt.BDORDEM '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFTOMADOR having COUNT(*) = 2 and SUM(Y.BDVALVFT) = 0.02) ';

       wsql = wsql||' order by FOL.BDCODEMPORIG,FOL.BDCODCOLORIG,FOt.BDREFTOMADOR,FOt.BDORDEM ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT '||
              'from TEMPRESAS FOL ';
       wsql = wsql||'join vrhf_emp_tverbatomador FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and FOLN.BDORDEM = FO.BDORDEM) ';
       wsql = wsql||'where FO.BDREFTOMADOR >= '||wrefini||' and FO.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';
     
       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       wsql = wsql||' and FOL.BDCODMATRIZ = fot.BDCODEMPORIG ';

       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFTOMADOR, COUNT(*) BDTOT, SUM(Y.BDVALVFT) BDSOMA from VRHF_EMP_TVERBATOMADOR Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFTOMADOR = FO.BDREFTOMADOR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFTOMADOR having COUNT(*) = 2 and SUM(Y.BDVALVFT) = 0.02) ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM ';
     END

  wempatu   = 0;
  wcolatu   = 0;
  wrefatu   = 0;
  wordematu = 0;
  wpagemp   = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wordem,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wordematu = 0) THEN
       wordematu = wordem;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordem <> wordematu)) THEN
       BEGIN
         wpagemp        = 0;
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;
         wtipoclassecol = 0;
         EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

         SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
         JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
         INTO :wtipoclassecol;

         IF (wtipoclassecol = 2) THEN   -- pro-labore
            SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
         ELSE
            SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         SELECT
         CASE
           WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
           WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
           WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
           ELSE CC.BDAPECTA END BDNOMCC
         FROM (
           SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
           FROM vrhf_emp_tprepfn X
           JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
           LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
           LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
           WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
         ) CC INTO :wdesccc;

         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END
         ELSE
            BEGIN
              IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) = 12) THEN
                 wdataatu = CAST((CAST((CAST((SUBSTRING(wrefatu FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'-01-01') AS DATE);
              ELSE
              IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) < 9) THEN
                 wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-0'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1))||'-01') AS DATE);
              ELSE
                 wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2))||'-01') AS DATE);
     
              IF (wpagemp = 0) THEN -- m?s seguinte
                 BEGIN
                   wsind = NULL;
                   wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                   SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wsind;
     
                   wi = 1;
                   WHILE (wi <= 5) DO
                     BEGIN
                       SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefpagto, :wsind) INTO wferiado;
                       IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                          wi = wi + 1;
     
                       IF (wi <= 5) THEN
                          wdataatu = wdataatu + 1;
                     END
                 END
              ELSE
                 BEGIN
                   wdataatu = wdataatu - 1;
                   wi = 1;
                   WHILE (wi = 1) DO
                     BEGIN
                       SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefatu, :wsind) INTO wferiado;
                       IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                          wi = 0;
     
                       IF (wi = 1) THEN
                          wdataatu = wdataatu - 1;
                     END
                 END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              bdordem          = wordematu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;

              IF (wbaseir + winssn + wir > 0)  THEN
                 BDDEP = wdepatu;
              ELSE
                 BDDEP = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescis?o
                   BDINFADIC = wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres;
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = wordematu||' - '||wdesccc;
                 END

              SUSPEND;
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;
         wordematu = wordem;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
       winssn = winssn + wvalor;
    --                                     IR folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
    --                                     Lucro pessoa jur?dica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas m?dicas                                     Complemento de despesas m?dicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Di?rias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Pens?es judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pens?es aliment?cias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;

    IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '7.001.3') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '7.020') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '7.021')) THEN
       BEGIN
         IF (wtipocodver = 0) THEN   -- Provento
            windresc = windresc + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- Desconto
            windresc = windresc - wvalor;
       END

    --                                      Abono pec.                                      1/3 abono pec.                                  Abono pec. dobro                                1/3 abono pec.
    IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '3.003') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.004') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.007') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.008') OR
    --                                      Complemento de abono pecuni?rio                  Compl. 1/3 abono pecuni?rio
        (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
       wvalabo = wvalabo + wvalor;
    -- Rendimentos isentos
    IF (UPPER(wrendisentover) = 'TRUE') THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wordematu <> 0) THEN
     BEGIN
       wpagemp        = 0;
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;
       wtipoclassecol = 0;
       EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

       SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
       JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
       WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
       INTO :wtipoclassecol;

       IF (wtipoclassecol = 2) THEN    -- pro-labore
          SELECT COALESCE(BDPAGEMPCONTR,0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
       ELSE
          SELECT COALESCE(BDPAGEMP,0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       SELECT
       CASE
         WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
         WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
         WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
         ELSE CC.BDAPECTA END BDNOMCC
       FROM (
         SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
         FROM vrhf_emp_tprepfn X
         JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
         LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
         LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
       ) CC INTO :wdesccc;

       IF ((wtipomov = 0) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END
       ELSE
          BEGIN
            IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) = 12) THEN
               wdataatu = CAST((CAST((CAST((SUBSTRING(wrefatu FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'-01-01') AS DATE);
            ELSE
            IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) < 9) THEN
               wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-0'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1))||'-01') AS DATE);
            ELSE
               wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2))||'-01') AS DATE);
   
            IF (wpagemp = 0) THEN -- m?s seguinte
               BEGIN
                 wsind = NULL;
                 wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                 SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wsind;
   
                 wi = 1;
                 WHILE (wi <= 5) DO
                   BEGIN
                     SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefpagto, :wsind) INTO wferiado;
                     IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                        wi = wi + 1;
   
                     IF (wi <= 5) THEN
                        wdataatu = wdataatu + 1;
                   END
               END
            ELSE
               BEGIN
                 wdataatu = wdataatu - 1;
                 wi = 1;
                 WHILE (wi = 1) DO
                   BEGIN
                     SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefatu, :wsind) INTO wferiado;
                     IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                        wi = 0;
   
                     IF (wi = 1) THEN
                        wdataatu = wdataatu - 1;
                   END
               END
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            bdordem          = wordematu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;

            IF (wbaseir + winssn + wir > 0)  THEN
               BDDEP = wdepatu;
            ELSE
               BDDEP = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescis?o
                 BDINFADIC = wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres;
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = wordematu||' - '||wdesccc;
               END
            SUSPEND;
          END
     END


  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||' from (select BDCODEMPORIG BDCODEMP, BDCODCOLORIG BDCODCOL, BDCODEMPDEST, BDCODCOLDEST from VRH_EMP_TTRANSCOL) FOL ';
       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP and FO.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and '||
                                  'FN.BDREFFN = FO.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FO.BDREFFIR)) or ( ';

       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FOL.BDCODEMP and Y.BDCODCOL = FOL.BDCODCOL and Y.BDREFFN = FO.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FO.BDREFFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from TEMPRESAS FOL ';
       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'join (select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST BDCODEMP, BDCODCOLDEST BDCODCOL from VRH_EMP_TTRANSCOL) XX on (XX.BDCODEMP = FO.BDCODEMP and XX.BDCODCOL = FO.BDCODCOL) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and '||
                                  'FN.BDREFFN = FO.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FO.BDREFFIR)) or ( ';
     
       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';
     
       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';
    SUSPEND;
  END
END
^

/* Alter (SP_VRHF_DADOS_IR_INT) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_INT(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '',
PRPREVIARESC SMALLINT = 0,
PREXPORTACAO INTEGER = 0,
PRPORCC SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER,
BDCODCONTTI INTEGER)
 AS
declare variable WEHINDRESC varchar(5);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WPAGEMP integer;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(200);
declare variable WDATARESC date;
declare variable WDATAPAGRESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDESCCC varchar(100);
declare variable WREFINI integer;
declare variable WSIND integer;
declare variable WFERIADO varchar(5);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WTIPOCLASSECOL integer;
declare variable WGCLASS varchar(1000);
declare variable WDESCVER2 varchar(70);
declare variable WI integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WSQLAUX varchar(1000);
declare variable WISENTOABONO integer;
declare variable WCODCONTTI integer;
declare variable WCONTTIATU integer;
declare variable WINSSANTES numeric(18,6);
BEGIN
  /*
      FOLHA NORMAL
  */

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.bdcodver, VFN.BDCODCONTTI, VFN.BDVALVFN FROM vrhf_emp_tverbaint VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbaint FOL ';

       wsql = wsql||'left outer join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'left outer join vrhf_emp_tfolhaint FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN and FOLN.BDCODCONTTI = FOL.BDCODCONTTI) ';
       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';

       wsql = wsql||'where ((FOL.BDREFFN >= '||wrefini||' and FOL.BDREFFN <= '||prreffim||') or ';
       wsql = wsql||'       (FOL.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
     
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODCONTTI ';
     END
  ELSE
     BEGIN

       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL ';

             wsql = wsql||'INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDCODVER, VFN.BDCODCONTTI, VFN.BDVALVFN FROM vrhf_emp_tverbaint VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END
       ELSE
          BEGIN
             wSQL = wSQL ||'from TEMPRESAS FOL ';
             wsql = wsql||'join vrhf_emp_tverbaint FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
          END

       wsql = wsql||'left outer join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'left outer join vrhf_emp_tfolhaint FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFFN = FO.BDREFFN and FOLN.BDCODCONTTI = FO.BDCODCONTTI) ';
       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';
       wsql = wsql||'where ((FO.BDREFFN >= '||wrefini||' and FO.BDREFFN <= '||prreffim||') or ';
       wsql = wsql||'       (FO.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
             IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                wsql = wsql||' and (('||prcodemp||')';

             IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
                wsql = wsql||' or ('||prcodmatriz||')';
        
             IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
                wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODCONTTI ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wconttiatu = 0;
  wpagemp    = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';
  wehindresc = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wcodcontti,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wconttiatu = 0) THEN
       wconttiatu = wcodcontti;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wcodcontti <> wconttiatu)) THEN
       BEGIN
         wpagemp        = 0;
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;
         wtipoclassecol = 0;
         EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

         SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
         JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
         INTO :wtipoclassecol;

         IF (wtipoclassecol = 2) THEN   -- pro-labore
            SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
         ELSE
            SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              wsqlaux = 'select SUM(COALESCE(BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                        ' and ((COALESCE(BDREFFIN,0) >= '||wrefatu||') or (COALESCE(BDREFFIN,0) = 0)) ';
              EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

              winssantes = null;
              if (wrefpagto <> wrefatu) then
                 begin
                   wsqlaux = 'select SUM(BDINSSFN) from VRHF_EMP_TFOLHAINT where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFFN = '||wrefatu||' and BDDATAPGTOFN < '''||wdataatu||''' and BDCODCONTTI <> '||wconttiatu;
                   execute statement wsqlaux into :winssantes;
                 end

              if (winssantes is null) then
                 winssantes = 0;

              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDCODCONTTI      = wconttiatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn + winssantes;
              BDIR             = wir;

              IF (wbaseir + winssn + wir > 0)  THEN
                 BDDEP = wdepatu;
              ELSE
                 BDDEP = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;

              if (COALESCE(:wprevprivcad, 0) > 0) then
                 begin
                   if (COALESCE(:wprepri, 0) > 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;
                 end
              else
                 BDPREVPRIV = 0;

              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescisão
                   BDINFADIC = SUBSTRING(wcodpres||' - '||wdescpres FROM 1 FOR 300);
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = '';
                 END

              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wconttiatu = wcodcontti;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover, :wehindresc;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obrigações IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
       winssn = winssn + wvalor;
    --                                     IR folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;

    --                                     Lucro pessoa jurídica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas médicas                                     Complemento de despesas médicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Diárias/Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Pensões judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pensões alimentícias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previdência privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;

    IF (UPPER(wehindresc) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN   -- Provento
            windresc = windresc + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- Desconto
            windresc = windresc - wvalor;
       END

    wisentoabono = 0;
    --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
    IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
       BEGIN
         wvalabo = wvalabo + wvalor;
                 END
    ELSE
    -- Rendimentos isentos
    IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wconttiatu <> 0) THEN
     BEGIN
       wpagemp        = 0;
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;
       wtipoclassecol = 0;
       EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

       SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
       JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
       WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
       INTO :wtipoclassecol;

       IF (wtipoclassecol = 2) THEN  -- pro-labore
          SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
       ELSE
          SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select SUM(COALESCE(BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) ';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

            winssantes = null;
            if (wrefpagto <> wrefatu) then
               begin
                 wsqlaux = 'select SUM(BDINSSFN) from VRHF_EMP_TFOLHAINT where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFFN = '||wrefatu||' and BDDATAPGTOFN < '''||wdataatu||''' and BDCODCONTTI <> '||wconttiatu;
                 execute statement wsqlaux into :winssantes;
               end
 
            if (winssantes is null) then
               winssantes = 0;

            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDCODCONTTI      = wconttiatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn + winssantes;
            BDIR             = wir;

            IF (wbaseir + winssn + wir > 0)  THEN
               BDDEP = wdepatu;
            ELSE
               BDDEP = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;

            if (COALESCE(:wprevprivcad, 0) > 0) then
               begin
                 if (COALESCE(:wprepri, 0) > 0) then
                    BDPREVPRIV = wprepri;
                 else
                    BDPREVPRIV = wprevprivcad;
               end
            else
               BDPREVPRIV = 0;

            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescisão
                 BDINFADIC = SUBSTRING(wcodpres||' - '||wdescpres FROM 1 FOR 300);
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = '';
               END
            SUSPEND;
          END
     END

  /*
      FOLHA TOMADOR
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT '||
              'from vrhf_emp_tverbatomint FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'left outer join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';

       wsql = wsql||'left outer join ('||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODCONTTI, MAX(FOL.BDDATAPGTOFT) BDDATAPGTOFT, MAX(FOL.BDDATAPROCFT) BDDATAPROCFT, MAX(FOL.BDHORAPROCFT) BDHORAPROCFT, SUM(FOL.BDDEPFT) BDDEPFT '||
                        'from VRHF_EMP_TFOLHATOMINT FOL '||
                        'where FOL.BDREFTOMADOR >= '||wrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
            
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||'group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODCONTTI) FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and FOLN.BDCODCONTTI = FOL.BDCODCONTTI) ';

       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';
       wsql = wsql||'where ((FOL.BDREFTOMADOR >= '||wrefini||' and FOL.BDREFTOMADOR <= '||prreffim||') or ';
       wsql = wsql||'       (FOL.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODCONTTI ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wSQL = wSQL ||' from tmp_empresas_select FOL ';
          END
       ELSE
          wSQL = wSQL ||' from TEMPRESAS FOL ';

       wsql = wsql||'left outer join vrhf_emp_tverbatomint FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'left outer join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';

       wsql = wsql||'left outer join ('||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODCONTTI, MAX(FOL.BDDATAPGTOFT) BDDATAPGTOFT, MAX(FOL.BDDATAPROCFT) BDDATAPROCFT, MAX(FOL.BDHORAPROCFT) BDHORAPROCFT, SUM(FOL.BDDEPFT) BDDEPFT '||
                        'from VRHF_EMP_TFOLHATOMINT FOL '||
                        'where FOL.BDREFTOMADOR >= '||wrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (prpuxarfiliais = 0) AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODCONTTI) FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and FOLN.BDCODCONTTI = FO.BDCODCONTTI) ';


       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';
       wsql = wsql||'where ((FO.BDREFTOMADOR >= '||wrefini||' and FO.BDREFTOMADOR <= '||prreffim||') or ';
       wsql = wsql||'       (FO.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
             IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                wsql = wsql||' and (('||prcodemp||')';
         
             IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
                wsql = wsql||' or ('||prcodmatriz||')';
         
             IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
                wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODCONTTI ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wconttiatu = 0;
  wordematu  = -1;
  wpagemp    = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wordem,:wcodcontti,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wconttiatu = 0) THEN
       wconttiatu = wcodcontti;

    IF (prporcc = 0) THEN
       wordematu = COALESCE(wordem,0);
    ELSE
    IF (wordematu = -1) THEN
       wordematu = COALESCE(wordem,0);

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordematu <> COALESCE(wordem, 0)) OR (wcodcontti <> wconttiatu)) THEN
       BEGIN
         wpagemp        = 0;
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;
         wtipoclassecol = 0;
         EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

         SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
         JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
         INTO :wtipoclassecol;

         IF (wtipoclassecol = 2) THEN   -- pro-labore
            SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
         ELSE
            SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         SELECT
         CASE
           WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
           WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
           WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
           ELSE CC.BDAPECTA END BDNOMCC
         FROM (
           SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
           FROM vrhf_emp_tprepfn X
           JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
           LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
           LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
           WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
         ) CC INTO :wdesccc;

         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordematu <> COALESCE(wordem, 0))) THEN
                 BEGIN
                   wsqlaux = 'select SUM(COALESCE(BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                             ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||'))';
                   EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;
                 END

              winssantes = null;
              if (wrefpagto <> wrefatu) then
                 begin
                   wsqlaux = 'select SUM(BDINSSFT) from VRHF_EMP_TFOLHATOMINT where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||wrefatu||' and BDORDEM = '||wordematu||' and BDDATAPGTOFT < '''||wdataatu||''' and BDCODCONTTI <> '||wconttiatu;
                   execute statement wsqlaux into :winssantes;
                 end
   
              if (winssantes is null) then
                 winssantes = 0;

              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              bdordem          = wordematu;
              BDCODCONTTI      = wconttiatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn + winssantes;
              BDIR             = wir;

              IF (wbaseir + winssn + wir > 0)  THEN
                 BDDEP = wdepatu;
              ELSE
                 BDDEP = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;

              if (COALESCE(:wprevprivcad, 0) > 0) then
                 begin
                   if (COALESCE(:wprepri, 0) > 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;
                 end
              else
                 BDPREVPRIV = 0;

              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescisão
                   BDINFADIC = SUBSTRING(wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres FROM 1 FOR 300);
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = SUBSTRING(wordematu||' - '||wdesccc FROM 1 FOR 300);
                 END

              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wordematu  = wordem;
         wconttiatu = wcodcontti;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover, wehindresc;

    IF (wirver = 1) THEN -- IR Folha normal
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir = wbaseir + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obrigações IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir = wbaseir - wvalor;
            END
       END

    --                                     INSS folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
       winssn = winssn + wvalor;
    --                                     IR folha normal
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
       wir = wir + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
    --                                     Lucro pessoa jurídica
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
       wlucropj = wlucropj + wvalor;
    --                                     Despesas médicas                                     Complemento de despesas médicas
    IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
       wdespmed = wdespmed + wvalor;
    --                                     Diárias/Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Ajuda de custos
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
       wajcus = wajcus + wvalor;
    --                                     Pensões judiciais
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
       wpenjud = wpenjud + wvalor;
    --                                     Pensões alimentícias
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
       wpenalim = wpenalim + wvalor;
    --                                     Previdência privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
       wprepri = wprepri + wvalor;

--    if ((substring(wclassif from 1 for 7) = '7.001.3') or (substring(wclassif from 1 for 5) = '7.020') or (substring(wclassif from 1 for 5) = '7.021')) then
    IF (UPPER(wehindresc) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN   -- Provento
            windresc = windresc + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- Desconto
            windresc = windresc - wvalor;
       END

    wisentoabono = 0;
    --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
    IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
       BEGIN
         wvalabo = wvalabo + wvalor;
                 END
    ELSE
    -- Rendimentos isentos
    IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
       BEGIN
         wrendis = wrendis + wvalor;

         wi = 0;
         SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

         IF (wi = 0) THEN
            BEGIN
              wdescver2 = '';
              SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
              wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);

              IF (wdrendis <> '') THEN
                 wdrendis = wdrendis ||', ';

              wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
            END
       END
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wconttiatu <> 0) THEN
     BEGIN
       wpagemp        = 0;
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;
       wtipoclassecol = 0;
       EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

       SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
       JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
       WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
       INTO :wtipoclassecol;

       IF (wtipoclassecol = 2) THEN    -- pro-labore
          SELECT COALESCE(BDPAGEMPCONTR,0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
       ELSE
          SELECT COALESCE(BDPAGEMP,0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       SELECT
       CASE
         WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
         WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
         WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
         ELSE CC.BDAPECTA END BDNOMCC
       FROM (
         SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
         FROM vrhf_emp_tprepfn X
         JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
         LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
         LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
       ) CC INTO :wdesccc;

       IF ((wtipomov = 0) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select SUM(COALESCE(BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||'))';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

            winssantes = null;
            if (wrefpagto <> wrefatu) then
               begin
                 wsqlaux = 'select SUM(BDINSSFT) from VRHF_EMP_TFOLHATOMINT where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||wrefatu||' and BDORDEM = '||wordematu||' and BDDATAPGTOFT < '''||wdataatu||''' and BDCODCONTTI <> '||wconttiatu;
                 execute statement wsqlaux into :winssantes;
               end
 
            if (winssantes is null) then
               winssantes = 0;

            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            bdordem          = wordematu;
            BDCODCONTTI      = wconttiatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn + winssantes;
            BDIR             = wir;

            IF (wbaseir + winssn + wir > 0)  THEN
               BDDEP = wdepatu;
            ELSE
               BDDEP = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;

            if (COALESCE(:wprevprivcad, 0) > 0) then
               begin
                 if (COALESCE(:wprepri, 0) > 0) then
                    BDPREVPRIV = wprepri;
                 else
                    BDPREVPRIV = wprevprivcad;
               end
            else
               BDPREVPRIV = 0;

            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescisão
                 BDINFADIC = SUBSTRING(wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres FROM 1 FOR 300);
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = SUBSTRING(wordematu||' - '||wdesccc FROM 1 FOR 300);
               END
            SUSPEND;
          END
     END


  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9000,9001) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and '||
                                  'FN.BDREFFN = FOL.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FOL.BDREFFIR)) or ( ';

       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FOL.BDCODEMP and Y.BDCODCOL = FOL.BDCODCOL and Y.BDREFFN = FOL.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';
     
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';


       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wsql = wsql||'from tmp_empresas_select FOL ';
          END
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and '||
                                  'FN.BDREFFN = FO.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FO.BDREFFIR)) or ( ';
     
       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
             IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                wsql = wsql||' and (('||prcodemp||')';
             
             IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
                wsql = wsql||' or ('||prcodmatriz||')';
             
             IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
                wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';
    BDCODCONTTI = null;
    SUSPEND;
  END
END
^

/* Alter (SP_VRHF_DADOS_IR_INT13) */
ALTER PROCEDURE SP_VRHF_DADOS_IR_INT13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDREFPAG INTEGER,
BDTIPO INTEGER,
BDRENDTRIBUTAVEL NUMERIC(18,6),
BDINSS NUMERIC(18,6),
BDIR NUMERIC(18,6),
BDDEP NUMERIC(18,6),
BDLUCROPJ NUMERIC(18,6),
BDDESPMED NUMERIC(18,6),
BDAJCUSTOS NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDPREVPRIV NUMERIC(18,6),
BDINDRESC NUMERIC(18,6),
BDVALABO NUMERIC(18,6),
BDRENDISENTOS NUMERIC(18,6),
BDDRENDISENTOS VARCHAR(200),
BDDATAPGTO DATE,
BDINFADIC VARCHAR(300),
BDDATAPROC DATE,
BDHORAPROC TIME,
BDORDEM INTEGER,
BDCODCONTTI INTEGER)
 AS
declare variable WULTDIAMES integer;
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(200);
declare variable WREFINI integer;
declare variable WDATARESC date;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDATAPGTO date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WSQLAUX varchar(1000);
declare variable WEXISTE13MES integer;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCODCONTTI integer;
declare variable WCONTTIATU integer;
declare variable WINSS13ANTES numeric(18,6);
BEGIN
  WUSARTMP_EMP_SELECT = 0;
  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  /* 13? FOLHA NORMAL */
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,CAST(null as DATE),FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,0,FOLN.BDDATAPGTOFN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDCODCONTTI, VFN.bdcodver, VFN.BDVALVFN FROM vrhf_emp_tverbaint VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbaint FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhaint FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN and FOLN.BDCODCONTTI = FOL.BDCODCONTTI) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOL.BDREFFN >= '||wrefini||' and FOL.BDREFFN <= '||prreffim;
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODCONTTI ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,CAST(null as DATE),FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,0,FOLN.BDDATAPGTOFN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDCODCONTTI, VFN.BDCODVER,VFN.BDVALVFN FROM vrhf_emp_tverbaint VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbaint FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhaint FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFFN = FO.BDREFFN and FOLN.BDCODCONTTI = FO.BDCODCONTTI) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FO.BDCODEMP and COL.BDCODCOL = FO.BDCODCOL) ';
       wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FO.BDREFFN >= '||wrefini||' and FO.BDREFFN <= '||prreffim;

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||') ';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODCONTTI ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wconttiatu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wcodcontti,:wcodver,:wvalor,:wdep,:wclassif,:wdescver,:wdataresc,:wdataproc,:whoraproc,:wtipomov,:wdatapgto DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF (wconttiatu = 0) THEN
       wconttiatu = wcodcontti;
    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wcodcontti <> wconttiatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                        ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 '||
                        ' order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
              EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

              winss13antes = null;
              if (wrefpagto <> wrefatu) then
                 begin
                   wsqlaux = 'select SUM(BDINSS13FN) from VRHF_EMP_TFOLHAINT where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFFN = '||wrefatu||' and BDDATAPGTOFN < '''||wdataatu||''' and BDCODCONTTI <> '||wconttiatu;
                   execute statement wsqlaux into :winss13antes;
                 end
   
              if (winss13antes is null) then
                 winss13antes = 0;

              winss13 = winss13 + winss13antes;

              if (wbaseir13 < 0) then
                 wbaseir13 = 0;

              if (winss13 < 0) then
                 winss13 = 0;

              if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
                 begin
                   /*Se tiver 13? no m?s da rescis?o n?o deve considerar o dependente novamente*/
                   wsqlaux = 'select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = '||wempatu||' and dt.bdcodcol = '||wcolatu||' and dt.bdref13 ='||wrefpagto;
                   wexiste13mes = NULL;
                   EXECUTE STATEMENT wsqlaux INTO :wexiste13mes;
                   IF (wexiste13mes IS NOT NULL) THEN
                      wdepatu = 0;
          
                   BDCODEMP         = wempatu;
                   BDCODCOL         = wcolatu;
                   BDREF            = wrefatu;
                   BDCODCONTTI      = wconttiatu;
                   BDREFPAG         = wrefpagto;
                   BDRENDTRIBUTAVEL = wbaseir13;
                   BDINSS           = winss13;
                   BDIR             = wir13;
          
                   IF (wbaseir13 <= 0 AND winss13 <= 0) THEN
                      wdepatu = 0;
          
                   BDDEP            = wdepatu;
                   BDLUCROPJ        = 0;
                   BDDESPMED        = 0;
                   BDAJCUSTOS       = 0;
                   BDPENJUD         = 0;
                   BDPENALIM        = 0;
     
                   if (wprepri <> 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;
     
                   BDVALABO         = 0;
                   BDRENDISENTOS    = 0;
                   BDDRENDISENTOS   = '';
                   BDDATAPGTO       = wdataatu;
                   BDTIPO           = 10;    -- 13? rescis?o
                   BDINFADIC        = '';
                   BDDATAPROC       = wdataproca;
                   BDHORAPROC       = whoraproca;
                   SUSPEND;
                 end
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wconttiatu = wcodcontti;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         wrendis    = 0;
         wdrendis   = '';
       END

    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;
    IF (wirver = 3) THEN -- 13? sal?rio
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir13 = wbaseir13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir13 = wbaseir13 - wvalor;
            END
       END
    --                                     INSS 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.6') THEN
       winss13 = winss13 + wvalor;
    --                                     IR 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.A') THEN
       wir13 = wir13 + wvalor;
    --                                     Previd?ncia privada
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.601.8.2') THEN
       wprepri = wprepri + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;

    wdataproca = wdataproc;
    whoraproca = whoraproc;

  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wconttiatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

            winss13antes = null;
            if (wrefpagto <> wrefatu) then
               begin
                 wsqlaux = 'select SUM(BDINSS13FN) from VRHF_EMP_TFOLHAINT where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFFN = '||wrefatu||' and BDDATAPGTOFN < '''||wdataatu||''' and BDCODCONTTI <> '||wconttiatu;
                 execute statement wsqlaux into :winss13antes;
               end
 
            if (winss13antes is null) then
               winss13antes = 0;

            winss13 = winss13 + winss13antes;

            if (wbaseir13 < 0) then
               wbaseir13 = 0;

            if (winss13 < 0) then
               winss13 = 0;

            if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
               begin
            /*Se tiver 13? no m?s da rescis?o n?o deve considerar o dependente novamente*/
            wsqlaux = 'select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = '||wempatu||' and dt.bdcodcol = '||wcolatu||' and dt.bdref13 ='||wrefpagto;
            wexiste13mes = NULL;
            EXECUTE STATEMENT wsqlaux INTO :wexiste13mes;
            IF (wexiste13mes IS NOT NULL) THEN
               wdepatu = 0;
     
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDCODCONTTI      = wconttiatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;

            if (wprepri <> 0) then
               BDPREVPRIV = wprepri;
            else
               BDPREVPRIV = wprevprivcad;

            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 10;    -- 13? rescis?o
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
               end
          END
     END

  /*  13? FOLHA TOMADOR  */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,CAST(null as DATE),FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,0,FOLN.BDDATAPGTOFT ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFTOMADOR, VFN.BDORDEM, VFN.BDCODCONTTI, VFN.bdcodver, VFN.BDVALVFT FROM vrhf_emp_tverbatomint VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbatomint FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhatomint FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and FOLN.BDORDEM = FOL.BDORDEM and FOLN.BDCODCONTTI = FOL.BDCODCONTTI) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOL.BDREFTOMADOR >= '||wrefini||' and FOL.BDREFTOMADOR <= '||prreffim;

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODCONTTI ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,cast(null as DATE),FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,0,FOLN.BDDATAPGTOFT ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFTOMADOR, VFN.BDORDEM, VFN.BDCODCONTTI, VFN.BDCODVER,VFN.BDVALVFT FROM vrhf_emp_tverbatomint VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||'from TEMPRESAS FOL join vrhf_emp_tverbatomint FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhatomint FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and FOLN.BDORDEM = FO.BDORDEM and FOLN.BDCODCONTTI = FO.BDCODCONTTI) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FO.BDCODEMP and COL.BDCODCOL = FO.BDCODCOL) ';
       wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FO.BDREFTOMADOR >= '||wrefini||' and FO.BDREFTOMADOR <= '||prreffim;

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODCONTTI ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wordematu  = 0;
  wconttiatu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wordem,:wcodcontti,:wcodver,:wvalor,:wdep,:wclassif,:wdescver,:wdataresc,:wdataproc,:whoraproc,:wtipomov,:wdatapgto DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF (wordematu = 0) THEN
       wordematu = wordem;
    IF (wconttiatu = 0) THEN
       wconttiatu = wcodcontti;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordem <> wordematu) OR (wcodcontti <> wconttiatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
                   wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                             ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 '||
                             ' order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
                   EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

              winss13antes = null;
              if (wrefpagto <> wrefatu) then
                 begin
                   wsqlaux = 'select SUM(BDINSS13FT) from VRHF_EMP_TFOLHATOMINT where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||wrefatu||' and bdordem = '||wordematu||' and BDDATAPGTOFT < '''||wdataatu||''' and BDCODCONTTI <> '||wconttiatu;
                   execute statement wsqlaux into :winss13antes;
                 end
   
              if (winss13antes is null) then
                 winss13antes = 0;

              winss13 = winss13 + winss13antes;

              if (wbaseir13 < 0) then
                 wbaseir13 = 0;

              if (winss13 < 0) then
                 winss13 = 0;

              if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
                 begin
                   /*Se tiver 13? no m?s da rescis?o n?o deve considerar o dependente novamente*/
                   wsqlaux = 'select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = '||wempatu||' and dt.bdcodcol = '||wcolatu||' and dt.bdref13 ='||wrefpagto;
                   wexiste13mes = NULL;
                   EXECUTE STATEMENT wsqlaux INTO :wexiste13mes;
                   IF (wexiste13mes IS NOT NULL) THEN
                      wdepatu = 0;
          
                   BDCODEMP         = wempatu;
                   BDCODCOL         = wcolatu;
                   BDREF            = wrefatu;
                   BDREFPAG         = wrefpagto;
                   bdordem          = wordematu;
                   BDCODCONTTI      = wconttiatu;
                   BDRENDTRIBUTAVEL = wbaseir13;
                   BDINSS           = winss13;
                   BDIR             = wir13;
                   BDDEP            = wdepatu;
                   BDLUCROPJ        = 0;
                   BDDESPMED        = 0;
                   BDAJCUSTOS       = 0;
                   BDPENJUD         = 0;
                   BDPENALIM        = 0;

                   if (wprepri <> 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;

                   BDVALABO         = 0;
                   BDRENDISENTOS    = 0;
                   BDDRENDISENTOS   = '';
                   BDDATAPGTO       = wdataatu;
                   BDTIPO           = 10;    -- 13? rescis?o
                   BDINFADIC        = '';
                   BDDATAPROC       = wdataproca;
                   BDHORAPROC       = whoraproca;
                   SUSPEND;
                 end
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wordematu  = wordem;
         wconttiatu = wcodcontti;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         wrendis    = 0;
         wdrendis   = '';
       END

    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

    IF (wirver = 3) THEN -- 13? sal?rio
       BEGIN
         IF (wtipocodver = 0) THEN   -- provento
            wbaseir13 = wbaseir13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN   -- desconto
            BEGIN
              --                                      INSS                                              Obriga??es IR
              IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                 wbaseir13 = wbaseir13 - wvalor;
            END
       END
    --                                     INSS 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.6') THEN
       winss13 = winss13 + wvalor;
    --                                     IR 13? sal?rio rescis?o
    IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.A') THEN
       wir13 = wir13 + wvalor;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wordematu <> 0 and wconttiatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            wsqlaux = 'select first 1 COALESCE(BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFINI <= '||wrefatu||
                      ' and ((COALESCE(BDREFFIN, 0) = 0) or (COALESCE(BDREFFIN, 0) >= '||wrefatu||')) and COALESCE(BDVAL13SAL,0) > 0 '||
                      ' order by BDCODEMP,BDCODCOL,BDREFINI DESC ';
            EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

            winss13antes = null;
            if (wrefpagto <> wrefatu) then
               begin
                 wsqlaux = 'select SUM(BDINSS13FT) from VRHF_EMP_TFOLHATOMINT where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||wrefatu||' and bdordem = '||wordematu||' and BDDATAPGTOFT < '''||wdataatu||''' and BDCODCONTTI <> '||wconttiatu;
                 execute statement wsqlaux into :winss13antes;
               end
 
            if (winss13antes is null) then
               winss13antes = 0;

            winss13 = winss13 + winss13antes;

            if (wbaseir13 < 0) then
               wbaseir13 = 0;

            if (winss13 < 0) then
               winss13 = 0;

            if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
               begin
            /*Se tiver 13? no m?s da rescis?o n?o deve considerar o dependente novamente*/
            wsqlaux = 'select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = '||wempatu||' and dt.bdcodcol = '||wcolatu||' and dt.bdref13 ='||wrefpagto;
            wexiste13mes = NULL;
            EXECUTE STATEMENT wsqlaux INTO :wexiste13mes;
            IF (wexiste13mes IS NOT NULL) THEN
               wdepatu = 0;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            bdordem          = wordematu;
            BDCODCONTTI      = wconttiatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;

            if (wprepri <> 0) then
               BDPREVPRIV = wprepri;
            else
               BDPREVPRIV = wprevprivcad;

            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 10;    -- 13? rescis?o
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            SUSPEND;
               end
          END
     END

  /*  DADOS IMPORTADOS OU CADASTRADOS NA FICHA  */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9002,9012,9099,9100) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select S13.BDCODEMP,S13.BDCODCOL,S13.BDREF13 from VRHF_EMP_T13SAL S13 where S13.BDCODEMP = FOL.BDCODEMP and S13.BDCODCOL = FOL.BDCODCOL and '||
                                'S13.BDREF13 = FOL.BDREFFIR) and '||
                    'not exists (select A13.BDCODEMP,A13.BDCODCOL,A13.BDREFA13 from VRHF_EMP_TA13SAL A13 where A13.BDCODEMP = FOL.BDCODEMP and A13.BDCODCOL = FOL.BDCODCOL and '||
                                'A13.BDREFA13 = FOL.BDREFFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'from tmp_empresas_select FOL ';
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9002,9012,9099,9100) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select S13.BDCODEMP,S13.BDCODCOL,S13.BDREF13 from VRHF_EMP_T13SAL S13 where S13.BDCODEMP = FO.BDCODEMP and S13.BDCODCOL = FO.BDCODCOL and '||
                                'S13.BDREF13 = FO.BDREFFIR) and '||
                    'not exists (select A13.BDCODEMP,A13.BDCODCOL,A13.BDREFA13 from VRHF_EMP_TA13SAL A13 where A13.BDCODEMP = FO.BDCODEMP and A13.BDCODCOL = FO.BDCODCOL and '||
                                'A13.BDREFA13 = FO.BDREFFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO :BDCODEMP,:BDCODCOL,:BDREF,:BDREFPAG,:BDTIPO,:BDRENDTRIBUTAVEL,:BDINSS,:BDIR,:BDDEP,:BDLUCROPJ,:BDDESPMED,:BDAJCUSTOS,:BDPENJUD,:BDPENALIM,
                                  :BDPREVPRIV,:BDINDRESC,:BDVALABO,:BDRENDISENTOS,:BDDRENDISENTOS,:BDDATAPGTO,:BDINFADIC
  DO
  BEGIN
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    BDCODCONTTI = null;
    SUSPEND;
  END

END
^

/* Alter (SP_VRHF_DADOS_PIS_13) */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6))
 AS
DECLARE VARIABLE WTIPOVER INTEGER;
DECLARE VARIABLE WBASEPIS VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WCLASSIF VARCHAR(20);
BEGIN
  /* Procedure Text */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDCODVER,FOL.BDVALV13,VER.BDCLAVER '||
              'from vrhf_emp_tverba13 FOL ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_t13sal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREF13 = FOL.BDREF13) ';
       wsql = wsql||'where FOL.BDREF13 >= '||prrefini||' and FOL.BDREF13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13 ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'FOL.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDCODVER,FO.BDVALV13,VER.BDCLAVER '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverba13 FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) '||
              'join vrhf_emp_t13sal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREF13 = FO.BDREF13) ';
       wsql = wsql||'where FO.BDREF13 >= '||prrefini||' and FO.BDREF13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREF13 ';
     END

--  suspend;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba ? base 13?
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba ? base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Sen?o ? base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

END
^

/* Alter (SP_VRHF_DADOS_PIS_C13) */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_C13(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6))
 AS
DECLARE VARIABLE WTIPOVER INTEGER;
DECLARE VARIABLE WBASEPIS VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WCLASSIF VARCHAR(20);
BEGIN
  /* Procedure Text */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFC13,FOL.BDCODVER,FOL.BDVALVC13,VER.BDCLAVER '||
              'from vrhf_emp_tverbac13 FOL ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tc13sal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFC13 = FOL.BDREFC13) ';
       wsql = wsql||'where FOL.BDREFC13 >= '||prrefini||' and FOL.BDREFC13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFC13 ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFC13,FO.BDCODVER,FO.BDVALVC13,VER.BDCLAVER '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbac13 FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) '||
              'join vrhf_emp_tc13sal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFC13 = FO.BDREFC13) ';
       wsql = wsql||'where FO.BDREFC13 >= '||prrefini||' and FO.BDREFC13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREF13 ';
     END

--  suspend;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba ? base 13?
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba ? base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Sen?o ? base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

END
^

/* Alter (SP_VRHF_DADOS_PIS_FC) */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_FC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(20))
 AS
DECLARE VARIABLE WTIPOVER INTEGER;
DECLARE VARIABLE WBASEPIS VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WCLASSIF VARCHAR(20);
BEGIN
  /* Procedure Text */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFC,VER.BDCLAVER '||
              'from vrhf_emp_tverbafc FOL ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (fol.BDREFFC = foln.BDREFFC and FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFfn = FOL.BDREFfn) ';
       wsql = wsql||'where FOL.BDREFfn >= '||prrefini||' and FOL.BDREFfn <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFfn ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFC,VER.BDCLAVER '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbafc FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) '||
              'join vrhf_emp_tfolhacomp FOLN on (fo.BDREFFC = foln.BDREFFC and foln.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFfn = FO.BDREFfn) ';
       wsql = wsql||'where FO.BDREFfn >= '||prrefini||' and FO.BDREFfn <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFfn ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba ? base 13?
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba ? base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Sen?o ? base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /* Folha por tomador */
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDCODVER,FOL.BDVALVFC,VER.BDCLAVER,prep.BDCODCENTRO,prep.bdcodtpcc, cen.bdctalon '||
              'from vrhf_emp_tverbafctomador FOL ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfoltomcomp FOLN on (fol.BDREFFC = foln.BDREFFC and FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and fol.bdordem = foln.bdordem) ';
       wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FOLN.BDCODEMP = prep.BDCODEMP and FOLN.BDCODCOL = prep.BDCODCOL and prep.bdordem = foln.bdordem) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.bdcodtpcc) ';
       wsql = wsql||'where FOL.BDREFTOMADOR >= '||prrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDCODVER,FO.BDVALVFC,VER.BDCLAVER,prep.BDCODCENTRO,prep.bdcodtpcc, cen.bdctalon '||
              'from TEMPRESAS FOL '||
              'join VRHF_EMP_TVERBAFCTOMADOR FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) '||
              'join vrhf_emp_tfoltomcomp FOLN on (fo.BDREFFC = foln.BDREFFC and FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and fo.bdordem = foln.bdordem) ';
       wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FOLN.BDCODEMP = prep.BDCODEMP and FOLN.BDCODCOL = prep.BDCODCOL and prep.bdordem = foln.bdordem) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.bdcodtpcc) ';
       wsql = wsql||'where FO.BDREFTOMADOR >= '||prrefini||' and FO.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif,:BDCODCENTRO,:bdcodtpcc, :bdctalon DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba ? base 13?
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba ? base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Sen?o ? base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

END
^

/* Alter (SP_VRHF_DADOS_PIS_FN) */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_FN(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(20))
 AS
declare variable WTIPOVER integer;
declare variable WBASEPIS varchar(10);
declare variable WSQL varchar(5000);
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
BEGIN
  /* Procedure Text */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN,VER.BDCLAVER from (';

       wsql = wsql||'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN '||
              'from vrhf_emp_tverbafn FOL ';
       wsql = wsql||'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFfn = FOL.BDREFfn) ';
       wsql = wsql||'where FOL.BDREFfn >= '||prrefini||' and FOL.BDREFfn <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' union all select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN '||
              'from vrhf_emp_tverbaint FOL ';
       wsql = wsql||'join vrhf_emp_tfolhaint FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFfn = FOL.BDREFfn and FOLN.BDCODCONTTI = FOL.BDCODCONTTI) ';
       wsql = wsql||'where FOL.BDREFfn >= '||prrefini||' and FOL.BDREFfn <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||') FOL join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFfn ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,VER.BDCLAVER from (';

       wsql = wsql||'select '||
                'FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbafn FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFfn = FO.BDREFfn) ';
       wsql = wsql||'where FO.BDREFfn >= '||prrefini||' and FO.BDREFfn <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' union all select '||
                'FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbaint FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrhf_emp_tfolhaint FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFfn = FO.BDREFfn and FOLN.BDCODCONTTI = FO.BDCODCONTTI) ';
       wsql = wsql||'where FO.BDREFfn >= '||prrefini||' and FO.BDREFfn <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||') FO join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFfn ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba ? base 13?
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 9) = '0.800.6.2')) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba ? base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Sen?o ? base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /* Folha por tomador */
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDCODVER,FOL.BDVALVFT,VER.BDCLAVER,prep.BDCODCENTRO,prep.bdcodtpcc, cen.BDCTALON from (';
       wsql = wsql||'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDCODVER,FOL.BDVALVFT, FOL.BDORDEM '||
              'from vrhf_emp_tverbatomador FOL ';
       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and fol.bdordem = foln.bdordem) ';
       wsql = wsql||'where FOL.BDREFTOMADOR >= '||prrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' union all select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDCODVER,FOL.BDVALVFT,FOL.BDORDEM '||
              'from vrhf_emp_tverbatomint FOL ';
       wsql = wsql||'join vrhf_emp_tfolhatomint FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and fol.bdordem = foln.bdordem and FOLN.BDCODCONTTI = FOL.BDCODCONTTI) ';
       wsql = wsql||'where FOL.BDREFTOMADOR >= '||prrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||') FOL join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FOL.BDCODEMP = prep.BDCODEMP and FOL.BDCODCOL = prep.BDCODCOL and prep.bdordem = fol.bdordem) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.BDCODTPCC) ';
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDCODVER,FO.BDVALVFT,VER.BDCLAVER,prep.BDCODCENTRO,prep.bdcodtpcc, cen.BDCTALON from (';
       wsql = wsql||'select FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDCODVER,FO.BDVALVFT,FO.BDORDEM '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbatomador FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and fo.bdordem = foln.bdordem) ';
       wsql = wsql||'where FO.BDREFTOMADOR >= '||prrefini||' and FO.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' union all select FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDCODVER,FO.BDVALVFT,FO.BDORDEM '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbatomint FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrhf_emp_tfolhatomint FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and fo.bdordem = foln.bdordem and FOLN.BDCODCONTTI = FO.BDCODCONTTI) ';
       wsql = wsql||'where FO.BDREFTOMADOR >= '||prrefini||' and FO.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';


       wsql = wsql||') FO join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FO.BDCODEMP = prep.BDCODEMP and FO.BDCODCOL = prep.BDCODCOL and prep.bdordem = fo.bdordem) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.BDCODTPCC) ';
       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif,:BDCODCENTRO,:bdcodtpcc,:bdctalon DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba ? base 13?
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 9) = '0.800.6.2')) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba ? base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Sen?o ? base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

END
^

/* Alter (SP_VRHF_DECLARACAO_DOMESTICO) */
ALTER PROCEDURE SP_VRHF_DECLARACAO_DOMESTICO(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRANOBASE INTEGER,
PRTOMADOR INTEGER,
PRCODSIND INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRORDEM VARCHAR(50),
PRDATAEMISSAO VARCHAR(10),
PRSITUACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADM DATE,
BDDATARESCISAO DATE,
BDPIS VARCHAR(14),
BDCPF VARCHAR(14),
BDCOMPETENCIA INTEGER,
BDSALMIN NUMERIC(15,6),
BDBINSSN NUMERIC(15,6),
BDBINSSFE NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDREMUNERACAO NUMERIC(18,6),
BDINSSPATRONAL NUMERIC(15,6),
BDDIFERENCAINSS NUMERIC(15,6),
BDTOTALCONTRPATRONAL NUMERIC(15,6),
BDPARCELANAODEDUTIVEL NUMERIC(15,6),
BDINF VARCHAR(20),
BDORDEM VARCHAR(50),
BDDATAEMISSAO VARCHAR(10),
BDANOBASE INTEGER)
 AS
declare variable WULTDIA varchar(10);
declare variable WPRIDIA varchar(10);
declare variable WDIA varchar(10);
declare variable WMES varchar(10);
declare variable WORDEM varchar(50);
declare variable WPRIDIAEMISSAO varchar(10);
declare variable WULTDIAEMISSAO varchar(10);
declare variable WWHERE varchar(30000);
declare variable WSQLALIQ varchar(500);
declare variable WSQL varchar(30000);
declare variable WALIQINSS numeric(18,6);
declare variable WBASE numeric(18,6);
BEGIN
  wpridia = '01/01/'||pranobase;
  wultdia = '12/31/'||pranobase;

  wmes = SUBSTRING(:prdataemissao FROM 4 FOR 2);
  SELECT ultdia FROM ultimo_dia_mes(:wmes, :pranobase) INTO :wdia;
  wpridiaemissao = wmes||'/01/'||pranobase;
  wultdiaemissao = wmes||'/'||wdia||'/'||pranobase;

  wwhere = '';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       wwhere = ' where ' || prcodemp;

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wwhere = wwhere || ' and ' || prcodcol;
     END
  ELSE
     BEGIN
       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wwhere = ' where ' || prcodcol;
     END

  IF (prtomador > 0) THEN
     wordem = ', ORDEM ';
  ELSE
     wordem = ', null ';

  wsql = 'select distinct BDCODEMPRESA, BDCODCOLABORADOR, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOCREF.BDPISCOL, COL.BDCPFCOL, REF, ' ||
         'max(SALMIN.BDSALMIN) SALMIN, COALESCE(INSS, 0), COALESCE(INSSFE, 0), COALESCE(INSS13, 0), INF ' || wordem;

  IF (prtomador > 0) THEN
     wordem = ', NULL AS ORDEM ';
  ELSE
     wordem = '';

  wsql = wsql || 'from (select FN.BDCODEMP as BDCODEMPRESA, FN.BDCODCOL as BDCODCOLABORADOR, FN.BDREFFN as REF, ' ||
         'FN.BDBINSSFN as INSS, FN.BDBINSSFEFOLFN as INSSFE, FN.BDBINSS13FN as INSS13, '''' as INF ' || wordem || ' from VRHF_EMP_TFOLHANORMAL FN ' || wwhere;

  wsql = wsql || ' union all select FC.BDCODEMP as BDCODEMPRESA, FC.BDCODCOL as BDCODCOLABORADOR, FC.BDREFCOMP as REF, ' ||
            'FC.BDBINSSFC as INSS, FC.BDBINSSFEFOLFC as INSSFE, FC.BDBINSS13FC as INSS13, ''Fol. Compl.'' as INF' || wordem || ' from VRHF_EMP_TFOLHACOMP FC ' || wwhere;

  wsql = wsql || ' union all select F13SAL.BDCODEMP as BDCODEMPRESA, F13SAL.BDCODCOL as BDCODCOLABORADOR, F13SAL.BDREF13 as REF, ' ||
            'F13SAL.BDBASEINSS13 as INSS, 0 as INSSFE, 0 as INSS13, ''13? Sal.'' as INF' || wordem || ' from VRHF_EMP_T13SAL F13SAL ' || wwhere;

  IF (prtomador > 0) THEN
     wordem = ', FT.BDORDEM AS ORDEM ';

  wsql = wsql || ' union all select FT.BDCODEMP as BDCODEMPRESA, FT.BDCODCOL as BDCODCOLABORADOR, FT.BDREFTOMADOR as REF, ' ||
            'SUM(FT.BDBINSSFT) as INSS, SUM(FT.BDBINSSFEFOLFT) as INSSFE, SUM(FT.BDBINSS13FT) as INSS13, '''' as INF' || wordem || ' from VRHF_EMP_TFOLHATOMADOR FT ' || wwhere ||
            ' group by REF, BDCODEMPRESA, BDCODCOLABORADOR, INF';

  IF (prtomador > 0) THEN
     BEGIN
       wsql = wsql || ', FT.BDORDEM ';
       wordem = ', FTC.BDORDEM AS ORDEM ';
     END

  wsql = wsql || ' union all select FTC.BDCODEMP as BDCODEMPRESA, FTC.BDCODCOL as BDCODCOLABORADOR, FTC.bdreftomador as REF, ' ||
            'FTC.BDBINSSFC as INSS, FTC.BDBINSSFEFOLFC as INSSFE, FTC.BDBINSS13FC as INSS13, ''Fol. Compl'' as INF' || wordem || ' from VRHF_EMP_TFOLTOMCOMP FTC ' || wwhere;

  IF (prtomador > 0) THEN
     wordem = ', FER.BDORDEM AS ORDEM';

  wsql = wsql || ' union all select FER.BDCODEMP as BDCODEMPRESA, FER.BDCODCOL as BDCODCOLABORADOR, FER.BDREFINIFE as REF, ' ||
            'FER.BDBASEINSSFE as INSS, 0 as INSSFE, 0 as INSS13, ''F?rias'' as INF' || wordem || ' from VRH_EMP_TFERIAS FER ' || wwhere || ') ';

  wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = BDCODEMPRESA and COL.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRH_EMP_TCOLCON_DOC DOC on (DOC.BDCODEMP = COL.BDCODEMP and DOC.BDCODCOL = COL.BDCODCOL) ' ||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = BDCODEMPRESA and RESC.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRHF_TABELAS_TSALMIN SALMIN on (SALMIN.BDREFSM <= REF) ' ||
         'left outer join VRH_EMP_TCOLCON_VINC VINC on (VINC.BDCODEMP = BDCODEMPRESA and VINC.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRH_BASE_TCLASSE CLAS on (VINC.BDCODCLA = CLAS.BDCODCLA) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = BDCODEMPRESA and COLCAD.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = BDCODEMPRESA and DOCREF.BDCODCOL = BDCODCOLABORADOR) ';

  -- Filtros
  IF (prtomador > 0) THEN
     BEGIN
       wsql = wsql || 'left outer join VRHF_EMP_TPREPFN PREP on (prep.bdcodemp = bdcodempresa and prep.bdcodcol = bdcodcolaborador and prep.bdordem = ordem) ';
     END

  IF (prcodsind > 0) THEN
     wsql = wsql || 'left outer join VRH_EMP_TCOL_VINC VINC2 on (vinc2.bdcodemp = bdcodempresa and vinc2.bdcodcol = bdcodcolaborador) ';

  IF (prfuncao > 0) THEN
     wsql = wsql || 'left outer join VRH_EMP_TCOL_VINCDIA coldia on (coldia.bdcodemp = bdcodempresa and coldia.bdcodcol = bdcodcolaborador) ';

  IF (prsituacao = 0) THEN
     wSql = wSql || ' join SP_SOMENTE_ATIVOS(''' || wpridia || ''', ''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ';

  IF (prsituacao = 2) THEN
     wSql = wSql || ' join SP_SOMENTE_DEMITIDOS(''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 3) THEN
     wSql = wSql || ' join SP_SOMENTE_ADMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 4) THEN
     wSql = wSql || ' join SP_SOMENTE_DEMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 5) THEN
     wSql = wSql || ' join SP_ATIVOS_SEM_DEMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 6) THEN
     wSql = wSql || ' join SP_ATI_SEM_DEM_COM_TRANSF(''' || wpridia || ''',''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 7) THEN
     wSql = wSql || ' join SP_ATI_SEM_AFAST_MES_INT(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 8) THEN
     wSql = wSql || ' join SP_AFASTADOS_MES_INTEIRO(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  -- Where e filtros
  wwhere = ' where clas.bdgrupocla = 7 and SUBSTRING(CAST(REF AS VARCHAR(6)) FROM 1 FOR 4) = ' || pranobase;

  IF (prtomador > 0) THEN
     BEGIN
       wwhere = wwhere || ' and prep.bdcodtpcc = '||prtomador;
       wordem = ', ORDEM ';
     END
  ELSE
     wordem = '';

  IF (prcodsind > 0) THEN
     wwhere = wwhere||' and vinc2.bdcodsintrab = '||prcodsind;

  IF (prclasse > 0) THEN
     wwhere = wwhere||' and vinc.bdcodcla = '||prclasse;

  IF (prfuncao > 0) THEN
     wwhere = wwhere||' and coldia.bdcodtfuc = '||prfuncao;

  wsql = wsql || wwhere || ' group by BDCODEMPRESA, BDCODCOLABORADOR, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOCREF.BDPISCOL, COL.BDCPFCOL, REF, ' ||
         'INSS, INSSFE, INSS13, INF ' || wordem;

  IF (prordem IS NOT NULL AND prordem <> '') THEN
     BEGIN
       IF (PRORDEM = 'BDCODCOL') THEN
          wsql = wsql || 'ORDER BY BDCODEMPRESA, BDCODCOLABORADOR, REF, INF ';
       ELSE
          wsql = wsql || 'ORDER BY BDCODEMPRESA, COLCAD.BDNOMCOL, REF, INF ';
     END
  ELSE
     wsql = wsql || 'ORDER BY BDCODEMPRESA, REF, INF ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcodcol,
    :bdnomcol,
    :bddataadm,
    :bddatarescisao,
    :bdpis,
    :bdcpf,
    :bdcompetencia,
    :bdsalmin,
    :bdbinssn,
    :bdbinssfe,
    :bdbinss13,
    :bdinf,
    :bdordem
  DO
    BEGIN
      bdremuneracao = bdbinssn + bdbinssfe + bdbinss13;
      bddataemissao = prdataemissao;
      bdanobase = pranobase;
      bdtotalcontrpatronal  = bdremuneracao * 12 / 100;

      IF ((bdremuneracao - bdsalmin) > 0) THEN
         bdparcelanaodedutivel = (bdremuneracao - bdsalmin) * 12 / 100;
      ELSE
         bdparcelanaodedutivel = 0;

      wbase = 0;
      IF (bdbinssn IS NOT NULL AND bdbinssn > 0) THEN
         BEGIN
           wbase = bdbinssn;
           wsqlaliq = 'select fol.bdaliqinssfn from vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
                || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
         END
      ELSE
      IF (bdbinssfe IS NOT NULL AND bdbinssfe > 0) THEN
         BEGIN
           wbase = bdbinssfe;
           wsqlaliq = 'select fol.bdaliqinssfefolfn from vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
           || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
         END
      ELSE
      IF (bdbinss13 IS NOT NULL AND bdbinss13 > 0) THEN
        BEGIN
          wbase = bdbinss13;
          wsqlaliq = 'select fol.bdaliqinss13fn vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
          || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
        END
      ELSE
      -- N?o tem c?lculo nenhum
        wsqlaliq = '';

      IF (wsqlaliq IS NOT NULL AND wsqlaliq <> '') THEN
        BEGIN
          FOR EXECUTE STATEMENT wsqlaliq
          INTO
            :waliqinss
          DO
            BEGIN
              bdinsspatronal = wbase * waliqinss / 100;
            
              IF (bdremuneracao < bdsalmin) THEN
                 bddiferencainss = 0;
              ELSE
                 bddiferencainss = (bdremuneracao - bdsalmin) * waliqinss / 100;
            END
        END
      ELSE
        BEGIN
          bdinsspatronal = 0;
          bddiferencainss = 0;
        END

      SUSPEND;
    END
END
^

/* Alter (SP_VRHF_EMP_BASES_RESCISAO) */
ALTER PROCEDURE SP_VRHF_EMP_BASES_RESCISAO(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFAUXVFN NUMERIC(15,6),
BDREFVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDSALBASEFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDCNPJEMP VARCHAR(18),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDDATANASCCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL VARCHAR(10),
BDDSERIECTPSCOL VARCHAR(1),
BDDATAOPCAOFGTSCOL DATE,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAPAGRESCISAO DATE,
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCODPRES INTEGER,
BDSALDOFGTS NUMERIC(15,6),
BDDESCPRES VARCHAR(110))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wsql = 'select '||
            'FN.BDCODEMP, '||
            'FN.BDCODCOL, '||
            'FN.BDCODVER, '||
            'FN.BDREFFN, '||
            'FN.BDREFAUXVFN, '||
            'FN.BDREFVFN, '||
            'FN.BDVALVFN, '||
            'FN.BDIGNREFVFN, '||
            'FN.BDIGNVALVFN, '||
            'FNB.BDSALBASEFN, '||
            'FNB.BDMAIORREMFN, '||
            'FNB.BDBFGTSFN, '||
            'FNB.BDFGTSFN, '||
            'FNB.BDFGTSCSFN, '||
            'FNB.BDBFGTS13FN, '||
            'FNB.BDFGTS13FN, '||
            'FNB.BDFGTS13CSFN, '||
            'VERBAS.BDCLAVER, '||
            'VERBAS.BDORDEMVER, '||
            'EMP.BDCNPJEMP, '||
            'EMPR.BDLOGREMP, '||
            'EMPR.BDENDEMP, '||
            'EMPR.BDNUMEMP, '||
            'EMPR.BDCOMPLEMP, '||
            'EMPR.BDBAIEMP, '||
            'EMPR.BDCEPEMP, '||
            'EMPR.BDDDDEMP, '||
            'EMPR.BDFONEEMP, '||
            'EMPR.BDDDDFAXEMP, '||
            'EMPR.BDFAXEMP, '||
            'EMPR.BDEMAILEMP, '||
            'COLCAD.BDNOMCOL, '||
            'COLCON.BDDATAADMCOL, '||
            'COLCON.BDDATANASCCOL, '||
            'COLCONDOC.BDCPFCOL, '||
            'DOCREF.BDPISCOL, '||
            'DOCREF.BDCTPSCOL, '||
            'DOCREF.BDSERIECTPSCOL, '||
            'DOCREF.BDDSERIECTPSCOL, '||
            'COLCONFGTS.BDDATAOPCAOFGTSCOL, '||
            'CID.BDNOMCID, '||
            'UF.BDSIGLAUF, '||
            'UFCTPS.BDSIGLAUF, '||
            'RESC.BDDATARESCISAO, '||
            'RESC.BDDATAAVPREVIO, '||
            'RESC.BDDATAPAGRESCISAO, '||
            'RESC.BDMAIORREMUNERACAO, '||
            'RESC.BDCODPRES, '||
            'RESC.BDSALDOFGTS, '||
            'PRESC.BDDESCPRES '
            ;
            
  wsql = wsql||'from VRHF_SP_TVERBAFN(null, null, '||prref||', '||prref||', 1) FN '||
               'join VRHF_SP_TFOLHA_NORMAL(null, null, '||prref||', '||prref||', 1) FNB on (FNB.BDCODEMP = FN.BDCODEMP and FNB.BDCODCOL = FN.BDCODCOL and FNB.BDREFFN = FN.BDREFFN) '||
               'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FN.BDCODVER ) '||
               'join TEMPRESAS EMP on (EMP.BDCODEMP = FN.BDCODEMP) '||
               'join VW_TEMPRESAS_REF EMPR on (EMPR.BDCODEMP = FN.BDCODEMP and EMPR.BDCODEMP = EMP.BDCODEMP) '||
               'join VRH_EMP_TCOLCON COLCON on (COLCON.BDCODEMP = FN.BDCODEMP and COLCON.BDCODCOL = FN.BDCODCOL) '||
               'join VRH_EMP_TCOLCON_DOC COLCONDOC on (COLCONDOC.BDCODEMP = FN.BDCODEMP and COLCONDOC.BDCODCOL = FN.BDCODCOL) '||
               'join VRH_EMP_TCOL_DOC COLDOC on (COLDOC.BDCODEMP = FN.BDCODEMP and COLDOC.BDCODCOL = FN.BDCODCOL) '||
               'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS COLCONFGTS on (COLCONFGTS.BDCODEMP = FN.BDCODEMP and COLCONFGTS.BDCODCOL = FN.BDCODCOL) '||
               'left outer join TCIDADE CID on (CID.BDCODCID = EMPR.BDCODCID) '||
               'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) '||
               'left outer join TUF UFCTPS on (UFCTPS.BDCODUF = DOCREF.BDCODUF) '||
               'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FN.BDCODEMP and RESC.BDCODCOL = FN.BDCODCOL) '||
               'left outer join VRH_BASE_TPREPRESC PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) '||
               'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FN.BDCODEMP and COLCAD.BDCODCOL = FN.BDCODCOL) '||
               'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FN.BDCODEMP and DOCREF.BDCODCOL = FN.BDCODCOL) '
               ;

  wsql = wsql||'where exists(select X.BDCODEMP, X.BDCODCOL from VRH_EMP_TRESCISAO X where FN.BDCODEMP = X.BDCODEMP and FN.BDCODCOL = X.BDCODCOL and X.BDREFRESCISAO = '||prref||') ';
  
  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFAUXVFN,
    :BDREFVFN,
    :BDVALVFN,
    :BDIGNREFVFN,
    :BDIGNVALVFN,
    :BDSALBASEFN,
    :BDMAIORREMFN,
    :BDBFGTSFN,
    :BDFGTSFN, 
    :BDFGTSCSFN,
    :BDBFGTS13FN,
    :BDFGTS13FN, 
    :BDFGTS13CSFN,
    :BDCLAVER,
    :BDORDEMVER,
    :BDCNPJEMP,
    :BDLOGREMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDCOMPLEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDDDDFAXEMP,
    :BDFAXEMP,
    :BDEMAILEMP,
    :BDNOMCOL,
    :BDDATAADMCOL,
    :BDDATANASCCOL,
    :BDCPFCOL,
    :BDPISCOL,
    :BDCTPSCOL,
    :BDSERIECTPSCOL,
    :BDDSERIECTPSCOL,
    :BDDATAOPCAOFGTSCOL,
    :BDNOMCID,
    :BDSIGLAUF,
    :BDSIGLAUFCTPS,
    :BDDATARESCISAO,
    :BDDATAAVPREVIO,
    :BDDATAPAGRESCISAO,
    :BDMAIORREMUNERACAO,
    :BDCODPRES,
    :BDSALDOFGTS,
    :BDDESCPRES
  DO
  SUSPEND;
END
^

/* Alter (SP_VRHF_EXPORTACAO_CONTABIL) */
ALTER PROCEDURE SP_VRHF_EXPORTACAO_CONTABIL(PREMP VARCHAR(25000),
PRREF INTEGER,
PRAGRUPACOL INTEGER = 0,
PRFOLHANORMAL INTEGER = 0,
PRFOLHACOMP INTEGER = 0,
PRFERIAS INTEGER = 0,
PRADTOSAL INTEGER = 0,
PRADTO13 INTEGER = 0,
PR13SAL INTEGER = 0,
PRC13SAL INTEGER = 0,
PRFOLHAAVULSA INTEGER = 0,
PRPROVFER INTEGER = 0,
PRPROV13 INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDDATALAN DATE,
BDCTADEB INTEGER,
BDCODTPCCDEB INTEGER,
BDCTACCDEB INTEGER,
BDAPECCDEB VARCHAR(20),
BDNOMCTACCDEB VARCHAR(40),
BDCTACRED INTEGER,
BDCODTPCCCRED INTEGER,
BDCTACCCRED INTEGER,
BDAPECCCRED VARCHAR(20),
BDNOMCTACCCRED VARCHAR(40),
BDVALORLANC NUMERIC(15,2),
BDCOMPLHIST VARCHAR(200))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQLA VARCHAR(5000);
DECLARE VARIABLE WCODPLACC INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,2);
DECLARE VARIABLE WDEBCRE INTEGER;
DECLARE VARIABLE WAPECTACC VARCHAR(20);
DECLARE VARIABLE WNOMCTACC VARCHAR(40);
BEGIN
  wsql = '';

  -- Folha normal
  IF (COALESCE(prfolhanormal, 0) = 1) THEN
     BEGIN
       -- Verbas
       wsql = wsql||'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_fn '||
                    'where BDREFFN = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||' union all '||
                    'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_ft '||
                    'where BDREFTOMADOR = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       -- L?quido
       wsql = wsql||' union all '||
                    'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_fn '||
                    'where BDREFFN = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||' union all '||
                    'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_ft '||
                    'where BDREFTOMADOR = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END

  -- Folha complementar
  IF (COALESCE(prfolhacomp, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_fn_fc '||
                    'where SUBSTRING(BDREFFC FROM 1 FOR 6) = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||' union all '||
                    'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_ft_fc '||
                    'where SUBSTRING(BDREFFC FROM 1 FOR 6) = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       -- L?quido
       wsql = wsql||' union all '||
                    'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_fn_fc '||
                    'where SUBSTRING(BDREFFC FROM 1 FOR 6) = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||' union all '||
                    'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_ft_fc '||
                    'where SUBSTRING(BDREFFC FROM 1 FOR 6) = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END

  -- F?rias
  IF (COALESCE(prferias, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, fer.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrh_emp_tferias where SUBSTRING(CAST(BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') fer '||
                     'join tol_vrhf_emp_tverba_fer L on (fer.bdcodemp = L.BDCODEMP and fer.BDCODCOL = L.BDCODCOL and fer.BDINIPERAQUISFE = L.BDINIPERAQUISFE and fer.BDCODFE = L.BDCODFE) ';

       -- L?quido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, fer.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrh_emp_tferias where SUBSTRING(CAST(BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') fer '||
                    'join tol_vrhf_emp_tcalc_fer L on (fer.bdcodemp = L.BDCODEMP and fer.BDCODCOL = L.BDCODCOL and fer.BDINIPERAQUISFE = L.BDINIPERAQUISFE and fer.BDCODFE = L.BDCODFE) ';
     END

  -- Adiantamento salarial
  IF (COALESCE(pradtosal, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, ad.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrhf_emp_tadsal where SUBSTRING(CAST(BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') ad '||
              'join tol_vrhf_emp_tverba_ad L on (ad.bdcodemp = L.BDCODEMP and ad.BDCODCOL = L.BDCODCOL and ad.BDDATAAD = L.BDDATAAD) ';

       -- L?quido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, ad.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrhf_emp_tadsal where SUBSTRING(CAST(BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
       wsql = wsql||') ad '||
              'join tol_vrhf_emp_tcalc_ad L on (ad.bdcodemp = L.BDCODEMP and ad.BDCODCOL = L.BDCODCOL and ad.BDDATAAD = L.BDDATAAD) ';
     END

  -- Folha avulsa
  IF (COALESCE(prfolhaavulsa, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_fa where SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       -- L?quido
       wsql = wsql||' union all '||
                    'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_fa where SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END

  -- Adiantamento de 13? sal?rio
  IF (COALESCE(pradto13, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, ad13.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrhf_emp_ta13sal where BDREFA13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') ad13 '||
              'join tol_vrhf_emp_tverba_a13 L on (ad13.bdcodemp = L.BDCODEMP and ad13.BDCODCOL = L.BDCODCOL and ad13.BDREFA13 = L.BDREFA13) ';

       -- L?quido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, ad13.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrhf_emp_ta13sal where BDREFA13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
       wsql = wsql||') ad13 '||
              'join tol_vrhf_emp_tcalc_a13 L on (ad13.bdcodemp = L.BDCODEMP and ad13.BDCODCOL = L.BDCODCOL and ad13.BDREFA13 = L.BDREFA13) ';
     END


  -- 13? sal?rio
  IF (COALESCE(pr13sal, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, s13.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrhf_emp_t13sal where BDREF13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') s13 '||
              'join tol_vrhf_emp_tverba_13 L on (s13.bdcodemp = L.BDCODEMP and s13.BDCODCOL = L.BDCODCOL and s13.BDREF13 = L.BDREF13) ';

       -- L?quido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, s13.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrhf_emp_t13sal where BDREF13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
       wsql = wsql||') s13 '||
              'join tol_vrhf_emp_tcalc_13 L on (s13.bdcodemp = L.BDCODEMP and s13.BDCODCOL = L.BDCODCOL and s13.BDREF13 = L.BDREF13) ';
     END


  -- Complemento de 13? sal?rio
  IF (COALESCE(prc13sal, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, c13.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrhf_emp_tc13sal where BDREFC13 = '||prref||' and UPPER(COALESCE(BDPAGOFNC13, ''FALSE'')) = ''FALSE''' ;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') c13 '||
              'join tol_vrhf_emp_tverba_c13 L on (c13.bdcodemp = L.BDCODEMP and c13.BDCODCOL = L.BDCODCOL and c13.BDREF13 = L.BDREF13 and c13.BDREFC13 = L.BDREFC13) ';

       -- L?quido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, c13.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrhf_emp_tc13sal where BDREF13 = '||prref||' and UPPER(COALESCE(BDPAGOFNC13, ''FALSE'')) = ''FALSE''' ;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
       wsql = wsql||') c13 '||
              'join tol_vrhf_emp_tcalc_c13 L on (c13.bdcodemp = L.BDCODEMP and c13.BDCODCOL = L.BDCODCOL and c13.BDREF13 = L.BDREF13 and c13.BDREFC13 = L.BDREFC13) ';
     END

  -- Provis?o de f?rias
  IF (COALESCE(prprovfer, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Provis?o
       wsql = wsql||'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tprovfer_det where BDREFPFER = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END

  -- Provis?o de 13? sal?rio
  IF (COALESCE(prprov13, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Provis?o
       wsql = wsql||'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tprov13_det where BDREFP13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END


  IF (wsql <> '') THEN
     BEGIN
       IF (pragrupacol = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, CAST(null as integer) BDCHAVE, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC, LAN.BDDEBITO, LAN.BDCREDITO, SUM(COALESCE(LAN.BDVALOR,0)), '||
                          'iif(position(''COL.'', UPPER(lan.bdcompl)) > 0, SUBSTRING(lan.bdcompl FROM 1 FOR position(''COL.'', UPPER(lan.bdcompl)) - 1), lan.bdcompl) BDCOMPL, '||
                          'TPCC.BDAPECTA, TPCC.BDNOMCTA from ('||
                   wsql||') FOL ' ||
                   ' left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                   ' left outer join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = FOL.BDCODEMP and LAN.BDCHAVE = FOL.BDCHAVE) '||
                   ' left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FOL.BDCODEMP and PFN.BDCODCOL = FOL.BDCODCOL and PFN.BDORDEM = FOL.BDORDEM) '||
                   ' left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.BDCODTPCC = PFN.BDCODTPCC) '||
                   ' group by FOL.BDCODEMP, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC, LAN.BDDEBITO, LAN.BDCREDITO, BDCOMPL, TPCC.BDAPECTA, TPCC.BDNOMCTA'||
                   ' order by FOL.BDCODEMP, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC ';
          END
       ELSE
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCHAVE, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC, LAN.BDDEBITO, LAN.BDCREDITO, LAN.BDVALOR, LAN.BDCOMPL, TPCC.BDAPECTA, TPCC.BDNOMCTA from ('||
                   wsql||') FOL ' ||
                   ' left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                   ' left outer join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = FOL.BDCODEMP and LAN.BDCHAVE = FOL.BDCHAVE) '||
                   ' left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FOL.BDCODEMP and PFN.BDCODCOL = FOL.BDCODCOL and PFN.BDORDEM = FOL.BDORDEM) '||
                   ' left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.BDCODTPCC = PFN.BDCODTPCC) '||
                   'order by FOL.BDCODEMP, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC, FOL.BDCHAVE ';

          END

       FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :wchave, :bddatalan, :wcodplacc, :wcodtpcc, :bdctadeb, :bdctacred, :bdvalorlanc, :bdcomplhist, :wapectacc, :wnomctacc DO
         BEGIN
           wdebcre = NULL;
           wvalor = NULL;
           IF (COALESCE(pragrupacol,0) = 1) THEN
              wsqla = 'select SUM(tlcc.BDVALOR), tlcc.BDDEBCRE from VSUC_EMPRESAS_TLCC tlcc '||
                      'join VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tlcc.BDCODEMP and lan.BDCHAVE = tlcc.BDCHAVE) '||
                      'where tlcc.BDCODEMP = '||bdcodemp||' and COALESCE(tlcc.BDCODCENTRO,0) = '||COALESCE(wcodplacc,0)||' and COALESCE(tlcc.BDCODTPCC,0) = '||COALESCE(wcodtpcc,0)||
                         ' and lan.BDDATA = '''||bddatalan||''' and COALESCE(lan.BDDEBITO,0) = '||COALESCE(bdctadeb, 0)||' and COALESCE(lan.BDCREDITO, 0) = '||COALESCE(bdctacred, 0)||
                         ' and iif(position(''COL.'', UPPER(lan.bdcompl)) > 0, SUBSTRING(lan.bdcompl FROM 1 FOR position(''COL.'', UPPER(lan.bdcompl)) - 1), lan.bdcompl) = '''||bdcomplhist||''''||
                         ' group by tlcc.BDDEBCRE ';
           ELSE
              wsqla = 'select BDVALOR, BDDEBCRE from VSUC_EMPRESAS_TLCC where BDCODEMP = '||bdcodemp||' and BDCHAVE = '||wchave||' and COALESCE(BDCODCENTRO,0) = '||COALESCE(wcodplacc,0)||' and COALESCE(BDCODTPCC,0) = '||COALESCE(wcodtpcc,0);

           FOR EXECUTE STATEMENT wsqla INTO :wvalor, :wdebcre DO
             BEGIN
               IF (wdebcre = 1) THEN
                  BEGIN
                    bdapecccred = wapectacc;
                    bdctacccred = bdctacred;
                    bdnomctacccred = wnomctacc;
                    bdcodtpcccred = wcodtpcc;
                    bdapeccdeb = NULL;
                    bdctaccdeb = NULL;
                    bdnomctaccdeb = NULL;
                    bdcodtpccdeb = NULL;
                    bdvalorlanc = wvalor;
                    SUSPEND;
                  END
               ELSE
                  BEGIN
                    bdapecccred = NULL;
                    bdctacccred = NULL;
                    bdnomctacccred = NULL;
                    bdcodtpcccred = NULL;
                    bdapeccdeb = wapectacc;
                    bdctaccdeb = bdctadeb;
                    bdnomctaccdeb = wnomctacc;
                    bdcodtpccdeb = wcodtpcc;
                    bdvalorlanc = wvalor;
                    SUSPEND;
                  END
             END

           IF (wdebcre IS NULL) THEN
              BEGIN
                bdctacccred = NULL;
                bdctaccdeb  = NULL;
                bdnomctacccred = NULL;
                bdnomctaccdeb = NULL;
                bdapecccred = NULL;
                bdapeccdeb = NULL;
                SUSPEND;
              END
         END
     END
END
^

/* Alter (SP_VRHF_FC_VALORES_INDENIZADOS) */
ALTER PROCEDURE SP_VRHF_FC_VALORES_INDENIZADOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRDATAGRRF DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDDATAGRRFFC DATE,
BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* tem que executar a procedure que seta a compet?ncia */

  wsql = 'select COLCON.BDCODEMP, '||
                'COLCON.BDCODCOL, '||
                'COLCON.BDREFFN, '||
                'COLCON.BDDATAGRRFFC, '||
                'Sum(COLCON.BDVALVFC) BDVALOR '||
         'from (select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN, FOLC.BDDATAGRRFFC, COLCON.BDVALVFC '||
               'from VRHF_EMP_TVERBAFC COLCON '||
               'join VRHF_EMP_TFOLHACOMP FOLC on (FOLC.BDCODEMP = COLCON.BDCODEMP and FOLC.BDCODCOL = COLCON.BDCODCOL and FOLC.BDREFFN = COLCON.BDREFFN and FOLC.BDREFFC = COLCON.BDREFFC) '||
               'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = COLCON.BDCODVER) '||
               'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = COLCON.BDCODVER) '||
               'where COLCON.BDREFFN = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     END

  wsql = wsql||' and (VER.BDCLAVER like ''7.001.3%'' or VER.BDCLAVER like ''7.020%'' or VER.BDCLAVER like ''7.021%'' or VER.BDCLAVER like ''7.060%'') '||
                 'and VERF.BDFGTSVER > 0 '||
                 'and FOLC.BDDATAGRRFFC = '''||prdatagrrf||''' ';

  wsql = wsql||' union all '||
               'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, FOLC.BDDATAGRRFFC, COLCON.BDVALVFC '||
               'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
               'join VRHF_EMP_TFOLTOMCOMP FOLC on (FOLC.BDCODEMP = COLCON.BDCODEMP and FOLC.BDCODCOL = COLCON.BDCODCOL and FOLC.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLC.BDREFFC = COLCON.BDREFFC and FOLC.BDORDEM = COLCON.BDORDEM) '||
               'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = COLCON.BDCODVER) '||
               'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = COLCON.BDCODVER) '||
               'where COLCON.BDREFTOMADOR = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     END

  wsql = wsql||' and (VER.BDCLAVER like ''7.001.3%'' or VER.BDCLAVER like ''7.020%'' or VER.BDCLAVER like ''7.021%'' or VER.BDCLAVER like ''7.060%'') '||
                 'and VERF.BDFGTSVER > 0 '||
                 'and FOLC.BDDATAGRRFFC = '''||prdatagrrf||''' ';

  wsql = wsql||') COLCON group by COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN, COLCON.BDDATAGRRFFC ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDDATAGRRFFC,
    :BDVALOR
  DO
  SUSPEND;
END
^

/* Alter (SP_VRHF_FN_VALORES_INDENIZADOS) */
ALTER PROCEDURE SP_VRHF_FN_VALORES_INDENIZADOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WCODEMP VARCHAR(20000);
DECLARE VARIABLE WCODCOL VARCHAR(32700);
BEGIN
  /* tem que executar a procedure que seta a compet?ncia */

  IF (prcodemp IS NULL OR (prcodemp = '')) THEN
     wcodemp = 'null';
  ELSE
     wcodemp = ''''||prcodemp||'''';

  IF (prcodcol IS NULL OR (prcodcol = '')) THEN
     wcodcol = 'null';
  ELSE
     wcodcol = ''''||prcodcol||'''';


  wsql = 'select COLCON.BDCODEMP, '||
                'COLCON.BDCODCOL, '||
                'COLCON.BDREFFN, '||
                'Sum(COLCON.BDVALVFN) BDVALOR '||
         'from vrhf_sp_tverbafn('||wcodemp||','||wcodcol||','||pranomes||','||pranomes||',1) COLCON, '||
              'VRH_BASE_TVERBAS VER, '||
              'VW_VERBAS_REF_ATUAL VERF ';

  wwhere = 'where VER.BDCODVER = COLCON.BDCODVER '||
                 'and VERF.BDCODVER = COLCON.BDCODVER '||
                 'and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                 'and VERF.BDFGTSVER > 0 ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||'and '||prcodemp||' ';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||'and '||prcodcol||' ';

  IF (pranomes IS NOT NULL AND pranomes <> 0) THEN
     wwhere = wwhere||'and COLCON.BDREFFN = '||pranomes||' ';

  wsql = wsql||wwhere||'group by COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDVALOR
  DO
  SUSPEND;
END
^

/* Alter (SP_VRHF_MEDIAS) */
ALTER PROCEDURE SP_VRHF_MEDIAS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREF INTEGER,
BDTIPO INTEGER,
BDCC INTEGER,
BDVREF NUMERIC(18,6),
BDVREFAUX NUMERIC(18,6),
BDVVAL NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  -- HORAS EXTRAS
  -- FOLHA NORMAL
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFN, '||
           '0 BDTIPOCALC, '||
           '0 BDCCFN, '||
           'PL.BDREFVFN, '||
           'PL.BDREFAUXVFN, '||
           'PL.BDVALVFN '||
         'FROM '||
         'VRHF_EMP_TVERBAFN PL ';

  wsql = wsql||' where PL.BDREFFN >= '||prrefini||' and PL.BDREFFN <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;


  -- Em caso de transfer?ncia
  wsql = 'SELECT '||
           'TR.BDCODEMPDEST, TR.BDCODCOLDEST, PL.BDCODVER, PL.BDREFFN, 9999 BDTIPOCALC, 0 BDCCFN, PL.BDREFVFN, PL.BDREFAUXVFN, PL.BDVALVFN '||
         'FROM '||
         'VRHF_EMP_TVERBAFN PL '||
         'JOIN VRH_EMP_TTRANSCOL TR on (TR.BDCODEMPORIG = PL.BDCODEMP and TR.BDCODCOLORIG = PL.BDCODCOL) ';

  wsql = wsql||' where TR.BDREFTRF = PL.BDREFFN ';
  wsql = wsql||'and SUBSTRING(CAST(TR.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 7) = SUBSTRING(CAST(TR.BDDATATRF -1 AS VARCHAR(10)) FROM 1 FOR 7) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||REPLACE(UPPER(prcodemp), 'PL.BDCODEMP', 'TR.BDCODEMPDEST');

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'PL.BDCODCOL', 'TR.BDCODCOLDEST');

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    BEGIN
      IF (bdref >= prrefini AND bdref <= prreffim) THEN
        SUSPEND;
    END

  -- FOLHA POR TOMADOR
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFTOMADOR, '||
           '100 BDTIPOCALC, '||
           'PL.BDORDEM, '||
           'PL.BDREFVFT, '||
           'PL.BDREFAUXVFT, '||
           'PL.BDVALVFT '||
         'FROM '||
         'VRHF_EMP_TVERBATOMADOR PL ';

  wsql = wsql||' where PL.BDREFTOMADOR >= '||prrefini||' and PL.BDREFTOMADOR <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- Em caso de transfer?ncia
  wsql = 'SELECT '||
           'TR.BDCODEMPDEST, TR.BDCODCOLDEST, PL.BDCODVER, PL.BDREFTOMADOR, 9999 BDTIPOCALC, PL.BDORDEM, PL.BDREFVFT, PL.BDREFAUXVFT, PL.BDVALVFT '||
         'FROM '||
         'VRHF_EMP_TVERBATOMADOR PL '||
         'JOIN VRH_EMP_TTRANSCOL TR on (TR.BDCODEMPORIG = PL.BDCODEMP and TR.BDCODCOLORIG = PL.BDCODCOL) ';

  wsql = wsql||' where TR.BDREFTRF = PL.BDREFTOMADOR ';
  wsql = wsql||'and SUBSTRING(CAST(TR.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 7) = SUBSTRING(CAST(TR.BDDATATRF -1 AS VARCHAR(10)) FROM 1 FOR 7) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||REPLACE(UPPER(prcodemp), 'PL.BDCODEMP', 'TR.BDCODEMPDEST');

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'PL.BDCODCOL', 'TR.BDCODCOLDEST');

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    BEGIN
      IF (bdref >= prrefini AND bdref <= prreffim) THEN
        SUSPEND;
    END

  -- FOLHA COMPLEMENTAR
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFN, '||
           '1 BDTIPOCALC, '||
           '0 BDCCFC, '||
           'PL.BDREFVFC, '||
           'PL.BDREFAUXVFC, '||
           'PL.BDVALVFC '||
         'FROM '||
         'VRHF_EMP_TVERBAFC PL ';

  wsql = wsql||' where PL.BDREFFN >= '||prrefini||' and PL.BDREFFN <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- FOLHA COMPLEMENTAR POR TOMADOR
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFTOMADOR, '||
           '101 BDTIPOCALC, '||
           'PL.BDORDEM, '||
           'PL.BDREFVFC, '||
           'PL.BDREFAUXVFC, '||
           'PL.BDVALVFC '||
         'FROM '||
         'VRHF_EMP_TVERBAFCTOMADOR PL ';

  wsql = wsql||' where PL.BDREFTOMADOR >= '||prrefini||' and PL.BDREFTOMADOR <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- FOLHA AVULSA
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'CAST((SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER), '||
           '200 BDTIPOCALC, '||
           '0 BDCCFHE, '||
           'PL.BDREFVFA, '||
           'PL.BDREFAUXVFA, '||
           'PL.BDVALVFA '||
         'FROM '||
           'VRHF_EMP_TVERBAFA PL ';

  wsql = wsql||' where CAST((SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prrefini||' and CAST((SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- VALORES LAN?ADOS NA FICHA FINANCEIRA HE
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFHE, '||
           '9999 BDTIPOCALC, '||
           '0 BDCCFHE, '||
           'PL.BDVREFFHE, '||
           '0.000000 BDREFAUXFHE, '||
           'PL.BDVVALFHE '||
         'FROM '||
         'VRHF_EMP_TFICHAHE PL '||
         'WHERE '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFHE) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFHE) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFHE) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFHE) '||
           'AND '||
           'PL.BDREFFHE >= '||prrefini||' AND PL.BDREFFHE <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- VALORES LAN?ADOS NA FICHA FINANCEIRA RV
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFRV, '||
           '9999 BDTIPOCALC, '||
           '0 BDCCFRV, '||
           'PL.BDVREFFRV, '||
           '0.000000 BDREFAUXFRV, '||
           'PL.BDVVALFRV '||
         'FROM '||
         'VRHF_EMP_TFICHARV PL '||
         'WHERE '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFRV) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFRV) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFRV) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFRV) '||
           'AND '||
           'PL.BDREFFRV >= '||prrefini||' AND PL.BDREFFRV <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;


  -- VALORES LAN?ADOS NA FICHA FINANCEIRA HN
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFHN, '||
           '9999 BDTIPOCALC, '||
           '0 BDCCFHN, '||
           'PL.BDVREFFHN, '||
           '0.000000 BDREFAUXFHN, '||
           'PL.BDVVALFHN '||
         'FROM '||
         'VRHF_EMP_TFICHAHN PL '||
         'WHERE '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFHN) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFHN) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFHN) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFHN) '||
           'AND '||
           'PL.BDREFFHN >= '||prrefini||' AND PL.BDREFFHN <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;


  -- VALORES LAN?ADOS NA FICHA FINANCEIRA OUTRAS
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFOT, '||
           '9999 BDTIPOCALC, '||
           '0 BDCCFOT, '||
           'PL.BDVREFFOT, '||
           '0.000000 BDREFAUXFOT, '||
           'PL.BDVVALFOT '||
         'FROM '||
         'VRHF_EMP_TFICHAOUTRAS PL '||
         'WHERE '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFOT) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFOT) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFOT) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFOT) '||
           'AND '||
           'PL.BDREFFOT >= '||prrefini||' AND PL.BDREFFOT <= '||prreffim;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

END
^

/* Alter (SP_VRHF_RELATORIOFF_VALOR) */
ALTER PROCEDURE SP_VRHF_RELATORIOFF_VALOR(PREMP VARCHAR(20000),
PRCOL VARCHAR(32700),
PRAUT VARCHAR(12000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRBASES SMALLINT = 0,
PRFN SMALLINT = 0,
PRFC SMALLINT = 0,
PRADS SMALLINT = 0,
PRAD13 SMALLINT = 0,
PR13 SMALLINT = 0,
PRC13 SMALLINT = 0,
PRFA SMALLINT = 0,
PRCODFA INTEGER = 0,
PRSERV SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDVALOR NUMERIC(18,4),
BDTIPO VARCHAR(5),
BDDATARESCISAO DATE,
BDDESCVER VARCHAR(40),
BDCLAVER VARCHAR(20))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WBFGTS NUMERIC(18,4);
DECLARE VARIABLE WFGTS NUMERIC(18,4);
DECLARE VARIABLE WBFGTS13 NUMERIC(18,4);
DECLARE VARIABLE WFGTS13 NUMERIC(18,4);
DECLARE VARIABLE WBINSS NUMERIC(18,4);
DECLARE VARIABLE WBINSS13 NUMERIC(18,4);
DECLARE VARIABLE WBIR NUMERIC(18,4);
DECLARE VARIABLE WBIR13 NUMERIC(18,4);
DECLARE VARIABLE WDEPFN NUMERIC(18,4);
BEGIN
  BDCODTER = NULL;

  IF (UPPER(COALESCE(prcol, '')) <> 'NENHUM') THEN
     BEGIN
       IF (COALESCE(prfn, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDCODVER, FOL.BDVALVFN, '||
                   'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''M'' end BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from ('||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDCODVER, FOL.BDVALVFN '||
                   'from VRHF_EMP_TVERBAFN FOL '||
                   'where FOL.BDREFFN between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' union all '||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODVER, SUM(FOL.BDVALVFT) BDVALVFT '||
                   'from VRHF_EMP_TVERBATOMADOR FOL '||
                   'where FOL.BDREFTOMADOR between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODVER) FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';

     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
     
            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDBFGTSFN, FOL.BDFGTSFN, FOL.BDBFGTS13FN, FOL.BDFGTS13FN, '||
                          'FOL.BDBINSSAPFN, FOL.BDBIRRFFN, FOL.BDBINSS13APFN, FOL.BDBIRRF13FN, FOL.BDDEPFN, '||
                        'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''M'' end BDTIPO, RESC.BDDATARESCISAO '||
                        'from ('||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDBFGTSFN + FOL.BDBFGTSFEFN BDBFGTSFN, FOL.BDFGTSFN + FOL.BDFGTSFEFN BDFGTSFN, FOL.BDBFGTS13FN, FOL.BDFGTS13FN, '||
                          'FOL.BDBINSSAPFN, FOL.BDBIRRFFN + FOL.BDBIRRFFEFN BDBIRRFFN, FOL.BDBINSS13APFN, FOL.BDBIRRF13FN, FOL.BDDEPFN '||
                        'from VRHF_EMP_TFOLHANORMAL FOL '||
                        'where FOL.BDREFFN between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 wsql = wsql||' union all '||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, SUM(FOL.BDBFGTSFT + FOL.BDBFGTSFEFT), SUM(FOL.BDFGTSFT + FOL.BDFGTSFEFT), SUM(FOL.BDBFGTS13FT), SUM(FOL.BDFGTS13FT), '||
                          'SUM(FOL.BDBINSSAPFT), SUM(FOL.BDBIRRFFT + FOL.BDBIRRFFEFT), SUM(FOL.BDBINSS13APFT), SUM(FOL.BDBIRRF13FT), SUM(FOL.BDDEPFT) '||
                        'from VRHF_EMP_TFOLHATOMADOR FOL '||
                        'where FOL.BDREFTOMADOR between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR) FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';
     
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbfgts, :wfgts, :wbfgts13, :wfgts13, :wbinss, :wbir, :wbinss13, :wbir13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de FGTS';
                     BDVALOR = wbfgts;
                     SUSPEND;
     
                     BDDESCVER = 'Valor de FGTS';
                     BDVALOR = wfgts;
                     SUSPEND;
     
                     BDDESCVER = 'Base de INSS';
                     BDVALOR = wbinss;
                     SUSPEND;
     
                     BDDESCVER = 'Base de IR';
                     BDVALOR = wbir;
                     SUSPEND;
     
                     BDDESCVER = 'Dependente de IR';
                     BDVALOR = wdepfn;
                     SUSPEND;

                     IF (BDTIPO = 'C') THEN
                        BEGIN
                          BDDESCVER = 'Base de FGTS 13?';
                          BDVALOR = wbfgts13;
                          SUSPEND;
          
                          BDDESCVER = 'Valor de FGTS 13?';
                          BDVALOR = wfgts13;
                          SUSPEND;
          
                          BDDESCVER = 'Base de INSS 13?';
                          BDVALOR = wbinss13;
                          SUSPEND;
                          BDDESCVER = 'Base de IR 13?';
                          BDVALOR = wbir13;
                          SUSPEND;
                       END
                   END
               END
          END
     
       IF (COALESCE(prfc, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFCOMP, FOL.BDCODVER, FOL.BDVALVFC, '||
                   'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''F'' end BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from ('||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FC.BDREFCOMP, FOL.BDCODVER, FOL.BDVALVFC '||
                   'from VRHF_EMP_TVERBAFC FOL '||
                   'join VRHF_EMP_TFOLHACOMP FC on (FC.BDCODEMP = FOL.BDCODEMP and FC.BDCODCOL = FOL.BDCODCOL and FC.BDREFFN = FOL.BDREFFN and FC.BDREFFC = FOL.BDREFFC) '||
                   'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' union all '||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FC.BDREFCOMP, FOL.BDCODVER, SUM(FOL.BDVALVFC) BDVALVFC '||
                   'from VRHF_EMP_TVERBAFCTOMADOR FOL '||
                   'join VRHF_EMP_TFOLTOMCOMP FC on (FC.BDCODEMP = FOL.BDCODEMP and FC.BDCODCOL = FOL.BDCODCOL and FC.BDREFTOMADOR = FOL.BDREFTOMADOR and FC.BDREFFC = FOL.BDREFFC and FC.bdordem = FOL.BDORDEM) '||
                   'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FC.BDREFCOMP, FOL.BDCODVER) FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFCOMP, FOL.BDBFGTSFC, FOL.BDFGTSFC, FOL.BDBFGTS13FC, FOL.BDFGTS13FC, '||
                          'FOL.BDBINSSAPFC, FOL.BDBIRRFFC, FOL.BDBINSS13APFC, FOL.BDBIRRF13FC, FOL.BDDEPFC, '||
                        'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''F'' end BDTIPO, RESC.BDDATARESCISAO '||
                        'from ('||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDREFCOMP, FOL.BDBFGTSFC + FOL.BDBFGTSFEFC BDBFGTSFC, FOL.BDFGTSFC + FOL.BDFGTSFEFC BDFGTSFC, FOL.BDBFGTS13FC, FOL.BDFGTS13FC, '||
                          'FOL.BDBINSSAPFC, FOL.BDBIRRFFC + FOL.BDBIRRFFEFC BDBIRRFFC, FOL.BDBINSS13APFC, FOL.BDBIRRF13FC, FOL.BDDEPFC '||
                        'from VRHF_EMP_TFOLHACOMP FOL '||
                        'where FOL.BDREFCOMP between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 wsql = wsql||' union all '||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDREFCOMP, SUM(FOL.BDBFGTSFC + FOL.BDBFGTSFEFC), SUM(FOL.BDFGTSFC + FOL.BDFGTSFEFC), SUM(FOL.BDBFGTS13FC), SUM(FOL.BDFGTS13FC), '||
                          'SUM(FOL.BDBINSSAPFC), SUM(FOL.BDBIRRFFC + FOL.BDBIRRFFEFC), SUM(FOL.BDBINSS13APFC), SUM(FOL.BDBIRRF13FC), SUM(FOL.BDDEPFC) '||
                        'from VRHF_EMP_TFOLTOMCOMP FOL '||
                        'where FOL.BDREFCOMP between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDREFCOMP) FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';
     
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbfgts, :wfgts, :wbfgts13, :wfgts13, :wbinss, :wbir, :wbinss13, :wbir13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de FGTS';
                     BDVALOR = wbfgts;
                     SUSPEND;
     
                     BDDESCVER = 'Valor de FGTS';
                     BDVALOR = wfgts;
                     SUSPEND;
     
                     BDDESCVER = 'Base de INSS';
                     BDVALOR = wbinss;
                     SUSPEND;
     
                     BDDESCVER = 'Base de IR';
                     BDVALOR = wbir;
                     SUSPEND;
     
                     BDDESCVER = 'Dependente de IR';
                     BDVALOR = wdepfn;
                     SUSPEND;

                     IF (BDTIPO = 'C') THEN
                        BEGIN
                          BDDESCVER = 'Base de FGTS 13?';
                          BDVALOR = wbfgts13;
                          SUSPEND;
          
                          BDDESCVER = 'Valor de FGTS 13?';
                          BDVALOR = wfgts13;
                          SUSPEND;
          
                          BDDESCVER = 'Base de INSS 13?';
                          BDVALOR = wbinss13;
                          SUSPEND;
          
                          BDDESCVER = 'Base de IR 13?';
                          BDVALOR = wbir13;
                          SUSPEND;
                       END
                   END
               END
          END
     
       IF (COALESCE(prads, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, AD.BDREFAD, FOL.BDCODVER, FOL.BDVALVAD, '||
                   '''A'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAAD FOL '||
                   'join VRHF_EMP_TADSAL AD on (AD.BDCODEMP = FOL.BDCODEMP and AD.BDCODCOL = FOL.BDCODCOL and AD.BDDATAAD = FOL.BDDATAAD) '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where AD.BDREFAD between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFAD, FOL.BDBASEIRAD, FOL.BDDEPIRAD, '||
                        '''A'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_TADSAL FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREFAD between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbir, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de IR';
                     BDVALOR = wbir;
                     SUSPEND;

                     BDDESCVER = 'Dependente de IR';
                     BDVALOR = wdepfn;
                     SUSPEND;
                   END
               END

          END
     
       IF (COALESCE(prad13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDCODVER, FOL.BDVALVA13, '||
                   '''1'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAA13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREFA13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
     
            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDBASEFGTSA13, FOL.BDFGTSA13, '||
                        '''1'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_TA13SAL FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREFA13 between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbfgts13, :wfgts13, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de FGTS 13?';
                     BDVALOR = :wbfgts13;
                     SUSPEND;

                     BDDESCVER = 'Valor de FGTS 13?';
                     BDVALOR = :wfgts13;
                     SUSPEND;
                   END
               END

          END
     
       IF (COALESCE(pr13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDCODVER, FOL.BDVALV13, '||
                   '''2'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBA13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREF13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDBASEIR13, FOL.BDBASEFGTS13, FOL.BDFGTS13, FOL.BDBASEINSS13, FOL.BDDEP13, '||
                        '''2'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_T13SAL FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREF13 between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbir13, :wbfgts13, :wfgts13, :wbinss13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de IR 13?';
                     BDVALOR = :wbir13;
                     SUSPEND;

                     BDDESCVER = 'Base de FGTS 13?';
                     BDVALOR = :wbfgts13;
                     SUSPEND;

                     BDDESCVER = 'Valor de FGTS 13?';
                     BDVALOR = :wfgts13;
                     SUSPEND;

                     BDDESCVER = 'Base de INSS 13?';
                     BDVALOR = :wbinss13;
                     SUSPEND;

                     BDDESCVER = 'Dependente de IR 13?';
                     BDVALOR = :wdepfn;
                     SUSPEND;
                   END

               END

          END
     
       IF (COALESCE(prc13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFC13, FOL.BDCODVER, FOL.BDVALVC13, '||
                   '''3'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAC13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREFC13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDBASEIRC13, FOL.BDBASEFGTSC13, FOL.BDFGTSC13, FOL.BDBASEINSSC13, FOL.BDDEPC13, '||
                        '''2'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_TC13SAL FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREFC13 between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbir13, :wbfgts13, :wfgts13, :wbinss13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de IR 13?';
                     BDVALOR = :wbir13;
                     SUSPEND;

                     BDDESCVER = 'Base de FGTS 13?';
                     BDVALOR = :wbfgts13;
                     SUSPEND;

                     BDDESCVER = 'Valor de FGTS 13?';
                     BDVALOR = :wfgts13;
                     SUSPEND;

                     BDDESCVER = 'Base de INSS 13?';
                     BDVALOR = :wbinss13;
                     SUSPEND;

                     BDDESCVER = 'Dependente de IR 13?';
                     BDVALOR = :wdepfn;
                     SUSPEND;
                   END
               END
          END
     
       IF (COALESCE(prfa, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FA.BDREF, FOL.BDCODVER, FOL.BDVALVFA, '||
                   '''P'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAFA FOL '||
                   'join VRHF_EMP_TFOLHAAVULSA FA on (FA.BDCODEMP = FOL.BDCODEMP and FA.BDCODCOL = FOL.BDCODCOL and FA.BDDATAFA = FOL.BDDATAFA and FA.BDCODTCA = FOL.BDCODTCA) '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FA.BDREF between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            IF (COALESCE(prcodfa, 0) > 0) THEN
               wsql = wsql||' and FOL.BDCODTCA = '||prcodfa;
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF, FOL.BDBFGTSFA, FOL.BDFGTSFA, FOL.BDBINSSFA, FOL.BDBIRRFFA, FOL.BDDEPFA, '||
                        '''P'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_TFOLHAAVULSA FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREF between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 IF (COALESCE(prcodfa, 0) > 0) THEN
                    wsql = wsql||' and FOL.BDCODTCA = '||prcodfa;
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbfgts, :wfgts, :wbinss, :wbir, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de FGTS';
                     BDVALOR = :wbfgts;
                     SUSPEND;

                     BDDESCVER = 'Valor de FGTS';
                     BDVALOR = :wfgts;
                     SUSPEND;

                     BDDESCVER = 'Base de INSS';
                     BDVALOR = :wbinss;
                     SUSPEND;

                     BDDESCVER = 'Base de IR';
                     BDVALOR = :wbir;
                     SUSPEND;

                     BDDESCVER = 'Dependente de IR';
                     BDVALOR = :wdepfn;
                     SUSPEND;
                   END
               END
          END
     END

  IF (COALESCE(prserv, 0) = 1 AND UPPER(COALESCE(praut, '')) <> 'NENHUM') THEN
     BEGIN
       BDCODCOL = NULL;
       wsql = 'select FOL.BDCODEMP, FOL.BDCODTER, SERV.BDREFINSSSERV, FOL.BDCODVER, FOL.BDVALOR, '||
              '''S'' BDTIPO, cast(null as date) BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
              'from VRHF_BASE_ITEMS_CALCTERC FOL '||
              'join VRHF_BASE_CALC_TERC SERV on (SERV.BDCODEMP = FOL.BDCODEMP and SERV.BDCODTER = FOL.BDCODTER and SERV.BDCODSERV = FOL.BDCODSERV) '||
              'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
              'where SERV.BDREFINSSSERV between '||prrefini||' and '||prreffim;
     
       IF (premp IS NOT NULL AND premp <> '') THEN
          BEGIN
            wsql = wsql||' and '||premp;

            IF (praut IS NOT NULL AND praut <> '') THEN
               wsql = wsql||' and '||praut;
          END

       FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODTER, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
         SUSPEND;

       IF (COALESCE(prbases,0) = 1) THEN
          BEGIN
            BDCODVER = 999999;
            BDCLAVER = '99999999999999999999';
            wsql = 'select FOL.BDCODEMP, FOL.BDCODTER, FOL.BDREFINSSSERV, FOL.BDBASEIR, FOL.BDBASEINSS, FOL.BDVALOUTENTIDADES, FOL.BDVALORDEP, '||
                   '''S'' BDTIPO, cast(null as date) BDDATARESCISAO '||
                   'from VRHF_BASE_CALC_TERC FOL '||
                   'where FOL.BDREFINSSSERV between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (praut IS NOT NULL AND praut <> '') THEN
                    wsql = wsql||' and '||praut;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODTER, :BDREF, :wbir, :wbinss, :wbfgts13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
              BEGIN
                BDDESCVER = 'Base de IR';
                BDVALOR = wbir;
                SUSPEND;

                BDDESCVER = 'Base de INSS';
                BDVALOR = wbinss;
                SUSPEND;

                BDDESCVER = 'Valor outras entidades';
                BDVALOR = wbfgts13;
                SUSPEND;

                BDDESCVER = 'Depdendente de IR';
                BDVALOR = wdepfn;
                SUSPEND;
              END
          END
     END
END
^

/* Alter (SP_VRHF_SEGDESEMPREGO3MESES) */
ALTER PROCEDURE SP_VRHF_SEGDESEMPREGO3MESES(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREF INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDMAIORREMUNERACAO NUMERIC(18,6),
BDORIGEM SMALLINT)
 AS
DECLARE VARIABLE WREFRESCISAO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WULTDIA INTEGER;
DECLARE VARIABLE WDATAFIM DATE;
DECLARE VARIABLE WDATAINI DATE;
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WREMUNERACAO NUMERIC(18,6);
DECLARE VARIABLE WTIPOCOL INTEGER;
DECLARE VARIABLE WHORASMES NUMERIC(18,6);
DECLARE VARIABLE WTEMCALC SMALLINT;
DECLARE VARIABLE WVERMAIORREM DM_BOOLEAN;
DECLARE VARIABLE WCLAVER VARCHAR(7);
DECLARE VARIABLE WSALBASE NUMERIC(18,6);
DECLARE VARIABLE WVINTREMUNERACAO NUMERIC(18,6);
BEGIN
/*
  O retorno de BDORIGEM:

  1 = C?lculo
  2 = Ficha financeira de FGTS
  3 = Sal?rio base atual
  0 = N?o tem nada

*/
  wtipocol = 0;
  wrefrescisao = NULL;
  IF ((prref IS NULL) OR (prref = 0)) THEN
     SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol INTO :wrefrescisao;
  ELSE
     wrefrescisao = prref;

  IF (wrefrescisao IS NOT NULL) THEN
     BEGIN
       IF (SUBSTRING(:wrefrescisao FROM 5 FOR 2) = '01') THEN
          wrefrescisao = CAST((CAST((CAST((SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
       ELSE
       IF (CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) > 10) THEN
          wrefrescisao = SUBSTRING(:wrefrescisao FROM 1 FOR 4)||CAST((CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2));
       ELSE
          wrefrescisao = SUBSTRING(:wrefrescisao FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));

       wconta = 1;
       WHILE (wconta <= 3) DO
         BEGIN
           bdcodemp = prcodemp;
           bdcodcol = prcodcol;
           bdreffn  = wrefrescisao;
           bdmaiorremuneracao = 0;
           wtemcalc = 0;
           bdorigem = 0;
           wsql = 'select COALESCE(VFOL.BDVALVFN,0.0), COALESCE(VFOL.BDVALVIFN,0.0), UPPER(VERREF.BDBASEMAIORVER), SUBSTRING(VER.BDCLAVER FROM 1 FOR 7) from VRHF_EMP_TVERBAFN VFOL '||
                  'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = VFOL.BDCODVER) '||
                  'join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = VFOL.BDCODVER) '||
                  'where VFOL.BDCODEMP = '||prcodemp||' and VFOL.BDCODCOL = '||prcodcol||' and VFOL.BDREFFN = '||wrefrescisao;

           wsql = wsql||' UNION ALL ';
           wsql = wsql||
                  'select COALESCE(VFOL.BDVALVFT,0.0), COALESCE(VFOL.BDVALVIFT,0.0), UPPER(VERREF.BDBASEMAIORVER), SUBSTRING(VER.BDCLAVER FROM 1 FOR 7) from VRHF_EMP_TVERBATOMADOR VFOL '||
                  'join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = VFOL.BDCODVER) '||
                  'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = VFOL.BDCODVER) '||
                  'where VFOL.BDCODEMP = '||prcodemp||' and VFOL.BDCODCOL = '||prcodcol||' and VFOL.BDREFTOMADOR = '||wrefrescisao;


           SELECT ULTDIA FROM ultimo_dia_mes(CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS SMALLINT), CAST((SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS INTEGER)) INTO :wultdia;

           IF (wultdia < 10) THEN
              wdatafim = CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)||'-0'||wultdia||'-'||SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS DATE);
           ELSE
              wdatafim = CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)||'-'||wultdia||'-'||SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS DATE);

           wdataini = CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)||'-01-'||SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS DATE);

           wremuneracao = 0;
           wvintremuneracao = 0;

           SELECT BDTIPOCOL FROM VW_VRHF_EMP_TCOL_CALC WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol  INTO :wtipocol;

           EXECUTE PROCEDURE sp_seta_competencia(:wrefrescisao, :wdataini, :wdatafim);
           FOR EXECUTE STATEMENT wsql INTO :wremuneracao, :wvintremuneracao, :wvermaiorrem, :wclaver DO
             BEGIN
               wtemcalc = 1;

               IF ((wtipocol <> 4) AND (wvermaiorrem = 'TRUE' AND wclaver <> '0.001.0' AND wclaver <> '0.001.1' AND wclaver <> '0.001.2')) THEN
                 BEGIN
                   IF (wvintremuneracao > 0) THEN
                     bdmaiorremuneracao = bdmaiorremuneracao + wvintremuneracao;
                   ELSE
                     bdmaiorremuneracao = bdmaiorremuneracao + wremuneracao;
                 END
               ELSE
                 IF ((wtipocol = 4) AND (wvermaiorrem = 'TRUE' AND wclaver <> '0.001.0' AND wclaver <> '0.001.2')) THEN --Para horistas especiais deve se considerar a verba '0.001.1'.
                   BEGIN
                     IF (wvintremuneracao > 0) THEN
                       bdmaiorremuneracao = bdmaiorremuneracao + wvintremuneracao;
                     ELSE
                       bdmaiorremuneracao = bdmaiorremuneracao + wremuneracao;
                   END
             END

           wsql = 'select COALESCE(COLVINCDIA.BDSALBASECOL,0.0), COALESCE(COLCALC.BDHORASMENSAISCOL,0.0) '||
                  'from VW_VRH_EMP_TCOLCON_CALCDIA COLVINCDIA '||
                  'left outer join VW_VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COLVINCDIA.BDCODEMP and COLCALC.BDCODCOL = COLVINCDIA.BDCODCOL) '||
                  'where COLVINCDIA.BDCODEMP = '||prcodemp||' and COLVINCDIA.BDCODCOL = '||prcodcol;

           wremuneracao = 0;
           whorasmes = 0;
           wsalbase = 0;

           EXECUTE STATEMENT wsql INTO :wremuneracao, :whorasmes;

           IF (wtipocol = 2) THEN   -- Horista
              wsalbase = CAST((wremuneracao * whorasmes / 30 * wultdia) AS NUMERIC(18,2));
           ELSE
              wsalbase = CAST(wremuneracao AS NUMERIC(18,2));

           IF (wtemcalc = 1) THEN
              BEGIN
                bdmaiorremuneracao = bdmaiorremuneracao + wsalbase;
                bdorigem = 1;
              END

           IF (bdmaiorremuneracao = 0) THEN   -- Se n?o tiver c?lculo o sal?rio do m?s n?o ser? adicionado e ir? buscar da ficha de FGTS
              BEGIN
                wremuneracao = 0;
                wsql = 'select first 1 coalesce(FN.BDBFGTS_FFGTS, 0) from VRHF_EMP_TFICHAFGTS FN '||
                       'where FN.BDTIPO_FFGTS = 1 and FN.BDCODEMP = '||prcodemp||' and FN.BDCODCOL = '||prcodcol||' and FN.BDREF_FFGTS = '||wrefrescisao;
                EXECUTE STATEMENT wsql INTO :wremuneracao;
                bdmaiorremuneracao = bdmaiorremuneracao + wremuneracao;
              END


           IF (bdmaiorremuneracao = 0) THEN   -- Se n?o tiver ficha de FGTS o sistema joga o sal?rio base atual
              BEGIN
                bdmaiorremuneracao = wsalbase;
                bdorigem = 3;    -- Sal?rio base
              END
           ELSE
           IF ((bdorigem IS NULL) OR (bdorigem = 0)) THEN
              bdorigem = 2;  -- Ficha de FGTS


           SUSPEND;

           wconta = wconta + 1;

           IF (SUBSTRING(:wrefrescisao FROM 5 FOR 2) = '01') THEN
              wrefrescisao = CAST((CAST((CAST((SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
           ELSE
           IF (CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) > 10) THEN
              wrefrescisao = SUBSTRING(:wrefrescisao FROM 1 FOR 4)||CAST((CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2));
           ELSE
              wrefrescisao = SUBSTRING(:wrefrescisao FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));
         END
     END
  ELSE
     BEGIN
       bdcodemp = prcodemp;
       bdcodcol = prcodcol;
       bdreffn = NULL;
       bdmaiorremuneracao = 0;
       bdorigem = 0;
       SUSPEND;
     END
END
^

/* Alter (SP_VRHF_TCOL_VINC_REF) */
ALTER PROCEDURE SP_VRHF_TCOL_VINC_REF(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFCOL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDCODSINTRAB INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prREFCOL, NULL, NULL);

  wsql = 'select BDCODEMP, BDCODCOL, BDREFCOL, BDCODSINTRAB '||
         'from vw_vrh_emp_tcol_vinc '||
         'where BDCODEMP = '||prCODEMP||' and BDCODCOL = '||prCODCOL;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDCODSINTRAB
  DO
  SUSPEND;
END
^

/* Alter (SP_VRHF_UNION_FN_FT_MES) */
ALTER PROCEDURE SP_VRHF_UNION_FN_FT_MES(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDCODVER INTEGER,
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDREFVFN_SUM NUMERIC(15,6),
BDREFAUXVFN_SUM NUMERIC(15,6),
BDREFVFN_MAX NUMERIC(15,6),
BDREFAUXVFN_MAX NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDVALVIFN NUMERIC(15,6),
BDIGNREFVFN DM_BOOLEAN,
BDIGNREFAVFN DM_BOOLEAN,
BDIGNVALVFN DM_BOOLEAN,
BDORVERBA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WVERATU INTEGER;
DECLARE VARIABLE WHOREMP DM_BOOLEAN;
DECLARE VARIABLE WTIPOREFVER INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREFFN INTEGER;
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WCOMPESP VARCHAR(300);
DECLARE VARIABLE WFORMREFAUX VARCHAR(5000);
DECLARE VARIABLE WFORMREF VARCHAR(5000);
DECLARE VARIABLE WFORMVAL VARCHAR(5000);
DECLARE VARIABLE WREFVSUM NUMERIC(15,6);
DECLARE VARIABLE WREFAUXVSUM NUMERIC(15,6);
DECLARE VARIABLE WREFVMAX NUMERIC(15,6);
DECLARE VARIABLE WREFAUXVMAX NUMERIC(15,6);
DECLARE VARIABLE WVALV NUMERIC(15,6);
DECLARE VARIABLE WVALIV NUMERIC(15,6);
DECLARE VARIABLE WIGREF DM_BOOLEAN;
DECLARE VARIABLE WIGREFAUX DM_BOOLEAN;
DECLARE VARIABLE WIGVAL DM_BOOLEAN;
DECLARE VARIABLE WORVERBA INTEGER;
DECLARE VARIABLE WCOMPESPANT VARCHAR(300);
DECLARE VARIABLE WFORMREFAUXANT VARCHAR(5000);
DECLARE VARIABLE WFORMREFANT VARCHAR(5000);
DECLARE VARIABLE WFORMVALANT VARCHAR(5000);
DECLARE VARIABLE WREFVSUMANT NUMERIC(15,6);
DECLARE VARIABLE WREFAUXVSUMANT NUMERIC(15,6);
DECLARE VARIABLE WVALVANT NUMERIC(15,6);
DECLARE VARIABLE WVALIVANT NUMERIC(15,6);
DECLARE VARIABLE WIGREFANT DM_BOOLEAN;
DECLARE VARIABLE WIGREFAUXANT DM_BOOLEAN;
DECLARE VARIABLE WIGVALANT DM_BOOLEAN;
DECLARE VARIABLE WORVERBAANT INTEGER;
DECLARE VARIABLE WFRACAO NUMERIC(15,6);
BEGIN
  wsql = 'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFFN, '||
           'FN.BDCODVER, '||
           'FN.BDCOMPESP, '||
           'FN.BDFORMREFAUX, '||
           'FN.BDFORMREF, '||
           'FN.BDFORMVAL, '||
           'FN.BDREFVFN, '||
           'FN.BDREFAUXVFN, '||
           'FN.BDREFVFN, '||
           'FN.BDREFAUXVFN, '||
           'FN.BDVALVFN, '||
           'FN.BDVALVIFN, '||
           'FN.BDIGNREFVFN, '||
           'FN.BDIGNREFAVFN, '||
           'FN.BDIGNVALVFN, '||
           'FN.BDORVERBAFN '||
         'FROM '||
           'VRHF_EMP_TVERBAFN FN ';

  wsql = wsql||
         'where FN.BDREFFN = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDCODVER,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL,
    :BDREFVFN_SUM,
    :BDREFAUXVFN_SUM,
    :BDREFVFN_MAX,
    :BDREFAUXVFN_MAX,
    :BDVALVFN,
    :BDVALVIFN,
    :BDIGNREFVFN,
    :BDIGNREFAVFN,
    :BDIGNVALVFN,
    :BDORVERBA
  DO
    SUSPEND;


  wsql = 'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFTOMADOR, '||
           'FN.BDCODVER, '||
           'FN.BDCOMPESP, '||
           'FN.BDFORMREFAUX, '||
           'FN.BDFORMREF, '||
           'FN.BDFORMVAL, '||
           'FN.BDREFVFT, '||
           'FN.BDREFAUXVFT, '||
           'FN.BDVALVFT, '||
           'FN.BDVALVIFT, '||
           'FN.BDIGNREFVFT, '||
           'FN.BDIGNREFAVFT,'||
           'FN.BDIGNVALVFT, '||
           'FN.BDORVERBAFT, '||
           'EMPCALC.BDREFHOREMP, '||
           'VERREF.BDTIPOREFVER '||
         'FROM '||
           'VRHF_EMP_TVERBATOMADOR FN '||
         'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = FN.BDCODEMP) '||
         'left outer join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) '||
         'where FN.BDREFTOMADOR = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     END
  wsql = wsql||' order by FN.BDCODEMP, FN.BDCODCOL, FN.BDREFTOMADOR, FN.BDCODVER';

  wempatu     = 0;
  wcolatu     = 0;
  wrefatu     = 0;
  wveratu     = 0;
  wcompesp    = '';
  wformrefaux = '';
  wformref    = '';
  wformval    = '';
  wrefvsum    = 0;
  wrefauxvsum = 0;
  wrefvmax    = 0;
  wrefauxvmax = 0;
  wvalv       = 0;
  wvaliv      = 0;
  wigref      = '';
  wigrefaux   = '';
  wigval      = '';
  worverba    = -1;

  FOR EXECUTE STATEMENT wsql INTO
    :wcodemp,
    :wcodcol,
    :wreffn,
    :wcodver,
    :wcompespant,
    :wformrefauxant,
    :wformrefant,
    :wformvalant,
    :wrefvsumant,
    :wrefauxvsumant,
    :wvalvant,
    :wvalivant,
    :wigrefant,
    :wigrefauxant,
    :wigvalant,
    :worverbaant,
    :whoremp,
    :wtiporefver
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF (wrefatu = 0) THEN
         wrefatu = wreffn;

      IF (wveratu = 0) THEN
         wveratu = wcodver;

      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreffn) OR (wveratu <> wcodver)) THEN
         BEGIN
           BDCODEMP        = wempatu;
           BDCODCOL        = wcolatu;
           BDREFFN         = wrefatu;
           BDCODVER        = wveratu;
           BDCOMPESP       = wcompesp;
           BDFORMREFAUX    = wformrefaux;
           BDFORMREF       = wformref;
           BDFORMVAL       = wformval;
           BDREFVFN_SUM    = wrefvsum;
           BDREFAUXVFN_SUM = wrefauxvsum;
           BDREFVFN_MAX    = wrefvmax;
           BDREFAUXVFN_MAX = wrefauxvmax;
           BDVALVFN        = wvalv;
           BDVALVIFN       = wvaliv;
           BDIGNREFVFN     = wigref;
           BDIGNREFAVFN    = wigrefaux;
           BDIGNVALVFN     = wigval;
           BDORVERBA       = worverba;
           SUSPEND;

           wempatu     = wcodemp;
           wcolatu     = wcodcol;
           wrefatu     = wreffn;
           wveratu     = wcodver;
           wcompesp    = '';
           wformrefaux = '';
           wformref    = '';
           wformval    = '';
           wrefvsum    = 0;
           wrefauxvsum = 0;
           wrefvmax    = 0;
           wrefauxvmax = 0;
           wvalv       = 0;
           wvaliv      = 0;
           wigref      = '';
           wigrefaux   = '';
           wigval      = '';
           worverba    = -1;
         END

      IF (wcompesp <> '') THEN
         wcompesp = wcompesp||'. ' ;

      wcompesp = SUBSTRING((wcompesp||wcompespant) FROM 1 FOR 300);

      IF (wformrefaux <> '') THEN
         wformrefaux = wformrefaux||'. ' ;

      wformrefaux = SUBSTRING((wformrefaux||wformrefauxant) FROM 1 FOR 5000);

      IF (wformref <> '') THEN
         wformref = wformref||'. ' ;

      wformref = SUBSTRING((wformref||wformrefant) FROM 1 FOR 5000);

      IF (wformval <> '') THEN
         wformval = wformval||'. ' ;

      wformval = SUBSTRING((wformval||wformvalant) FROM 1 FOR 5000);

      -- Converte horas e tipo de refer?ncia da verba ? Horas
      IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvsumant > 0) THEN
         BEGIN
           -- Converte a referencia atual de Horas para Valor
           wfracao      = wrefvsumant - CAST((wrefvsumant - 0.5) AS INTEGER);
           IF (wrefvsumant > 0) THEN
              BEGIN
                wrefvsumant = wrefvsumant - wfracao;
                wfracao     = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsumant = wrefvsumant + wfracao;
              END

           -- Converte a soma atual de Horas para Valor
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END

           -- Soma os VALORES
           wrefvsum = wrefvsum +  wrefvsumant;

           -- Converte o resultado novamente em Horas
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END
         END
      ELSE
         wrefvsum = wrefvsum + wrefvsumant;

      wrefauxvsum = wrefauxvsum + wrefauxvsumant;

      IF (wrefvmax < wrefvsumant) THEN
         wrefvmax    = wrefvsumant;

      IF (wrefauxvmax < wrefauxvsumant) THEN
         wrefauxvmax = wrefauxvsumant;

      wvalv       = wvalv + wvalvant;
      wvaliv      = wvaliv + wvalivant;

      wigref      = wigrefant;
      wigrefaux   = wigrefauxant;
      wigval      = wigvalant;
      worverba    = worverbaant;
    END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wveratu <> 0) THEN
     BEGIN
       BDCODEMP        = wempatu;
       BDCODCOL        = wcolatu;
       BDREFFN         = wrefatu;
       BDCODVER        = wveratu;
       BDCOMPESP       = wcompesp;
       BDFORMREFAUX    = wformrefaux;
       BDFORMREF       = wformref;
       BDFORMVAL       = wformval;
       BDREFVFN_SUM    = wrefvsum;
       BDREFAUXVFN_SUM = wrefauxvsum;
       BDREFVFN_MAX    = wrefvmax;
       BDREFAUXVFN_MAX = wrefauxvmax;
       BDVALVFN        = wvalv;
       BDVALVIFN       = wvaliv;
       BDIGNREFVFN     = wigref;
       BDIGNREFAVFN    = wigrefaux;
       BDIGNVALVFN     = wigval;
       BDORVERBA       = worverba;
       SUSPEND;
     END
END
^

/* Alter (SP_VRHF_UNION_FT_MES) */
ALTER PROCEDURE SP_VRHF_UNION_FT_MES(PRCODEMP INTEGER,
PRANOMES INTEGER,
PRFILTROCC VARCHAR(20000) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFTOMADOR INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCODVER INTEGER,
BDREFVFN_SUM NUMERIC(15,6),
BDREFAUXVFN_SUM NUMERIC(15,6),
BDREFVFN_MAX NUMERIC(15,6),
BDREFAUXVFN_MAX NUMERIC(15,6),
BDVALVFT NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WVERATU INTEGER;
DECLARE VARIABLE WCODCENTROANT INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WHOREMP DM_BOOLEAN;
DECLARE VARIABLE WTIPOREFVER INTEGER;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREFFN INTEGER;
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WREFVSUM NUMERIC(15,6);
DECLARE VARIABLE WREFAUXVSUM NUMERIC(15,6);
DECLARE VARIABLE WREFVMAX NUMERIC(15,6);
DECLARE VARIABLE WREFAUXVMAX NUMERIC(15,6);
DECLARE VARIABLE WVALV NUMERIC(15,6);
DECLARE VARIABLE WREFVSUMANT NUMERIC(15,6);
DECLARE VARIABLE WREFAUXVSUMANT NUMERIC(15,6);
DECLARE VARIABLE WVALVANT NUMERIC(15,6);
DECLARE VARIABLE WFRACAO NUMERIC(15,6);
BEGIN
  wsql = 'select * from ('||
         'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFTOMADOR, ';

  IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
    wsql = wsql||
           'Y.BDCODCENTRO, '||
           'COALESCE(Y.BDCODTPCC,0) BDCODTPCC, ';
  ELSE
    wsql = wsql||
           '0 BDCODCENTRO, '||
           '0 BDCODTPCC, ';

  wsql = wsql||
           'FN.BDCODVER, '||
           'FN.BDREFVFT, '||
           'FN.BDREFAUXVFT, '||
           'FN.BDVALVFT, '||
           'EMPCALC.BDREFHOREMP, '||
           'VERREF.BDTIPOREFVER '||
         'FROM '||
           'VRHF_EMP_TVERBATOMADOR FN '||
         'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = FN.BDCODEMP) '||
         'left outer join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';

  IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
    wsql = wsql||
         'left outer join VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = FN.BDCODEMP and Y.BDCODCOL = FN.BDCODCOL and Y.BDORDEM = FN.BDORDEM) ';

  wsql = wsql||
         'where FN.BDREFTOMADOR = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     BEGIN
       wsql = wsql||' and FN.BDCODEMP = '||prcodemp;
     END

  IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
     wsql = wsql||' and '||:prfiltrocc;

  wsql = wsql||') order by BDCODEMP, BDCODCOL, BDREFTOMADOR, BDCODTPCC, BDCODVER ';

  wempatu     = 0;
  wcolatu     = 0;
  wrefatu     = 0;
  wveratu     = 0;
  wcodtpccatu = -1;
  wrefvsum    = 0;
  wrefauxvsum = 0;
  wrefvmax    = 0;
  wrefauxvmax = 0;
  wvalv       = 0;

  FOR EXECUTE STATEMENT wsql INTO
    :wcodemp,
    :wcodcol,
    :wreffn,
    :wcodcentro,
    :wcodtpcc,
    :wcodver,
    :wrefvsumant,
    :wrefauxvsumant,
    :wvalvant,
    :whoremp,
    :wtiporefver
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF (wrefatu = 0) THEN
         wrefatu = wreffn;

      IF (wveratu = 0) THEN
         wveratu = wcodver;

      IF (wcodtpccatu = -1) THEN
         wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreffn) OR (wcodtpccatu <> wcodtpcc) OR (wveratu <> wcodver)) THEN
         BEGIN
           BDCODEMP        = wempatu;
           BDCODCOL        = wcolatu;
           BDREFTOMADOR    = wrefatu;
           BDCODCENTRO     = wcodcentroant;
           BDCODTPCC       = wcodtpccatu;
           BDCODVER        = wveratu;
           BDREFVFN_SUM    = wrefvsum;
           BDREFAUXVFN_SUM = wrefauxvsum;
           BDREFVFN_MAX    = wrefvmax;
           BDREFAUXVFN_MAX = wrefauxvmax;
           BDVALVFT        = wvalv;
           SUSPEND;

           wempatu     = wcodemp;
           wcolatu     = wcodcol;
           wrefatu     = wreffn;
           wcodtpccatu = wcodtpcc;
           wveratu     = wcodver;
           wrefvsum    = 0;
           wrefauxvsum = 0;
           wrefvmax    = 0;
           wrefauxvmax = 0;
           wvalv       = 0;
         END

      -- Converte horas e tipo de refer?ncia da verba ? Horas
      IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvsumant > 0) THEN
         BEGIN
           -- Converte a referencia atual de Horas para Valor
           wfracao      = wrefvsumant - CAST((wrefvsumant - 0.5) AS INTEGER);
           IF (wrefvsumant > 0) THEN
              BEGIN
                wrefvsumant = wrefvsumant - wfracao;
                wfracao     = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsumant = wrefvsumant + wfracao;
              END

           -- Converte a soma atual de Horas para Valor
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END

           -- Soma os VALORES
           wrefvsum = wrefvsum +  wrefvsumant;

           -- Converte o resultado novamente em Horas
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END
         END
      ELSE
         wrefvsum = wrefvsum + wrefvsumant;

      wrefauxvsum = wrefauxvsum + wrefauxvsumant;

      IF (wrefvmax < wrefvsumant) THEN
         wrefvmax    = wrefvsumant;

      IF (wrefauxvmax < wrefauxvsumant) THEN
         wrefauxvmax = wrefauxvsumant;

      wvalv         = wvalv + wvalvant;
      wcodcentroant = wcodcentro;
    END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wcodtpccatu <> -1 AND wveratu <> 0) THEN
     BEGIN
       BDCODEMP        = wempatu;
       BDCODCOL        = wcolatu;
       BDREFTOMADOR    = wrefatu;
       BDCODCENTRO     = wcodcentroant;
       BDCODTPCC       = wcodtpccatu;
       BDCODVER        = wveratu;
       BDREFVFN_SUM    = wrefvsum;
       BDREFAUXVFN_SUM = wrefauxvsum;
       BDREFVFN_MAX    = wrefvmax;
       BDREFAUXVFN_MAX = wrefauxvmax;
       BDVALVFT        = wvalv;
       SUSPEND;
     END
END
^

/* Alter (SP_VRHF_UNION_INT_INTTOM_MES) */
ALTER PROCEDURE SP_VRHF_UNION_INT_INTTOM_MES(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRCONTRATO INTEGER,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDCODCONTTI INTEGER,
BDCODVER INTEGER,
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDREFVFN_SUM NUMERIC(15,6),
BDREFAUXVFN_SUM NUMERIC(15,6),
BDREFVFN_MAX NUMERIC(15,6),
BDREFAUXVFN_MAX NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDVALVIFN NUMERIC(15,6),
BDIGNREFVFN DM_BOOLEAN,
BDIGNREFAVFN DM_BOOLEAN,
BDIGNVALVFN DM_BOOLEAN,
BDORVERBA INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WVERATU integer;
declare variable WCONTTIATU integer;
declare variable WHOREMP DM_BOOLEAN;
declare variable WTIPOREFVER integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFFN integer;
declare variable WCODVER integer;
declare variable WCODCONTTI integer;
declare variable WCOMPESP varchar(300);
declare variable WFORMREFAUX varchar(5000);
declare variable WFORMREF varchar(5000);
declare variable WFORMVAL varchar(5000);
declare variable WREFVSUM numeric(15,6);
declare variable WREFAUXVSUM numeric(15,6);
declare variable WREFVMAX numeric(15,6);
declare variable WREFAUXVMAX numeric(15,6);
declare variable WVALV numeric(15,6);
declare variable WVALIV numeric(15,6);
declare variable WIGREF DM_BOOLEAN;
declare variable WIGREFAUX DM_BOOLEAN;
declare variable WIGVAL DM_BOOLEAN;
declare variable WORVERBA integer;
declare variable WCOMPESPANT varchar(300);
declare variable WFORMREFAUXANT varchar(5000);
declare variable WFORMREFANT varchar(5000);
declare variable WFORMVALANT varchar(5000);
declare variable WREFVSUMANT numeric(15,6);
declare variable WREFAUXVSUMANT numeric(15,6);
declare variable WVALVANT numeric(15,6);
declare variable WVALIVANT numeric(15,6);
declare variable WIGREFANT DM_BOOLEAN;
declare variable WIGREFAUXANT DM_BOOLEAN;
declare variable WIGVALANT DM_BOOLEAN;
declare variable WORVERBAANT integer;
declare variable WFRACAO numeric(15,6);
BEGIN
  wsql = 'SELECT '||
           'FOL.BDCODEMP, '||
           'FOL.BDCODCOL, '||
           'FOL.BDREFFN, '||
           'FOL.BDCODCONTTI, '||
           'FOL.BDCODVER, '||
           'FOL.BDCOMPESP, '||
           'FOL.BDFORMREFAUX, '||
           'FOL.BDFORMREF, '||
           'FOL.BDFORMVAL, '||
           'FOL.BDREFVFN, '||
           'FOL.BDREFAUXVFN, '||
           'FOL.BDVALVFN, '||
           'FOL.BDVALIFN, '||
           'FOL.BDIGNREFVFN, '||
           'FOL.BDIGNREFAVFN, '||
           'FOL.BDIGNVALVFN, '||
           'FOL.BDORVERBAFN, '||
           'EMPCALC.BDREFHOREMP, '||
           'VERREF.BDTIPOREFVER '||
         'FROM (';

  wsql = wsql||'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFFN, '||
           'FN.BDCODCONTTI, '||
           'FN.BDCODVER, '||
           'FN.BDCOMPESP, '||
           'FN.BDFORMREFAUX, '||
           'FN.BDFORMREF, '||
           'FN.BDFORMVAL, '||
           'FN.BDREFVFN, '||
           'FN.BDREFAUXVFN, '||
           'FN.BDVALVFN, '||
           'FN.BDVALIFN, '||
           'FN.BDIGNREFVFN, '||
           'FN.BDIGNREFAVFN, '||
           'FN.BDIGNVALVFN, '||
           'FN.BDORVERBAFN '||
         'FROM '||
           'VRHF_EMP_TVERBAINT FN ';

  wsql = wsql||
         'where FN.BDREFFN = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       if (coalesce(prcontrato, 0) <> 0) then
          wsql = wsql||' and FN.BDCODCONTTI = '||prcontrato;
     END

  wsql = wsql||' union all ';

  wsql = wsql||'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFTOMADOR, '||
           'FN.BDCODCONTTI,'||
           'FN.BDCODVER, '||
           'FN.BDCOMPESP, '||
           'FN.BDFORMREFAUX, '||
           'FN.BDFORMREF, '||
           'FN.BDFORMVAL, '||
           'FN.BDREFVFT, '||
           'FN.BDREFAUXVFT, '||
           'FN.BDVALVFT, '||
           'FN.BDVALIFT, '||
           'FN.BDIGNREFVFT, '||
           'FN.BDIGNREFAVFT,'||
           'FN.BDIGNVALVFT, '||
           'FN.BDORVERBAFT '||
         'FROM '||
           'VRHF_EMP_TVERBATOMINT FN '||
         'where FN.BDREFTOMADOR = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       if (coalesce(prcontrato, 0) <> 0) then
          wsql = wsql||' and FN.BDCODCONTTI = '||prcontrato;
     END

  wsql = wsql||') FOL '||
         'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = FOL.BDCODVER) '||
         'order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDCODCONTTI, FOL.BDCODVER';

  wempatu     = 0;
  wcolatu     = 0;
  wrefatu     = 0;
  wveratu     = 0;
  wconttiatu  = 0;
  wcompesp    = '';
  wformrefaux = '';
  wformref    = '';
  wformval    = '';
  wrefvsum    = 0;
  wrefauxvsum = 0;
  wrefvmax    = 0;
  wrefauxvmax = 0;
  wvalv       = 0;
  wvaliv      = 0;
  wigref      = '';
  wigrefaux   = '';
  wigval      = '';
  worverba    = -1;

  FOR EXECUTE STATEMENT wsql INTO
    :wcodemp,
    :wcodcol,
    :wreffn,
    :wcodcontti,
    :wcodver,
    :wcompespant,
    :wformrefauxant,
    :wformrefant,
    :wformvalant,
    :wrefvsumant,
    :wrefauxvsumant,
    :wvalvant,
    :wvalivant,
    :wigrefant,
    :wigrefauxant,
    :wigvalant,
    :worverbaant,
    :whoremp,
    :wtiporefver
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF (wrefatu = 0) THEN
         wrefatu = wreffn;

      IF (wveratu = 0) THEN
         wveratu = wcodver;

      IF (wconttiatu = 0) THEN
         wconttiatu = wcodcontti;


      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreffn) OR (wveratu <> wcodver) OR (wconttiatu <> wcodcontti)) THEN
         BEGIN
           BDCODEMP        = wempatu;
           BDCODCOL        = wcolatu;
           BDREFFN         = wrefatu;
           BDCODVER        = wveratu;
           BDCODCONTTI     = wconttiatu;
           BDCOMPESP       = wcompesp;
           BDFORMREFAUX    = wformrefaux;
           BDFORMREF       = wformref;
           BDFORMVAL       = wformval;
           BDREFVFN_SUM    = wrefvsum;
           BDREFAUXVFN_SUM = wrefauxvsum;
           BDREFVFN_MAX    = wrefvmax;
           BDREFAUXVFN_MAX = wrefauxvmax;
           BDVALVFN        = wvalv;
           BDVALVIFN       = wvaliv;
           BDIGNREFVFN     = wigref;
           BDIGNREFAVFN    = wigrefaux;
           BDIGNVALVFN     = wigval;
           BDORVERBA       = worverba;
           SUSPEND;

           wempatu     = wcodemp;
           wcolatu     = wcodcol;
           wrefatu     = wreffn;
           wveratu     = wcodver;
           wconttiatu  = wcodcontti;
           wcompesp    = '';
           wformrefaux = '';
           wformref    = '';
           wformval    = '';
           wrefvsum    = 0;
           wrefauxvsum = 0;
           wrefvmax    = 0;
           wrefauxvmax = 0;
           wvalv       = 0;
           wvaliv      = 0;
           wigref      = '';
           wigrefaux   = '';
           wigval      = '';
           worverba    = -1;
         END

      IF (wcompesp <> '') THEN
         wcompesp = wcompesp||'. ' ;

      wcompesp = SUBSTRING((wcompesp||wcompespant) FROM 1 FOR 300);

      IF (wformrefaux <> '') THEN
         wformrefaux = wformrefaux||'. ' ;

      wformrefaux = SUBSTRING((wformrefaux||wformrefauxant) FROM 1 FOR 5000);

      IF (wformref <> '') THEN
         wformref = wformref||'. ' ;

      wformref = SUBSTRING((wformref||wformrefant) FROM 1 FOR 5000);

      IF (wformval <> '') THEN
         wformval = wformval||'. ' ;

      wformval = SUBSTRING((wformval||wformvalant) FROM 1 FOR 5000);

      -- Converte horas e tipo de refer?ncia da verba ? Horas
      IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvsumant > 0) THEN
         BEGIN
           -- Converte a referencia atual de Horas para Valor
           wfracao      = wrefvsumant - CAST((wrefvsumant - 0.5) AS INTEGER);
           IF (wrefvsumant > 0) THEN
              BEGIN
                wrefvsumant = wrefvsumant - wfracao;
                wfracao     = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsumant = wrefvsumant + wfracao;
              END

           -- Converte a soma atual de Horas para Valor
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END

           -- Soma os VALORES
           wrefvsum = wrefvsum +  wrefvsumant;

           -- Converte o resultado novamente em Horas
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END
         END
      ELSE
         wrefvsum = wrefvsum + wrefvsumant;

      wrefauxvsum = wrefauxvsum + wrefauxvsumant;

      IF (wrefvmax < wrefvsumant) THEN
         wrefvmax    = wrefvsumant;

      IF (wrefauxvmax < wrefauxvsumant) THEN
         wrefauxvmax = wrefauxvsumant;

      wvalv       = wvalv + wvalvant;
      wvaliv      = wvaliv + wvalivant;

      wigref      = wigrefant;
      wigrefaux   = wigrefauxant;
      wigval      = wigvalant;
      worverba    = worverbaant;
    END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wveratu <> 0 and wconttiatu <> 0) THEN
     BEGIN
       BDCODEMP        = wempatu;
       BDCODCOL        = wcolatu;
       BDREFFN         = wrefatu;
       BDCODVER        = wveratu;
       BDCODCONTTI     = wconttiatu;
       BDCOMPESP       = wcompesp;
       BDFORMREFAUX    = wformrefaux;
       BDFORMREF       = wformref;
       BDFORMVAL       = wformval;
       BDREFVFN_SUM    = wrefvsum;
       BDREFAUXVFN_SUM = wrefauxvsum;
       BDREFVFN_MAX    = wrefvmax;
       BDREFAUXVFN_MAX = wrefauxvmax;
       BDVALVFN        = wvalv;
       BDVALVIFN       = wvaliv;
       BDIGNREFVFN     = wigref;
       BDIGNREFAVFN    = wigrefaux;
       BDIGNVALVFN     = wigval;
       BDORVERBA       = worverba;
       SUSPEND;
     END
END
^

/* empty dependent procedure body */
/* Clear: SP_VRHM_FF_OP_REF for: SP_VRHM_FF_OP_ANO */
ALTER PROCEDURE SP_VRHM_FF_OP_REF(PREMP VARCHAR(32000) = '',
PRCOL VARCHAR(32000) = '',
PRREFINI INTEGER = 0,
PRREFFIM INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* Alter (SP_VRHM_FF_OP_ANO) */
ALTER PROCEDURE SP_VRHM_FF_OP_ANO(PREMP VARCHAR(32000) = '',
PRCOL VARCHAR(32000) = '',
PRANO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
declare variable WDATA varchar(10);
declare variable WINI integer;
declare variable WFIM integer;
declare variable WCOMPANT integer;
declare variable WSQL varchar(5000);
declare variable WEMP varchar(20000);
declare variable WCOL varchar(30000);
declare variable WDESPMED numeric(18,6);
declare variable WDESPMEDLANCVALM numeric(18,6);
declare variable WDESPMEDLANCVALC numeric(18,6);
declare variable WSQL2 varchar(5000);
BEGIN
  /* Procedure Text */
--  suspend;
 wIni = CAST(CAST(prano AS VARCHAR(4))||'01' AS INTEGER);
 wfim = CAST(CAST(prano AS VARCHAR(4))||'12' AS INTEGER);
 WCOMPANT = 0;

 IF ((premp IS NULL) OR (premp = '')) THEN
    wemp = 'null';
 ELSE
    wemp = ''''||SUBSTRING(premp FROM 1 FOR 20000)||'''';

 IF ((prcol IS NULL) OR (prcol = '')) THEN
    wcol = 'null';
 ELSE
    wcol = ''''||SUBSTRING(prcol FROM 1 FOR 30000)||'''';


 wsql = ' select a.bdref,a.bdcodemp,a.bdcodcol,a.bddespmed '||
          ' from ('||
              'select * from SP_VRHF_DADOS_IR_DIRF('||wemp||','||wcol||','||wini||','||wfim||') where (BDDESPMED > 0) and BDTIPO < 9000) a ';
 wsql = wsql||' group by a.bdref, a.bdcodemp, a.bdcodcol, a.bddespmed ';
 wsql = wsql||' order by a.bdref';

 FOR EXECUTE STATEMENT wsql INTO
   bdref,bdcodemp,bdcodcol,:wdespmed DO
   BEGIN
     wsql2 = 'select bdnome, bdtipo, bdcodplaconvsau, bdcodoperadora, bdcodconvenio, bdvalormensalidade, bdvalorcopar '||
             'from SP_VRH_CONVSAU_DIRF('||bdcodemp||', '||bdcodcol||', '||bdref||') ';

     for execute statement wsql2 
     into :BDNOME, :BDTIPO, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO
     do
        SUSPEND;

     /*SELECT SUM(COALESCE(BDVALORMENSALIDADE, 0)) BDVALORMENSALIDADE, SUM(COALESCE(BDVALORCOPAR, 0)) BDVALORCOPAR
     FROM VW_VRHM_EMP_VAL_TOD_OP_ATU WHERE bdcodemp = :bdcodemp AND bdcodcol = :bdcodcol 
     GROUP BY BDCODEMP, BDCODCOL INTO wdespmedlancvalm, wdespmedlancvalc;

     IF (wdespmedlancvalm + wdespmedlancvalc = wdespmed) THEN
     BEGIN
       wsql2 = 'SELECT bdnome, bdtipo, b.bdcodplaconvsau, b.bdcodoperadora, b.bdcodconvenio, b.bdvalormensalidade, b.bdvalorcopar '||
               'FROM vw_vrhm_emp_val_tod_op_atu b '||
               'WHERE bdcodemp = '||:bdcodemp||' AND bdcodcol = '||:bdcodcol||' AND ((COALESCE(b.bdvalormensalidade,0) > 0) OR (COALESCE(b.bdvalorcopar,0) > 0))';
     END
     ELSE
     BEGIN
       wsql2 = 'SELECT first 1 bdnome, bdtipo, b.bdcodplaconvsau, b.bdcodoperadora, b.bdcodconvenio, '||:wdespmed||', 0 '||
               'FROM vw_vrhm_emp_val_tod_op_atu b '||
               'WHERE bdcodemp = '||:bdcodemp||' AND bdcodcol = '||:bdcodcol||' AND b.bdtipo < 9000 ';
     END

     FOR EXECUTE STATEMENT wsql2
     INTO bdnome, bdtipo, bdcodplaconvsau, bdcodoperadora, bdcodconvenio, bdmensalidade, bdcoparticipacao DO
       BEGIN
         SUSPEND;
       END      */
   END

 wIni = CAST(CAST(prano AS VARCHAR(4))||'01' AS INTEGER);
 wfim = CAST(CAST(prano AS VARCHAR(4))||'12' AS INTEGER);
 WCOMPANT = 0;

 IF ((premp IS NULL) OR (premp = '')) THEN
    wemp = 'null';
 ELSE
    wemp = ''''||SUBSTRING(premp FROM 1 FOR 20000)||'''';

 IF ((prcol IS NULL) OR (prcol = '')) THEN
    wcol = 'null';
 ELSE
    wcol = ''''||SUBSTRING(prcol FROM 1 FOR 30000)||'''';


 wsql = ' select a.bdref,a.bdcodemp,a.bdcodcol,a.bddespmed '||
          ' from ('||
              'select * from SP_VRHF_DADOS_IR_DIRF('||wemp||','||wcol||','||wini||','||wfim||') where (BDDESPMED > 0) and BDTIPO >= 9000) a ';
 wsql = wsql||' group by a.bdref,a.bdcodemp,a.bdcodcol,a.bddespmed ';
 wsql = wsql||' order by a.bdref';

 FOR EXECUTE STATEMENT wsql INTO
   bdref,bdcodemp,bdcodcol,:wdespmed DO
   BEGIN
     IF (wcompant <> bdref) THEN
        BEGIN
          wData = SUBSTRING(''||:bdref FROM 5 FOR 2)||'/01/'||SUBSTRING(''||:bdref FROM 1 FOR 4);
          EXECUTE PROCEDURE sp_seta_competencia(:bdref,:wData,NULL);
          wcompant = bdref;
        END

     wsql2 = 'select bdnome, 9000, bdcodplaconvsau, bdcodoperadora, bdcodconvenio, bdvalormensalidade, bdvalorcopar '||
             'from SP_VRH_CONVSAU_DIRF('||bdcodemp||', '||bdcodcol||', '||bdref||') ';
     for execute statement wsql2
     into :BDNOME, :BDTIPO, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO
     do
        SUSPEND;


/*     SELECT SUM(COALESCE(BDVALORMENSALIDADE, 0)) BDVALORMENSALIDADE, SUM(COALESCE(BDVALORCOPAR, 0)) BDVALORCOPAR
     FROM VW_VRHM_EMP_VAL_TOD_OP_ATU WHERE bdcodemp = :bdcodemp AND bdcodcol = :bdcodcol 
     GROUP BY BDCODEMP, BDCODCOL INTO wdespmedlancvalm, wdespmedlancvalc;

     IF (wdespmedlancvalm + wdespmedlancvalc = wdespmed) THEN
     BEGIN
       wsql2 = 'SELECT bdnome, 9000, b.bdcodplaconvsau, b.bdcodoperadora, b.bdcodconvenio, b.bdvalormensalidade, b.bdvalorcopar '||
               'FROM vw_vrhm_emp_val_tod_op_atu b '||
               'WHERE bdcodemp = '||:bdcodemp||' AND bdcodcol = '||:bdcodcol||' AND ((COALESCE(b.bdvalormensalidade,0) > 0) OR (COALESCE(b.bdvalorcopar,0) > 0))';
     END
     ELSE
     BEGIN
       wsql2 = 'SELECT first 1 bdnome, 9000, b.bdcodplaconvsau, b.bdcodoperadora, b.bdcodconvenio, '||:wdespmed||', 0 '||
               'FROM vw_vrhm_emp_val_tod_op_atu b '||
               'WHERE bdcodemp = '||:bdcodemp||' AND bdcodcol = '||:bdcodcol||' AND b.bdtipo = 0 '||
               'order by BDNOME, B.BDCODPLACONVSAU, B.BDCODOPERADORA, B.BDCODCONVENIO ';
     END

     FOR EXECUTE STATEMENT wsql2
     INTO bdnome,bdtipo,bdcodplaconvsau, bdcodoperadora, bdcodconvenio,bdmensalidade, bdcoparticipacao DO
       BEGIN
         SUSPEND;
       END       */
   END

END
^

/* Alter (SP_VRHM_FF_OP_REF) */
ALTER PROCEDURE SP_VRHM_FF_OP_REF(PREMP VARCHAR(32000) = '',
PRCOL VARCHAR(32000) = '',
PRREFINI INTEGER = 0,
PRREFFIM INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
DECLARE VARIABLE WANOINI INTEGER;
DECLARE VARIABLE WANOFIM INTEGER;
BEGIN
  /* Procedure Text */

  wAnoIni = CAST(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wAnoFim = CAST(SUBSTRING(CAST(prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  WHILE (wanoini <= wanofim) DO
    BEGIN
      FOR SELECT BDCODEMP, BDCODCOL, BDREF, BDNOME, BDTIPO, BDCODPLACONVSAU, BDCODOPERADORA, BDCODCONVENIO, BDMENSALIDADE, BDCOPARTICIPACAO
      FROM sp_vrhm_ff_op_ano(:premp,:prcol,:wanoini)
         INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDNOME, :BDTIPO, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO DO
        BEGIN
          IF ((bdref >= prrefini) AND (bdref <= prreffim)) THEN
             SUSPEND;

        END



      wanoini = wanoini + 1;
    END

--  suspend;
END
^

/* Alter (SP_VRHM_VAL_PS_COL) */
ALTER PROCEDURE SP_VRHM_VAL_PS_COL(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDREF INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDVALORMENSALIDADE NUMERIC(15,6),
BDVALLORCOPAR NUMERIC(15,6),
BDCODTIPOCONV INTEGER,
BDCODEMP INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WWHERE VARCHAR(30000);
DECLARE VARIABLE WREFINI VARCHAR(6);
DECLARE VARIABLE WREFFIM VARCHAR(6);
DECLARE VARIABLE WAUX VARCHAR(2);
BEGIN
  /* Procedure Text */
--  suspend;
  IF (prcodemp IS NULL) THEN
     prcodemp = '';

  IF (prcodcol IS NULL) THEN
     prcodcol = '';

  IF (prrefini IS NULL) THEN
     prrefini = 0;

  IF (prreffim IS NULL) THEN
     prreffim = prrefini;

  SELECT str FROM strzero(:prrefini,6) INTO wrefini;
  SELECT str FROM strzero(:prreffim,6) INTO wreffim;

  IF (wrefini <> 0) THEN
     BEGIN
       WHILE (wrefini <= wreffim) DO
         BEGIN
           bdref = wrefini;
     
           wsql = ' select x.bdcodplaconvsau,x.bdcodoperadora, x.bdcodconvenio, tab.bdcodemp, tab.bdcodcol, tab.bdnomcol, '||
                  ' coalesce(x.BDVALORMENSALIDADEFUN,0) bdvalormensalidade, x.bdvalorcoparfun bdvalorcopar, y.bdcodtipoconv '||
                  ' from vw_vrh_emp_tcolcon_cad tab '||
                  ' join VW_VRHM_EMP_VAL_COL_OP_ATU x on (tab.bdcodemp = x.bdcodemp and tab.bdcodcol = x.bdcodcol) '||
                  ' join VRH_BASE_CONVENIO_OPERADORAS y on (y.bdcodplaconvsau = x.bdcodplaconvsau and y.bdcodoperadora = x.bdcodoperadora and y.bdcodconvenio = x.bdcodconvenio) ';


           EXECUTE PROCEDURE sp_seta_competencia(:wrefini,NULL,NULL);

           wwhere = '';
           IF (prcodemp <> '') THEN
              BEGIN
                wwhere = wwhere||' where '||prcodemp;

                IF (prcodcol <> '') THEN
                   wwhere = wwhere||' and '||prcodcol;
              END

           wsql = wsql||wwhere;

           FOR EXECUTE STATEMENT wsql INTO
             :bdcodplaconvsau,
             :bdcodoperadora,
             :bdcodconvenio,
             :bdcodemp,
             :bdcodcol,
             :bdnomcol,
             :bdvalormensalidade,
             :bdvallorcopar,
             :bdcodtipoconv DO
             BEGIN
               SUSPEND;
             END


           --suspend;
           IF (SUBSTRING(wrefini FROM 5 FOR 2) = '12') THEN
              BEGIN
                wrefini = (CAST(SUBSTRING(wrefini FROM 1 FOR 4) AS INTEGER)+1)||'01';
              END
           ELSE
              BEGIN
                waux = (CAST(SUBSTRING(wrefini FROM 5 FOR 2) AS INTEGER)+1);
                wrefini = SUBSTRING(wrefini FROM 1 FOR 4);

                IF (CAST(waux AS INTEGER) >= 10) THEN
                   wrefini = wrefini||waux;
                ELSE
                   wrefini = wrefini||'0'||waux;
              END
         END
     END
END
^

/* Alter (SP_VRHM_VAL_PS_DEP) */
ALTER PROCEDURE SP_VRHM_VAL_PS_DEP(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDREF INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDVALORMENSALIDADE NUMERIC(15,6),
BDVALLORCOPAR NUMERIC(15,6),
BDCODEMP INTEGER,
BDCODDPN INTEGER,
BDNOMDEP VARCHAR(70))
 AS
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(30000);
declare variable WREFINI varchar(6);
declare variable WREFFIM varchar(6);
declare variable WAUX varchar(2);
BEGIN
  /* Procedure Text */
--  suspend;
  IF (prcodemp IS NULL) THEN
     prcodemp = '';

  IF (prcodcol IS NULL) THEN
     prcodcol = '';

  IF (prrefini IS NULL) THEN
     prrefini = 0;

  IF (prreffim IS NULL) THEN
     prreffim = prrefini;

  SELECT str FROM strzero(:prrefini,6) INTO wrefini;
  SELECT str FROM strzero(:prreffim,6) INTO wreffim;

  IF (wrefini <> 0) THEN
     BEGIN
       WHILE (wrefini <= wreffim) DO
         BEGIN
           bdref = wrefini;
     
           wsql = ' select tab.bdcodemp, tab.bdcodcol, tab.bdcoddpn, tab.bdcodplaconvsau, '||
                  ' tab.bdcodoperadora,tab.bdcodconvenio, men.bdmensalidade, '||
                  ' coalesce(x.bdvalorcopardep,0) bdvalorcopardep, col.bdnomcol, dep.bdnomedpn '||
                  ' from VW_VRHM_EMP_VINC_DEP_CONV_ATU tab '||
                  ' left outer join VW_VRH_EMP_TCOLCON_CAD col on (tab.bdcodemp = col.bdcodemp and tab.bdcodcol = col.bdcodcol) '||
                  ' join vw_vrh_emp_tdep_ref dep on (tab.bdcodemp = dep.bdcodemp and tab.bdcodcol = dep.bdcodcol and tab.bdcoddpn = dep.bdcoddpn) '||
                  ' left outer join VW_VRHM_EMP_DEP_COP_OP_SAU x on (x.bdcodemp = tab.bdcodemp and x.bdcodcol = tab.bdcodcol and x.bdcodconvenio = tab.bdcodconvenio and x.bdcoddpn = tab.bdcoddpn) '||
                  ' join VW_VRHM_EMP_DEP_VAL_OP_SAU men on (men.bdcodemp = tab.bdcodemp and men.bdcodcol = tab.bdcodcol and men.bdcoddpn = tab.bdcoddpn and men.bdcodconvenio = tab.bdcodconvenio) ';


           EXECUTE PROCEDURE sp_seta_competencia(:wrefini,NULL,NULL);

           wwhere = '';
           IF (prcodemp <> '') THEN
              BEGIN
                wwhere = wwhere||' where '||prcodemp;

                IF (prcodcol <> '') THEN
                   wwhere = wwhere||' and '||prcodcol;
              END

           wsql = wsql||wwhere;

           FOR EXECUTE STATEMENT wsql INTO
             :bdcodemp,
             :bdcodcol,
             :bdcoddpn,
             :bdcodplaconvsau,
             :bdcodoperadora,
             :bdcodconvenio,
             :bdvalormensalidade,
             :bdvallorcopar,
             :bdnomcol,
             :bdnomdep DO
             BEGIN
               SUSPEND;
             END


           --suspend;
           IF (SUBSTRING(wrefini FROM 5 FOR 2) = '12') THEN
              BEGIN
                wrefini = (CAST(SUBSTRING(wrefini FROM 1 FOR 4) AS INTEGER)+1)||'01';
              END
           ELSE
              BEGIN
                waux = (CAST(SUBSTRING(wrefini FROM 5 FOR 2) AS INTEGER)+1);
                wrefini = SUBSTRING(wrefini FROM 1 FOR 4);

                IF (CAST(waux AS INTEGER) >= 10) THEN
                   wrefini = wrefini||waux;
                ELSE
                   wrefini = wrefini||'0'||waux;
              END
         END
     END
END
^

/* Alter (SPCODIMPGPSCOMPLEMENTAR) */
ALTER PROCEDURE SPCODIMPGPSCOMPLEMENTAR(PRCODEMP VARCHAR(32000),
PRREF INTEGER,
PRREFPAG INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTIPOFC INTEGER,
BDCODIMP INTEGER,
BDCODMATRIZ INTEGER,
BDEMPIMP INTEGER)
 AS
DECLARE VARIABLE WSQLCALC VARCHAR(32000);
DECLARE VARIABLE WSQLIMP VARCHAR(3000);
DECLARE VARIABLE WWHEREEMP VARCHAR(3000);
BEGIN
  /* Procedure Text */
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     wwhereemp = ' and '||prcodemp;

  wsqlcalc = 'select emp.bdcodemp,emp.bdcodtipofc from vrhf_emp_tfolhacomp emp '||
             ' where emp.bdreffn = '||prref||' and emp.bdrefcomp = '||prrefpag||wwhereemp||
             ' union '||
             ' select emp.bdcodemp,emp.bdcodtipofc from vrhf_emp_tfoltomcomp emp '||
             ' where emp.bdreftomador = '||prref||' and emp.bdrefcomp = '||prrefpag||wwhereemp;

  EXECUTE PROCEDURE sp_seta_competencia(:prref,NULL,NULL);

  FOR EXECUTE STATEMENT wsqlcalc INTO bdcodemp, bdcodtipofc DO
    BEGIN
      bdcodimp = NULL;
      bdcodmatriz = NULL;
      bdempimp = NULL;

      /* Verifica se existe um imposto para GPS complementar de dissidio e conven??o */
      IF ((COALESCE(bdcodtipofc,1)) <> 1) THEN
         BEGIN
           wsqlimp = ' select first 1 impemp.bdcodemp bdempimp, emp.bdcodmatriz, impemp.bdcodimp '||
                     ' from tempresas emp '||
                     ' join vw_tempresaimpostoref impemp on ((impemp.bdcodemp in (emp.bdcodemp,emp.bdcodmatriz)) and impemp.BDDOCARRECADACAO = 12) '||
                     ' where emp.bdcodemp = '||bdcodemp||' and impemp.BDGPSPRINCIPAL <> '||'''TRUE'''||' and impemp.BDTIPOIMPDOC = 23 ';

           EXECUTE STATEMENT wsqlimp INTO bdempimp,bdcodmatriz,bdcodimp;

           IF (bdcodimp = 0) THEN
              bdcodimp = NULL;
         END

      /* Verifica o codigo da gps padrao */
      IF (bdcodimp IS NULL) THEN
         BEGIN
           wsqlimp = ' select first 1 impemp.bdcodemp bdempimp, emp.bdcodmatriz, impemp.bdcodimp '||
                     ' from tempresas emp '||
                     ' join vw_tempresaimpostoref impemp on ((impemp.bdcodemp in (emp.bdcodemp,emp.bdcodmatriz)) and impemp.BDDOCARRECADACAO = 12) '||
                     ' where emp.bdcodemp = '||bdcodemp||' and impemp.BDGPSPRINCIPAL = '||'''TRUE''';

           EXECUTE STATEMENT wsqlimp INTO bdempimp,bdcodmatriz,bdcodimp;

           IF (bdcodimp = 0) THEN
              bdcodimp = NULL;
         END


      IF (bdcodimp IS NOT NULL) THEN
         SUSPEND;
    END

--  suspend;
END
^

/* empty dependent procedure body */
/* Clear: SPCORRIGEACENTOS for: SPCORACENTOS */
ALTER PROCEDURE SPCORRIGEACENTOS AS
 BEGIN EXIT; END
^

/* Alter (SPCORACENTOS) */
ALTER PROCEDURE SPCORACENTOS(PRTXT VARCHAR(1000))
 RETURNS(BDTXT VARCHAR(1000))
 AS
BEGIN
  /* Procedure Text */

  bdtxt = REPLACE(prtxt,'çã','??');
  bdtxt = REPLACE(bdtxt,'ó','?');
  bdtxt = REPLACE(bdtxt,'ã','?');
  bdtxt = REPLACE(bdtxt,'í','?');
  bdtxt = REPLACE(bdtxt,'é','?');
  bdtxt = REPLACE(bdtxt,'ê','?');
  bdtxt = REPLACE(bdtxt,'º','?');
  bdtxt = REPLACE(bdtxt,'á','?');
  bdtxt = REPLACE(bdtxt,'ú','?');
  bdtxt = REPLACE(bdtxt,'ç','?');

  SUSPEND;
END
^

/* Alter (SPCORRIGEACENTOS) */
ALTER PROCEDURE SPCORRIGEACENTOS AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WNOME VARCHAR(1000);
DECLARE VARIABLE WDESC VARCHAR(1000);
DECLARE VARIABLE WFIELD VARCHAR(1000);
BEGIN
  /* Procedure Text */
  wsql = 'select rdb$relation_name "NOME", rdb$description "DESC" from rdb$relations'||
         ' where rdb$description is not null';

  FOR EXECUTE STATEMENT wsql INTO
    wnome,
    wdesc
  DO
    BEGIN
      SELECT bdtxt FROM SPCORACENTOS(:wdesc) INTO wdesc;
      UPDATE rdb$relations SET rdb$description = :wdesc WHERE rdb$relation_name = :wnome;
    END

  wsql = 'select RDB$FIELD_NAME,RDB$RELATION_NAME,rdb$description from RDB$RELATION_FIELDS'||
         ' where rdb$description is not null';

  FOR EXECUTE STATEMENT wsql INTO
    wfield,
    wnome,
    wdesc
  DO
    BEGIN
      SELECT bdtxt FROM SPCORACENTOS(:wdesc) INTO wdesc;
      UPDATE RDB$RELATION_FIELDS SET rdb$description = :wdesc WHERE rdb$relation_name = :wnome AND RDB$FIELD_NAME  = :wfield;
    END

--  suspend;
END
^

/* Alter (SPRH_CALC_13SALARIO) */
ALTER PROCEDURE SPRH_CALC_13SALARIO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'S13.BDCODEMP, '||
               'S13.BDCODCOL, '||
               'S13.BDCODVER, '||
               'S13.BDREF13, '||
               'S13.BDREFV13, '||
               'S13.BDREFV13, '||
               'S13.BDREFAUXV13, '||
               'S13.BDREFAUXV13, '||
               'S13.BDVALV13, '||
               'S13.BDIGNREFV13, '||
               'S13.BDIGNREFAV13, '||
               'S13.BDIGNVALV13, '||
               'S13.BDORVERBA13, '||
               'EMPREF.BDREFHOREMP, '||
               'FS13.BDDATABAIXA13, '||
               'FS13.BDBASEFGTS13, '||
               'FS13.BDFGTS13, '||
               'FS13.BDFGTSCS13, '||
               '0.0 BDBFGTS13_, '||
               '0.0 BDFGTS13_, '||
               '0.0 BDFGTSCS13_, '||
               '0.0 BDMAIORREM13, '||
               'FS13.BDBASEINSS13, '||
               'FS13.BDPERCINSS13, '||
               'FS13.BDVALORINSS13, '||
               'FS13.BDBASEIR13, '||
               'FS13.BDPERCIR13, '||
               'FS13.BDVALORIR13, '||
               '0.0 BDBINSS1313, '||
               '0.0 BDALIQINSS1313, '||
               '0.0 BDINSS1313, '||
               '0.0 BDBASEIR1313, '||
               '0.0 BDPERCIR1313, '||
               '0.0 BDVALORIR1313, '||
               '0.0 BDBSALFAM1313, '||
               '0.0 BDSALFAM1313, '||
               'FS13.BDBRAIS13, '||
               'FS13.BDSALBASE13, '||
               'FS13.BDDEP13, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               'FS13.BDCREDITO13, '||
               'FS13.BDDEBITO13, '||
               'S13.BDCOMPESP, '||
               'S13.BDFORMREFAUX, '||
               'S13.BDFORMREF, '||
               'S13.BDFORMVAL ';

  wsql = wsql||'from VRHF_EMP_TVERBA13 S13, '||
               'VW_VRHF_BASE_TEMPCALC EMPREF, '||
               'VRHF_EMP_T13SAL FS13 ';

  wsql = wsql||'where EMPREF.BDCODEMP = S13.BDCODEMP and FS13.BDCODEMP = S13.BDCODEMP and FS13.BDCODCOL = S13.BDCODCOL and FS13.BDREF13 = S13.BDREF13 and '||
               'S13.BDCODEMP = '||PRCODEMP||' and S13.BDCODCOL = '||PRCODCOL||' and S13.BDREF13 = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, S13.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SPRH_CALC_AD13SALARIO) */
ALTER PROCEDURE SPRH_CALC_AD13SALARIO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'A13.BDCODEMP, '||
               'A13.BDCODCOL, '||
               'A13.BDCODVER, '||
               'A13.BDREFA13, '||
               'A13.BDREFVA13, '||
               'A13.BDREFVA13, '||
               'A13.BDREFAUXVA13, '||
               'A13.BDREFAUXVA13, '||
               'A13.BDVALVA13, '||
               'A13.BDIGNREFVA13, '||
               'A13.BDIGNREFAVA13, '||
               'A13.BDIGNVALVA13, '||
               'A13.BDORVERBAA13, '||
               'EMPREF.BDREFHOREMP, '||
               'FA13.BDDATABAIXAA13, '||
               '0.0 BDBFGTSA13, '||
               '0.0 BDFGTSA13, '||
               '0.0 BDFGTSCSA13, '||
               'FA13.BDBASEFGTSA13, '||
               'FA13.BDFGTSA13, '||
               'FA13.BDFGTSCSA13, '||
               '0.0 BDMAIORREMA13, '||
               '0.0 BDBINSSA13, '||
               '0.0 BDALIQINSSA13, '||
               '0.0 BDINSSA13, '||
               '0.0 BDBIRRFA13, '||
               '0.0 BDALIQIRRFA13, '||
               '0.0 BDIRRFA13, '||
               '0.0 BDBINSS13A13, '||
               '0.0 BDALIQINSS13A13, '||
               '0.0 BDINSS13A13, '||
               'FA13.BDBASEIRA13, '||
               'FA13.BDPERCIRA13, '||
               'FA13.BDVALORIRA13, '||
               'FA13.BDBSALFAMA13, '||
               'FA13.BDSALFAMA13, '||
               'FA13.BDBRAISA13, '||
               'FA13.BDSALBASEA13, '||
               'FA13.BDDEPA13, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               'FA13.BDCREDITOA13, '||
               'FA13.BDDEBITOA13, '||
               'A13.BDCOMPESP, '||
               'A13.BDFORMREFAUX, '||
               'A13.BDFORMREF, '||
               'A13.BDFORMVAL ';

  wsql = wsql||'from VRHF_EMP_TVERBAA13 A13, '||
               'VW_VRHF_BASE_TEMPCALC EMPREF, '||
               'VRHF_EMP_TA13SAL FA13 ';

  wsql = wsql||'where EMPREF.BDCODEMP = A13.BDCODEMP and FA13.BDCODEMP = A13.BDCODEMP and FA13.BDCODCOL = A13.BDCODCOL and FA13.BDREFA13 = A13.BDREFA13 '||
               ' and A13.BDCODEMP = '||PRCODEMP||' and A13.BDCODCOL = '||PRCODCOL||' and A13.BDREFA13 = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, A13.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SPRH_CALC_ADSAL) */
ALTER PROCEDURE SPRH_CALC_ADSAL(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDDATAAD DATE,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'ASAL.BDCODEMP, '||
               'ASAL.BDCODCOL, '||
               'ASAL.BDCODVER, '||
               'FASAL.BDREFAD, '||
               'ASAL.BDDATAAD, '||
               'ASAL.BDREFVAD, '||
               'ASAL.BDREFVAD, '||
               'ASAL.BDREFAUXVAD, '||
               'ASAL.BDREFAUXVAD, '||
               'ASAL.BDVALVAD, '||
               'ASAL.BDIGNREFVAD, '||
               'ASAL.BDIGNREFAVAD, '||
               'ASAL.BDIGNVALVAD, '||
               'ASAL.BDORVERBAAD, '||
               'EMPREF.BDREFHOREMP, '||
               'FASAL.BDDATABAIXAAD, '||
               '0.0 BDBFGTSA13, '||
               '0.0 BDFGTSA13, '||
               '0.0 BDFGTSCSA13, '||
               '0.0 BDBASEFGTSA13, '||
               '0.0 BDFGTSA13, '||
               '0.0 BDFGTSCSA13, '||
               '0.0 BDMAIORREMA13, '||
               '0.0 BDBINSSA13, '||
               '0.0 BDALIQINSSA13, '||
               '0.0 BDINSSA13, '||
               'FASAL.BDBASEIRAD, '||
               'FASAL.BDPERCIRAD, '||
               'FASAL.BDVALORIRAD, '||
               '0.0 BDBINSS13A13, '||
               '0.0 BDALIQINSS13A13, '||
               '0.0 BDINSS13A13, '||
               '0.0 BDBIRRFA13, '||
               '0.0 BDALIQIRRFA13, '||
               '0.0 BDIRRFA13, '||
               '0.0 BDBSALFAMA13, '||
               '0.0 BDSALFAMA13, '||
               '0.0 BDBRAISA13, '||
               'FASAL.BDSALBASEAD, '||
               'FASAL.BDDEPIRAD, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               'FASAL.BDCREDITOAD, '||
               'FASAL.BDDEBITOAD, '||
               'ASAL.BDCOMPESP, '||
               'ASAL.BDFORMREFAUX, '||
               'ASAL.BDFORMREF, '||
               'ASAL.BDFORMVAL ';

  wsql = wsql||'from VRHF_EMP_TVERBAAD ASAL, '||
               'VW_VRHF_BASE_TEMPCALC EMPREF, '||
               'VRHF_EMP_TADSAL FASAL ';

  wsql = wsql||'where EMPREF.BDCODEMP = ASAL.BDCODEMP and FASAL.BDCODEMP = ASAL.BDCODEMP and FASAL.BDCODCOL = ASAL.BDCODCOL and FASAL.BDDATAAD = ASAL.BDDATAAD '||
               ' and ASAL.BDCODEMP = '||PRCODEMP||' and ASAL.BDCODCOL = '||PRCODCOL||' and FASAL.BDREFAD = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, A13.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDDATAAD,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SPRH_CALC_AUTONOMO) */
ALTER PROCEDURE SPRH_CALC_AUTONOMO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER,
PRCODSERV INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
/*01*/  wsql = wsql||'FN.BDCODEMP, '||
/*02*/               'FN.BDCODTER, '||
/*03*/               'FN.BDCODVER, '||
/*04*/               'FN.BDCODSERV, '||
/*05*/               'FN.BDREFERENCIA, '||
                     'FN.BDREFERENCIA, '||
/*06*/               'FN.BDREFAUXILIAR, '||
                     'FN.BDREFAUXILIAR, '||
/*07*/               'FN.BDVALOR, '||
/*08*/               'FN.BDIGNFORREF, '||
                     'FN.BDIGNFORREFA, '||
/*09*/               'FN.BDIGNFORVAL, '||
                     'FN.BDORVERBATERC, '||
/*40*/               'EMPREF.BDREFHOREMP, '||
/*41*/               'SERV.BDDATABAIXA,'||/*'FOLN.BDDATABAIXAFN, '|| /*CRIAR CAMPO TABELA*/
/*42*/               '0.0, '|| /*FOLN.BDBFGTSFN*/
/*43*/               '0.0, '|| /*FOLN.BDFGTSFN*/
/*44*/               '0.0, '|| /*FOLN.BDFGTSCSFN*/
/*45*/               '0.0, '|| /*FOLN.BDBFGTS13FN*/
/*46*/               '0.0, '|| /*FOLN.BDFGTS13FN*/
/*47*/               '0.0, '|| /*FOLN.BDFGTS13CSFN*/
/*48*/               '0.0, '|| /*FOLN.BDMAIORREMFN*/
/*49*/               'FOLN.BDBASEINSS, '||
/*50*/               'FOLN.BDFAIXAINSS, '||
/*51*/               'FOLN.BDVALORINSS, '||
/*52*/               'FOLN.BDBASEIR, '||
/*53*/               'FOLN.BDFAIXAIR, '||
/*54*/               'FOLN.BDVALORIR, '||
/*55*/               '0.0, '|| /*FOLN.BDBINSS13FN*/
/*56*/               '0.0, '|| /*FOLN.BDALIQINSS13FN*/
/*57*/               '0.0, '|| /*FOLN.BDINSS13FN*/
/*58*/               '0.0, '|| /*FOLN.BDBIRRF13FN*/
/*59*/               '0.0, '|| /*FOLN.BDALIQIRRF13FN*/
/*60*/               '0.0, '|| /*FOLN.BDIRRF13FN*/
/*61*/               '0.0, '|| /*FOLN.BDBSALFAMFN*/
/*62*/               '0.0, '|| /*FOLN.BDSALFAMFN*/
/*63*/               '0.0, '|| /*FOLN.BDBRAISFN*/
/*64*/               'SERV.BDVALORSERV, '||
/*65*/               'FOLN.BDVALORDEP, '||
/*67*/               '0.0, '|| /*FOLN.BDBINSSFEFOLFN*/
/*68*/               '0.0, '|| /*FOLN.BDINSSFEFOLFN*/
/*69*/               '0.0, '|| /*FOLN.BDALIQINSSFEFOLFN*/
/*70*/               'FOLN.BDCREDITOSERV, '||
/*71*/               'FOLN.BDDEBITOSERV, '||
                     'FN.BDCOMPESP, '||
                     'FN.BDFORMREFAUX, '||
                     'FN.BDFORMREF, '||
                     'FN.BDFORMVAL ';

  wsql = wsql||'from VRHF_BASE_ITEMS_CALCTERC FN, '|| /*OK*/
                  'VRH_BASE_TSERVTERC SERV, '||
                  'VW_VRHF_EMPRESAS_REF_ATUAL EMPREF, '|| /*OK*/
                  'VRHF_BASE_CALC_TERC FOLN '; /*OK*/

  wwhere = ' where SERV.BDCODEMP = FN.BDCODEMP and SERV.BDCODTER = FN.BDCODTER and SERV.BDCODSERV = FN.BDCODSERV and EMPREF.BDCODEMP = FN.BDCODEMP '||
           ' and FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODTER = FN.BDCODTER and FOLN.BDCODSERV = FN.BDCODSERV ';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere||' and FN.BDCODEMP = '||PRCODEMP;

  IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
     wwhere = wwhere||' and FN.BDCODTER = '||PRCODCOL;

  IF (prcodserv IS NOT NULL AND prcodserv <> 0) THEN
     wwhere = wwhere||' and FN.BDCODSERV = '||prcodserv;

  IF (prreferencia IS NOT NULL AND prreferencia <> 0) THEN
     wwhere = wwhere||' and (select bdaaaamm from aaaamm(SERV.bddataserv) ) = '||prreferencia;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SPRH_CALC_COMP13SALARIO) */
ALTER PROCEDURE SPRH_CALC_COMP13SALARIO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'C13.BDCODEMP, '||
               'C13.BDCODCOL, '||
               'C13.BDCODVER, '||
               'C13.BDREFC13, '||
               'C13.BDREFVC13, '||
               'C13.BDREFVC13, '||
               'C13.BDREFAUXVC13, '||
               'C13.BDREFAUXVC13, '||
               'C13.BDVALVC13, '||
               'C13.BDIGNREFVC13, '||
               'C13.BDIGNREFAVC13, '||
               'C13.BDIGNVALVC13, '||
               'C13.BDORVERBAC13, '||
               'EMPREF.BDREFHOREMP, '||
               'FC13.BDDATABAIXAC13, '||
               'FC13.BDBASEFGTSC13, '||
               'FC13.BDFGTSC13, '||
               'FC13.BDFGTSCSC13, '||
               '0.0 BDBFGTS13_, '||
               '0.0 BDFGTS13_, '||
               '0.0 BDFGTSCS13_, '||
               '0.0 BDMAIORREM13, '||
               'FC13.BDBASEINSSC13, '||
               'FC13.BDPERCINSSC13, '||
               'FC13.BDVALORINSSC13, '||
               'FC13.BDBASEIRC13, '||
               'FC13.BDPERCIRC13, '||
               'FC13.BDVALORIRC13, '||
               '0.0 BDBINSS1313, '||
               '0.0 BDALIQINSS1313, '||
               '0.0 BDINSS1313, '||
               '0.0 BDBASEIR1313, '||
               '0.0 BDPERCIR1313, '||
               '0.0 BDVALORIR1313, '||
               'BDBSALFAMC13, '||
               'BDSALFAMC13, '||
               'FC13.BDBRAISC13, '||
               'FC13.BDSALBASEC13, '||
               'S13.BDDEP13, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               'FC13.BDCREDITOC13, '||
               'FC13.BDDEBITOC13, '||
               'C13.BDCOMPESP, '||
               'C13.BDFORMREFAUX, '||
               'C13.BDFORMREF, '||
               'C13.BDFORMVAL ';

  wsql = wsql||'from VRHF_EMP_TVERBAC13 C13, '||
               'VW_VRHF_BASE_TEMPCALC EMPREF, '||
               'VRHF_EMP_TC13SAL FC13, '||
               'VRHF_EMP_T13SAL S13 ';

  wsql = wsql||'where EMPREF.BDCODEMP = C13.BDCODEMP and FC13.BDCODEMP = C13.BDCODEMP and FC13.BDCODCOL = C13.BDCODCOL and FC13.BDREF13 = C13.BDREF13 and '||
               'FC13.BDREFC13 = C13.BDREFC13 and C13.BDCODEMP = S13.BDCODEMP and C13.BDCODCOL = S13.BDCODCOL and C13.BDREF13 = S13.BDREF13 and '||
               'C13.BDCODEMP = '||PRCODEMP||' and C13.BDCODCOL = '||PRCODCOL||' and C13.BDREFC13 = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, C13.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SPRH_CALC_FERIAS) */
ALTER PROCEDURE SPRH_CALC_FERIAS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODFE INTEGER,
PRINIPERAQUISFE DATE,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDREFFN INTEGER,
BDCODFE INTEGER,
BDINIPERAQUISFE DATE,
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDBASEIROUT NUMERIC(15,6),
BDVALORIROUT NUMERIC(15,6),
BDDEPIROUT NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'FE.BDCODEMP, '||
               'FE.BDCODCOL, '||
               'FE.BDCODVER, '||
               'FE.BDREFVFE, '||
               'FE.BDREFVFE, '||
               'FE.BDREFAUXVFE, '||
               'FE.BDREFAUXVFE, '||
               'FE.BDVALVFE, '||
               'FE.BDIGNREFVFE, '||
               'FE.BDIGNREFAVFE, '||
               'FE.BDIGNVALVFE, '||
               'FE.BDORVERBAFE, '||
               'EMPREF.BDREFHOREMP, '||
               'FE.BDDATABAIXAFE, '||
               'FE.BDBASEFGTSFE, '||
               'FE.BDVALORFGTSFE, '||
               'FE.BDVALORFGTSCSFE, '||
               'FE.BDBFGTS13, '||
               'FE.BDFGTS13, '||
               '0.0 BDAPE03, '||
               'FE.BDMAIORREMFE, '||
               'FE.BDBASEINSSFE, '||
               'FE.BDALIQINSSFE, '||
               'FE.BDVALORINSSFE, '||
               'FE.BDBASEIRFE, '||
               'FE.BDALIQIRFE, '||
               'FE.BDVALORIRFE, '||
               '0.0 BDAPE04, '||
               '0.0 BDAPE05, '||
               '0.0 BDAPE06, '||
               '0.0 BDAPE07, '||
               '0.0 BDAPE08, '||
               '0.0 BDAPE09, '||
               'FE.BDBSALFAMFE, '||
               'FE.BDSALFAMFE, '||
               '0.0 BDAPE10, '||
               'FE.BDSALBASEFE, '||
               'FE.BDDEPFE, '||
               'FE.BDDETALHE, '||
               'FE.BDREFFN, '||
               'FE.BDCODFE, '||
               'FE.BDINIPERAQUISFE, '||
               '0.0 BDAPE11, '||
               '0.0 BDAPE12, '||
               '0.0 BDAPE13, '||
               'FE.BDBASEIROUTFE, '||
               'FE.BDVALORIROUTFE, '||
               'FE.BDDEPIROUTFE, '||
               'FE.BDCREDITOFE, '||
               'FE.BDDEBITOFE, '||
               'FE.BDCOMPESP, '||
               'FE.BDFORMREFAUX, '||
               'FE.BDFORMREF, '||
               'FE.BDFORMVAL ';

  wsql = wsql||'from VW_VRHF_EMP_FERIAS FE, '||
                    'VW_VRHF_BASE_TEMPCALC EMPREF ';

  wwhere = ' where EMPREF.BDCODEMP = FE.BDCODEMP ';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wwhere||' and '||PRCODEMP;

  IF (prcodcol IS NOT NULL) THEN
     wwhere = wwhere||' and '||PRCODCOL;

  IF (prcodfe IS NOT NULL AND prcodfe <> 0) THEN
     wwhere = wwhere||' and FE.BDCODFE = '||PRCODFE;

  IF (priniperaquisfe IS NOT NULL) THEN
     wwhere = wwhere||' and FE.BDINIPERAQUISFE = '||''''||priniperaquisfe||'''';


  wsql = wsql||wwhere;

--  wsql = wsql||' order by RVA.BDTIPOCODVER, FE.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDREFFN,
    :BDCODFE,
    :BDINIPERAQUISFE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDBASEIROUT,
    :BDVALORIROUT,
    :BDDEPIROUT,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SPRH_CALC_FOLHACOMP) */
ALTER PROCEDURE SPRH_CALC_FOLHACOMP(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'FC.BDCODEMP, '||
               'FC.BDCODCOL, '||
               'FC.BDCODVER, '||
               'FC.BDREFFN, '||
               'FC.BDREFVFN_MAX, '||
               'FC.BDREFVFN_SUM, '||
               'FC.BDREFAUXVFN_MAX, '||
               'FC.BDREFAUXVFN_SUM, '||
               'FC.BDVALVFN, '||
               'FC.BDIGNREFVFN, '||
               'FC.BDIGNVALVFN, '||
               'FC.BDORVERBAFC, '||
               'EMPREF.BDREFHOREMP, '||
               'FOLC.BDDATABAIXA, '||
               'FOLC.BDBFGTS, '||
               'FOLC.BDFGTS, '||
               'FOLC.BDFGTSCS, '||
               'FOLC.BDBFGTS13, '||
               'FOLC.BDFGTS13, '||
               'FOLC.BDFGTS13CS, '||
               'FOLC.BDMAIORREM, '||
               'FOLC.BDBINSS, '||
               'FOLC.BDALIQINSS, '||
               'FOLC.BDINSS, '||
               'FOLC.BDBIRRF, '||
               'FOLC.BDALIQIRRF, '||
               'FOLC.BDIRRF, '||
               'FOLC.BDBINSS13, '||
               'FOLC.BDALIQINSS13, '||
               'FOLC.BDINSS13, '||
               'FOLC.BDBIRRF13, '||
               'FOLC.BDALIQIRRF13, '||
               'FOLC.BDIRRF13, '||
               'FOLC.BDBSALFAM, '||
               'FOLC.BDSALFAM, '||
               'FOLC.BDBRAIS, '||
               'FOLC.BDSALBASE, '||
               'FOLC.BDDEP, '||
               '''Competencia: '''||'||substring(FC.BDREFFN from 5 for 2)||'||'''/'''||'||substring(FC.BDREFFN from 1 for 4) BDDETALHE, '||
               'FOLC.BDBINSSFEFOL, '||
               'FOLC.BDINSSFEFOL, '||
               'FOLC.BDALIQINSSFEFOL, '||
               'FOLC.BDCREDITO, '||
               'FOLC.BDDEBITO, '||
               'FC.BDCOMPESP, '||
               'FC.BDFORMREFAUX, '||
               'FC.BDFORMREF, '||
               'FC.BDFORMVAL ';

  wsql = wsql||'from VWRH_UNION_FC_FCT_MES FC, '||
               'VW_VRHF_BASE_TEMPCALC EMPREF, '||
               'VWRH_UNION_FC_FCT_MES_BASES FOLC ';

  wsql = wsql||'where EMPREF.BDCODEMP = FC.BDCODEMP and FOLC.BDCODEMP = FC.BDCODEMP and FOLC.BDCODCOL = FC.BDCODCOL and FOLC.BDREFFN = FC.BDREFFN and '||
               'FC.BDCODEMP = '||PRCODEMP||' and FC.BDCODCOL = '||PRCODCOL||' and FC.BDREFFN = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, FC.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SPRH_CONS_CALC_13SALARIO) */
ALTER PROCEDURE SPRH_CONS_CALC_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wsql = :PRANOMES;
  ELSE
     wsql = :PRANO||'12';

  EXECUTE PROCEDURE sp_seta_competencia(CAST(wsql AS INTEGER), NULL, NULL);

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERREF.BDDESCVER, '||
                'VERREF.bddescredver, '||
                'GRUPOVERBAS.BDREFV13, '||
                'GRUPOVERBAS.BDREFAUXV13, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALV13 '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALV13 '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFAV13, '||
                'GRUPOVERBAS.BDIGNREFV13, '||
                'GRUPOVERBAS.BDIGNVALV13, '||
                'VERREF.BDCLAVER, '||
                'VERREF.BDORDEMVER, '||
                'GRUPOVERBAS.BDREF13, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDMESESPROP13, '||
                'Y.BDBASEIR13, '||
                'Y.BDBASEFGTS13, '||
                'Y.BDFGTS13, '||
                'Y.BDFGTSCS13, '||
                'Y.BDDATABAIXA13, '||
                'Y.BDREFBAIXA13, '||
                'Y.BDPERCIR13, '||
                'Y.BDVALORIR13, '||
                'Y.BDBASEINSS13, '||
                'Y.BDPERCINSS13, '||
                'Y.BDVALORINSS13, '||
                'Y.BDSALBASE13, '||
                'Y.BDDEP13, '||
                'Y.BDCREDITO13, '||
                'Y.BDDEBITO13 '||
         'from vrhf_emp_tverba13 GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL, '||
         'VW_TVERBAS_REF VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_EMP_T13SAL Y ';

  wwhere = 'where GRUPOVERBAS.BDCODEMP = EMP.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER '||
           'and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREF13 = GRUPOVERBAS.BDREF13 and '||
           'GRUPOVERBAS.BDREF13 = '||:PRANOMES||' ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :bddescredver,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFAV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :bdmesesprop13,
    :bdbaseir13,
    :bdbasefgts13,
    :bdfgts,
    :bdfgtscs13,
    :bddatabaixa13,
    :bdrefbaixa13,
    :bdpercir13,
    :bdirrf,
    :bdbaseinss13,
    :bdpercinss13,
    :bdinss,
    :BDSALBASE,
    :bddep,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;
END
^

/* Alter (SPRH_CONS_CALC_AD13SALARIO) */
ALTER PROCEDURE SPRH_CONS_CALC_AD13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDPERC NUMERIC(15,6),
BDVAL NUMERIC(15,6),
BDTIPOPROP INTEGER,
BDMESESPROP INTEGER,
BDBASEIR NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBASEFGTS NUMERIC(15,6),
BDDATABAIXA DATE,
BDREFBAIXA INTEGER,
BDPERCIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERREF.BDDESCVER, '||
                'VERREF.bddescredver, '||
                'GRUPOVERBAS.BDREFVA13, '||
                'GRUPOVERBAS.BDREFAUXVA13, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVA13 '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALVA13 '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFVA13, '||
                'GRUPOVERBAS.BDIGNVALVA13, '||
                'VERREF.BDCLAVER, '||
                'VERREF.BDORDEMVER, '||
                'GRUPOVERBAS.BDREFA13, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDPERCA13, '||
                'Y.BDVALA13, '||
                'Y.BDTIPOPROPA13, '||
                'Y.BDMESESPROPA13, '||
                'Y.BDBASEIRA13, '||
                'Y.BDFGTSA13, '||
                'Y.BDFGTSCSA13, '||
                'Y.BDBASEFGTSA13, '||
                'Y.BDDATABAIXAA13, '||
                'Y.BDREFBAIXAA13, '||
                'Y.BDPERCIRA13, '||
                'Y.BDVALORIRA13, '||
                'Y.BDSALBASEA13, '||
                'Y.BDDEPA13, '||
                '0.0 BDINSSA13, '||
                '0.0 BDIRRFA13, '||
                'Y.BDCREDITOA13, '||
                'Y.BDDEBITOA13 '||
         'from vrhf_emp_tverbaa13 GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL, '||
         'VW_TVERBAS_REF VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_EMP_TA13SAL Y ';

  wwhere = 'where GRUPOVERBAS.BDCODEMP = EMP.BDCODEMP and GRUPOVERBAS.BDCODEMP = COl.BDCODEMP and GRUPOVERBAS.BDCODCOL = COL.BDCODCOL and '||
           'VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and '||
           'Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREFA13 = GRUPOVERBAS.BDREFA13 and GRUPOVERBAS.BDREFA13 = '||:PRANOMES||' ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  wsql = wsql||wwhere;

  EXECUTE PROCEDURE sp_seta_competencia(:PRANOMES, NULL, NULL);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :bddescredver,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDPERC,
    :BDVAL,
    :BDTIPOPROP,
    :BDMESESPROP,
    :BDBASEIR,
    :BDFGTS,
    :BDFGTSCS,
    :BDBASEFGTS,
    :BDDATABAIXA,
    :BDREFBAIXA,
    :BDPERCIR,
    :BDVALORIR,
    :BDSALBASE,
    :bddep,
    :bdinss,
    :bdirrf,
    :BDCREDITO,
    :BDDEBITO
  DO
  SUSPEND;
END
^

/* Alter (SPRH_DIVERGDADOSDIARIOSCOL) */
ALTER PROCEDURE SPRH_DIVERGDADOSDIARIOSCOL RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA DATE,
BDDESC VARCHAR(100))
 AS
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDDATACOL date;
declare variable WBDCODMAS integer;
declare variable WBDSALBASECOL numeric(15,2);
declare variable WBDCODPLAFUC integer;
declare variable WBDCODTFUC integer;
declare variable WBDCODQH integer;
declare variable WBDREGJORTRAB integer;
declare variable WBDDESCMAS varchar(100);
declare variable WBDTIPOJORNADA integer;
declare variable WBDCODTIPOCONTRATO integer;
declare variable WBDDATAFIMPRAZO1COL date;
declare variable WBDDATAFIMPRAZO2COL date;
declare variable WBDDATAFIMPRAZO date;
declare variable WBDCODEMP_ integer;
declare variable WBDCODCOL_ integer;
declare variable WBDDATACOL_ date;
declare variable WBDCODMAS_ integer;
declare variable WBDSALBASECOL_ numeric(15,2);
declare variable WBDCODPLAFUC_ integer;
declare variable WBDCODTFUC_ integer;
declare variable WBDCODQH_ integer;
declare variable WBDREGJORTRAB_ integer;
declare variable WBDDESCMAS_ varchar(100);
declare variable WBDTIPOJORNADA_ integer;
declare variable WBDCODTIPOCONTRATO_ integer;
declare variable WBDDATAFIMPRAZO1COL_ date;
declare variable WBDDATAFIMPRAZO2COL_ date;
declare variable WBDDATAFIMPRAZO_ date;
declare variable WDIVERGENCIA integer;
begin
  for select COLCON_DIA.BDCODEMP,
             COLCON_DIA.BDCODCOL,
             COLCON_DIA.BDDATACOL,
             COLCON_CALCDIA.BDCODMAS,
             COLCON_CALCDIA.BDSALBASECOL,
             COL_VINCDIA.BDCODPLAFUC,
             COL_VINCDIA.BDCODTFUC,
             COL_VINCDIA.BDCODQH,
             COL_VINCDIA.BDREGJORTRAB,
             MOTAUM.BDDESCMAS,
             COL_VINCDIA.BDTIPOJORNADA,
             TPCONT.BDCODTIPOCONTRATO,
             BDDATAFIMPRAZO1COL,
             BDDATAFIMPRAZO2COL,
             case when BDDATAFIMPRAZO2COL is not null then BDDATAFIMPRAZO2COL else BDDATAFIMPRAZO1COL end BDDATAFIMPRAZO
      from VRH_EMP_TCOLCON_DIA COLCON_DIA
      left outer join VRH_EMP_TCOLCON_CALCDIA COLCON_CALCDIA on (COLCON_CALCDIA.BDCODEMP = COLCON_DIA.BDCODEMP and COLCON_CALCDIA.BDCODCOL = COLCON_DIA.BDCODCOL and COLCON_CALCDIA.BDDATACOL = COLCON_DIA.BDDATACOL)
      left outer join VRH_EMP_TCOL_VINCDIA COL_VINCDIA on (COL_VINCDIA.BDCODEMP = COLCON_DIA.BDCODEMP and COL_VINCDIA.BDCODCOL = COLCON_DIA.BDCODCOL and COL_VINCDIA.BDDATACOL = COLCON_DIA.BDDATACOL)
      left outer join VRHF_BASE_TEMPVINC EMP_VINC on (EMP_VINC.BDCODEMP = COLCON_DIA.BDCODEMP and EMP_VINC.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF where BDCODEMP = EMP_VINC.BDCODEMP and BDREFEMP <= substring(COLCON_DIA.BDDATACOL from 1 for 4) || substring(COLCON_DIA.BDDATACOL from 6 for 2)))
      left outer join VRH_BASE_TMOTAUMSAL MOTAUM on (MOTAUM.BDCODMAS = COLCON_CALCDIA.BDCODMAS)
      left outer join VRH_EMP_TCOLCON_PARTIDA PAR on (PAR.BDCODEMP = COLCON_DIA.BDCODEMP and PAR.BDCODCOL = COLCON_DIA.BDCODCOL)
      left outer join VRH_TIPO_CONTRATO_EXP TPCONT on (TPCONT.BDCODTIPOCONTRATO = PAR.BDCODTIPOCONTRATO)
      left outer join VRH_EMP_TCOL_ADM ADM on (ADM.BDCODEMP = COLCON_DIA.BDCODEMP) and (ADM.BDCODCOL = COLCON_DIA.BDCODCOL)

      where exists (select first 1 * from VRH_EMP_TCOLCON_CALCDIA CALCDIA
                    inner join VRH_BASE_TMOTAUMSAL MOTAUMSAL on (MOTAUMSAL.BDCODMAS = CALCDIA.BDCODMAS and ((MOTAUMSAL.bddescmas = 'Prorroga??o do contrato de trabalho') or (MOTAUMSAL.bddescmas = 'Altera??o autom?tica do contrato de trabalho')))
                    where CALCDIA.bdcodemp = COLCON_DIA.bdcodemp
                    and CALCDIA.bdcodcol = COLCON_DIA.bdcodcol)

      order by COLCON_DIA.bdcodemp asc, COLCON_DIA.bdcodcol asc, COLCON_DIA.BDDATACOL DESC
      into :wBDCODEMP,:wBDCODCOL,:wBDDATACOL,:wBDCODMAS,:wBDSALBASECOL,:wBDCODPLAFUC,:wBDCODTFUC,:wBDCODQH,:wBDREGJORTRAB,:wBDDESCMAS,:wBDTIPOJORNADA,:wBDCODTIPOCONTRATO,:wBDDATAFIMPRAZO1COL,:wBDDATAFIMPRAZO2COL,:wBDDATAFIMPRAZO do
      begin
        BDDESC = '';

        if ((wBDCODEMP <> wBDCODEMP_) or (wBDCODCOL <> wBDCODCOL_)) then
        begin
          wBDCODEMP_ = null;
          wBDCODCOL_ = null;
        end

        if ((wBDCODEMP_ is not null) and (wBDCODCOL_ is not null)) then
        begin
          BDCODEMP = wBDCODEMP_;
          BDCODCOL = wBDCODCOL_;
          BDDATA = wBDDATACOL_;

          if (wBDCODMAS <> wBDCODMAS_) then
             BDDESC = 'Motivo da altera??o';
          if (wBDSALBASECOL > wBDSALBASECOL_) then
             BDDESC = 'Sal?rio base (Valor anterior de '||wBDSALBASECOL||' diminuiu para '||wBDSALBASECOL_||')';
          if (wBDCODPLAFUC <> wBDCODPLAFUC_) then
             BDDESC = 'Plano de fun??o';
          if (wBDCODTFUC <> wBDCODTFUC_) then
             BDDESC = 'Fun??o';
          if (wBDCODQH <> wBDCODQH_) then
             BDDESC = 'Quadro de hor?rio';
          if (wBDREGJORTRAB <> wBDREGJORTRAB_) then
             BDDESC = 'Regime jornada de trabalho';
          if (wBDDESCMAS <> wBDDESCMAS_) then
             BDDESC = 'Motivo da altera??o';
          if (wBDTIPOJORNADA <> wBDTIPOJORNADA_) then
             BDDESC = 'Tipo de jornada';
          if (wBDCODTIPOCONTRATO <> wBDCODTIPOCONTRATO_) then
             BDDESC = 'Tipo de contrato';

          if (BDDESC <> '') then
          begin
            suspend;
          end
        end

        wBDCODEMP_ = wBDCODEMP;
        wBDCODCOL_ = wBDCODCOL;
        wBDDATACOL_ = wBDDATACOL;
        wBDCODMAS_ = wBDCODMAS;
        wBDSALBASECOL_ = wBDSALBASECOL;
        wBDCODPLAFUC_ = wBDCODPLAFUC;
        wBDCODTFUC_ = wBDCODTFUC;
        wBDCODQH_ = wBDCODQH;
        wBDREGJORTRAB_ = wBDREGJORTRAB;
        wBDDESCMAS_ = wBDDESCMAS;
        wBDTIPOJORNADA_ = wBDTIPOJORNADA;
        wBDCODTIPOCONTRATO_ = wBDCODTIPOCONTRATO;
        wBDDATAFIMPRAZO1COL_ = wBDDATAFIMPRAZO1COL;
        wBDDATAFIMPRAZO2COL_ = wBDDATAFIMPRAZO2COL;
        wBDDATAFIMPRAZO_ = wBDDATAFIMPRAZO;
      end
end
^

/* Alter (SPRH_MENSAGENS_RECIBO) */
ALTER PROCEDURE SPRH_MENSAGENS_RECIBO(PRREF INTEGER,
PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000))
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDTXTMEN VARCHAR(2000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WWHERE VARCHAR(2000);
BEGIN
  /*
    N?o se esque?a de executar a procedure para setar a compet?ncia.
  */

  wmes = CAST((SUBSTRING(CAST(:prref AS VARCHAR(6)) FROM 5 FOR 2)) AS INTEGER);
  wwhere = '';

  IF (wmes = 12) THEN
     BEGIN
       wmes = 1;
     END
  ELSE
     BEGIN
       wmes = wmes + 1;
     END

  IF (PRCODCOL <> '') THEN
    BEGIN
        wwhere = wwhere || ' and ' || PRCODCOL;
    END
    
  IF (PRCODEMP <> '') THEN
    BEGIN
        wwhere = wwhere || ' and ' || PRCODEMP;
    END
    
  wsql = 'select '  ||
            'list(BDTXTMEN, ''. '') as BDTXTMEN, ' ||
            'BDCODCOL, ' ||
            'BDCODEMP '  ||
         'from (' ||
            'select ' || 
                'COL.BDCODEMP, ' ||
                'COL.BDCODCOL, ' ||
                'MSG.BDTXTMEN ' ||
            'from ' ||
                'VRH_EMP_TCOLCON COL ' ||
            'join ' ||
                'VW_VRHF_BASE_TEMPVINC EMP on (EMP.BDCODEMP = COL.BDCODEMP) ' ||
            'join ' || 
                'VRH_BASE_TMENSAGENS MSG on (MSG.BDCODMEN = EMP.BDCODMEN) ' ||
            'where ' ||
                'MSG.BDTXTMEN <> '''' and ' ||
                'COALESCE(EXTRACT(MONTH FROM COL.BDDATANASCCOL), 0) = ' || wmes ||
                wwhere ||
            ' union all select ' ||
                'COL.BDCODEMP, ' ||
                'COL.BDCODCOL, ' ||
                'MSG.BDTXTMEN ' ||
            'from ' ||
                'VRH_EMP_TLANMENSAGENS COL ' ||
            'join ' ||
                'VRH_BASE_TMENSAGENS MSG on (COL.BDCODMEN = MSG.BDCODMEN) ' ||
            'where ' ||
                'MSG.BDTXTMEN <> '''' and ' ||
                'COL.BDREFLAN = '|| prRef ||
                wwhere ||
         ') ' ||
         'group by ' ||
            'BDCODEMP, ' ||
            'BDCODCOL ';

  FOR EXECUTE STATEMENT wsql INTO    -- Mensagens de anivers?rio    
    BDTXTMEN,
    BDCODCOL,
    BDCODEMP

    DO
      SUSPEND;
END
^

/* Alter (SPRH_TREEVIEW_CONS_13SAL) */
ALTER PROCEDURE SPRH_TREEVIEW_CONS_13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREF13 INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wsql = :PRANOMES;
  --ELSE
     --wsql = :PRANO||'12';

  EXECUTE PROCEDURE sp_seta_competencia(CAST(wsql AS INTEGER), NULL, NULL);

  wsql = 'select DECTERC.BDCODEMP, EMP.BDNOMEMP, '||
                'DECTERC.BDCODCOL, COL.BDNOMCOL, '||
                'DECTERC.BDREF13 '||
         'from VRHF_EMP_T13SAL DECTERC, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL ';

  wwhere = ' where DECTERC.BDCODEMP = EMP.BDCODEMP and DECTERC.BDCODEMP = COL.BDCODEMP and DECTERC.BDCODCOL = COL.BDCODCOL ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  /*IF (:PRANO IS NOT NULL AND :PRANO <> 0) THEN
     wwhere = wwhere||' and DECTERC.BDANO13 = '||:PRANO;
  ELSE
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wwhere = wwhere||' and DECTERC.BDREF13 = '||:PRANOMES;*/

  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     BEGIN
       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere||' and DECTERC.BDREF13 = '||:PRANOMES;
       ELSE
         IF (:PRMESESANTERIORES = 1) THEN
            wwhere = wwhere||' and substring(DECTERC.BDREF13 from 1 for 4) = '||SUBSTRING(:PRANOMES FROM 1 FOR 4)||' ';
     END 

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdnomemp,
    :bdcodcol,
    :bdnomcol,
    :bdref13
  DO
  SUSPEND;
END
^

/* Alter (SPRH_TREEVIEW_CONS_AD13SAL) */
ALTER PROCEDURE SPRH_TREEVIEW_CONS_AD13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREFA13 INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wsql = :PRANOMES;
  --ELSE
     --wsql = :PRANO||'12';

  EXECUTE PROCEDURE sp_seta_competencia(CAST(wsql AS INTEGER), NULL, NULL);

  wsql = 'select A13.BDCODEMP, EMP.BDNOMEMP, '||
                'A13.BDCODCOL, COL.BDNOMCOL, '||
                'A13.BDREFA13 '||
         'from VRHF_EMP_TA13SAL A13, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL ';

  wwhere = ' where A13.BDCODEMP = EMP.BDCODEMP and COL.BDCODEMP = A13.BDCODEMP and COL.BDCODCOL = A13.BDCODCOL ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  /*IF (:PRANO IS NOT NULL AND :PRANO <> 0) THEN
     wwhere = wwhere||' and A13.BDANOA13 = '||:PRANO;
  ELSE
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wwhere = wwhere||' and A13.BDREFA13 = '||:PRANOMES;*/

  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     BEGIN
       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere||' and A13.BDREFA13 = '||:PRANOMES;
       ELSE
         IF (:PRMESESANTERIORES = 1) THEN
            wwhere = wwhere||' and substring(A13.BDREFA13 from 1 for 4) = '||SUBSTRING(:PRANOMES FROM 1 FOR 4)||' ';
     END    

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFA13
  DO
  SUSPEND;
END
^

/* Alter (SPVAL_ITINERARIO) */
ALTER PROCEDURE SPVAL_ITINERARIO(PRITI INTEGER,
PRREF INTEGER)
 RETURNS(BDITI INTEGER,
BDVALOR NUMERIC(15,6))
 AS
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  SELECT bdcoditi,BDVALITI FROM VW_VRHF_BASE_TITINERARIOS_REF WHERE bdcoditi = :priti INTO :bditi,:bdvalor;

  SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: MAXSCI for: STRTRAN */
ALTER PROCEDURE MAXSCI(PRCAMPO VARCHAR(1024),
PRORDEM VARCHAR(1024),
PRCONDICAO VARCHAR(1024),
PRTABELA VARCHAR(1024))
 RETURNS(BDRESULT INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRH_VAL_RAIS_FF_REF for: STRTRAN */
ALTER PROCEDURE SP_VRH_VAL_RAIS_FF_REF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_EXTRATO_FGTS for: STRTRAN */
ALTER PROCEDURE VRHF_SP_EXTRATO_FGTS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA INTEGER,
BDMOVIMENTACAO VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDACUMULADO NUMERIC(15,6),
BDVALORJAM NUMERIC(15,6),
BDVALORDEPOSITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TFOLHA_NORMAL for: STRTRAN */
ALTER PROCEDURE VRHF_SP_TFOLHA_NORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = null,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = null)
 RETURNS(BDGRUPOCLA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDREFFN INTEGER,
BDDATABAIXAFN DATE,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDBASEPISFEFN NUMERIC(15,6),
BDBASEPIS13FN NUMERIC(15,6),
BDBSALMATEMPFN NUMERIC(15,6),
BDSALMATEMPFN NUMERIC(15,6),
BDBRATAPOFN NUMERIC(15,6),
BDBRATAPOFEFN NUMERIC(15,6),
BDBRATAPO13FN NUMERIC(15,6),
BDBINSSFEFOLFN NUMERIC(15,6),
BDINSSFEFOLFN NUMERIC(15,6),
BDALIQINSSFEFOLFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCREDITOFN NUMERIC(15,6),
BDDEBITOFN NUMERIC(15,6),
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6),
BDBMATEMPFNFN NUMERIC(15,6),
BDBMATEMP13FN NUMERIC(15,6),
BDVMATEMPFNFN NUMERIC(15,6),
BDVMATEMP13FN NUMERIC(15,6),
BDLIQUIDOFN NUMERIC(18,6),
BDDATAPGTO DATE,
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDCODCONTTI INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TFOLHA_NORMAL_PREV_RESC for: STRTRAN */
ALTER PROCEDURE VRHF_SP_TFOLHA_NORMAL_PREV_RESC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = NULL)
 RETURNS(BDGRUPOCLA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDREFFN INTEGER,
BDDATABAIXAFN DATE,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDBASEPISFEFN NUMERIC(15,6),
BDBASEPIS13FN NUMERIC(15,6),
BDBSALMATEMPFN NUMERIC(15,6),
BDSALMATEMPFN NUMERIC(15,6),
BDBRATAPOFN NUMERIC(15,6),
BDBRATAPOFEFN NUMERIC(15,6),
BDBRATAPO13FN NUMERIC(15,6),
BDBINSSFEFOLFN NUMERIC(15,6),
BDINSSFEFOLFN NUMERIC(15,6),
BDALIQINSSFEFOLFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCREDITOFN NUMERIC(15,6),
BDDEBITOFN NUMERIC(15,6),
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6),
BDBMATEMPFNFN NUMERIC(15,6),
BDBMATEMP13FN NUMERIC(15,6),
BDVMATEMPFNFN NUMERIC(15,6),
BDVMATEMP13FN NUMERIC(15,6),
BDLIQUIDOFN NUMERIC(18,6),
BDDATAPGTO DATE,
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TFOLHACOMP for: STRTRAN */
ALTER PROCEDURE VRHF_SP_TFOLHACOMP(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(28000),
PRREFINICOMP INTEGER,
PRREFFIMCOMP INTEGER,
PRREFINIPAG INTEGER,
PRREFFIMPAG INTEGER,
PRAGRUPATOMADOR INTEGER,
PRTIPOFC INTEGER = 0,
PRSEPARCALC INTEGER = 0,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDREFFN INTEGER,
BDREFFC INTEGER,
BDREFCOMP INTEGER,
BDDATAPAGFC DATE,
BDDATABAIXAFC DATE,
BDBFGTSFC NUMERIC(15,6),
BDFGTSFC NUMERIC(15,6),
BDFGTSCSFC NUMERIC(15,6),
BDBFGTS13FC NUMERIC(15,6),
BDFGTS13FC NUMERIC(15,6),
BDFGTS13CSFC NUMERIC(15,6),
BDMAIORREMFC NUMERIC(15,6),
BDBINSSFC NUMERIC(15,6),
BDALIQINSSFC NUMERIC(15,6),
BDINSSFC NUMERIC(15,6),
BDBIRRFFC NUMERIC(15,6),
BDALIQIRRFFC NUMERIC(15,6),
BDIRRFFC NUMERIC(15,6),
BDBINSS13FC NUMERIC(15,6),
BDALIQINSS13FC NUMERIC(15,6),
BDINSS13FC NUMERIC(15,6),
BDBIRRF13FC NUMERIC(15,6),
BDALIQIRRF13FC NUMERIC(15,6),
BDIRRF13FC NUMERIC(15,6),
BDBSALFAMFC NUMERIC(15,6),
BDSALFAMFC NUMERIC(15,6),
BDBRAISFC NUMERIC(15,6),
BDSALBASEFC NUMERIC(15,6),
BDDEPFC NUMERIC(15,6),
BDBASEPISFC NUMERIC(15,6),
BDBASEPISFEFC NUMERIC(15,6),
BDBASEPIS13FC NUMERIC(15,6),
BDBSALMATEMPFC NUMERIC(15,6),
BDSALMATEMPFC NUMERIC(15,6),
BDBRATAPOFC NUMERIC(15,6),
BDBRATAPOFEFC NUMERIC(15,6),
BDBRATAPO13FC NUMERIC(15,6),
BDBINSSFEFOLFC NUMERIC(15,6),
BDINSSFEFOLFC NUMERIC(15,6),
BDALIQINSSFEFOLFC NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFEFC NUMERIC(15,6),
BDFGTSFEFC NUMERIC(15,6),
BDCODTIPOFC INTEGER,
BDBINSSMVFC NUMERIC(18,6),
BDBINSSMV13FC NUMERIC(18,6),
BDINSSMVFC NUMERIC(18,6),
BDINSSMV13FC NUMERIC(18,6),
BDBINSSAPFC NUMERIC(18,6),
BDBINSS13APFC NUMERIC(18,6),
BDINSSAPFC NUMERIC(18,6),
BDINSS13APFC NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDINSSFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDLIQUIDOFC NUMERIC(18,6),
BDDATAGRRF DATE)
 AS
 BEGIN SUSPEND; END
^

/* Alter (STRTRAN) */
ALTER PROCEDURE STRTRAN(PRTEXTO VARCHAR(30000),
PRSUBSTR VARCHAR(1024),
PRSTR VARCHAR(1024))
 RETURNS(BDRESULT VARCHAR(30000))
 AS
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WSTRLEN INTEGER;
BEGIN
  -- Gilberto - 29/10/2011 - implementado o la?o do STRTRAN
  wpos = 1;
  wstrlen = strlen(prsubstr);
  bdresult = '';
  WHILE (wpos <= strlen(prtexto)) DO
    BEGIN
      IF (SUBSTRING(prtexto FROM wpos FOR wstrlen) = prsubstr) THEN
         BEGIN
           bdresult = bdresult||prstr;
           wpos = wpos + wstrlen - 1;
         END
      ELSE
         bdresult = bdresult||SUBSTRING(prtexto FROM wpos FOR 1);
      wpos = wpos + 1;
    END
  SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: DIA_SEGUINTE for: ULTIMO_DIA_MES */
ALTER PROCEDURE DIA_SEGUINTE(PRDATA DATE)
 RETURNS(PRDIASEGUINTE DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CALC_DEPRECIACAO for: ULTIMO_DIA_MES */
ALTER PROCEDURE SP_CALC_DEPRECIACAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
PRCORRECAOPERIODO NUMERIC(15,2),
PRVALORCORRIGIDOATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
PRDEPRECIACAOPERIODO NUMERIC(15,2),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
PRVALORRESIDUALCONTABIL NUMERIC(15,2),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,2),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
PRVALORBAIXAREAL NUMERIC(15,2),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_CONS_CALC_DEP_CORRECAO for: ULTIMO_DIA_MES */
ALTER PROCEDURE SP_CONS_CALC_DEP_CORRECAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER,
PRVLRMOEDA NUMERIC(15,6),
PRPOSSUIBAIXA VARCHAR(5),
PRCODBEMORIGINAL INTEGER,
PRVALORAQUISICAO NUMERIC(15,6),
PRTAXADEPANUAL NUMERIC(6,6),
PRDATAAQUISICAO DATE,
PRDATAORIGAQUISICAO DATE,
PRDEPDIA VARCHAR(5),
PRDEPMENSAL VARCHAR(5),
PRDEPMESBAIXA VARCHAR(5),
PRDATAINICIOCALC DATE,
PRDATAFIMCALC DATE,
PRDATAULTIMOITEMDEP DATE,
PRVALDEPACUMUBEM NUMERIC(15,6),
PRCTADEBDEPRE INTEGER,
PRNUMDIAS INTEGER,
PRDEPDIADATA INTEGER,
PRVALORBAIXABEM NUMERIC(15,6),
PRMESESDEPRECIADOSOUTRATAXA INTEGER,
PRVALORACUMULADOANTERIOR NUMERIC(15,6))
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,6),
PRCORRECAOPERIODO NUMERIC(15,6),
PRVALORCORRIGIDOATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6),
PRDEPRECIACAOPERIODO NUMERIC(15,6),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6),
PRVALORRESIDUALCONTABIL NUMERIC(15,6),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,6),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,6),
PRVALORBAIXAREAL NUMERIC(15,6),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,6),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,6),
PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_EXP_SEFIP_MOVIMENTACAO_COL for: ULTIMO_DIA_MES */
ALTER PROCEDURE SP_EXP_SEFIP_MOVIMENTACAO_COL(PRREFINI INTEGER = 0,
PRREFFIM INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA DATE,
BDDATASTR VARCHAR(10),
BDMOTIVO VARCHAR(5),
BDINDFGTS INTEGER,
BDCODMFG INTEGER,
BDDATAFIM DATE,
BDINSSINTSIT /* DM_BOOLEAN */ VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_PRAZO_EXPERIENCIA_SITUACAO for: ULTIMO_DIA_MES */
ALTER PROCEDURE SP_PRAZO_EXPERIENCIA_SITUACAO(PRCODEMP VARCHAR(30000),
PRCODCOL VARCHAR(30000),
PRDIASPRAZO1COL INTEGER,
PRDIASPRAZO2COL INTEGER,
PRCODSIT INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_RELDEMRECDESP for: ULTIMO_DIA_MES */
ALTER PROCEDURE SP_RELDEMRECDESP(PRCODESC VARCHAR(500),
PRTIPODEM INTEGER,
PRDATAINICIAL VARCHAR(10),
PRDATAFINAL VARCHAR(10),
PRCHAVECTABAN VARCHAR(500),
PRCODOBRSER VARCHAR(10240),
PRCODDESP VARCHAR(10240),
PRNIVEL INTEGER,
PRTIPORECDESP INTEGER,
PRDEMLANCREEMBOLSO /* DM_BOOLEAN */ VARCHAR(5))
 RETURNS(BDCODSERDESP INTEGER,
BDCLASSIFICACAO VARCHAR(60),
BDDESCRICAO VARCHAR(100),
BDTIPO INTEGER,
BDPERIODO01 VARCHAR(12),
BDVLRPERIODO01 NUMERIC(15,2),
BDPERIODO02 VARCHAR(12),
BDVLRPERIODO02 NUMERIC(15,2),
BDPERIODO03 VARCHAR(12),
BDVLRPERIODO03 NUMERIC(15,2),
BDPERIODO04 VARCHAR(12),
BDVLRPERIODO04 NUMERIC(15,2),
BDPERIODO05 VARCHAR(12),
BDVLRPERIODO05 NUMERIC(15,2),
BDPERIODO06 VARCHAR(12),
BDVLRPERIODO06 NUMERIC(15,2),
BDPERIODO07 VARCHAR(12),
BDVLRPERIODO07 NUMERIC(15,2),
BDPERIODO08 VARCHAR(12),
BDVLRPERIODO08 NUMERIC(15,2),
BDPERIODO09 VARCHAR(12),
BDVLRPERIODO09 NUMERIC(15,2),
BDPERIODO10 VARCHAR(12),
BDVLRPERIODO10 NUMERIC(15,2),
BDPERIODO11 VARCHAR(12),
BDVLRPERIODO11 NUMERIC(15,2),
BDPERIODO12 VARCHAR(12),
BDVLRPERIODO12 NUMERIC(15,2),
BDVLRTOTPERIODO NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_VRHF_DECLARACAO_DOMESTICO for: ULTIMO_DIA_MES */
ALTER PROCEDURE SP_VRHF_DECLARACAO_DOMESTICO(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRANOBASE INTEGER,
PRTOMADOR INTEGER,
PRCODSIND INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRORDEM VARCHAR(50),
PRDATAEMISSAO VARCHAR(10),
PRSITUACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADM DATE,
BDDATARESCISAO DATE,
BDPIS VARCHAR(14),
BDCPF VARCHAR(14),
BDCOMPETENCIA INTEGER,
BDSALMIN NUMERIC(15,6),
BDBINSSN NUMERIC(15,6),
BDBINSSFE NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDREMUNERACAO NUMERIC(18,6),
BDINSSPATRONAL NUMERIC(15,6),
BDDIFERENCAINSS NUMERIC(15,6),
BDTOTALCONTRPATRONAL NUMERIC(15,6),
BDPARCELANAODEDUTIVEL NUMERIC(15,6),
BDINF VARCHAR(20),
BDORDEM VARCHAR(50),
BDDATAEMISSAO VARCHAR(10),
BDANOBASE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VLAL_SP_LAN_PARTEA for: ULTIMO_DIA_MES */
ALTER PROCEDURE VLAL_SP_LAN_PARTEA(PREMPRESA INTEGER,
PRCODLLA INTEGER,
PRCODUSU INTEGER,
PRANOBASE INTEGER,
PRCODPARTEA INTEGER,
PRCODLPA INTEGER,
PRCODTPHI INTEGER,
PRANUALACUMULADO SMALLINT,
PRVALOR1 NUMERIC(15,2),
PRCOMPL1 VARCHAR(200),
PRVALOR2 NUMERIC(15,2),
PRCOMPL2 VARCHAR(200),
PRVALOR3 NUMERIC(15,2),
PRCOMPL3 VARCHAR(200),
PRVALOR4 NUMERIC(15,2),
PRCOMPL4 VARCHAR(200),
PRVALOR5 NUMERIC(15,2),
PRCOMPL5 VARCHAR(200),
PRVALOR6 NUMERIC(15,2),
PRCOMPL6 VARCHAR(200),
PRVALOR7 NUMERIC(15,2),
PRCOMPL7 VARCHAR(200),
PRVALOR8 NUMERIC(15,2),
PRCOMPL8 VARCHAR(200),
PRVALOR9 NUMERIC(15,2),
PRCOMPL9 VARCHAR(200),
PRVALOR10 NUMERIC(15,2),
PRCOMPL10 VARCHAR(200),
PRVALOR11 NUMERIC(15,2),
PRCOMPL11 VARCHAR(200),
PRVALOR12 NUMERIC(15,2),
PRCOMPL12 VARCHAR(200),
PRREFEMP INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: VRH_SP_AUMENTOSALARIO for: ULTIMO_DIA_MES */
ALTER PROCEDURE VRH_SP_AUMENTOSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODCOL INTEGER,
BDNOMCOL /* DM_BDNOMCOL */ VARCHAR(70),
BDDATAADMCOL DATE,
BDDATACOL DATE,
BDSALBASECOLANT NUMERIC(15,2),
BDSALBASECOLATU NUMERIC(15,2),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDHORASMENSAISCOL NUMERIC(15,2),
BDTIPOCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SP_TPREPFN_REF for: ULTIMO_DIA_MES */
ALTER PROCEDURE VRHF_SP_TPREPFN_REF(PRREFERENCIA INTEGER,
PREMPRESA VARCHAR(32700),
PRCOLABORADOR VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* Alter (ULTIMO_DIA_MES) */
ALTER PROCEDURE ULTIMO_DIA_MES(PRMES SMALLINT,
PRANO INTEGER)
 RETURNS(ULTDIA INTEGER)
 AS
DECLARE VARIABLE wanobisexto SMALLINT;
BEGIN

  IF (prmes = 2) THEN
     BEGIN

       SELECT prBisexto FROM ano_bisexto(:prano) INTO wanobisexto;

       IF (wanobisexto = 1) THEN
          ultdia = 29;
       ELSE
          ultdia = 28;

     END
  ELSE
     BEGIN
       IF ((prmes = 4) OR (prmes = 6) OR (prmes = 9) OR (prmes = 11)) THEN
          ultdia = 30;
       ELSE
          ultdia = 31;
     END

  SUSPEND;

END
^

/* Alter (VCT_TAREFAS_AUTOMATICAS) */
ALTER PROCEDURE VCT_TAREFAS_AUTOMATICAS(CODEMP INTEGER = 0,
DATA DATE = CURRENT_DATE)
 RETURNS(TOTAL INTEGER,
IMPOSTOS INTEGER,
OBRIGACOES INTEGER,
SERVICOS INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WCONT INTEGER;
DECLARE VARIABLE WBDCODEMP INTEGER NOT NULL;
DECLARE VARIABLE WBDCODUSU INTEGER;
DECLARE VARIABLE WBDCODCOL INTEGER;
DECLARE VARIABLE WBDCODIMP INTEGER;
DECLARE VARIABLE WBDCODOBRIGACAO INTEGER;
DECLARE VARIABLE WBDCODSERVICO INTEGER;
DECLARE VARIABLE WBDCODTIPO INTEGER;
DECLARE VARIABLE WBDDATASOL DATE;
DECLARE VARIABLE WBDFATURAR VARCHAR(5);
DECLARE VARIABLE WBDDATASOLICITADA DATE;
DECLARE VARIABLE WBDDATAPREVISAO DATE;
DECLARE VARIABLE WBDDATAFIM DATE;
DECLARE VARIABLE WBDSERIE VARCHAR(10);
DECLARE VARIABLE WBDREFSOL INTEGER;
DECLARE VARIABLE WBDQUANTIDADE NUMERIC(15,6);
DECLARE VARIABLE WBDVALORUNITARIO NUMERIC(15,2);
DECLARE VARIABLE WBDVALORDESCONTO NUMERIC(15,2);
DECLARE VARIABLE WBDTIPODESCONTO INTEGER;
DECLARE VARIABLE WBDPARCELAS INTEGER;
DECLARE VARIABLE WBDTIPOSOLICITACAO INTEGER;
DECLARE VARIABLE WBDVENCIMENTO DATE;
DECLARE VARIABLE WBDENTREGA DATE;
DECLARE VARIABLE WBDALERTA DATE;
DECLARE VARIABLE WBDPERIODICIDADE INTEGER;
DECLARE VARIABLE WCURRENT_DATE DATE = CURRENT_DATE;
DECLARE VARIABLE WRECONTABILIZANDO DM_BOOLEAN;
DECLARE VARIABLE WBDDIASEMANA INTEGER;
DECLARE VARIABLE WDIASEMANADATA INTEGER;
DECLARE VARIABLE WDATAVENCAUX DATE;
DECLARE VARIABLE WBDCODCID INTEGER;
DECLARE VARIABLE WBDDIAENTREGACAD INTEGER;
DECLARE VARIABLE WBDANTECIPAR VARCHAR(5);
DECLARE VARIABLE wTotal INTEGER;
DECLARE VARIABLE wTotalImpostos INTEGER;
DECLARE VARIABLE wTotalServicos INTEGER;
DECLARE VARIABLE wTotalObrigacoes INTEGER;
BEGIN
  wcurrent_date = data;
  WCODEMP = 0;

      -- gilberto - 19/09/2014 - n?o gerar tarefas autom?ticas para clientes que n?o estejam personalizados para o controles
  IF (((SELECT bdcodigo FROM tpersonalizacao WHERE bdsistemas CONTAINING '58') IS NULL) OR
      -- gilberto - 24/10/2014 - n?o gerar tarefas antes da data configurada
      ((SELECT bddatatarefa FROM vct_config_datas WHERE bddatatarefa <= :wcurrent_date) IS NULL) OR
      -- gilberto - 15/09/2014 - n?o deixar gerar tarefas autom?ticas no cadastro de empresas
      (COALESCE((SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_CADEMPRESA'))) AS INTEGER) FROM rdb$database), 0) <> 0)) THEN
     EXIT;

  /* sol.: #10892 Jean 19/01/2015: Estava dando Lock conflict no after-insert na tabela TEMPRESAS_REF durante o
  processo de recontabiliza??o */
  SELECT TRIM(UPPER(COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_RECONTABILIZA'), '')))
  FROM RDB$DATABASE
  INTO :wrecontabilizando;
  IF (wrecontabilizando = 'TRUE') THEN
    EXIT;  

  total = 0;
  impostos = 0;
  obrigacoes = 0;
  servicos = 0;
  UPDATE OR INSERT INTO VCT_BASE_PARAMETROS (bddata) VALUES (:wcurrent_date) MATCHING (bddata);

  -- Obriga??es
  wsql = 'SELECT bdcodemp, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo, ';
  wsql = wsql||'bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim, ';
  wsql = wsql||'bdserie, bdperiodicidade, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas, ';
  wsql = wsql||'bdtiposolicitacao, bdvencimento, bdentrega, bdalerta, bddiasemana, BDANTECIPAR, BDDIAENTREGACAD, BDCODCID ';
  wsql = wsql||'FROM (SELECT trib.bdcodemp, NULL AS bdcodst, NULL AS bdcodcol, ';
  wsql = wsql||'NULL AS bdcodimp, tobr.bdcodobrser AS bdcodobrigacao, NULL AS bdcodservico, 501 AS bdcodtipo, ';
  wsql = wsql||'cast('''||wcurrent_date||''' as date) AS bddatasol, NULL AS bdfaturar, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', tobr.bddia, tobr.bdantecipar, tobr.bdvence, tobr.bdperiodicidade, NULL, tobr.bdcodcid, tobr.bdmesvence, trib.bdcodemp)) AS bddatasolicitada, ';
  wsql = wsql||'NULL AS bddataprevisao, ';
  wsql = wsql||'NULL AS bddatafim, NULL AS bdserie, tobr.bdperiodicidade, ';
  wsql = wsql||'CAST(CASE WHEN (tobr.bdperiodicidade = 10) THEN SUBSTRING('''||wcurrent_date||''' FROM 1 FOR 4) ';
  wsql = wsql||'ELSE SUBSTRING('''||wcurrent_date||''' FROM 1 FOR 4)||SUBSTRING('''||wcurrent_date||''' FROM 6 FOR 2) END AS INTEGER) AS bdrefsol, ';
  wsql = wsql||'1 AS bdquantidade, 0 AS bdvalorunitario, 0 AS bdvalordesconto, 0 AS bdtipodesconto, 1 AS bdparcelas, 1 AS bdtiposolicitacao, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', tobr.bddia, tobr.bdantecipar, tobr.bdvence, tobr.bdperiodicidade, NULL, tobr.bdcodcid, tobr.bdmesvence, trib.bdcodemp)) AS bdvencimento, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', tobr.bddia, tobr.bdantecipar, tobr.bdvence, tobr.bdperiodicidade, COALESCE(tobr.bdentrega, 0), tobr.bdcodcid, tobr.bdmesvence, trib.bdcodemp)) AS bdentrega, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', tobr.bddia, tobr.bdantecipar, tobr.bdvence, tobr.bdperiodicidade, COALESCE(tobr.bdalerta, 0), tobr.bdcodcid, tobr.bdmesvence, trib.bdcodemp)) AS bdalerta, ';
  wsql = wsql||'coalesce(BDDIASEMANA, 0) BDDIASEMANA, BDANTECIPAR, COALESCE(tobr.bdentrega, 0) BDDIAENTREGACAD, BDCODCID ';
  wsql = wsql||'FROM vct_base_obrigacao tobr ';
  wsql = wsql||'INNER JOIN vct_tributario_empresa trib ON (trib.bdcodobr = tobr.bdcodobrser AND trib.bdrefini <= SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 1 FOR 4)||SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 6 FOR 2) AND (trib.bdreffin >= SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 1 FOR 4)||SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 6 FOR 2) OR (trib.bdreffin IS NULL))) ';
  wsql = wsql||'INNER JOIN tempresas temp ON (temp.bdcodemp = trib.bdcodemp AND temp.bddatainiativemp < '''||wcurrent_date||''' AND ((temp.bddatafimativemp > '''||wcurrent_date||''') OR (temp.bddatafimativemp IS NULL))) ';
  wsql = wsql||'WHERE ((BDCRIACAO <= '''||wcurrent_date||''') OR (BDCRIACAO IS NULL)) ';
  wsql = wsql||'AND ((BDEXTINTO >= '''||wcurrent_date||''') OR (BDEXTINTO IS NULL)) ';
  wsql = wsql||'AND tobr.bdtipo = 1 ';
  wsql = wsql||'AND tobr.bdperiodicidade <> 11 ';-- indefinido
  IF (codemp <> 0) THEN
     wsql = wsql||'AND trib.bdcodemp = '||CODEMP;
  wsql = wsql||') AS trib ';
  FOR EXECUTE STATEMENT wsql
  INTO :wbdcodemp, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
       :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
       :wbdserie, :WBDPERIODICIDADE, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
       :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta, :wbddiasemana, :wbdantecipar, :wbddiaentregacad, :wbdcodcid DO
  BEGIN
    -- Apenas empresas ativas
    IF ((SELECT FIRST 1 bdsitemp FROM tempresas_ref WHERE bdcodemp = :wbdcodemp AND bdrefemp <= :wbdrefsol ORDER BY bdrefemp DESC) <> 'TRUE') THEN
    BEGIN
          -- mensal - vencimento conforme par?metros
       IF ((wbdperiodicidade IN (0,1,2,3,4,5,6)) OR
          -- trimestral - gera mar?o, junho, setembro, dezembro com vencimento conforme parametros
          ((wbdperiodicidade = 7) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (3,6,9,12))) OR
          -- anual - gera no primeiro m?s do ano com vencimento no ano seguinte
          ((wbdperiodicidade = 10) AND (SUBSTRING(:wcurrent_date FROM 6 FOR 2) = 1))) THEN
       BEGIN
         -- Adilson Hasckel - sol. 18235 - 04/05/2017 - tarefa semanal de obriga??es   
         IF (wbdperiodicidade = 0) THEN -- se for segunda feira criar tarefa autom?tica semanal
            BEGIN
              wDataVencAux = wcurrent_date;
              wDiaSemanaData = EXTRACT(WEEKDAY FROM :wcurrent_date);
              IF (wDiaSemanaData = 1) THEN
                BEGIN
                   WHILE (EXTRACT(WEEKDAY FROM :wDataVencAux) <> :wbddiasemana) DO
                     wDataVencAux = wDataVencAux + 1;
                   -- verifica se h? a obriga??o nas tarefas
                   IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodobrigacao = :wbdcodobrigacao AND bdrefsol = :wbdrefsol AND bddatasol = :wcurrent_date) IS NULL) THEN
                   BEGIN
                     wbdvencimento = wDataVencAux;
                     wbdalerta     = wDataVencAux;
                     SELECT bddata FROM get_vencimento(:wbdvencimento, EXTRACT(DAY FROM :wbdvencimento), :wbdantecipar, 0, 0, :wbddiaentregacad, :wbdCodCid, 0, :wbdcodemp) INTO :wbdentrega;

                     INSERT INTO vct_empresa_tsolicitatarefa
                     (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
                      bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
                      bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
                      bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)
                     VALUES
                     (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
                      :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
                      :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
                      :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

                     obrigacoes = obrigacoes + 1;
                     total = total + 1;
                   END
                END
            END
         ELSE
         -- verifica se h? a obriga??o nas tarefas
         IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodobrigacao = :wbdcodobrigacao AND bdrefsol = :wbdrefsol) IS NULL) THEN
         BEGIN
           INSERT INTO vct_empresa_tsolicitatarefa
           (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
            bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
            bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
            bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)
           VALUES
           (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
            :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
            :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
            :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

           obrigacoes = obrigacoes + 1;
           total = total + 1;
         END
       END
       ELSE
       -- trimestral parcelado - gera em mar?o com vencimento em Abril, Maio e junho
       --                      - gera em junho com vencimento em julho, agosto e setembro
       --                      - gera em setembro com vencimento em outubro, novembro e dezembro
       --                      - gera em dezembro com vencimento em janeiro, fevereiro e mar?o do ano seguinte
       IF (((wbdperiodicidade = 8) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (3,6,9,12))) OR
       -- trimestral antecipado - gera em janeiro com vencimento em fevereiro, mar?o e abril
       --                       - gera em abril com vencimento em maio, junho e julho
       --                       - gera em julho com vencimento em agosto, setembro e outubro
       --                       - gera em outubro com vencimento em novembro, dezembro e janeiro do pr?ximo ano
       ((wbdperiodicidade = 9) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (1,4,7,10)))) THEN
       BEGIN
         wcont = 0;
         wdata = :wcurrent_date;
         WHILE (wcont <= 2) DO
         BEGIN
           IF (wcont > 0) THEN
              wdata = addmonth(:wcurrent_date, wcont);
           wbdrefsol = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);
           SELECT (SELECT bddata FROM get_vencimento(:wdata, tobr.bddia, tobr.bdantecipar, tobr.bdvence, tobr.bdperiodicidade, NULL, tobr.bdcodcid, tobr.bdmesvence, :wcodemp)) AS bddatasolicitada,
                  (SELECT bddata FROM get_vencimento(:wdata, tobr.bddia, tobr.bdantecipar, tobr.bdvence, tobr.bdperiodicidade, NULL, tobr.bdcodcid, tobr.bdmesvence, :wcodemp)) AS bdvencimento,
                  (SELECT bddata FROM get_vencimento(:wdata, tobr.bddia, tobr.bdantecipar, tobr.bdvence, tobr.bdperiodicidade, COALESCE(tobr.bdentrega, 0), tobr.bdcodcid, tobr.bdmesvence, :wcodemp)) AS bdentrega,
                  (SELECT bddata FROM get_vencimento(:wdata, tobr.bddia, tobr.bdantecipar, tobr.bdvence, tobr.bdperiodicidade, COALESCE(tobr.bdalerta, 0), tobr.bdcodcid, tobr.bdmesvence, :wcodemp)) AS bdalerta
           FROM vct_base_obrigacao tobr
           WHERE tobr.bdcodobrser = :wbdcodobrigacao
           INTO :wbddatasolicitada, :wbdvencimento, :wbdentrega, :wbdalerta;

           IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodobrigacao = :wbdcodobrigacao AND bdrefsol = :wbdrefsol) IS NULL) THEN
           BEGIN
             INSERT INTO vct_empresa_tsolicitatarefa
             (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
              bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
              bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
              bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)
             VALUES
             (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
              :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
              :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
              :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

             obrigacoes = obrigacoes + 1;
             total = total + 1;
           END
           wcont = wcont + 1;
         END
       END
       ELSE
       IF (wbdperiodicidade = 12) THEN --Periodicidade di?ria, verifica??o todos os dias (n?o usa par?metro de antecipa??o de vencimento ? o pr?prio dia)
       BEGIN
          IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodobrigacao = :wbdcodobrigacao AND bdrefsol = :wbdrefsol AND bdvencimento = :wcurrent_date) IS NULL) THEN
             BEGIN
                wbdvencimento = wcurrent_date;
                wbdentrega    = wcurrent_date;
                wbdalerta     = wcurrent_date;
                INSERT INTO vct_empresa_tsolicitatarefa
                (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
                bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
                bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
                bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)
               VALUES
               (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
                :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
                :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
                :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);
    
               obrigacoes = obrigacoes + 1;
               total = total + 1;
             END
       END
    END
  END


  -- servi?os
  wsql = 'SELECT bdcodemp, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo, ';
  wsql = wsql||'bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim, ';
  wsql = wsql||'bdserie, bdperiodicidade, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas, ';
  wsql = wsql||'bdtiposolicitacao, bdvencimento, bdentrega, bdalerta, bddiasemana, BDANTECIPAR, BDDIAENTREGACAD, BDCODCID ';
  wsql = wsql||'FROM (SELECT trib.bdcodemp, NULL AS bdcodst, NULL AS bdcodcol, ';
  wsql = wsql||'NULL AS bdcodimp, NULL AS bdcodobrigacao, tser.bdcodobrser AS bdcodservico, 501 AS bdcodtipo, ';
  wsql = wsql||'cast('''||wcurrent_date||''' as date) AS bddatasol, NULL AS bdfaturar, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', tser.bddia, tser.bdantecipar, tser.bdvence, tser.bdperiodicidade, NULL, NULL, tser.bdmesvence, trib.bdcodemp)) AS bddatasolicitada, ';
  wsql = wsql||'NULL AS bddataprevisao, ';
  wsql = wsql||'NULL AS bddatafim, NULL AS bdserie, tser.bdperiodicidade, ';
  wsql = wsql||'CAST(CASE WHEN (tser.bdperiodicidade = 10) THEN SUBSTRING('''||wcurrent_date||''' FROM 1 FOR 4) ';
  wsql = wsql||'ELSE SUBSTRING('''||wcurrent_date||''' FROM 1 FOR 4)||SUBSTRING('''||wcurrent_date||''' FROM 6 FOR 2) END AS INTEGER) AS bdrefsol, ';
  wsql = wsql||'1 AS bdquantidade, 0 AS bdvalorunitario, 0 AS bdvalordesconto, 0 AS bdtipodesconto, 1 AS bdparcelas, 2 AS bdtiposolicitacao, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', tser.bddia, tser.bdantecipar, tser.bdvence, tser.bdperiodicidade, NULL, NULL, tser.bdmesvence, trib.bdcodemp)) AS bdvencimento, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', tser.bddia, tser.bdantecipar, tser.bdvence, tser.bdperiodicidade, COALESCE(tser.bdentrega, 0), NULL, tser.bdmesvence, trib.bdcodemp)) AS bdentrega, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', tser.bddia, tser.bdantecipar, tser.bdvence, tser.bdperiodicidade, COALESCE(tser.bdalerta, 0), NULL, tser.bdmesvence, trib.bdcodemp)) AS bdalerta, ';
  wsql = wsql||'coalesce(bddiasemana, 0) bddiasemana, BDANTECIPAR, COALESCE(tser.bdentrega, 0) BDDIAENTREGACAD, NULL as BDCODCID ';
  wsql = wsql||'FROM vct_base_servico tser ';
  wsql = wsql||'INNER JOIN vct_tributario_empresa trib ON (trib.bdcodser = tser.bdcodobrser AND trib.bdrefini <= SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 1 FOR 4)||SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 6 FOR 2) AND (trib.bdreffin >= SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 1 FOR 4)||SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 6 FOR 2) OR (trib.bdreffin IS NULL))) ';
  wsql = wsql||'inner join tempresas temp on (temp.bdcodemp = trib.bdcodemp and temp.bddatainiativemp < '''||wcurrent_date||''' and ((temp.bddatafimativemp > '''||wcurrent_date||''') or (temp.bddatafimativemp is null)))  ';
  wsql = wsql||'WHERE ((BDCRIACAO <= '''||wcurrent_date||''') OR (BDCRIACAO IS NULL)) ';
  wsql = wsql||'AND ((BDEXTINTO >= '''||wcurrent_date||''') OR (BDEXTINTO IS NULL)) ';
  wsql = wsql||'AND tser.bdtipo = 1 ';
  wsql = wsql||'AND tser.bdperiodicidade <> 11 ';-- indefinido
  IF (CODEMP <> 0) THEN
  wsql = wsql||'AND trib.bdcodemp = '||codemp;
  wsql = wsql||') AS trib ';
  FOR EXECUTE STATEMENT wsql
  INTO :wbdcodemp, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
       :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
       :wbdserie, :WBDPERIODICIDADE, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
       :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta, :wbdDIASEMANA, :wbdantecipar, :wbddiaentregacad, :wbdcodcid DO
  BEGIN
    -- Apenas empresas ativas
    IF ((SELECT FIRST 1 bdsitemp FROM tempresas_ref WHERE bdcodemp = :wbdcodemp AND bdrefemp <= :wbdrefsol ORDER BY bdrefemp DESC) <> 'TRUE') THEN
    BEGIN
       -- mensal - vencimento conforme par?metros
      IF ((wbdperiodicidade IN (0,1,2,3,4,5,6)) OR
       -- trimestral - gera mar?o, junho, setembro, dezembro com vencimento conforme parametros
       ((wbdperiodicidade = 7) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (3,6,9,12))) OR
       -- anual - gera no primeiro m?s do ano com vencimento no ano seguinte
       ((wbdperiodicidade = 10) AND (SUBSTRING(:wcurrent_date FROM 6 FOR 2) = 1))) THEN
      BEGIN
          -- Adilson Hasckel - sol. 18235 - 04/05/2017 - tarefa semanal de servi?os
          IF (wbdperiodicidade = 0) THEN -- se for segunda feira criar tarefa autom?tica semanal
            BEGIN
              wDataVencAux = wcurrent_date;
              wDiaSemanaData = EXTRACT(WEEKDAY FROM :wcurrent_date);
              IF (wDiaSemanaData = 1) THEN
                BEGIN
                   WHILE (EXTRACT(WEEKDAY FROM :wDataVencAux) <> :wbddiasemana) DO
                     wDataVencAux = wDataVencAux + 1;
                   -- verifica se h? o servi?o nas tarefas
                   IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodservico = :wbdcodservico AND bdrefsol = :wbdrefsol AND bddatasol = :wcurrent_date) IS NULL) THEN
                   BEGIN
                     wbdvencimento = wDataVencAux;
                     SELECT bddata FROM get_vencimento(:wbdvencimento, EXTRACT(DAY FROM :wbdvencimento), :wbdantecipar, 0, 0, :wbddiaentregacad, :wbdCodCid, 0, :wbdcodemp) INTO :wbdentrega;
                     wbdalerta     = wDataVencAux;
                     INSERT INTO vct_empresa_tsolicitatarefa
                      (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
                       bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
                       bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
                       bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)     
                      VALUES
                      (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
                       :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
                       :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
                       :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);
            
                      servicos = servicos + 1;
                      total = total + 1;
                   END
                END
            END
        ELSE
         -- verifica se h? o servi?o nas tarefas
        IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodservico = :wbdcodservico AND bdrefsol = :wbdrefsol) IS NULL) THEN
        BEGIN
          INSERT INTO vct_empresa_tsolicitatarefa
          (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
           bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
           bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
           bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)     
          VALUES
          (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
           :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
           :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
           :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

          servicos = servicos + 1;
          total = total + 1;
        END
      END
      ELSE
      -- trimestral parcelado - gera em mar?o com vencimento em Abril, Maio e junho
      --                      - gera em junho com vencimento em julho, agosto e setembro
      --                      - gera em setembro com vencimento em outubro, novembro e dezembro
      --                      - gera em dezembro com vencimento em janeiro, fevereiro e mar?o do ano seguinte
      IF (((wbdperiodicidade = 8) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (3,6,9,12))) OR
      -- trimestral antecipado - gera em janeiro com vencimento em fevereiro, mar?o e abril
      --                       - gera em abril com vencimento em maio, junho e julho
      --                       - gera em julho com vencimento em agosto, setembro e outubro
      --                       - gera em outubro com vencimento em novembro, dezembro e janeiro do pr?ximo ano
         ((wbdperiodicidade = 9) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (1,4,7,10)))) THEN
      BEGIN
        wcont = 0;
        wdata = :wcurrent_date;
        WHILE (wcont <= 2) DO
        BEGIN
          IF (wcont > 0) THEN
             wdata = addmonth(:wcurrent_date, wcont);
          wbdrefsol = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);
          SELECT (SELECT bddata FROM get_vencimento(:wdata, tser.bddia, tser.bdantecipar, tser.bdvence, tser.bdperiodicidade, NULL, NULL, tser.bdmesvence, :wcodemp)) AS bddatasolicitada,
                 (SELECT bddata FROM get_vencimento(:wdata, tser.bddia, tser.bdantecipar, tser.bdvence, tser.bdperiodicidade, NULL, NULL, tser.bdmesvence, :wcodemp)) AS bdvencimento,
                 (SELECT bddata FROM get_vencimento(:wdata, tser.bddia, tser.bdantecipar, tser.bdvence, tser.bdperiodicidade, COALESCE(tser.bdentrega, 0), NULL, tser.bdmesvence, :wcodemp)) AS bdentrega,
                 (SELECT bddata FROM get_vencimento(:wdata, tser.bddia, tser.bdantecipar, tser.bdvence, tser.bdperiodicidade, COALESCE(tser.bdalerta, 0), NULL, tser.bdmesvence, :wcodemp)) AS bdalerta
          FROM vct_base_servico tser
          WHERE tser.bdcodobrser = :wbdcodservico
          INTO :wbddatasolicitada, :wbdvencimento, :wbdentrega, :wbdalerta;

          -- verifica se h? o servi?o nas tarefas
          IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodservico = :wbdcodservico AND bdrefsol = :wbdrefsol) IS NULL) THEN
          BEGIN
            INSERT INTO vct_empresa_tsolicitatarefa
            (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
             bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
             bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
             bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)     
            VALUES
            (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
             :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
             :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
             :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

            servicos = servicos + 1;
            total = total + 1;
          END
          wcont = wcont + 1;
        END
      END
      ELSE
      IF (wbdperiodicidade = 12) THEN --Periodicidade di?ria, verifica??o todos os dias (n?o usa par?metro de antecipa??o de vencimento ? o pr?prio dia)
      BEGIN
        IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodservico = :wbdcodservico AND bdrefsol = :wbdrefsol AND bdvencimento = :wcurrent_date) IS NULL) THEN
        BEGIN
          wbdvencimento = wcurrent_date;
          wbdentrega    = wcurrent_date;
          wbdalerta     = wcurrent_date;
          INSERT INTO vct_empresa_tsolicitatarefa
          (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
           bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
           bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
           bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)     
          VALUES
          (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
           :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
           :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
           :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

          servicos = servicos + 1;
          total = total + 1;
        END
      END
    END
  END

      
  --Impostos
  wsql = 'SELECT bdcodemp, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo, ';
  wsql = wsql||'bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim, ';
  wsql = wsql||'bdserie, bdperiodicidade, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas, ';
  wsql = wsql||'bdtiposolicitacao, bdvencimento, bdentrega, bdalerta, bddiasemana, BDANTECIPA, BDDIAENTREGACAD, BDCODCID ';
  wsql = wsql||'FROM (SELECT trib.bdcodemp, NULL AS bdcodst, NULL AS bdcodcol, ';
  wsql = wsql||'timp.bdcodimp AS bdcodimp, NULL AS bdcodobrigacao, NULL AS bdcodservico, 501 AS bdcodtipo, ';
  wsql = wsql||'cast('''||wcurrent_date||''' as date) AS bddatasol, NULL AS bdfaturar, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', timp.bddiavencto, timp.bdantecipa, timp.bdmesvencto, timp.bdperapuracao, NULL, timp.bdcodcid, timp.bdmesvence, trib.bdcodemp)) AS bddatasolicitada, ';
  wsql = wsql||'NULL AS bddataprevisao, ';
  wsql = wsql||'NULL AS bddatafim, NULL AS bdserie, timp.bdperapuracao AS bdperiodicidade, ';
  wsql = wsql||'CAST(CASE WHEN (timp.bdperapuracao = 10) THEN SUBSTRING('''||wcurrent_date||''' FROM 1 FOR 4) ';
  wsql = wsql||'ELSE SUBSTRING('''||wcurrent_date||''' FROM 1 FOR 4)||SUBSTRING('''||wcurrent_date||''' FROM 6 FOR 2) END AS INTEGER) AS bdrefsol, ';
  wsql = wsql||'1 AS bdquantidade, 0 AS bdvalorunitario, 0 AS bdvalordesconto, 0 AS bdtipodesconto, 1 AS bdparcelas, 0 AS bdtiposolicitacao, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', timp.bddiavencto, timp.bdantecipa, timp.bdmesvencto, timp.bdperapuracao, NULL, timp.bdcodcid, timp.bdmesvence, trib.bdcodemp)) AS bdvencimento, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', timp.bddiavencto, timp.bdantecipa, timp.bdmesvencto, timp.bdperapuracao, COALESCE(timp.bdentrega, 0), timp.bdcodcid, timp.bdmesvence, trib.bdcodemp)) AS bdentrega, ';
  wsql = wsql||'(SELECT bddata FROM get_vencimento('''||wcurrent_date||''', timp.bddiavencto, timp.bdantecipa, timp.bdmesvencto, timp.bdperapuracao, COALESCE(timp.bdalertadias, 0), timp.bdcodcid, timp.bdmesvence, trib.bdcodemp)) AS bdalerta, ';
  wsql = wsql||'coalesce(bddiasemana, 0) bddiasemana, BDANTECIPA, COALESCE(timp.bdentrega, 0) BDDIAENTREGACAD, timp.bdcodcid ';
  wsql = wsql||'FROM timposto timp ';
  wsql = wsql||'INNER JOIN tempresaimposto trib ON (trib.bdcodimp = timp.bdcodimp AND trib.bdrefemp <= SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 1 FOR 4)||SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 6 FOR 2) AND (trib.bdreffimimp >= SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 1 FOR 4)||SUBSTRING(CAST('''||wcurrent_date||''' AS DATE) FROM 6 FOR 2) OR (trib.bdreffimimp IS NULL))) ';
  wsql = wsql||'inner join tempresas temp on (temp.bdcodemp = trib.bdcodemp and temp.bddatainiativemp < '''||wcurrent_date||''' and ((temp.bddatafimativemp > '''||wcurrent_date||''') or (temp.bddatafimativemp is null)))  ';
  wsql = wsql||'WHERE ((timp.bddatacriacao <= '''||wcurrent_date||''') OR (timp.bddatacriacao IS NULL)) ';
  wsql = wsql||'AND ((timp.bddataextinto >= '''||wcurrent_date||''') OR (timp.bddataextinto IS NULL)) ';
  wsql = wsql||'AND timp.BDTIPOCLASSIMP = 1 ';
  wsql = wsql||'AND timp.bdperapuracao <> 11 ';-- indefinido
  IF (codemp <> 0) THEN
     wsql = wsql||'AND trib.bdcodemp = '||CODEMP;
  wsql = wsql||') AS trib ';
  FOR EXECUTE STATEMENT wsql 
  INTO :wbdcodemp, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
       :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
       :wbdserie, :WBDPERIODICIDADE, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
       :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta, :wbddiasemana, :wbdantecipar, :wbddiaentregacad, :wbdcodcid DO
  BEGIN
    -- Apenas empresas ativas
    IF ((SELECT FIRST 1 bdsitemp FROM tempresas_ref WHERE bdcodemp = :wbdcodemp AND bdrefemp <= :wbdrefsol ORDER BY bdrefemp DESC) <> 'TRUE') THEN
    BEGIN
      -- mensal - vencimento conforme par?metros
      IF ((wbdperiodicidade IN (0,1,2,3,4,5,6)) OR
      -- trimestral - gera mar?o, junho, setembro, dezembro com vencimento conforme parametros
         ((wbdperiodicidade = 7) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (3,6,9,12))) OR
      -- anual - gera no primeiro m?s do ano com vencimento no ano seguinte
         ((wbdperiodicidade = 10) AND (SUBSTRING(:wcurrent_date FROM 6 FOR 2) = 1))) THEN
      BEGIN
          -- Adilson Hasckel - sol. 18235 - 04/05/2017 - tarefa semanal de impostos
          IF (wbdperiodicidade = 0) THEN -- se for segunda feira criar tarefa autom?tica semanal
            BEGIN
              wDataVencAux = wcurrent_date;
              wDiaSemanaData = EXTRACT(WEEKDAY FROM :wcurrent_date);
              IF (wDiaSemanaData = 1) THEN
                BEGIN
                   WHILE (EXTRACT(WEEKDAY FROM :wDataVencAux) <> :wbddiasemana) DO
                     wDataVencAux = wDataVencAux + 1;
                   -- verifica se h? a obriga??o nas tarefas
                   IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodimp = :wbdcodimp AND bdrefsol = :wbdrefsol AND bddatasol = :wcurrent_date) IS NULL) THEN
                   BEGIN
                     wbdvencimento = wDataVencAux;
                     SELECT bddata FROM get_vencimento(:wbdvencimento, EXTRACT(DAY FROM :wbdvencimento), :wbdantecipar, 0, 0, :wbddiaentregacad, :wbdCodCid, 0, :wbdcodemp) INTO :wbdentrega;
                     wbdalerta     = wDataVencAux;
                     INSERT INTO vct_empresa_tsolicitatarefa
                      (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
                       bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
                       bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
                       bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)
                      VALUES
                      (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
                       :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
                       :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
                       :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

                      impostos = impostos +1;
                      total = total + 1;
                   END
                END
            END
        ELSE
        -- verifica se h? o imposto nas tarefas
        IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodimp = :wbdcodimp AND bdrefsol = :wbdrefsol) IS NULL) THEN
        BEGIN
          INSERT INTO vct_empresa_tsolicitatarefa
          (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
           bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
           bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
           bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)
          VALUES
          (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
           :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
           :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
           :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

          impostos = impostos +1;
          total = total + 1;
        END
      END
      ELSE
      -- trimestral parcelado - gera em mar?o com vencimento em Abril, Maio e junho
      --                      - gera em junho com vencimento em julho, agosto e setembro
      --                      - gera em setembro com vencimento em outubro, novembro e dezembro
      --                      - gera em dezembro com vencimento em janeiro, fevereiro e mar?o do ano seguinte
      IF (((wbdperiodicidade = 8) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (3,6,9,12))) OR
      -- trimestral antecipado - gera em janeiro com vencimento em fevereiro, mar?o e abril
      --                       - gera em abril com vencimento em maio, junho e julho
      --                       - gera em julho com vencimento em agosto, setembro e outubro
      --                       - gera em outubro com vencimento em novembro, dezembro e janeiro do pr?ximo ano
        ((wbdperiodicidade = 9) AND (SUBSTRING(wbdrefsol FROM 5 FOR 2) IN (1,4,7,10)))) THEN
      BEGIN
        wcont = 0;
        wdata = :wcurrent_date;
        WHILE (wcont <= 2) DO
        BEGIN
          IF (wcont > 0) THEN
             wdata = addmonth(:wcurrent_date, wcont);
          wbdrefsol = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);
          SELECT (SELECT bddata FROM get_vencimento(:wdata, timp.bddiavencto, timp.bdantecipa, timp.bdmesvencto, timp.bdperapuracao, NULL, timp.bdcodcid, timp.bdmesvence, :wcodemp)) AS bddatasolicitada,
                 (SELECT bddata FROM get_vencimento(:wdata, timp.bddiavencto, timp.bdantecipa, timp.bdmesvencto, timp.bdperapuracao, NULL, timp.bdcodcid, timp.bdmesvence, :wcodemp)) AS bdvencimento,
                 (SELECT bddata FROM get_vencimento(:wdata, timp.bddiavencto, timp.bdantecipa, timp.bdmesvencto, timp.bdperapuracao, COALESCE(timp.bdentrega, 0), timp.bdcodcid, timp.bdmesvence, :wcodemp)) AS bdentrega,
                 (SELECT bddata FROM get_vencimento(:wdata, timp.bddiavencto, timp.bdantecipa, timp.bdmesvencto, timp.bdperapuracao, COALESCE(timp.bdalertadias, 0), timp.bdcodcid, timp.bdmesvence, :wcodemp)) AS bdalerta
          FROM timposto timp
          WHERE timp.bdcodimp = :wbdcodimp
          INTO :wbddatasolicitada, :wbdvencimento, :wbdentrega, :wbdalerta;


          -- verifica se h? o imposto nas tarefas
          IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodimp = :wbdcodimp AND bdrefsol = :wbdrefsol) IS NULL) THEN
          BEGIN
            INSERT INTO vct_empresa_tsolicitatarefa
            (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
             bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
             bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
             bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)
            VALUES
            (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
             :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
             :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
             :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

            impostos = impostos +1;
            total = total + 1;
          END
          wcont = wcont + 1;
        END
      END
      ELSE
      IF (wbdperiodicidade = 12) THEN --Periodicidade di?ria, verifica??o todos os dias (n?o usa par?metro de antecipa??o de vencimento ? o pr?prio dia)
      BEGIN
        IF ((SELECT bdcodst FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = :wbdcodemp AND bdcodimp = :wbdcodimp AND bdrefsol = :wbdrefsol AND bdvencimento = :wcurrent_date) IS NULL) THEN
        BEGIN
          wbdvencimento = wcurrent_date;
          wbdentrega    = wcurrent_date;
          wbdalerta     = wcurrent_date;
          INSERT INTO vct_empresa_tsolicitatarefa
          (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
           bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
           bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
           bdtiposolicitacao, bdvencimento, bdentrega, bdalerta)
          VALUES
          (:wbdcodemp, NULL, :wbdcodcol, :wbdcodimp, :wbdcodobrigacao, :wbdcodservico, :wbdcodtipo,
           :wbddatasol, :wbdfaturar, :wbddatasolicitada, :wbddataprevisao, :wbddatafim,
           :wbdserie, :wbdrefsol, :wbdquantidade, :wbdvalorunitario, :wbdvalordesconto, :wbdtipodesconto, :wbdparcelas,
           :wbdtiposolicitacao, :wbdvencimento, :wbdentrega, :wbdalerta);

          impostos = impostos +1;
          total = total + 1;
        END
      END
    END
  END

 wTotalImpostos   = impostos;
 wTotalServicos   = servicos;
 wTotalObrigacoes = obrigacoes;
 wTotal           = total;

  SUSPEND;

  EXECUTE PROCEDURE sp_inserir_log(:codemp, NULL, COALESCE((SELECT bdcodusu FROM sp_get_usuario), 1), NULL, 8, NULL, :wcurrent_date, CURRENT_TIME, 'O servidor executou a rotina de gera??o das tarefas autom?ticas'||ASCII_CHAR(13)||'Impostos: '||:wTotalImpostos||ASCII_CHAR(13)||'Obriga??es: '||:wTotalObrigacoes||ASCII_CHAR(13)||'Servi?os: '||:wTotalServicos||ASCII_CHAR(13)||'Total: '||:wTotal, 0, 0, 'Servidor', 'Servidor', 'ServidorSCI', 'Thread de tarefas autom?ticas', NULL, 'VCT_TAREFAS_AUTOMATICAS', NULL, 'FALSE', :wcurrent_date);
END
^

/* Alter (VEF_COPIA_PLANO) */
ALTER PROCEDURE VEF_COPIA_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
IMPOSTO VARCHAR(10))
 RETURNS(CODIGONOVORETORNO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WTABCONF VARCHAR(32);
DECLARE VARIABLE WTABQUADROS VARCHAR(32);
DECLARE VARIABLE WTABFORMULA VARCHAR(32);
DECLARE VARIABLE WCAMPO VARCHAR(32);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(1000);
DECLARE VARIABLE WCAMPOPK VARCHAR(10);
BEGIN
  /* Zera os nomes das tabelas */
  wCampoPK    = '';
  wTabConf    = '';
  wTabQuadros = '';
  wTabFormula = '';
  /* Obt?m as tabelas do plano */
  IF (IMPOSTO = 'DASN') THEN
    BEGIN
      wCampoPK    = IMPOSTO;
      wTabConf    = 'VEF_BASE_TCONFDASN';
      wTabQuadros = 'VEF_BASE_TCONFDASNQ';
      wTabFormula = 'VEF_BASE_TCONFDASNFORM';
    END
  ELSE
    IF (IMPOSTO = 'DIME') THEN
      BEGIN
        wCampoPK    = 'DIMESC';
        wTabConf    = 'VEF_ESTADOS_TCONFDIMESC';
        wTabQuadros = 'VEF_ESTADOS_TCONFDIMEQ';
        wTabFormula = 'VEF_ESTADOS_TCONFDIMEFORM';
      END

  /* Insere os registros das formulas */
  IF ((wTabConf <> '') AND (wTabQuadros <> '') AND (wTabFormula <> '')) THEN
    BEGIN
      /* Caso o c?digo novo seja zero, obt?m o c?digo novo */
      IF ((CodigoNovo IS NULL) OR (CodigoNovo = 0)) THEN
        BEGIN
          wSQL = 'SELECT MAX(BDCODCONF'||wCampoPK||') FROM '||wTabConf;
          EXECUTE STATEMENT wSQL INTO CodigoNovo;
        END
      /* Retorno o c?digo novo */
      CodigoNovoRetorno = CodigoNovo;
      /* Limpa a tabela de formulas no c?digo novo */
      wSQL = 'DELETE FROM '||wTabFormula||' WHERE BDCODCONF'||wCampoPK||' = '||:CodigoNovo;
      EXECUTE STATEMENT wSQL;
      /* Obt?m os campos da tabela de formulas */
      wSQL = 'SELECT r.RDB$FIELD_NAME as BDCAMPO '||
             'FROM RDB$RELATION_FIELDS r '||
             'WHERE r.RDB$RELATION_NAME = '''||wTabFormula||'''';
      wCamposInsert = '';
      FOR EXECUTE STATEMENT wSQL
      INTO wCampo DO
        BEGIN
          IF (wCampo <> 'BDCODCONF'||wCampoPK) THEN
            wCamposInsert = wCamposInsert||','||TRIM(wCampo);
        END
      /* Cria insert da tabela de formulas */
      wSQL = 'INSERT INTO '||wTabFormula||' ('||'BDCODCONF'||wCampoPK||wCamposInsert||') '||
             ' SELECT '||CodigoNovo||wCamposInsert||' FROM '||wTabFormula||' WHERE '||'BDCODCONF'||wCampoPK||' = '||CODIGOCOPIAR;
      EXECUTE STATEMENT wSQL;
    END
END
^

/* Alter (VEF_COPIA_PLANO_DIME) */
ALTER PROCEDURE VEF_COPIA_PLANO_DIME(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(1000);
DECLARE VARIABLE WCAMPO VARCHAR(32);
BEGIN
  /* Insere as formulas */
  EXECUTE STATEMENT 'EXECUTE PROCEDURE VEF_COPIA_PLANO('||CodigoNovo||','||CodigoCopiar||',''DIME'')' INTO CodigoNovo;

  /*** VEF_ESTADOS_TCONFDIMEFQ46 ***/
  /* Deleta os registros do quadro 46 */
  wSQL = 'DELETE FROM VEF_ESTADOS_TCONFDIMEFQ46 WHERE BDCODCONFDIMESC = '||:CodigoNovo;
  EXECUTE STATEMENT wSQL;

  /* Obt?m os campos da tabela "VEF_ESTADOS_TCONFDIMEFQ46" */
  wSQL = 'SELECT r.RDB$FIELD_NAME as BDCAMPO '||
         'FROM RDB$RELATION_FIELDS r '||
         'WHERE r.RDB$RELATION_NAME = ''VEF_ESTADOS_TCONFDIMEFQ46''';
  wCamposInsert = '';
  FOR EXECUTE STATEMENT wSQL
  INTO wCampo DO
    BEGIN
      IF (wCampo <> 'BDCODCONFDIMESC') THEN
        wCamposInsert = wCamposInsert||','||TRIM(wCampo);
    END
  /* Cria insert da tabela "VEF_ESTADOS_TCONFDIMEFQ46" */
  wSQL = 'INSERT INTO VEF_ESTADOS_TCONFDIMEFQ46 (BDCODCONFDIMESC'||wCamposInsert||') '||
         ' SELECT '||CodigoNovo||wCamposInsert||' FROM VEF_ESTADOS_TCONFDIMEFQ46 WHERE BDCODCONFDIMESC = '||CODIGOCOPIAR;
  EXECUTE STATEMENT wSQL;


  /*** VEF_ESTADOS_TCONFDIMEFQ12 ***/
  /* Deleta os registros do quadro 12 */
  wSQL = 'DELETE FROM VEF_ESTADOS_TCONFDIMEFQ12 WHERE BDCODCONFDIMESC = '||:CodigoNovo;
  EXECUTE STATEMENT wSQL;

  /* Obt?m os campos da tabela "VEF_ESTADOS_TCONFDIMEFQ12" */
  wSQL = 'SELECT r.RDB$FIELD_NAME as BDCAMPO '||
         'FROM RDB$RELATION_FIELDS r '||
         'WHERE r.RDB$RELATION_NAME = ''VEF_ESTADOS_TCONFDIMEFQ12''';
  wCamposInsert = '';
  FOR EXECUTE STATEMENT wSQL
  INTO wCampo DO
    BEGIN
      IF (wCampo <> 'BDCODCONFDIMESC') THEN
        wCamposInsert = wCamposInsert||','||TRIM(wCampo);
    END
  /* Cria insert da tabela "VEF_ESTADOS_TCONFDIMEFQ12" */
  wSQL = 'INSERT INTO VEF_ESTADOS_TCONFDIMEFQ12 (BDCODCONFDIMESC'||wCamposInsert||') '||
         ' SELECT '||CodigoNovo||wCamposInsert||' FROM VEF_ESTADOS_TCONFDIMEFQ12 WHERE BDCODCONFDIMESC = '||CODIGOCOPIAR;
  EXECUTE STATEMENT wSQL;
END
^

/* Alter (VEF_COPIA_PLANO_GIA) */
ALTER PROCEDURE VEF_COPIA_PLANO_GIA(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
TIPOGIA VARCHAR(10))
 AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WINSERT VARCHAR(1000);
DECLARE VARIABLE WBDCODCONF INTEGER;
DECLARE VARIABLE WBDCODQ INTEGER;
DECLARE VARIABLE WBDNUMCAMPO INTEGER;
DECLARE VARIABLE WBDNUMITEM VARCHAR(5); --integer
DECLARE VARIABLE WBDDESCFORM VARCHAR(60);
DECLARE VARIABLE WBDCAMPOINATIVO VARCHAR(5);
DECLARE VARIABLE WBDFORMULA VARCHAR(30000);
DECLARE VARIABLE WBDCODITEMONLINE INTEGER;
DECLARE VARIABLE WBDCODIMP INTEGER;
DECLARE VARIABLE WBDSEQLIVRO VARCHAR(3);
DECLARE VARIABLE WBDINIVALIDADE DATE;
DECLARE VARIABLE WBDFIMVALIDADE DATE;
BEGIN

  WSQL = 'delete from VEF_ESTADOS_TCONFGIA'||TIPOGIA||'FORM WHERE BDCODCONF = '||:codigonovo;
  EXECUTE STATEMENT WSQL;

  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
     BEGIN
        WSQL = 'SELECT max(BDCODCONF) from VEF_ESTADOS_TCONFGIA'||TIPOGIA;
        EXECUTE STATEMENT WSQL INTO codigonovo;
     END

  WSQL = ' select BDCODCONF, BDCODQUADRO,bdnumcampo,BDDESCFORM,BDFORMULA,BDNUMITEM, BDCAMPOINATIVO,BDCODITEMONLINE ';
  IF (TIPOGIA = 'MG') THEN
    WSQL = WSQL || ', BDCODIMP, BDSEQLIVRO, BDINIVALIDADE, BDFIMVALIDADE ';
  WSQL = WSQL || ' from VEF_ESTADOS_TCONFGIA'||TIPOGIA||'form ';
  WSQL = WSQL || ' where BDCODCONF = '|| :codigocopiar;

  IF (TIPOGIA = 'MG') THEN
    BEGIN -- Alt.: 11211 - N?o estava levando as informa??es de c?digo de imposto e sequ?ncial do livro na c?pia do MG.
      FOR EXECUTE STATEMENT WSQL
          INTO
            wBDCODCONF,
            wBDCODQ,
            wBDNUMCAMPO,
            wBDDESCFORM,
            wBDFORMULA,
            wBDNUMITEM,
            wBDCAMPOINATIVO,
            wBDCODITEMONLINE,
            wBDCODIMP,
            wBDSEQLIVRO,
            WBDINIVALIDADE,
            WBDFIMVALIDADE  DO
         BEGIN
            WINSERT = 'UPDATE OR INSERT INTO VEF_ESTADOS_TCONFGIA'||TIPOGIA||'FORM (BDCODCONF, bdcodquadro,bdnumcampo,BDDESCFORM,BDFORMULA,BDNUMITEM, BDCAMPOINATIVO,BDCODITEMONLINE, BDCODIMP, BDSEQLIVRO, BDINIVALIDADE, BDFIMVALIDADE)';
            WINSERT = WINSERT || ' values ('||:codigonovo||','||wBDCODQ||','||wBDNUMCAMPO||','''||:wBDDESCFORM||''','''||:wbdformula||''','||:wBDNUMITEM||','''||:wBDCAMPOINATIVO||''',';
    
            IF (wBDCODITEMONLINE IS NULL) THEN
              WINSERT = WINSERT ||'null,';
            ELSE
              WINSERT = WINSERT ||:wBDCODITEMONLINE||',';

            IF (wBDCODIMP IS NULL) THEN
              WINSERT = WINSERT ||'null,';
            ELSE
              WINSERT = WINSERT ||:wBDCODIMP||',';

            IF (wBDSEQLIVRO IS NULL) THEN
              WINSERT = WINSERT ||'null,';
            ELSE
              WINSERT = WINSERT ||''''||:wBDSEQLIVRO||''',';

            --sol:10586
            IF (WBDINIVALIDADE IS NULL) THEN
              WINSERT = WINSERT ||'null,';
            ELSE
              WINSERT = WINSERT ||''''||:WBDINIVALIDADE||''',';

            --sol:10586
            IF (WBDFIMVALIDADE IS NULL) THEN
              WINSERT = WINSERT ||'null)';
            ELSE
              WINSERT = WINSERT ||''''||:WBDFIMVALIDADE||''')';

            WINSERT = WINSERT||' MATCHING (BDCODCONF, BDCODQUADRO, BDNUMCAMPO)';
    
            EXECUTE STATEMENT WINSERT;
         END
    END
  ELSE
    BEGIN
      FOR EXECUTE STATEMENT WSQL
          INTO
            wBDCODCONF,
            wBDCODQ,
            wBDNUMCAMPO,
            wBDDESCFORM,
            wBDFORMULA,
            wBDNUMITEM,
            wBDCAMPOINATIVO,
            wBDCODITEMONLINE  DO
         BEGIN
            WINSERT = 'UPDATE OR INSERT INTO VEF_ESTADOS_TCONFGIA'||TIPOGIA||'FORM (BDCODCONF, bdcodquadro,bdnumcampo,BDDESCFORM,BDFORMULA,BDNUMITEM, BDCAMPOINATIVO,BDCODITEMONLINE)';
            WINSERT = WINSERT || ' values ('||:codigonovo||','||wBDCODQ||','||wBDNUMCAMPO||','''||:wBDDESCFORM||''','''||:wbdformula||''','||:wBDNUMITEM||','''||:wBDCAMPOINATIVO||''',';
    
            IF (wBDCODITEMONLINE IS NULL) THEN
              BEGIN
                WINSERT = WINSERT ||'null)';
              END
            ELSE
              BEGIN
                WINSERT = WINSERT ||:wBDCODITEMONLINE||')';
              END
    
            WINSERT = WINSERT||' MATCHING (BDCODCONF, BDCODQUADRO, BDNUMCAMPO)';
    
            EXECUTE STATEMENT WINSERT;
         END
    END

END
^

/* Alter (VEF_SP_BASE_CONFBASESNNATOP) */
ALTER PROCEDURE VEF_SP_BASE_CONFBASESNNATOP(PRATV VARCHAR(15),
PRNAT INTEGER,
PRFORMASEQUENCIA INTEGER)
 RETURNS(BDCODCONFSN INTEGER,
BDDESCIMP VARCHAR(200),
BDDESCTIPOIMP VARCHAR(200),
BDDESC VARCHAR(500),
BDCODNAT INTEGER,
BDCODATIVSIMPNAC INTEGER,
BDCODCONFSNREAL INTEGER,
BDATIVIDADE INTEGER,
BDCODIMPOSTO INTEGER,
BDCODTIPOIMPOSTO INTEGER,
BDCODBASESN INTEGER,
BDCODCONFATVMSN INTEGER,
BDPREPONDERANTE VARCHAR(5),
BDCODCONFSNTAB INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE FORDEM INTEGER;
BEGIN
  /* Procedure Text */

--  execute procedure sp_seta_competencia(pranomesinicial, null, null);

  wsql = '';

  wSql = wSql || ' select SN.bdcodconfsn, SNI.bddescimp, SNIT.bddesctipoimp ,snb.BDDESC, SN.bdcodnat,sn.BDCODATIVSIMPNAC, SN.bdcodconfsn bdcodconfsnReal, ';
  wSql = wSql || ' 0 BDATIVIDADE,SNI.BDCODIMPOSTO,SN.BDCODTIPOIMPOSTO,sn.bdcodbasesn, 0 BDCODCONFATVMSN, sn.bdpreponderante, SN.bdcodconfsn bdcodconfsntab ';
  wSql = wSql || ' from VEF_BASE_TNATOPCONFSN sn ';
  wSql = wSql || ' left outer join VEF_BASE_TCADIMPOSTOSN SNI on (sni.bdcodimposto = sn.bdcodimposto) ';
  wSql = wSql || ' left outer join VEF_BASE_TCADTIPOIMPOSTO SNIT on (snit.bdcodtipoimposto = sn.bdcodtipoimposto) ';
  wsql = wsql || ' left outer join VEF_BASE_TCADBASESN SNb on (snb.bdcodbasesn = sn.bdcodbasesn) ';

  IF ((prAtv IS NOT NULL) AND (prAtv <> ''))  THEN
    BEGIN
      wsql = wsql || ' where sn.BDCODATIVSIMPNAC in('||pratv||') ';
    END

  IF ((prNat IS NOT NULL) AND (prNat <> 0))  THEN
    BEGIN
      wsql = wsql || ' and sn.BDCODNAT = '||prNat;
    END

  Fordem = 0;
  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodconfsn,
      :bddescimp,
      :bddesctipoimp,
      :BDDESC,
      :bdcodnat,
      :BDCODATIVSIMPNAC,
      :bdcodconfsnReal,
      :BDATIVIDADE,
      :BDCODIMPOSTO,
      :BDCODTIPOIMPOSTO,
      :bdcodbasesn,
      :BDCODCONFATVMSN,
      :bdpreponderante,
      :bdcodconfsntab
    DO
    BEGIN
      /* se tem so uma atividade n?o vai forma outra sequencia*/
      IF (prFormaSequencia = 1)  THEN
        BEGIN
          Fordem = FOrdem + 1;
          bdcodconfsn = fordem;
        END
      SUSPEND;
  
    END
  
END
^

/* Alter (VEF_SP_CONSULTA_VINCULOISS) */
ALTER PROCEDURE VEF_SP_CONSULTA_VINCULOISS(PRCODCID INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDREFVINCISS INTEGER,
BDCODTIPOISS INTEGER,
BDDESTIPOISS VARCHAR(50),
BDCODTIPOISSEXP INTEGER,
BDDESTIPOISSEXP VARCHAR(50),
BDPERISS DM_NUMERIC_7_4_ALIQ,
BDVALORLIMISS DM_NUMERIC_15_2,
BDCODTIPORPS INTEGER,
BDDESTIPORPS VARCHAR(50),
BDCODIBGE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WWHERE VARCHAR(3000);
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

    wSql = ' select ';
    wSql = wSql || 'BDCODCID, ';
    wSql = wSql || 'BDNOMCID, ';
    wSql = wSql || 'BDREFVINCISS, ';
    wSql = wSql || 'BDCODTIPOISS, ';
    wSql = wSql || 'BDDESTIPOISS, ';
    wSql = wSql || 'BDCODTIPOISSEXP, ';
    wSql = wSql || 'BDDESTIPOISSEXP, ';
    wSql = wSql || 'BDPERISS, ';
    wSql = wSql || 'BDVALORLIMISS, ';
    wSql = wSql || 'BDCODTIPORPS, ';
    wSql = wSql || 'BDDESTIPORPS, ';
    wSql = wSql || 'bdCODIBGE ';
    wSql = wsql || 'from vw_vef_base_tvinculoiss ';

    wwhere = '';

    IF (prCODCID >  0) THEN
       wWhere = 'where BDCODCID = '||prcodcid||' ';

    wsql = wsql||wwhere||'order by BDCODCID, BDREFVINCISS';
    FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODCID,
      :BDNOMCID ,
      :BDREFVINCISS,
      :BDCODTIPOISS,
      :BDDESTIPOISS,
      :BDCODTIPOISSEXP,
      :BDDESTIPOISSEXP,
      :BDPERISS,
      :BDVALORLIMISS,
      :BDCODTIPORPS,
      :BDDESTIPORPS,
      :bdCODIBGE
    DO
    SUSPEND;
END
^

/* Alter (VEF_SP_DADOS_ISS_EXP) */
ALTER PROCEDURE VEF_SP_DADOS_ISS_EXP(PRWHEREISS VARCHAR(10000) = NULL,
PRWHERECID VARCHAR(10000) = NULL,
PRWHEREEMP VARCHAR(32000) = NULL,
PRREFINI INTEGER = 0,
PRREFFIN INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODCID INTEGER,
BDCODTIPOISSEXP INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32000);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WMES VARCHAR(2);
DECLARE VARIABLE WANO VARCHAR(4);
BEGIN
  /*
    Data ?ltima altera??o: 02/08/2013 11:54
    para cada referencia entre a ref. inicial e final,
    cria um registro com:
      -c?digo da empresa
      -c?digo da cidade
      -referencia atual
      -c?digo do tipo de ISS
  */

  IF (NOT ((prwhereiss IS NULL) OR (prwherecid IS NULL) OR (PRWHEREEMP IS NULL) OR (PRREFINI = 0) OR (PRREFFIN = 0))) THEN
    BEGIN
      WWHERE  = '';
      WREFATU = PRREFINI;

      IF (PRWHEREEMP <> '') THEN
         WWHERE = ' WHERE '||PRWHEREEMP;
    
      WHILE (:WREFATU <= PRREFFIN) DO
        BEGIN
          --seta competencia para a referencia atual
          EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:WREFATU);

          /*se na tabela do vinculoISS existe cadastrado algum registro com referencia menor do que a referencia atual, utiliza esse registro,
            caso contrario, procura pelo registro com a menor referencia que seja maior do que a referencia atual*/
          WSQL = 'SELECT I.BDCODEMP, I.BDCODCID, ISS.BDCODTIPOISSEXP, i.BDREFVINCISS FROM ';
          WSQL = WSQL||'( ';
          WSQL = WSQL||'SELECT I.BDCODEMP, I.BDCODCID, MIN(I.BDREFVINCISS) BDREFVINCISS FROM ';
          WSQL = WSQL||'     ( ';

          --pega o registro com a maior referencia, menor ou igual a referencia atual
          WSQL = WSQL||'         SELECT E.BDCODEMP, I.BDCODCID, MAX(I.BDREFVINCISS) BDREFVINCISS FROM VEF_BASE_TVINCULOISS I ';
          WSQL = WSQL||'         INNER JOIN (SELECT E.BDCODEMP, E.BDCODCID, E.BDREFEMP FROM VW_TEMPRESAS_REF E'||WWHERE||') E ON E.BDCODCID = I.BDCODCID ';
          WSQL = WSQL||'         WHERE I.BDREFVINCISS <= '||WREFATU;
          WSQL = WSQL||'         GROUP BY E.BDCODEMP, I.BDCODCID ';

          WSQL = WSQL||'         UNION ALL ';

          --pega o registro com a menor referencia, maior do que a referencia atual
          WSQL = WSQL||'         SELECT E.BDCODEMP, I.BDCODCID, MIN(I.BDREFVINCISS) BDREFVINCISS FROM VEF_BASE_TVINCULOISS I ';
          WSQL = WSQL||'         INNER JOIN (SELECT E.BDCODEMP, E.BDCODCID, E.BDREFEMP FROM VW_TEMPRESAS_REF E'||WWHERE||') E ON E.BDCODCID = I.BDCODCID ';
          WSQL = WSQL||'         WHERE I.BDREFVINCISS >  '||WREFATU;
          WSQL = WSQL||'         GROUP by e.bdcodemp, i.bdcodcid ';

          wsql = wsql||'     ) i ';
          wsql = wsql||'group by i.bdcodemp, i.bdcodcid ';
          wsql = wsql||') i ';
          wsql = wsql||'LEFT outer join VEF_BASE_TVINCULOISS ISS ON ISS.BDCODCID = I.BDCODCID AND ISS.BDREFVINCISS = I.BDREFVINCISS ';

          IF (prwherecid <> '') THEN
             wsql = 'select * from ('||wsql||') i where '||prwherecid;

          IF (prwhereiss <> '') THEN
             wsql = 'select * from ('||wsql||') i where '||prwhereiss;

          FOR EXECUTE STATEMENT WSQL
          INTO
            :BDCODEMP,
            :BDCODCID,
            :BDCODTIPOISSEXP,
            :BDREFEMP
          DO
            BEGIN
              BDREFEMP = WREFATU;
              SUSPEND;
            END

          /*pegar pr?xima referencia*/
          WANO = SUBSTRING(:WREFATU FROM 1 FOR 4);
          WMES = SUBSTRING(:WREFATU FROM 5 FOR 2);

          SELECT R.ANO, R.MES FROM REF_SEGUINTE(:WMES, :WANO) R INTO :WANO, :WMES;

          IF (CHAR_LENGTH(:WMES) < 2) THEN
             WMES = '0'||:WMES;

          WREFATU = :WANO||:WMES;
        END
    END
END
^

/* Alter (VEF_SP_DIMEQ46) */
ALTER PROCEDURE VEF_SP_DIMEQ46 RETURNS(BDCODPERIODO INTEGER,
BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDCODQDIME INTEGER,
BDNUMCAMPO INTEGER,
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODUF INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDQ12 VARCHAR(5),
BDQ46 VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCONT INTEGER;
DECLARE VARIABLE WCODPERIODOAUX INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WREFERENCIAAUX INTEGER;
DECLARE VARIABLE WTOTAL NUMERIC(18,6);
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WCODQDIME INTEGER;
DECLARE VARIABLE WCODPERIODOBKP INTEGER;
DECLARE VARIABLE WCODEMPBKP INTEGER;
DECLARE VARIABLE WREFERENCIABKP INTEGER;
DECLARE VARIABLE WCODQDIMEBKP INTEGER;
DECLARE VARIABLE WNUMCAMPOBKP INTEGER;
DECLARE VARIABLE WCODNATBKP INTEGER;
DECLARE VARIABLE WVALORBKP NUMERIC(18,6);
DECLARE VARIABLE WCODCIDBKP INTEGER;
DECLARE VARIABLE WCODCIDTOTBKP INTEGER;
DECLARE VARIABLE WCODUFBKP INTEGER;
DECLARE VARIABLE WDATARECBKP DATE;
DECLARE VARIABLE WCLAVENDIMEGERQ12BKP INTEGER;
DECLARE VARIABLE WCODRECDIMEGERQ12BKP INTEGER;
DECLARE VARIABLE WORIGEMDIMEGERQ46BKP INTEGER;
DECLARE VARIABLE WIDENTIFICACAOREGESPBKP VARCHAR(15);
DECLARE VARIABLE WQ12BKP VARCHAR(5);
DECLARE VARIABLE WQ46BKP VARCHAR(5);
BEGIN
  wsql = 'select BDCODPERIODO,BDCODEMP,BDREFERENCIA,BDCODQDIME,BDNUMCAMPO,BDCODNAT,BDVALOR,BDCODCID,';
  wsql = wsql || ' BDCODCIDTOT,BDCODUF,BDDATAREC,BDCLAVENDIMEGERQ12,BDCODRECDIMEGERQ12,BDORIGEMDIMEGERQ46,BDIDENTIFICACAOREGESP,BDQ12,BDQ46';
  wsql = wsql || ' from VEF_SP_DADOSQ46 ';
  wsql = wsql || ' WHERE BDVALOR > 0';

  wsql = wsql || ' ORDER BY BDCODPERIODO,BDCODEMP,BDREFERENCIA';--FOI NECESS?RIO CRIAR OUTRA STORE PROCEDURE POIS N?O TEM COMO COLOCAR ORDER BY NO UNION
  WCont = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODPERIODO,
    BDCODEMP,
    BDREFERENCIA,
    BDCODQDIME,
    BDNUMCAMPO,
    BDCODNAT,
    BDVALOR,
    BDCODCID,
    BDCODCIDTOT,
    BDCODUF,
    BDDATAREC,
    BDCLAVENDIMEGERQ12,
    BDCODRECDIMEGERQ12,
    BDORIGEMDIMEGERQ46,
    BDIDENTIFICACAOREGESP,
    BDQ12,
    BDQ46
  DO
  BEGIN
    IF (wCont = 0) THEN
      BEGIN
         WCODPERIODOAUX = BDCODPERIODO;
         wcodempaux = BDCODEMP;
         wreferenciaaux = BDREFERENCIA;
         WTOTAL = 0;
      END

    wCont = 1;

    IF ((WCODPERIODOAUX <> BDCODPERIODO) OR (wcodempaux <> BDCODEMP) OR (wreferenciaaux <> BDREFERENCIA)) THEN--990
       BEGIN
        WCODPERIODOBKP = BDCODPERIODO;
        WCODEMPBKP = BDCODEMP;
        WREFERENCIABKP = BDREFERENCIA;
        WCODQDIMEBKP = BDCODQDIME;
        WNUMCAMPOBKP = BDNUMCAMPO;
        WCODNATBKP = BDCODNAT;
        WVALORBKP = BDVALOR;
        WCODCIDBKP = BDCODCID;
        WCODCIDTOTBKP = BDCODCIDTOT;
        WCODUFBKP = BDCODUF;
        WDATARECBKP = BDDATAREC;
        WCLAVENDIMEGERQ12BKP = BDCLAVENDIMEGERQ12;
        WCODRECDIMEGERQ12BKP = BDCODRECDIMEGERQ12;
        WORIGEMDIMEGERQ46BKP = BDORIGEMDIMEGERQ46;
        WIDENTIFICACAOREGESPBKP = BDIDENTIFICACAOREGESP;
        WQ12BKP = BDQ12;
        WQ46BKP = BDQ46;

        BDCODPERIODO = wCODPERIODO;
        BDCODEMP = wCODEMP;
        BDREFERENCIA = wREFERENCIA;
        BDCODQDIME = wCODQDIME;
        BDNUMCAMPO = 990;
        BDCODNAT = NULL;
        BDVALOR = WTOTAL;
        BDCODCID = NULL;
        BDCODCIDTOT = NULL;
        BDCODUF = NULL;
        BDDATAREC = NULL;
        BDCLAVENDIMEGERQ12 = NULL;
        BDCODRECDIMEGERQ12 = NULL;
        BDORIGEMDIMEGERQ46 = NULL;
        BDIDENTIFICACAOREGESP = NULL;
        BDQ12 = 'FALSE';
        BDQ46 = 'TRUE';

        SUSPEND;

        WTOTAL = 0;

        BDCODPERIODO = WCODPERIODOBKP;
        BDCODEMP = WCODEMPBKP;
        BDREFERENCIA = WREFERENCIABKP;
        BDCODQDIME = WCODQDIMEBKP;
        BDNUMCAMPO = WNUMCAMPOBKP;
        BDCODNAT = WCODNATBKP;
        BDVALOR = WVALORBKP;
        BDCODCID = WCODCIDBKP;
        BDCODCIDTOT = WCODCIDTOTBKP;
        BDCODUF = WCODUFBKP;
        BDDATAREC = WDATARECBKP;
        BDCLAVENDIMEGERQ12 = WCLAVENDIMEGERQ12BKP;
        BDCODRECDIMEGERQ12 = WCODRECDIMEGERQ12BKP;
        BDORIGEMDIMEGERQ46 = WORIGEMDIMEGERQ46BKP;
        BDIDENTIFICACAOREGESP = WIDENTIFICACAOREGESPBKP;
        BDQ12 = WQ12BKP;
        BDQ46 = WQ46BKP;
       END

    WTOTAL = WTOTAL + BDVALOR;

    SUSPEND;

    WCODPERIODO = BDCODPERIODO;
    WCODEMP = BDCODEMP;
    WREFERENCIA = BDREFERENCIA;
    WCODQDIME = BDCODQDIME;

    WCODPERIODOAUX = BDCODPERIODO;
    wcodempaux = BDCODEMP;
    wreferenciaaux = BDREFERENCIA;
  END

  IF (wCont > 0) THEN--990
    BEGIN
      BDCODPERIODO = wCODPERIODO;
      BDCODEMP = wCODEMP;
      BDREFERENCIA = wREFERENCIA;
      BDCODQDIME = wCODQDIME;
      BDNUMCAMPO = 990;
      BDCODNAT = NULL;
      BDVALOR = WTOTAL;
      BDCODCID = NULL;
      BDCODCIDTOT = NULL;
      BDCODUF = NULL;
      BDDATAREC = NULL;
      BDCLAVENDIMEGERQ12 = NULL;
      BDCODRECDIMEGERQ12 = NULL;
      BDORIGEMDIMEGERQ46 = NULL;
      BDIDENTIFICACAOREGESP = NULL;
      BDQ12 = 'FALSE';
      BDQ46 = 'TRUE';

      SUSPEND;
    END
END
^

/* Alter (VEF_SP_DIRF) */
ALTER PROCEDURE VEF_SP_DIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDREFLAN INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6),
BDACREDEDUIRSERJAN NUMERIC(18,6),
BDACREDEDUIRSERFEV NUMERIC(18,6),
BDACREDEDUIRSERMAR NUMERIC(18,6),
BDACREDEDUIRSERABR NUMERIC(18,6),
BDACREDEDUIRSERMAIO NUMERIC(18,6),
BDACREDEDUIRSERJUN NUMERIC(18,6),
BDACREDEDUIRSERJUL NUMERIC(18,6),
BDACREDEDUIRSERAGO NUMERIC(18,6),
BDACREDEDUIRSERSET NUMERIC(18,6),
BDACREDEDUIRSEROUT NUMERIC(18,6),
BDACREDEDUIRSERNOV NUMERIC(18,6),
BDACREDEDUIRSERDEZ NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WULTCODREC INTEGER;
DECLARE VARIABLE WULTCODEMP INTEGER;
DECLARE VARIABLE WULTCODTER INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMETER VARCHAR(100);
DECLARE VARIABLE WCGCTER VARCHAR(18);
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WREFLAN INTEGER;
DECLARE VARIABLE WVLRCONTAB NUMERIC(18,6);
DECLARE VARIABLE WVLRIMPOSTO NUMERIC(18,6);
DECLARE VARIABLE WVLRACREDEDUIRSER NUMERIC(18,6);
DECLARE VARIABLE WINDIMUNEISE INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wSql = 'select temp.BDCODEMP, ';
  wSql = wSql || 'vwterc.bdcodter, ';
  wSql = wSql || 'vwterc.bdcgcter, ';
  wSql = wSql || 'vwterc.bdnometer, ';
  wSql = wSql || 'vwterc.BDINDIMUNEISE, ';
  wSql = wSql || 'vwunionrec.BDCODREC, ';
  wSql = wSql || 'vwunionrec.BDREFLAN, ';
  wSql = wSql || 'sum(BDVLRCONTAB) SUMVLRCONTAB, ';
  wSql = wSql || 'sum(BDACREDEDUIRSER) SUMACREDEDUIRSER, ';
  wSql = wSql || 'sum(BDVLRIMPOSTO) SUMVLRIMPOSTO ';  
  IF (prempresas IS NOT NULL) THEN
    wSql = wSql || 'from (SELECT BDCODEMP FROM TEMPRESAS WHERE '||PREMPRESAS||') temp ';
  ELSE                              
    wSql = wSql || 'from TEMPRESAS temp ';
    
  --wSql = wSql || 'left outer join vw_unionrec_ir_pis_cofins_csll vwunionrec on (vwunionrec.bdcodemp = temp.bdcodemp) ';
  wSql = wSql || 'left outer join VW_REC_IR_PIS_COFINS_CSLL_Aux vwunionrec on (vwunionrec.bdcodemp = temp.bdcodemp) ';
  wSql = wSql || 'left outer join vw_tterceiro vwterc on (vwterc.bdcodter = vwunionrec.bdCODTER ) ';

  wwhere = '';

     --wwhere = wWhere||prempresas||' ';

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'vwunionrec.BDREFLAN >= '||prrefini||' ';
     END

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'vwunionrec.BDREFLAN <= '||prreffin||' ';
     END

  IF ((prexportarnotas IS NOT NULL) AND (prexportarnotas = 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'vwunionrec.BDVLRIMPOSTO > 0 ';
     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'vwunionrec.BDTIPLAN = 1 ';

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'vwunionrec.BDTIPIMPOSTO in (2,11,12)';


  IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

  wgroupby = 'group by temp.BDCODEMP,
                       vwterc.bdcodter,
                       vwterc.bdcgcter,
                       vwterc.bdnometer,
                       vwterc.bdindimuneise,
                       vwunionrec.BDCODREC,
                       vwunionrec.BDREFLAN ';

  worderby = 'order by temp.bdcodemp, vwterc.bdCODTER, vwunionrec.bdcodrec, vwunionrec.bdreflan ';

  wsql = wsql||wwhere||wgroupby||worderby;
  wultcodemp = 0;
  wultcodrec = 0;
  wultcodter = 0;
  FOR EXECUTE STATEMENT wsql
    INTO
      :wCODEMP,
      :wCODTER,
      :wCGCTER,
      :wNOMETER,
      :wINDIMUNEISE,
      :wCODREC,
      :wREFLAN,
      :wVLRCONTAB,
      :wVLRACREDEDUIRSER,
      :wVLRIMPOSTO
     DO
     BEGIN
        BDINDIMUNEISE   = wINDIMUNEISE;
        IF ((wultcodemp <> wcodemp) OR (wultcodter <> wcodter) OR (wultcodrec <> wcodrec))THEN
           BEGIN
              IF (wultcodrec <> 0) THEN
                 SUSPEND;
              bdcodemp       = wcodemp;
              bdcodter       = wcodter;
              bdcnpjivsup    = wcgcter;
              bdnomeempivsup = wnometer;
              bdcodrecivsup  = wcodrec;
              bdreflan       = wreflan;

              bdirJANivsup        = 0;
              bdrenJANivsup       = 0;
              bdacrededuirserjan  = 0;

              bdirFEVivsup        = 0;
              bdrenFEVivsup       = 0;
              bdacrededuirserfev  = 0;

              bdirMARivsup        = 0;
              bdrenMARivsup       = 0;
              bdacrededuirsermar  = 0;

              bdirABRivsup        = 0;
              bdrenABRivsup       = 0;
              bdacrededuirserabr  = 0;

              bdirMAIivsup        = 0;
              bdrenMAIivsup       = 0;
              bdacrededuirsermaio = 0;

              bdirJUNivsup        = 0;
              bdrenJUNivsup       = 0;
              bdacrededuirserjun  = 0;

              bdirJULivsup        = 0;
              bdrenJULivsup       = 0;
              bdacrededuirserjul  = 0;

              bdirAGOivsup        = 0;
              bdrenAGOivsup       = 0;
              bdacrededuirserago  = 0;

              bdirSETivsup        = 0;
              bdrenSETivsup       = 0;
              bdacrededuirserset  = 0;

              bdirOUTivsup        = 0;
              bdrenOUTivsup       = 0;
              bdacrededuirserout  = 0;

              bdirNOVivsup        = 0;
              bdrenNOVivsup       = 0;
              bdacrededuirsernov  = 0;

              bdirDEZivsup        = 0;
              bdrenDEZivsup       = 0;
              bdacrededuirserdez  = 0;

           END
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '01') THEN
             BEGIN
               bdirJANivsup       = wVLRIMPOSTO;
               bdrenJANivsup      = wvlrcontab;
               bdacrededuirserjan = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '02') THEN
             BEGIN
               bdirFEVivsup       = wVLRIMPOSTO;
               bdrenFEVivsup      = wvlrcontab;
               bdacrededuirserfev = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '03') THEN
             BEGIN
               bdirMARivsup       = wVLRIMPOSTO;
               bdrenMARivsup      = wvlrcontab;
               bdacrededuirsermar = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '04') THEN
             BEGIN
               bdirABRivsup       = wVLRIMPOSTO;
               bdrenABRivsup      = wvlrcontab;
               bdacrededuirserabr = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '05') THEN
             BEGIN
               bdirMAIivsup        = wVLRIMPOSTO;
               bdrenMAIivsup       = wvlrcontab;
               bdacrededuirsermaio = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '06') THEN
             BEGIN
               bdirJUNivsup       = wVLRIMPOSTO;
               bdrenJUNivsup      = wvlrcontab;
               bdacrededuirserjun = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '07') THEN
             BEGIN
               bdirJULivsup       = wVLRIMPOSTO;
               bdrenJULivsup      = wvlrcontab;
               bdacrededuirserjul = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '08') THEN
             BEGIN
               bdirAGOivsup       = wVLRIMPOSTO;
               bdrenAGOivsup      = wvlrcontab;
               bdacrededuirserago = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '09') THEN
             BEGIN
               bdirSETivsup       = wVLRIMPOSTO;
               bdrenSETivsup      = wvlrcontab;
               bdacrededuirserset = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '10') THEN
             BEGIN
               bdirOUTivsup       = wVLRIMPOSTO;
               bdrenOUTivsup      = wvlrcontab;
               bdacrededuirserout = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '11') THEN
             BEGIN
               bdirNOVivsup       = wVLRIMPOSTO;
               bdrenNOVivsup      = wvlrcontab;
               bdacrededuirsernov = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '12') THEN
             BEGIN
               bdirDEZivsup       = wVLRIMPOSTO;
               bdrenDEZivsup      = wvlrcontab;
               bdacrededuirserdez = wvlracrededuirser;
             END
           wultcodrec = wcodrec;
           wultcodemp = wcodemp;
           wultcodter = wcodter;
     END
   IF (:bdcodemp <> 0) THEN
      SUSPEND;
END
^

/* Alter (VEF_SP_DIRF_RTIRF) */
ALTER PROCEDURE VEF_SP_DIRF_RTIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
 AS
DECLARE VARIABLE WSUBSELECTSER VARCHAR(5000);
DECLARE VARIABLE WSUBSELECTDEM VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(1000);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WVLRIMPOSTO NUMERIC(18,6);
DECLARE VARIABLE WCNPJIVSUP VARCHAR(18);
DECLARE VARIABLE WNOMEEMPIVSUP VARCHAR(100);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WINDIMUNEISE INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wsubselectSer = 'select bdcodemp, bdchave, bdreflan, bdcodter from vef_emp_tmovser where (bdcodsitnf not in (2,3,4,5)) and (bdtiplan = 1)';
  WSUBSELECTDem = 'select bdcodemp, bdchave, bdreflan, bdcodter from VEF_EMP_TMOVDEMAISDOC_F100 where (BDIND_OPER = 1) ';
  wWhere = '';
  IF ((:prempresas IS NOT NULL) AND (:prempresas <> '')) THEN
    wWhere = :wWhere || ' and (' || :prempresas || ')';

  IF ((:prrefini IS NOT NULL) AND (:prrefini > 0)) THEN
    wWhere = :wWhere || ' and (bdreflan >= ' || :prrefini || ')';

  IF ((:prreffin IS NOT NULL) AND (:prreffin > 0)) THEN
    wWhere = :wWhere || ' and (bdreflan <= ' || :prreffin || ')';

  wsubselectser = wsubselectser || wwhere;
  WSUBSELECTDem = WSUBSELECTDem || wwhere;


  wsql = '';
  wsql = wsql || ' select s.bdcodemp, s.bdcodrec, s.bdcodter, t.bdcgcter, t.bdnometer, t.bdindimuneise, s.bdreflan, sum(s.bdvlrimposto) bdvlrimposto ';
  wsql = wsql || ' from ';
  wsql = wsql || ' ( ';
                       /*PIS*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodrecpis bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrpis bdvlrimposto ';
  wsql = wsql || '     from (' || wsubselectSer || ') mov ';
  wsql = wsql || '     inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodrecpis > 0) and (ret.bdvlrpis > 0) ';

  wsql = wsql || '     union all  ';
                       /*Cofins*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodreccofins bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrcofins bdvlrimposto ';
  wsql = wsql || '     from (' || wsubselectSer || ') mov ';
  wsql = wsql || '     inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccofins > 0) and (ret.bdvlrcofins > 0) ';

  wsql = wsql || '     union all ';
                       /*Contribui??o Social*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodreccsocial bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrcsocial bdvlrimposto ';
  wsql = wsql || '     from (' || wsubselectSer || ') mov ';
  wsql = wsql || '     inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccsocial > 0) and (ret.bdvlrcsocial > 0) ';

  wsql = wsql || '     union all ';
                       /*IRRF*/
  wsql = wsql || '     select mov.bdcodemp, itens.bdcodrec, mov.bdcodter, mov.bdreflan, itens.bdvlrirser bdvlrimposto ';
  wsql = wsql || '     from (' || wsubselectSer || ') mov ';
  wsql = wsql || '     inner join vef_emp_tmovseritens itens on (itens.bdcodemp = mov.bdcodemp) and (itens.bdchave = mov.bdchave) and (itens.bdcodrec > 0) and (itens.bdvlrirser > 0) ';

--demais documentos
  wsql = wsql || '     union all ';
                       /*PIS*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodrecpis bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrpis bdvlrimposto ';
  wsql = wsql || '     from (' || WSUBSELECTDem || ') mov ';
  wsql = wsql || '     inner join VEF_EMP_TMOVDEMRET ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodrecpis > 0) and (ret.bdvlrpis > 0) ';

  wsql = wsql || '     union all  ';
                       /*Cofins*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodreccofins bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrcofins bdvlrimposto ';
  wsql = wsql || '     from (' || WSUBSELECTDem || ') mov ';
  wsql = wsql || '     inner join VEF_EMP_TMOVDEMRET ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccofins > 0) and (ret.bdvlrcofins > 0) ';

  wsql = wsql || '     union all ';
                       /*Contribui??o Social*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodreccsocial bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrcsocial bdvlrimposto ';
  wsql = wsql || '     from (' || WSUBSELECTDem || ') mov ';
  wsql = wsql || '     inner join VEF_EMP_TMOVDEMRET ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccsocial > 0) and (ret.bdvlrcsocial > 0) ';

  wsql = wsql || '     union all ';
                       /*IRRF*/
  wsql = wsql || '     select MOV.BDCODEMP, ret.BDCODRECIR bdcodrec, MOV.BDCODTER, MOV.BDREFLAN, RET.BDVLRIR BDVLRIMPOSTO ';
  wsql = wsql || '     from (' || WSUBSELECTDem || ') mov ';
  wsql = wsql || '     inner join VEF_EMP_TMOVDEMRET RET on (RET.BDCODEMP = MOV.BDCODEMP) and (RET.BDCHAVE = MOV.BDCHAVE) and (RET.BDCODRECIR > 0) and (RET.bdvlrir > 0) ';

  wsql = wsql || ' ) s ';
  wsql = wsql || ' inner join tcodrec r on (r.bdcodrec = s.bdcodrec) and (r.bdtipoimposto in (2, 11, 12)) ';
  wsql = wsql || ' left outer join vw_tterceiro t on t.bdcodter = s.bdcodter ';
  wsql = wsql || ' group by s.bdcodemp, s.bdcodrec, s.bdcodter, t.bdcgcter, t.bdnometer, s.bdreflan, t.bdindimuneise ';

  /*garantir que ? nulo antes de entrar no for*/
  bdcodemp = NULL;
  bdcodrecivsup = NULL;
  bdcodter = NULL;
  FOR EXECUTE STATEMENT wsql 
      INTO :wcodemp,
           :wcodrec,
           :wcodter,
           :wcnpjivsup,
           :wnomeempivsup,
           :wINDIMUNEISE,
           :wmes,
           :wvlrimposto 
  DO
  BEGIN 
    /*
      se bdcodemp ou bdcodter for nulo, ? o primeiro registro e deve inicializar os totais
    */
    IF (((:wcodemp <> :bdcodemp) OR (:wcodter <> :bdcodter) OR (:wcodrec <> :bdcodrecivsup)) OR ((:bdcodemp IS NULL) AND (:bdcodter IS NULL) AND (:bdcodrecivsup IS NULL))) THEN
      BEGIN
        /*s? da suspend se os valores para o codigo da empresa e terceiro estiverem preenchidos*/
        IF ((:bdcodemp IS NOT NULL) AND (:bdcodter IS NOT NULL) AND (:bdcodrecivsup IS NOT NULL) AND ((bdcodemp > 0) AND (:bdcodter > 0) AND (:bdcodrecivsup > 0))) THEN
          SUSPEND;

        /*limpa os totais*/
        bdirjanivsup = 0;
        bdirfevivsup = 0;
        bdirmarivsup = 0;
        bdirabrivsup = 0;
        bdirmaiivsup = 0;
        bdirjunivsup = 0;
        bdirjulivsup = 0;
        bdiragoivsup = 0;
        bdirsetivsup = 0;
        bdiroutivsup = 0;
        bdirnovivsup = 0;
        bdirdezivsup = 0;
      END

    /*pega so o mes do reflan*/
    wmes = CAST(SUBSTRING(:wmes FROM 5 FOR 2) AS INTEGER);

    IF (:wmes = 1) THEN
      bdirjanivsup = :wvlrimposto;
    ELSE IF (:wmes = 2) THEN
      bdirfevivsup = :wvlrimposto;
    ELSE IF (:wmes = 3) THEN
      bdirmarivsup = :wvlrimposto;
    ELSE IF (:wmes = 4) THEN
      bdirabrivsup = :wvlrimposto;
    ELSE IF (:wmes = 5) THEN
      bdirmaiivsup = :wvlrimposto;
    ELSE IF (:wmes = 6) THEN
      bdirjunivsup = :wvlrimposto;
    ELSE IF (:wmes = 7) THEN
      bdirjulivsup = :wvlrimposto;
    ELSE IF (:wmes = 8) THEN
      bdiragoivsup = :wvlrimposto;
    ELSE IF (:wmes = 9) THEN
      bdirsetivsup = :wvlrimposto;
    ELSE IF (:wmes = 10) THEN
      bdiroutivsup = :wvlrimposto;
    ELSE IF (:wmes = 11) THEN
      bdirnovivsup = :wvlrimposto;
    ELSE IF (:wmes = 12) THEN
      bdirdezivsup = :wvlrimposto;
    
    bdcodemp = :wcodemp;
    bdcodrecivsup = :wcodrec;
    bdcodter = :wcodter;
    bdcnpjivsup = :wcnpjivsup;
    bdnomeempivsup = :wnomeempivsup;
    bdindimuneise = :windimuneise;
  END 
  /*suspend do ultimo registro*/
  IF ((:bdcodemp > 0) AND (:bdcodrecivsup > 0) AND (:bdcodter > 0)) THEN
    SUSPEND;
END
^

/* Alter (VEF_SP_DIRF_RTRT) */
ALTER PROCEDURE VEF_SP_DIRF_RTRT(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6))
 AS
DECLARE VARIABLE WSUBSELECT VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WVLRCONTAB NUMERIC(18,6);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wsubselect = 'select bdcodemp, bdchave, bdreflan, bdcodter from vef_emp_tmovser where (bdcodsitnf not in (2,3,4,5)) and (bdtiplan = 1)';

  IF ((prempresas IS NOT NULL) AND (prempresas <> '')) THEN
    wsubselect = wsubselect || ' and (' || prempresas || ')';

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
    wsubselect = wsubselect || ' and (bdreflan >= ' || prrefini || ')';

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
    wsubselect = wsubselect || ' and (bdreflan <= ' || prreffin || ')';

  wsql = '';
  wsql = '          SELECT MOV.BDCODEMP, MOV.BDCODTER, MOV.BDREFLAN, SUM(COALESCE(MOV.BDVLRCONTAB, 0)) AS BDVLRCONTAB ';
  wsql = wsql || '  FROM ( ';
  wsql = wsql ||        ' select mov.bdcodemp, ';
  wsql = wsql ||        '        mov.bdcodter, ';
  wsql = wsql ||        '        mov.bdreflan, ';
  wsql = wsql ||        '        sum(itens.bdvlrcontab) bdvlrcontab  ';
  wsql = wsql ||        ' from (' || wsubselect || ') mov  ';
  wsql = wsql ||        ' inner join vef_emp_tmovseritens itens on (itens.bdcodemp = mov.bdcodemp) and (itens.bdchave = mov.bdchave)  ';
  wsql = wsql ||        ' where (exists(select * from vef_emp_tmovseritens i ';
  wsql = wsql ||        '               inner join tcodrec r on (r.bdcodrec = i.bdcodrec) and (r.bdtipoimposto in (2, 11, 12)) ';
  wsql = wsql ||        '               where (i.bdcodemp = mov.bdcodemp) and ';
  wsql = wsql ||        '                     (i.bdchave = mov.bdchave) and ';
  wsql = wsql ||        '                     (i.bdcodrec > 0)) or ';
  wsql = wsql ||        '        exists(select * from vef_emp_tmovserret r';
  wsql = wsql ||        '               inner join tcodrec c on (c.bdtipoimposto in (2, 11, 12)) and ((c.bdcodrec = r.bdcodrecpis) or (c.bdcodrec = r.bdcodreccofins) or (c.bdcodrec = r.bdcodreccsocial)) ';
  wsql = wsql ||        '               where (r.bdcodemp = mov.bdcodemp) and ';
  wsql = wsql ||        '                    (r.bdchave = mov.bdchave) and ';
  wsql = wsql ||        '                    ((r.bdcodrecpis > 0) or ';
  wsql = wsql ||        '                    (r.bdcodreccofins > 0) or ';
  wsql = wsql ||        '                    (r.bdcodreccsocial > 0)))) ';

  IF ((:prexportarnotas IS NOT NULL) AND (:prexportarnotas = 1)) THEN /*1 = todas as notas de participantes que tiveram reten??o no periodo*/
    BEGIN
      wsql = wsql ||    '       or (mov.bdcodter in (select distinct bdcodter ';
      wsql = wsql ||    '                            from ';
      wsql = wsql ||    '                            ( ';
      wsql = wsql ||    '                                select s.bdcodter, s.bdcodrec ';
      wsql = wsql ||    '                                from ';
      wsql = wsql ||    '                                ( ';
      wsql = wsql ||    '                                 select mov.bdcodter, itens.bdcodrec from (' || wsubselect || ') mov ';
      wsql = wsql ||    '                                 inner join vef_emp_tmovseritens itens on itens.bdcodemp = mov.bdcodemp and itens.bdchave = mov.bdchave and itens.bdcodrec > 0  ';
                                                       
      wsql = wsql ||    '                                 union ';

      wsql = wsql ||    '                                 select mov.bdcodter, ret.bdcodrecpis bdcodrec from (' || wsubselect || ') mov ';
      wsql = wsql ||    '                                 inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodrecpis > 0) and (ret.bdvlrpis > 0) ';
      
      wsql = wsql ||    '                                 union ';

      wsql = wsql ||    '                                 select mov.bdcodter, ret.bdcodreccofins bdcodrec from (' || wsubselect || ') mov ';
      wsql = wsql ||    '                                 inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccofins > 0) and (ret.bdvlrcofins > 0) ';

      wsql = wsql ||    '                                 union ';
      
      wsql = wsql ||    '                                 select mov.bdcodter, ret.bdcodreccsocial bdcodrec from (' || wsubselect || ') mov ';
      wsql = wsql ||    '                                 inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccsocial > 0) and (ret.bdvlrcsocial > 0) ';
      wsql = wsql ||    '                                ) s ';
      wsql = wsql ||    '                                inner join tcodrec r on (r.bdcodrec = s.bdcodrec) and (r.bdtipoimposto in (2, 11, 12)) ';
      wsql = wsql ||    '                            ))) ';
    END
    
  wsql = wsql ||        ' group by mov.bdcodemp, mov.bdcodter, mov.bdreflan ';
  
  wsubselect = 'SELECT f100.bdcodemp, f100.bdchave, f100.bdreflan, f100.bdcodter, F100.bdvl_oper FROM VEF_EMP_TMOVDEMAISDOC_F100 f100 WHERE (f100.BDIND_OPER = 1) ';
  IF ((prempresas IS NOT NULL) AND (prempresas <> '')) THEN
    wsubselect = wsubselect || ' AND (' || prempresas || ')';
  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
    wsubselect = wsubselect || ' AND (bdreflan >= ' || prrefini || ')';

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
    wsubselect = wsubselect || ' AND (bdreflan <= ' || prreffin || ')';

  wsql = wsql ||        'UNION ALL ';
  wsql = wsql ||        ' SELECT D.BDCODEMP, D.BDCODTER, D.BDREFLAN, SUM(D.bdvl_oper) BDVLRCONTAB ';
  wsql = wsql ||        ' FROM ('||wsubselect||') D ';
  wsql = wsql ||        ' WHERE (EXISTS(SELECT * FROM VEF_EMP_TMOVDEMRET R ';
  wsql = wsql ||        '               INNER JOIN TCODREC C ON (C.BDTIPOIMPOSTO IN (2, 11, 12)) AND ((C.BDCODREC = R.BDCODRECPIS) OR (C.BDCODREC = R.BDCODRECCOFINS) OR (C.BDCODREC = R.BDCODRECCSOCIAL) OR (C.BDCODREC = R.BDCODRECIR)) ';
  wsql = wsql ||        '               WHERE (R.BDCODEMP = D.BDCODEMP) ';
  wsql = wsql ||        '               AND (R.BDCHAVE = D.BDCHAVE) ';
  wsql = wsql ||        '               AND ((R.BDCODRECPIS > 0) OR (R.BDCODRECCOFINS > 0) OR (R.BDCODRECCSOCIAL > 0) OR (R.BDCODRECIR > 0))) ';
  wsql = wsql ||        '       ) ';

  IF ((:prexportarnotas IS NOT NULL) AND (:prexportarnotas = 1)) THEN /*1 = todas as notas de participantes que tiveram reten??o no periodo*/
    BEGIN
      wsql = wsql ||    ' OR (D.bdcodter in ( ';
      wsql = wsql ||    '                    SELECT DISTINCT BDCODTER ';
      wsql = wsql ||    '                    FROM ( ';
      wsql = wsql ||    '                          SELECT F100.BDCODTER, F100.BDCODREC ';
      wsql = wsql ||    '                          FROM ( ';
      wsql = wsql ||    '                                SELECT MOV.BDCODTER, DEM.bdcodrecpis BDCODREC ';
      wsql = wsql ||    '                                FROM ('||wsubselect||') MOV ';
      wsql = wsql ||    '                                INNER JOIN VEF_EMP_TMOVDEMRET DEM ON (DEM.BDCODEMP = MOV.BDCODEMP) AND (DEM.BDCHAVE = MOV.BDCHAVE) AND (DEM.BDCODRECPIS > 0) AND (DEM.BDVLRPIS > 0) ';
      wsql = wsql ||    '                                UNION ';
      wsql = wsql ||    '                                SELECT MOV.BDCODTER, DEM.bdcodreccofins BDCODREC ';
      wsql = wsql ||    '                                FROM ('||wsubselect||') MOV ';
      wsql = wsql ||    '                                INNER JOIN VEF_EMP_TMOVDEMRET DEM ON (DEM.BDCODEMP = MOV.BDCODEMP) AND (DEM.BDCHAVE = MOV.BDCHAVE) AND (DEM.bdcodreccofins > 0) AND (DEM.bdvlrcofins > 0) ';
      wsql = wsql ||    '                                UNION ';
      wsql = wsql ||    '                                SELECT MOV.BDCODTER, DEM.bdcodreccsocial BDCODREC ';
      wsql = wsql ||    '                                FROM ('||wsubselect||') MOV ';
      wsql = wsql ||    '                                INNER JOIN VEF_EMP_TMOVDEMRET DEM ON (DEM.BDCODEMP = MOV.BDCODEMP) AND (DEM.BDCHAVE = MOV.BDCHAVE) AND (DEM.bdcodreccsocial > 0) AND (DEM.bdvlrcsocial > 0) ';
      wsql = wsql ||    '                                UNION ';
      wsql = wsql ||    '                                SELECT MOV.BDCODTER, DEM.bdcodrecir BDCODREC ';
      wsql = wsql ||    '                                FROM ('||wsubselect||') MOV ';
      wsql = wsql ||    '                                INNER JOIN VEF_EMP_TMOVDEMRET DEM ON (DEM.BDCODEMP = MOV.BDCODEMP) AND (DEM.BDCHAVE = MOV.BDCHAVE) AND (DEM.bdcodrecir > 0) AND (DEM.bdvlrir > 0) ';
      wsql = wsql ||    '                               ) F100 ';
      wsql = wsql ||    '                         ) ';
      wsql = wsql ||    '                   ) ';
      wsql = wsql ||    '    ) ';
    END

  wsql = wsql ||        ' GROUP BY D.BDCODEMP, D.BDCODTER, D.BDREFLAN ';

  wsql = wsql ||       ' ) MOV ';
  wsql = wsql || ' GROUP BY mov.bdcodemp, mov.bdcodter, mov.bdreflan ';
  wsql = wsql || ' ORDER BY mov.bdcodemp, mov.bdcodter, mov.bdreflan ';

  bdcodemp = NULL;
  bdcodter = NULL;
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp,
           :wcodter,
           :wmes,
           :wvlrcontab
  DO
  BEGIN
    /*
      se bdcodemp ou bdcodter for nulo, ? o primeiro registro e deve inicializar os totais
    */
    IF (((:wcodemp <> :bdcodemp) OR (:wcodter <> :bdcodter)) OR ((:bdcodemp IS NULL) AND (:bdcodter IS NULL))) THEN
      BEGIN
        /*s? da suspend se os valores para o codigo da empresa e terceiro estiverem preenchidos*/
        IF ((:bdcodemp IS NOT NULL) AND (:bdcodter IS NOT NULL) AND (:bdcodemp > 0) AND (:bdcodter > 0)) THEN
          SUSPEND;

        /*limpa os totais*/
        bdrenjanivsup = 0;
        bdrenfevivsup = 0;
        bdrenmarivsup = 0;
        bdrenabrivsup = 0;
        bdrenmaiivsup = 0;
        bdrenjunivsup = 0;
        bdrenjulivsup = 0;
        bdrenagoivsup = 0;
        bdrensetivsup = 0;
        bdrenoutivsup = 0;
        bdrennovivsup = 0;
        bdrendezivsup = 0;
      END
  
    wmes = CAST(SUBSTRING(:wmes FROM 5 FOR 2) AS INTEGER);
    
    IF (:wmes = 1) THEN
      bdrenjanivsup = :wvlrcontab;
    ELSE IF (:wmes = 2) THEN
      bdrenfevivsup = :wvlrcontab;
    ELSE IF (:wmes = 3) THEN
      bdrenmarivsup = :wvlrcontab;
    ELSE IF (:wmes = 4) THEN
      bdrenabrivsup = :wvlrcontab;
    ELSE IF (:wmes = 5) THEN
      bdrenmaiivsup = :wvlrcontab;
    ELSE IF (:wmes = 6) THEN
      bdrenjunivsup = :wvlrcontab;
    ELSE IF (:wmes = 7) THEN
      bdrenjulivsup = :wvlrcontab;
    ELSE IF (:wmes = 8) THEN
      bdrenagoivsup = :wvlrcontab;
    ELSE IF (:wmes = 9) THEN
      bdrensetivsup = :wvlrcontab;
    ELSE IF (:wmes = 10) THEN
      bdrenoutivsup = :wvlrcontab;
    ELSE IF (:wmes = 11) THEN
      bdrennovivsup = :wvlrcontab;
    ELSE IF (:wmes = 12) THEN
      bdrendezivsup = :wvlrcontab;
      
    bdcodemp = :wcodemp;
    bdcodter = :wcodter;
  END
  /*suspend do ?ltimo registro*/
  IF ((:bdcodemp > 0) AND (:bdcodter > 0)) THEN
    SUSPEND;
END
^

/* Alter (VEF_SP_EXCLUI_REDZVARCFOP_PLANO) */
ALTER PROCEDURE VEF_SP_EXCLUI_REDZVARCFOP_PLANO(PRSQL VARCHAR(4000),
PREMP INTEGER,
PRCHAVE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(6000);
DECLARE VARIABLE WQTDEVAR INTEGER;
DECLARE VARIABLE WQTDE INTEGER;
DECLARE VARIABLE WORDEMVARCFOP INTEGER;
DECLARE VARIABLE WFIRST INTEGER;
DECLARE VARIABLE WSKIP INTEGER;
BEGIN
  /*
   Alt.: 11421 - Procedure para ser utilizada nos Plano de trocas.
   Verifica diferen?a de quantos registros foram inseridos no 490/470(dependendo do perfil) e registros existentes nas v?rias CFOPs, excluindo essa diferen?a.
   Pode sempre excluir sem verificar a CFOPs das v?rias CFOPs, pois executa um Insert/Select antes nas ac?es dos plano de trocas.
   */
  EXECUTE STATEMENT 'select count(*) from ( '||prSQL||') ' INTO :wQtde;

  EXECUTE STATEMENT 'select count(*) from VEF_EMP_TREDZVARCFOP '||
                    'where BDCODEMP = '||prEMP||
                    '  and BDCHAVE  = '||prCHAVE||
                    '  and BDCODNAT in ( select BDCODNAT from ( '||prSQL||') ) ' INTO :wQtdeVar;

  IF ((wQtdeVar - wQtde) > 0) THEN
    BEGIN
      wSQL = 'Delete from VEF_EMP_TREDZVARCFOP '||
             'Where BDCODEMP = '||prEMP||
             '  and BDCHAVE  = '||prCHAVE||
             ' and BDORDEMVARCFOP in ( Select first '||(wQtdeVar - wQtde)||' skip '||(wQtde)||' BDORDEMVARCFOP from VEF_EMP_TREDZVARCFOP '||
             '                         Where bdcodemp = '||prEMP||
             '                           and bdchave  = '||prCHAVE||
             '                           and BDCODNAT in ( select BDCODNAT from ( '||prSQL||') ) '||
             '                         Order by BDORDEMVARCFOP desc )';
      EXECUTE STATEMENT wSQL;
    END

  SUSPEND;
END
^

/* Alter (VEF_SP_EXP_DIME) */
ALTER PROCEDURE VEF_SP_EXP_DIME(PRCODEMP VARCHAR(10000),
PRREFERENCIAINICIAL INTEGER,
PRREFERENCIAFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCCAMPO VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODNAT INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDSIGLAUF VARCHAR(2),
BDVLRCONT NUMERIC(15,6),
BDVLRBC NUMERIC(15,6),
BDVLRIMPOSTO NUMERIC(15,6),
BDVLRISENTRIB NUMERIC(15,6),
BDVLROUTRAS NUMERIC(15,6),
BDVLRICMSSTPE NUMERIC(15,6),
BDVLRICMSSTOP NUMERIC(15,6),
BDVLRCONTCONT NUMERIC(15,6),
BDVLRBCCONT NUMERIC(15,6),
BDVLRICMSST NUMERIC(15,6),
BDNUMITEM INTEGER,
BDCODTIPO INTEGER,
BDBASEST NUMERIC(15,6),
BDICMSRETST NUMERIC(15,6),
BDDIFALIQENT NUMERIC(15,6),
BDALIMPREP VARCHAR(5),
BDCODEXP48 VARCHAR(3))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WNAT INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WNUMCAMPO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(5);
DECLARE VARIABLE WDESCCAMPO VARCHAR(150);
DECLARE VARIABLE WVALOR NUMERIC(15,6);
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODCIDTOT INTEGER;
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WDATAREC DATE;
DECLARE VARIABLE WCLAVENDIMEGERQ12 INTEGER;
DECLARE VARIABLE WCODRECDIMEGERQ12 INTEGER;
DECLARE VARIABLE WORIGEMDIMEGERQ46 INTEGER;
DECLARE VARIABLE WIDENTIFICACAOREGESP VARCHAR(15);
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE WVLRCONT NUMERIC(15,6);
DECLARE VARIABLE WVLRBC NUMERIC(15,6);
DECLARE VARIABLE WVLRIMPOSTO NUMERIC(15,6);
DECLARE VARIABLE WVLRISENTRIB NUMERIC(15,6);
DECLARE VARIABLE WVLROUTRAS NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTPE NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTOP NUMERIC(15,6);
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WUF INTEGER;
DECLARE VARIABLE WVLRCONTCONT NUMERIC(15,6);
DECLARE VARIABLE WVLRBCCONT NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSST NUMERIC(15,6);
DECLARE VARIABLE WNUMITEMAUX INTEGER;
DECLARE VARIABLE WVLRCONTAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRBCAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRIMPOSTOAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRISENTRIBAUX NUMERIC(15,6);
DECLARE VARIABLE WVLROUTRASAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTPEAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTOPAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRCONTCONTAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRBCCONTAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTAUX NUMERIC(15,6);
DECLARE VARIABLE WNUMITEM46 INTEGER;
DECLARE VARIABLE WCODTIPO INTEGER;
DECLARE VARIABLE WCODREGAPU INTEGER;
DECLARE VARIABLE WBASEST NUMERIC(15,6);
DECLARE VARIABLE WICMSRETST NUMERIC(15,6);
DECLARE VARIABLE WDIFALIQENT NUMERIC(15,6);
DECLARE VARIABLE wTodasAsEmpresa dm_boolean;
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIAFINAL, NULL, NULL);

  wTodasAsEmpresa = 'FALSE';

  IF ((prcodemp IS NULL) OR (prcodemp = '') OR (prcodemp = '''''')) THEN
    wTodasAsEmpresa = 'TRUE';

  wsql = 'select DIME.BDCODEMP,';
  wsql = wsql||'DIME.BDREFERENCIA,';
  wsql = wsql||'DIME.BDNUMCAMPO,';
  wsql = wsql||'TCONF.bdclassificacao,';
  wsql = wsql||'TCONFDIMEFORMQ46.bddescformDIMEq46 BDDESCCAMPO,';
  wsql = wsql||'DIME.BDVALOR BDVALOR,';
  wsql = wsql||'TCID.BDCODEST bdcodcid,';
  wsql = wsql||'DIME.bdcodcidtot,';
  wsql = wsql||'DIME.BDCODNAT,';
  wsql = wsql||'DIME.BDDATAREC,';
  wsql = wsql||'DIME.BDCLAVENDIMEGERQ12,';
  wsql = wsql||'DIME.BDCODRECDIMEGERQ12,';
  wsql = wsql||'DIME.BDORIGEMDIMEGERQ46,';
  wsql = wsql||'DIME.BDIDENTIFICACAOREGESP, ';
  wsql = wsql||'UF.BDSIGLAUF,';
  wsql = wsql||' 0 BDVLRCONT,';
  wsql = wsql||' 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO,';
  wsql = wsql||' 0 BDVLRISENTRIB,';
  wsql = wsql||' 0 BDVLROUTRAS,';
  wsql = wsql||' TCONFDIMEFORM.bdnumitem,';
  wsql = wsql||' 0 BDVLRICMSSTPE,';
  wsql = wsql||' 0 BDVLRICMSSTOP,';
  wsql = wsql||' TCONFDIMEFORMQ46.BDNUMITEM BDNUMITEM46,';
  wsql = wsql||'TCONF.bdCODTIPO, ';
  wsql = wsql||'TCONFDIME.BDCODREGAPU, ';
  wsql = wsql||'DIME.BDALIMPREP, ';
  wsql = wsql||'CASE WHEN DIME.BDALIMPREP = ''TRUE''THEN ''008'' ELSE DIME.BDCODEXP48 END BDCODEXP48 ';

    /* Remvida a View "VW_VEF_EMP_TDIMEGERUNION" */
--  wsql = wsql||' from VW_VEF_EMP_TDIMEGERUNION DIME ';
  wsql = wsql||' from ( ';
  --------------------------------------------------------------------------------
  --                                                                            --
  --------------------------------------------------------------------------------
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               BDPREFIXONAT as BDCODNAT, ';
  wsql = wsql||'               SUM(COALESCE(BDVALOR,0)) as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, /* Q 47, Q48 BDCODCID */ ';
  wsql = wsql||'               NULL as BDCODCIDTOT, /* Q 47, Q48 BDCODCIDTOT */ ';
  wsql = wsql||'               NULL as BDCODUF, /* Q 49 BDCODUF */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERNAT dime ';
  IF (wTodasAsEmpresa = 'FALSE') THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END

  --sol:14445
  IF (((wTodasAsEmpresa = 'FALSE')) OR
      (:PRREFERENCIAINICIAL IS NOT NULL) OR
      (:PRREFERENCIAFINAL IS NOT NULL)) THEN
     wsql = wsql||' and bdvalor > 0 ';
  ELSE
     wsql = wsql||' where bdvalor > 0 ';

  wsql = wsql||'        GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDPREFIXONAT ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ47 dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               dime.BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL  as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               CASE WHEN bdcodcidtot = 99999 THEN 999 ELSE BDCODEXP END as BDCODEXP48,  /* Q48 */ ';
  wsql = wsql||'               ALIM.BDALIMPREP as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ48 dime ';
  wsql = wsql||'        JOIN  VW_VEF_BASE_TEMPPARESTSC Alim ON (alim.bdcodemp = dime.bdcodemp) ';
  wsql = wsql||'        LEFT OUTER JOIN VEF_BASE_TTABATIVQ48 exp48 ON (dime.bdcodativq48 = exp48.bdcodativq48) ';
  wsql = wsql||'        WHERE dime.bdcodativq48 IS NOT NULL OR BDCODCIDTOT = 99999 ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        AND ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               bdcoduf as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ49 dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               SUM(COALESCE(BDVALOR,0)) as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               bdcoduf as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ50 dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'        GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDCODNAT, BDCODCID, BDCODCIDTOT,bdcoduf, BDDATAREC, BDCLAVENDIMEGERQ12, BDCODRECDIMEGERQ12, BDORIGEMDIMEGERQ46,BDQ12, BDQ46 ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMESCGERREG dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               BDDATAREC as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               BDCLAVENDIMEGERQ12 as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               r.BDCODRECOF as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''TRUE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ12 dime ';
  wsql = wsql||'        left outer join TCODREC r on (r.BDCODREC = dime.BDCODRECDIMEGERQ12) ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'      UNION ';
  wsql = wsql||'      select /*null*/7 BDCODPERIODO, ';
  wsql = wsql||'             BDCODEMP, ';
  wsql = wsql||'             BDREFERENCIA, ';
  wsql = wsql||'             /*39*/48 BDCODQDIME, /* Q10*/ ';
  wsql = wsql||'             (BDITEMDEBESP+100) BDNUMCAMPO, /* Q10*/ ';
  wsql = wsql||'             null as BDCODNAT, ';
  wsql = wsql||'             BDVALOR as BDVALOR, ';
  wsql = wsql||'             null as BDCODCID, ';
  wsql = wsql||'             null as BDCODCIDTOT, ';
  wsql = wsql||'             null as BDCODUF, /* Q49 */ ';
  wsql = wsql||'             BDDATAVENCTO as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'             BDCLAVENC as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'             BDCODREC as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'             null as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'             null as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'             ''TRUE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'             ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'             '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'             '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'      from VEF_EMP_TDIMEGERDEBESP dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               BDCODNAT as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               BDCODUF as BDCODUF, ';
  wsql = wsql||'               BDDATAREC as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               BDCLAVENDIMEGERQ12 as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               BDCODRECDIMEGERQ12 as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               BDORIGEMDIMEGERQ46 as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               BDIDENTIFICACAOREGESP as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               BDQ12 as BDQ12, /* Q12 */ ';
  wsql = wsql||'               BDQ46 as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP /* Q48 */ ';
  wsql = wsql||'        FROM VEF_SP_DIMEQ46 dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  --------------------------------------------------------------------------------
  --                                                                            --
  --------------------------------------------------------------------------------
  wsql = wsql||') dime ';

  wsql = wsql||' left outer join VW_EMP_REF_TOTAL empresas on (empresas.bdcodemp = DIME.bdcodemp )';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMESC TCONFDIME ON (empresas.bdcodconfdimesc = TCONFDIME.BDCODCONFDIMESC) ';
--  wsql = wsql||'left outer join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = DIME.bdcodemp)';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMEQ TCONF on (TCONF.bdcodqdime = DIME.bdcodqdime)';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMEFORM TCONFDIMEFORM on (TCONFDIMEFORM.bdcodconfdimesc = empresas.bdcodconfdimesc and  TCONFDIMEFORM.bdcodqdime = DIME.BDCODQDIME and TCONFDIMEFORM.bdnumcampodime = DIME.BDNUMCAMPO)';

  wsql = wsql||'left outer join ( ';
  wsql = wsql||'                 select BDCODCONFDIMESC, BDCODQDIME, BDNUMCAMPODIMEQ12, BDDESCFORMDIMEQ12 from VEF_ESTADOS_TCONFDIMEFQ12 ';
  wsql = wsql||'                 union all ';
  wsql = wsql||'                 select f.BDCODCONFDIMESC, 48 as BDCODQDIME, (esp.BDITEMDEBESP+100) as BDNUMCAMPODIMEQ12, esp.BDDESCRICAO ';
  wsql = wsql||'                 from VEF_ESTADOS_TCONFDIMEFORM f ';
  wsql = wsql||'                 join VEF_BASE_TTABITEMDEBESP esp on ( esp.bdcodexportar = f.bdnumitem ) ';
  wsql = wsql||'                 where /*f.BDCODCONFDIMESC = EMPRESAS.BDCODCONFDIMESC and*/ f.BDCODQDIME = 39 ';
  wsql = wsql||'                 ) TCONFDIMEFORMQ12 on (TCONFDIMEFORMQ12.BDCODCONFDIMESC = EMPRESAS.BDCODCONFDIMESC and TCONFDIMEFORMQ12.BDCODQDIME = dime.BDCODQDIME and TCONFDIMEFORMQ12.BDNUMCAMPODIMEQ12 = dime.BDNUMCAMPO) ';

  wsql = wsql||' left outer join vef_estados_tconfdimefq46 TCONFDIMEFORMQ46 on (TCONFDIMEFORMQ46.bdcodconfdimesc = empresas.bdcodconfdimesc and  TCONFDIMEFORMQ46.bdcodqdime = DIME.BDCODQDIME and TCONFDIMEFORMQ46.bdnumcampodimeq46 = DIME.BDNUMCAMPO)';
  wsql = wsql||' left outer join TCIDADE TCID on tcid.bdcodcid = DIME.bdcodcid';
  wsql = wsql||' left outer join TUF UF on UF.bdcoduf = DIME.BDCODUF';

  --wwhere = ' where (DIME.BDCODQDIME <> 1) AND (DIME.BDCODQDIME <> 2) and (DIME.BDCODQDIME <> 71) and (DIME.BDCODQDIME <> 72) ';
  wwhere = ' where (TCONF.BDCODTIPO <> 2) AND (TCONF.BDCODTIPO <> 3) and (TCONF.BDCODTIPO <> 72) ';--and (TCONF.BDCODTIPO <> 48)';
  wwhere = wwhere||' and (TCONF.BDCODTIPO <> 78) AND (TCONF.BDCODTIPO <> 80)';


  IF ((wTodasAsEmpresa = 'FALSE')) THEN --Alt.: #6420 n?o estava validando se prcodemp era dif. de vazio, quando gerava DIME de todas as empresas n?o funcionava
     wwhere = wwhere||' AND '||:PRCODEMP;
     --wwhere = wwhere||:PRCODEMP;

  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;

     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFERENCIA,
    :BDNUMCAMPO,
    :BDCLASSIFICACAO,
    :BDDESCCAMPO,
    :BDVALOR,
    :BDCODCID,
    :BDCODCIDTOT,
    :BDCODNAT,
    :BDDATAREC,
    :BDCLAVENDIMEGERQ12,
    :BDCODRECDIMEGERQ12,
    :BDORIGEMDIMEGERQ46,
    :BDIDENTIFICACAOREGESP,
    :BDSIGLAUF,
    :BDVLRCONT,
    :BDVLRBC,
    :BDVLRIMPOSTO,
    :BDVLRISENTRIB,
    :BDVLROUTRAS,
    :BDNUMITEM,
    :BDVLROUTRAS,
    :BDVLROUTRAS,
    :WNUMITEM46,
    :BDCODTIPO,
    :WCODREGAPU,
    :BDALIMPREP,
    :BDCODEXP48
  DO
  BEGIN
    IF (BDCODCID IS NULL) THEN
       IF (BDCODCIDTOT = 99999) THEN
       BDCODCID = 99999;

    IF (BDCODCID IS NULL) THEN
       IF (BDCODCIDTOT = 80047) THEN
       BDCODCID = 80047;

    IF (BDNUMITEM IS NULL) THEN
       BDNUMITEM = WNUMITEM46;

    IF ((WCODREGAPU <> 3) OR ((WCODREGAPU = 3) AND (CAST(SUBSTRING(bdclassificacao FROM 1 FOR 2) AS INTEGER) <> 8))) THEN
       SUSPEND;
  END

  wsql = 'select DIME.BDCODEMP,';
  wsql = wsql||' DIME.BDREFERENCIA,';
  wsql = wsql||' DIME.BDNUMCAMPO,';
  wsql = wsql||'''46'' bdclassificacao,';
  wsql = wsql||' NULL BDDESCCAMPO, DIME.bdvalor BDVALOR, null bdcodcid, null bdcodcidtot, null BDCODNAT, null BDDATAREC, null BDCLAVENDIMEGERQ12, null BDCODRECDIMEGERQ12,';
  wsql = wsql||' DIME.bdorigemdimegerq46 BDORIGEMDIMEGERQ46, DIME.BDIDENTIFICACAOREGESP, null BDSIGLAUF, 0 BDVLRCONT, 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO, 0 BDVLRISENTRIB, 0 BDVLROUTRAS, DIME.BDNUMCAMPO bdnumitem, 0 BDVLRICMSSTPE, 0 BDVLRICMSSTOP';

  wsql = wsql||' from VEF_SP_DIMEQ46 DIME';

  wwhere = '';
  
  IF ((wTodasAsEmpresa = 'FALSE')) THEN --Alt.: #6420 n?o estava validando se prcodemp era dif. de vazio, quando gerava DIME de todas as empresas n?o funcionava
     wwhere = ' where '||:PRCODEMP;

  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;

     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFERENCIA,
    :BDNUMCAMPO,
    :BDCLASSIFICACAO,
    :BDDESCCAMPO,
    :BDVALOR,
    :BDCODCID,
    :BDCODCIDTOT,
    :BDCODNAT,
    :BDDATAREC,
    :BDCLAVENDIMEGERQ12,
    :BDCODRECDIMEGERQ12,
    :BDORIGEMDIMEGERQ46,
    :BDIDENTIFICACAOREGESP,
    :BDSIGLAUF,
    :BDVLRCONT,
    :BDVLRBC,
    :BDVLRIMPOSTO,
    :BDVLRISENTRIB,
    :BDVLROUTRAS,
    :BDNUMITEM,
    :BDVLROUTRAS,
    :BDVLROUTRAS
--    ,:BDCODEXP48
  DO
  BEGIN

    SUSPEND;
  END

  wsql = 'select DIME.BDCODEMP,';
  wsql = wsql||' DIME.BDREFERENCIA,';
  wsql = wsql||' DIME.BDORDEM BDNUMCAMPO,';
  wsql = wsql||'''12'' bdclassificacao,';
  wsql = wsql||' DIME.BDNUMACORDO BDDESCCAMPO,';
  wsql = wsql||' DIME.BDVALOR,';
  wsql = wsql||' null bdcodcid,';
  wsql = wsql||' null bdcodcidtot,';
  wsql = wsql||' null BDCODNAT,';
  wsql = wsql||' DIME.BDDATAVENCTO BDDATAREC,';
  wsql = wsql||' DIME.BDCLAVENC BDCLAVENDIMEGERQ12,';
  wsql = wsql||' DIME.BDCODRECCLAVENC BDCODRECDIMEGERQ12,';
  wsql = wsql||' DIME.BDORIGPAGTOIMP BDORIGEMDIMEGERQ46,';
  wsql = wsql||' NULL BDIDENTIFICACAOREGESP, ';
  wsql = wsql||' null BDSIGLAUF,';
  wsql = wsql||' 0 BDVLRCONT,';
  wsql = wsql||' 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO,';
  wsql = wsql||' 0 BDVLRISENTRIB,';
  wsql = wsql||' 0 BDVLROUTRAS,';
  wsql = wsql||' 0 bdnumitem,';
  wsql = wsql||' 0 BDVLRICMSSTPE,';
  wsql = wsql||' 0 BDVLRICMSSTOP';

  wsql = wsql||' from VEF_EMP_TDIMEGERPAGTOIMP DIME';
  
  wwhere = '';

  IF ((wTodasAsEmpresa = 'FALSE')) THEN --Alt.: #6420 n?o estava validando se prcodemp era dif. de vazio, quando gerava DIME de todas as empresas n?o funcionava
     wwhere = ' where '||:PRCODEMP;

  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;

     END  

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFERENCIA,
    :BDNUMCAMPO,
    :BDCLASSIFICACAO,
    :BDDESCCAMPO,
    :BDVALOR,
    :BDCODCID,
    :BDCODCIDTOT,
    :BDCODNAT,
    :BDDATAREC,
    :BDCLAVENDIMEGERQ12,
    :BDCODRECDIMEGERQ12,
    :BDORIGEMDIMEGERQ46,
    :BDIDENTIFICACAOREGESP,
    :BDSIGLAUF,
    :BDVLRCONT,
    :BDVLRBC,
    :BDVLRIMPOSTO,
    :BDVLRISENTRIB,
    :BDVLROUTRAS,
    :bdnumitem,
    :BDVLROUTRAS,
    :BDVLROUTRAS
   -- :BDCODEXP48
  DO
  BEGIN

    SUSPEND;
  END

  wwhere = NULL;

  IF ((wTodasAsEmpresa = 'FALSE')) THEN --Alt.: #6420 n?o estava validando se prcodemp era dif. de vazio, quando gerava DIME de todas as empresas n?o funcionava
    wwhere = ' where '||:PRCODEMP;
 
 IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
  BEGIN
    IF (wwhere IS NULL) THEN
       wwhere = ' where ';
    ELSE
       wwhere = wwhere||' and ';
    
    wwhere = wwhere||' DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    wwhere = wwhere||'  and ';
    wwhere = wwhere||' DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
  END

  wsql =       'select '; 
  wsql = wsql||'    DIME.BDCODEMP, ';
  wsql = wsql||'    DIME.BDREFERENCIA, ';
  wsql = wsql||'    DIME.BDNUMCAMPO, ';
  wsql = wsql||'    Q.bdclassificacao, ';
  wsql = wsql||'    null BDDESCCAMPO, ';
  wsql = wsql||'    DIME.BDVALOR, ';
  wsql = wsql||'    null bdcodcid, ';
  wsql = wsql||'    null bdcodcidtot, ';
  wsql = wsql||'    DIME.BDPREFIXONAT BDCODNAT, ';
  wsql = wsql||'    NULL BDDATAREC, ';
  wsql = wsql||'    NULL BDCLAVENDIMEGERQ12, ';
  wsql = wsql||'    NULL BDCODRECDIMEGERQ12, ';
  wsql = wsql||'    NULL BDORIGEMDIMEGERQ46, ';
  wsql = wsql||'    NULL BDIDENTIFICACAOREGESP, ';
  wsql = wsql||'    null BDSIGLAUF, ';
  wsql = wsql||'    0 BDVLRCONT, ';
  wsql = wsql||'    0 BDVLRBC, ';
  wsql = wsql||'    0 BDVLRIMPOSTO, ';
  wsql = wsql||'    0 BDVLRISENTRIB, ';
  wsql = wsql||'    0 BDVLROUTRAS, ';
  wsql = wsql||'    C.bdnumitem, ';
  wsql = wsql||'    0 BDVLRICMSSTPE, ';
  wsql = wsql||'    0 BDVLRICMSSTOP, ';
  wsql = wsql||'    Q.BDCODTIPO ';
  wsql = wsql||'from ( ';
  wsql = wsql||'    select ';
  wsql = wsql||'        DIME.bdcodemp, ';
  wsql = wsql||'        DIME.bdcodperiodo, ';
  wsql = wsql||'        DIME.bdreferencia, ';
  wsql = wsql||'        DIME.bdcodqdime, ';
  wsql = wsql||'        DIME.bdprefixonat, ';
  wsql = wsql||'        DIME.bdnumcampo, ';
  wsql = wsql||'        sum(DIME.bdvalor) bdvalor ';
  wsql = wsql||'    from vef_emp_tdimegernat DIME ';
  wsql = wsql||     wwhere;

  --sol:14445
  IF (wwhere = '') THEN
     wsql = wsql||' where bdvalor > 0 ';
  ELSE
     wsql = wsql||' and bdvalor > 0 ';

  wsql = wsql||'    group by ';
  wsql = wsql||'        DIME.bdcodemp, ';
  wsql = wsql||'        DIME.bdcodperiodo, ';
  wsql = wsql||'        DIME.bdreferencia, ';
  wsql = wsql||'        DIME.bdcodqdime, ';
  wsql = wsql||'        DIME.bdprefixonat,';
  wsql = wsql||'        DIME.bdnumcampo ';
  wsql = wsql||'      ) DIME, vef_estados_tconfdimeform C, VEF_EMP_TDIMESCGER D, vef_estados_tconfdimeq Q ';
  wsql = wsql||'WHERE ';
  wsql = wsql||'    D.bdcodemp = DIME.bdcodemp AND ';
  wsql = wsql||'    D.bdreferencia = DIME.bdreferencia AND ';
  wsql = wsql||'    D.bdcodperiodo = DIME.bdcodperiodo AND ';
  wsql = wsql||'    D.bdcodconf = C.bdcodconfdimesc AND ';
  wsql = wsql||'    DIME.bdnumcampo = C.bdnumcampodime AND ';
  wsql = wsql||'    DIME.bdcodqdime= C.bdcodqdime AND ';
  wsql = wsql||'    Q.bdcodqdime = DIME.bdcodqdime ';

  wnat = 0;
  wVLRCONTAux = 0;
  wVLRBCAux = 0;
  wVLRIMPOSTOAux = 0;
  wVLRISENTRIBAux = 0;
  wVLROUTRASAux = 0;
  wbasest = 0;
  wicmsretst = 0;
  wdifaliqent = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    :wCODEMP,
    :wREFERENCIA,
    :wNUMCAMPO,
    :wCLASSIFICACAO,
    :wDESCCAMPO,
    :wVALOR,
    :wCODCID,
    :wCODCIDTOT,
    :wCODNAT,
    :wDATAREC,
    :wCLAVENDIMEGERQ12,
    :wCODRECDIMEGERQ12,
    :wORIGEMDIMEGERQ46,
    :wIDENTIFICACAOREGESP,
    :wSIGLAUF,
    :wVLRCONT,
    :wVLRBC,
    :wVLRIMPOSTO,
    :wVLRISENTRIB,
    :wVLROUTRAS,
    :wnumitemaux,
    :wVLRICMSSTPE,
    :wVLRICMSSTOP,
    :wCODTIPO
 --   :BDCODEXP48
  DO
  --wnat = :BDCODNAT;
  BEGIN
    IF (wnat = 0) THEN
       wnat = :wCODNAT;

    IF (wnat <> :wCODNAT) THEN
      BEGIN
       wVLRCONTAux = 0;
       wVLRBCAux = 0;
       wVLRIMPOSTOAux = 0;
       wVLRISENTRIBAux = 0;
       wVLROUTRASAux = 0;
       wbasest = 0;
       wicmsretst = 0;
       wdifaliqent = 0;
      END

    IF (wnumitemaux =  4) THEN --Alt.: #6420 numitem modificado de 10 para 4
       wVLRCONTAux = WVALOR;
    ELSE
    IF (wnumitemaux =  5) THEN --Alt.: #6420 numitem modificado de 20 para 5
       wVLRBCAux = wVALOR;
    ELSE
    IF (wnumitemaux =  6) THEN --Alt.: #6420 numitem modificado de 30 para 6
       wVLRIMPOSTOAux = wVALOR;
    ELSE
    IF (wnumitemaux =  7) THEN --Alt.: #6420 numitem modificado de 40 para 7
       wVLRISENTRIBAux = wVALOR;
    ELSE
    IF (wnumitemaux =  8) THEN --Alt.: #6420 numitem modificado de 50 para 8
       wVLROUTRASAux = wVALOR;
    ELSE
    IF (wnumitemaux =  9) THEN --Alt.: #6420 adicionado
       wbasest = wvalor;
    ELSE
    IF (wnumitemaux = 10) THEN --Alt.: #6420 adicionado
       wicmsretst = wvalor;
    ELSE
    IF (wnumitemaux = 11) THEN --Alt.: #6420 adicionado
       wdifaliqent = wvalor;

    IF (wnat <> :wCODNAT) THEN
      BEGIN
        wnat = :wCODNAT;
        SUSPEND;
      END

    bdCODEMP = wCODEMP;
    bdREFERENCIA = wREFERENCIA;
    bdNUMCAMPO = wNUMCAMPO;
    bdCLASSIFICACAO = wCLASSIFICACAO;
    bdDESCCAMPO = wDESCCAMPO;
    bdVALOR = wVALOR;
    bdCODCID = wCODCID;
    bdCODCIDTOT = wCODCIDTOT;
    BDcodnat = wCODNAT;
    bdDATAREC = wDATAREC;
    bdCLAVENDIMEGERQ12 = wCLAVENDIMEGERQ12;
    bdCODRECDIMEGERQ12 = wCODRECDIMEGERQ12;
    bdORIGEMDIMEGERQ46 = wORIGEMDIMEGERQ46;
    BDIDENTIFICACAOREGESP = wIDENTIFICACAOREGESP;
    bdSIGLAUF = wSIGLAUF;
    bdVLRCONT = wVLRCONTAux;
    bdVLRBC = wVLRBCAux;
    bdVLRIMPOSTO = wVLRIMPOSTOAux;
    bdVLRISENTRIB = wVLRISENTRIBAux;
    bdVLROUTRAS = wVLROUTRASAux;
    bdbasest = wbasest;
    bdicmsretst = wicmsretst;
    bddifaliqent = wdifaliqent;
    BDNUMITEM = wnumitemaux;
    BDVLRICMSSTPE = wVLRICMSSTPE;
    BDVLRICMSSTOP = wVLRICMSSTOP;
    BDCODTIPO = wCODTIPO;
    IF (wCLASSIFICACAO = '01.02') THEN--alt:#7162 - n?o estava levando o valor da st e dif pro arquivo
      BEGIN
       --ALT#6650 zerado pois o siada n?o tem esses campos
        wdifaliqent = 0;
        wicmsretst  = 0;
      END
  END

  IF (bdCODNAT > 0) THEN
     SUSPEND;

  wsql = 'select  DIME.BDCODEMP,';
  wsql = wsql||' DIME.BDREFERENCIA,';
  wsql = wsql||' BDNUMCAMPO,';
  wsql = wsql||' Q.bdclassificacao,';
  wsql = wsql||' null BDDESCCAMPO,';
  wsql = wsql||' DIME.BDVALOR,';
  wsql = wsql||' null bdcodcid,';
  wsql = wsql||' null bdcodcidtot,';
  wsql = wsql||' null BDCODNAT,';
  wsql = wsql||' NULL BDDATAREC,';
  wsql = wsql||' NULL BDCLAVENDIMEGERQ12,';
  wsql = wsql||' NULL BDCODRECDIMEGERQ12,';
  wsql = wsql||' NULL BDORIGEMDIMEGERQ46,';
  wsql = wsql||' NULL BDIDENTIFICACAOREGESP, ';
  wsql = wsql||' U.BDSIGLAUF,';
  wsql = wsql||' 0 BDVLRCONT,';
  wsql = wsql||' 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO,';
  wsql = wsql||' 0 BDVLRISENTRIB,';
  wsql = wsql||' 0 BDVLROUTRAS,';
  wsql = wsql||' C.bdnumitem,';
  wsql = wsql||' 0 BDVLRICMSSTPE,';
  wsql = wsql||' 0 BDVLRICMSSTOP,';
  wsql = wsql||' DIME.BDCODUF,';
  wsql = wsql||' Q.BDCODTIPO';


  wsql = wsql||' FROM VEF_EMP_TDIMEGERQ49 DIME';

  wsql = wsql||' LEFT OUTER JOIN TUF U ON U.bdcoduf = DIME.BDCODUF';
  wsql = wsql||' INNER JOIN VEF_EMP_TDIMESCGER D ON (D.bdcodemp = DIME.bdcodemp AND D.bdreferencia = DIME.bdreferencia AND D.bdcodperiodo = DIME.bdcodperiodo)';
  wsql = wsql||' INNER JOIN vef_estados_tconfdimeform C ON (D.bdcodconf = C.bdcodconfdimesc AND DIME.bdnumcampo = C.bdnumcampodime AND  DIME.bdcodqdime= C.bdcodqdime)';
  wsql = wsql||' INNER JOIN vef_estados_tconfdimeq Q ON (Q.bdcodqdime = DIME.bdcodqdime)';

  IF ((wTodasAsEmpresa = 'FALSE')) THEN --Alt.: #6420 n?o estava validando se prcodemp era dif. de vazio, quando gerava DIME de todas as empresas n?o funcionava
     wwhere = ' AND '||:PRCODEMP;

  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
       wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
     END

  wsql = wsql||wwhere;

  wsql = wsql||' ORDER BY DIME.bdcodemp,DIME.bdcodperiodo, DIME.bdreferencia, DIME.bdcodqdime,DIME.bdcoduf desc, C.bdnumitem';

  wuf = 0;
  wVLRCONTAux = 0;
  wVLRBCAux = 0;
  wVLROUTRASAux = 0;
  wVLRICMSSTPEAux = 0;
  wVLRICMSSTOPAux = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    :wCODEMP,
    :wREFERENCIA,
    :wNUMCAMPO,
    :wCLASSIFICACAO,
    :wDESCCAMPO,
    :wVALOR,
    :wCODCID,
    :wCODCIDTOT,
    :wCODNAT,
    :wDATAREC,
    :wCLAVENDIMEGERQ12,
    :wCODRECDIMEGERQ12,
    :wORIGEMDIMEGERQ46,
    :wIDENTIFICACAOREGESP,
    :wSIGLAUF,
    :wVLRCONT,
    :wVLRBC,
    :wVLRIMPOSTO,
    :wVLRISENTRIB,
    :wVLROUTRAS,
    :wnumitemaux,
    :wVLRICMSSTPE,
    :wVLRICMSSTOP,
    :wCODUF,
    :wCODTIPO
 --   :BDCODEXP48
  DO
  BEGIN
    IF (wuf = 0) THEN
       wuf = :wCODUF;

    IF (wnumitemaux = 1) THEN
       wVLRCONTAux = wVALOR;
    ELSE
    IF (wnumitemaux = 2) THEN
       wVLRBCAux = wVALOR;
    ELSE
    IF (wnumitemaux = 3) THEN
       wVLROUTRASAux = wVALOR;
    ELSE
    IF (wnumitemaux = 4) THEN
       wVLRICMSSTPEAux = wVALOR;
    ELSE
    IF (wnumitemaux = 5) THEN
       wVLRICMSSTOPAux = wVALOR;

    IF ((wuf = 99999) AND (wSIGLAUF IS NULL)) THEN
       wSIGLAUF = 'TT';

    IF ((wSIGLAUF IS NULL) AND (wuf <> 99999)) THEN
       BEGIN
          SUSPEND;
          wSIGLAUF = 'TT';
          wuf = 99999;
       END
    ELSE
    IF (:wSIGLAUF <> 'TT') THEN
       IF ((wuf <> :wCODUF) OR (:wCODUF IS NULL)) THEN
          BEGIN
             wuf = :wCODUF;
             SUSPEND;
          END

    IF ((:wSIGLAUF = 'TT') AND ((wVLRCONTAux > 0) OR (wVLRBCAux > 0) OR (wVLROUTRASAux > 0) OR (wVLRICMSSTPEAux > 0) OR (wVLRICMSSTOPAux > 0)) AND
       ((bdCODEMP <> wCODEMP) OR (bdREFERENCIA <> wREFERENCIA))) THEN
       SUSPEND;

    bdCODEMP = wCODEMP;
    bdREFERENCIA = wREFERENCIA;
    bdNUMCAMPO = wNUMCAMPO;
    bdCLASSIFICACAO = wCLASSIFICACAO;
    bdDESCCAMPO = wDESCCAMPO;
    bdVALOR = wVALOR;
    bdCODCID = wCODCID;
    bdCODCIDTOT = wCODCIDTOT;
    bdcodnat = wCODNAT;
    bdDATAREC = wDATAREC;
    bdCLAVENDIMEGERQ12 = wCLAVENDIMEGERQ12;
    bdCODRECDIMEGERQ12 = wCODRECDIMEGERQ12;
    bdORIGEMDIMEGERQ46 = wORIGEMDIMEGERQ46;
    BDIDENTIFICACAOREGESP = wIDENTIFICACAOREGESP;
    bdSIGLAUF = wSIGLAUF;
    bdVLRCONT = wVLRCONTAux;
    bdVLRBC = wVLRBCAux;
    bdVLRIMPOSTO = wVLRIMPOSTOAux;
    bdVLRISENTRIB = wVLRISENTRIBAux;
    bdVLROUTRAS = wVLROUTRASAux;
    BDNUMITEM = wnumitemaux;
    BDVLRICMSSTPE = wVLRICMSSTPEAUX;
    BDVLRICMSSTOP = wVLRICMSSTOPAUX;
    BDCODTIPO = wCODTIPO;
  END

  IF ((wSIGLAUF = 'TT') AND ((wVLRCONTAux > 0) OR (wVLRBCAux > 0) OR (wVLROUTRASAux > 0) OR (wVLRICMSSTPEAux > 0) OR (wVLRICMSSTOPAux > 0)))THEN
     SUSPEND;


  wsql = 'select  DIME.BDCODEMP,';
  wsql = wsql||' DIME.BDREFERENCIA,';
  wsql = wsql||' BDNUMCAMPO,';
  wsql = wsql||' Q.bdclassificacao,';
  wsql = wsql||' null BDDESCCAMPO,';
  wsql = wsql||' DIME.BDVALOR,';
  wsql = wsql||' null bdcodcid,';
  wsql = wsql||' null bdcodcidtot,';
  wsql = wsql||' null BDCODNAT,';
  wsql = wsql||' NULL BDDATAREC,';
  wsql = wsql||' NULL BDCLAVENDIMEGERQ12,';
  wsql = wsql||' NULL BDCODRECDIMEGERQ12,';
  wsql = wsql||' NULL BDORIGEMDIMEGERQ46,';
  wsql = wsql||' NULL BDIDENTIFICACAOREGESP, ';
  wsql = wsql||' U.BDSIGLAUF,';
  wsql = wsql||' 0 BDVLRCONT,';
  wsql = wsql||' 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO,';
  wsql = wsql||' 0 BDVLRISENTRIB,';
  wsql = wsql||' 0 BDVLROUTRAS,';
  wsql = wsql||' C.bdnumitem,';
  wsql = wsql||' 0 BDVLRICMSSTPE,';
  wsql = wsql||' 0 BDVLRICMSSTOP,';
  wsql = wsql||' DIME.BDCODUF,';
  wsql = wsql||' 0 BDVLRCONTCONT,';
  wsql = wsql||' 0 BDVLRBCCONT,';
  wsql = wsql||' 0 BDVLRICMSST,';
  wsql = wsql||' Q.BDCODTIPO';

  wsql = wsql||' FROM VEF_EMP_TDIMEGERQ50 DIME';

  wsql = wsql||' LEFT OUTER JOIN TUF U ON U.bdcoduf = DIME.BDCODUF';
  wsql = wsql||' INNER JOIN VEF_EMP_TDIMESCGER D ON (D.bdcodemp = DIME.bdcodemp AND D.bdreferencia = DIME.bdreferencia AND D.bdcodperiodo = DIME.bdcodperiodo)';
  wsql = wsql||' INNER JOIN vef_estados_tconfdimeform C ON (D.bdcodconf = C.bdcodconfdimesc AND DIME.bdnumcampo = C.bdnumcampodime AND  DIME.bdcodqdime= C.bdcodqdime)';
  wsql = wsql||' INNER JOIN vef_estados_tconfdimeq Q ON (Q.bdcodqdime = DIME.bdcodqdime)';

  IF ((wTodasAsEmpresa = 'FALSE')) THEN --Alt.: #6420 n?o estava validando se prcodemp era dif. de vazio, quando gerava DIME de todas as empresas n?o funcionava
     wwhere = ' AND '||:PRCODEMP;

  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
       wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
     END

  wsql = wsql||wwhere;

  wsql = wsql||' ORDER BY DIME.bdcodemp,DIME.bdcodperiodo, DIME.bdreferencia, DIME.bdcodqdime,DIME.bdcoduf desc, C.bdnumitem';

  wuf = 0;
  wVLRCONTAux = 0;
  wVLRCONTCONTAux = 0;
  wVLRBCAux = 0;
  wVLRBCCONTAux = 0;
  wVLROUTRASAux = 0;
  wVLRICMSSTAux = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    :wCODEMP,
    :wREFERENCIA,
    :wNUMCAMPO,
    :wCLASSIFICACAO,
    :wDESCCAMPO,
    :wVALOR,
    :wCODCID,
    :wCODCIDTOT,
    :wCODNAT,
    :wDATAREC,
    :wCLAVENDIMEGERQ12,
    :wCODRECDIMEGERQ12,
    :wORIGEMDIMEGERQ46,
    :wIDENTIFICACAOREGESP,
    :wSIGLAUF,
    :wVLRCONT,
    :wVLRBC,
    :wVLRIMPOSTO,
    :wVLRISENTRIB,
    :wVLROUTRAS,
    :wnumitemaux,
    :wVLRICMSSTPE,
    :wVLRICMSSTOP,
    :wCODUF,
    :wVLRCONTCONT,
    :wVLRBCCONT,
    :wVLRICMSST,
    :wCODTIPO
   -- :BDCODEXP48
  DO
  BEGIN
    IF (wuf = 0) THEN
       wuf = :wCODUF;

    IF (wnumitemaux = 1) THEN
       wVLRCONTAux = wVALOR;
    ELSE
    IF (wnumitemaux = 2) THEN
       wVLRCONTCONTAux = wVALOR;
    ELSE
    IF (wnumitemaux = 3) THEN
       wVLRBCAux = wVALOR;
    ELSE
    IF (wnumitemaux = 4) THEN
       wVLRBCCONTAux = wVALOR;
    ELSE
    IF (wnumitemaux = 5) THEN
       wVLROUTRASAux = wVALOR;
    ELSE
    IF (wnumitemaux = 6) THEN
       wVLRICMSSTAux = wVALOR;

    IF ((wuf = 99999) AND (wSIGLAUF IS NULL)) THEN
       wSIGLAUF = 'TT';

    IF ((wSIGLAUF IS NULL) AND (wuf <> 99999)) THEN
       BEGIN
          SUSPEND;
          wSIGLAUF = 'TT';
          wuf = 99999;
       END
    ELSE
    IF (:wSIGLAUF <> 'TT') THEN
       IF ((wuf <> :wCODUF) OR (:wCODUF IS NULL)) THEN
          BEGIN
             wuf = :wCODUF;
             SUSPEND;
          END

    IF ((:wSIGLAUF = 'TT') AND ((wVLRCONTAux > 0) OR (wVLRCONTCONTAux > 0) OR(wVLRBCAux > 0) OR(wVLRBCCONTAux > 0) OR(wVLROUTRASAux > 0) OR(wVLRICMSSTAux > 0)) AND
       ((bdCODEMP <> wCODEMP) OR (bdREFERENCIA <> wREFERENCIA))) THEN
       SUSPEND;

    bdCODEMP = wCODEMP;
    bdREFERENCIA = wREFERENCIA;
    bdNUMCAMPO = wNUMCAMPO;
    bdCLASSIFICACAO = wCLASSIFICACAO;
    bdDESCCAMPO = wDESCCAMPO;
    bdVALOR = wVALOR;
    bdCODCID = wCODCID;
    bdCODCIDTOT = wCODCIDTOT;
    BDCODNAT = wCODNAT;
    bdDATAREC = wDATAREC;
    bdCLAVENDIMEGERQ12 = wCLAVENDIMEGERQ12;
    bdCODRECDIMEGERQ12 = wCODRECDIMEGERQ12;
    bdORIGEMDIMEGERQ46 = wORIGEMDIMEGERQ46;
    BDIDENTIFICACAOREGESP = wIDENTIFICACAOREGESP;
    bdSIGLAUF = wSIGLAUF;
    bdVLRCONT = wVLRCONTAux;
    bdVLRBC = wVLRBCAux;
    bdVLRIMPOSTO = wVLRIMPOSTOAux;
    bdVLRISENTRIB = wVLRISENTRIBAux;
    bdVLROUTRAS = wVLROUTRASAux;
    BDNUMITEM = wnumitemaux;
    BDVLRICMSSTPE = wVLRICMSSTPEAUX;
    BDVLRICMSSTOP = wVLRICMSSTOPAUX;
    BDVLRCONTCONT = WVLRCONTCONTAUX;
    BDVLRBCCONT = WVLRBCCONTAUX;
    BDVLRICMSST = WVLRICMSSTAUX;
    BDCODTIPO = wCODTIPO;
  END

  IF (((wVLRCONTAux > 0) OR (wVLRCONTCONTAux > 0) OR(wVLRBCAux > 0) OR (wVLRBCCONTAux > 0) OR(wVLROUTRASAux > 0) OR(wVLRICMSSTAux > 0)) AND (wSIGLAUF = 'TT')) THEN
     SUSPEND;
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG1_18) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_18(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC DM_BDEMAIL,
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT DM_BDTELEFONE,
BDDDDFAXCONT INTEGER,
BDFAXCONT DM_BDTELEFONE,
BDEMAILCONT DM_BDEMAIL,
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER,
BDVLRRECBRU32_CSLL NUMERIC(15,6))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WNUMITEM INTEGER;
DECLARE VARIABLE WCODQIRLP INTEGER;
DECLARE VARIABLE WVALORIRLPGER NUMERIC(15,6);
DECLARE VARIABLE WSEQREG INTEGER;
DECLARE VARIABLE WULTREFERENCIA INTEGER;
DECLARE VARIABLE WULTTRIMESTRE INTEGER;
DECLARE VARIABLE WTRIMESTREAUX INTEGER;
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);
  
/*$$IBEC$$     wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'trefemp.bdnomemp, ';
    wSql = wSql || 'trefemp.bdcodnatjur, ';
    wSql = wSql || 'trefemp.bdcodcnae, ';
    wSql = wSql || 'trefemp.bdlogremp, ';
    wSql = wSql || 'trefemp.bdendemp, ';
    wSql = wSql || 'trefemp.bdnumemp, ';
    wSql = wSql || 'trefemp.bdcomplemp, ';
    wSql = wSql || 'trefemp.bdbaiemp, ';
    wSql = wSql || 'tufemp.bdsiglauf, ';
    wSql = wSql || 'tcidemp.bdcodfed, ';
    wSql = wSql || 'trefemp.bdcepemp, ';
    wSql = wSql || 'trefemp.bddddemp, ';
    wSql = wSql || 'trefemp.bdfoneemp, ';
    wSql = wSql || 'trefemp.bddddfaxemp, ';
    wSql = wSql || 'trefemp.bdfaxemp, ';
    wSql = wSql || 'trefemp.bdemailemp, ';
    wSql = wSql || 'tsoc.bdnomsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdddsoc, ';
    wSql = wSql || 'tsoc.bdtelressoc, ';
    wSql = wSql || 'tsoc.bddddfaxsoc, ';
    wSql = wSql || 'tsoc.bdfaxsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdemailsoc, ';
    wSql = wSql || 'tcon.bdcodcont, ';
    wSql = wSql || 'tcon.bdnomecont, ';
    wSql = wSql || 'tcon.bdcrccont, ';
    wSql = wSql || 'tufcont.bdsiglauf, ';
    wSql = wSql || 'tcon.bdcpfcont, ';
    wSql = wSql || 'tcon.bddddcont, ';
    wSql = wSql || 'tcon.bdfonecont, ';
    wSql = wSql || 'tcon.bddddfaxcont, ';
    wSql = wSql || 'tcon.bdfaxcont, ';
    wSql = wSql || 'tcon.bdemailcont, ';
    wSql = wSql || 'tconfirlpform.bdnumitem, ';
    wSql = wSql || 'tirlpgerreg.bdReferencia, ';
    wSql = wSql || 'tirlpgerreg.bdvalor ';
    wSql = wSql || 'from TEMPRESAS temp ';
    wSql = wSql || 'left outer join vw_tempresas_ref trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
    wSql = wSql || 'left outer join tcidade tcidemp on (tcidemp.bdcodcid = trefemp.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
    wSql = wSql || 'left outer join TCONTADOR_PADRAO tcon on (tcon.BDCODCONT = trefemp.BDCODCONT) ';
    wSql = wSql || 'left outer join tcidade tcidcont on (tcidcont.bdcodcid = tcon.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufcont on (tufcont.bdcoduf = tcidcont.bdcoduf) ';
    wSql = wSql || 'left outer join EMPRESAS_TSOC tsoc on (tsoc.bdcodemp = temp.bdcodemp and upper(tsoc.bdresponsavelsoc) = '''||'TRUE'||''') ';
    wSql = wSql || 'left outer join VEF_EMP_TIRLPGER tirlpger on (tirlpger.bdcodperiodo in (8,9,10) and tirlpger.bdcodemp = temp.bdcodemp) and
                                                                  tirlpger.bdREFERENCIA >= '||prrefini||' and '||'tirlpger.bdREFERENCIA <= '||prreffin||' ';
    wSql = wSql || 'left outer join vef_emp_tirlpgerreg tirlpgerreg on (tirlpgerreg.bdcodemp = tirlpger.bdcodemp and tirlpgerreg.bdcodperiodo = tirlpger.bdcodperiodo and
                                                                        tirlpgerreg.bdreferencia = tirlpger.bdreferencia) ';
    wSql = wSql || 'left outer join vef_base_tconfirlpform tconfirlpform on tconfirlpform.bdcodconfirlp = tirlpger.bdcodconfirlp and tconfirlpform.bdcodqirlp = tirlpgerreg.bdcodqirlp and tconfirlpform.bdnumcampoirlp = tirlpgerreg.bdnumcampo '; $$IBEC$$*/

  wsql = ' select first 1 temp.bdcodemp, temp.bdcnpjemp, trefemp.bdnomemp, trefemp.bdcodnatjur, ';
  wsql = wsql||'          trefemp.bdcodcnae, trefemp.bdlogremp, trefemp.bdendemp, trefemp.bdnumemp, ';
  wsql = wsql||'          trefemp.bdcomplemp, trefemp.bdbaiemp, tufemp.bdsiglauf, tcidemp.bdcodfed, ';
  wsql = wsql||'          trefemp.bdcepemp, trefemp.bddddemp, trefemp.bdfoneemp, trefemp.bddddfaxemp, ';
  wsql = wsql||'          trefemp.bdfaxemp, trefemp.bdemailemp, tsoc.bdnomsoc, tsoc.bdcgcceisoc, ';
  wsql = wsql||'          tsoc.bdddsoc, tsoc.bdtelressoc, tsoc.bddddfaxsoc, tsoc.bdfaxsoc, ';
  wsql = wsql||'          tsoc.bdcgcceisoc, tsoc.bdemailsoc, tcon.bdcodcont, tcon.bdnomecont, ';
  wsql = wsql||'          tcon.bdcrccont, tufcont.bdsiglauf, tcon.bdcpfcont, tcon.bddddcont, ';
  wsql = wsql||'          tcon.bdfonecont, tcon.bddddfaxcont, tcon.bdfaxcont, tcon.bdemailcont ';
  wsql = wsql||'   from TEMPRESAS temp ';
  wsql = wsql||'   left outer join vw_tempresas_ref trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
  wsql = wsql||'   left outer join tcidade tcidemp on (tcidemp.bdcodcid = trefemp.bdcodcid) ';
  wsql = wsql||'   left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
  wsql = wsql||'   left outer join TCONTADOR_PADRAO tcon on (tcon.BDCODCONT = trefemp.BDCODCONT) ';
  wsql = wsql||'   left outer join tcidade tcidcont on (tcidcont.bdcodcid = tcon.bdcodcid) ';
  wsql = wsql||'   left outer join tuf tufcont on (tufcont.bdcoduf = tcidcont.bdcoduf) ';
  wsql = wsql||'   left outer join VW_EMPRESAS_TSOC_REF tsoc on (tsoc.bdcodemp = temp.bdcodemp and upper(tsoc.bdresponsavelsoc) = ''TRUE'') ';

  wwhere = '';
  
  IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
    wwhere = wWhere||'('||prempresas||') ';
  
  IF (wwhere <> '') THEN
    wwhere = 'where '||wwhere||' ';
  
  /*definir na aplica??o*/
--  worderby = 'order by bdcodemp, bdreferencia ';

  wsql = wsql||wwhere;--||worderby;

  EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcnpjemp,
    :bdnomemp,
    :bdcodnatjur,
    :bdcodcnae,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdcomplemp,
    :bdbaiemp,
    :bdsiglaufemp,
    :bdcodcidemp,
    :bdcepemp,
    :bddddemp,
    :bdfoneemp,
    :bddddfaxemp,
    :bdfaxemp,
    :bdemailemp,
    :bdnomsoc,
    :bdcgcceisoc,
    :bddddsoc,
    :bdtelressoc,
    :bddddfaxsoc,
    :bdfaxsoc,
    :bdcgcceisoc,
    :bdemailsoc,
    :bdcodcont,
    :bdnomecont,
    :bdcrccont,
    :bdsiglaufcont,
    :bdcpfcont,
    :bddddcont,
    :bdfonecont,
    :bddddfaxcont,
    :bdfaxcont,
    :bdemailcont;

  wsql = ' select ger.bdcodemp, tri.bdtrimestre, reg.bdnumcampo, reg.bdcodqirlp, sum(reg.bdvalor) bdvalor ';
  wsql = wsql||' from (select ger.bdcodemp, ger.bdcodperiodo, ger.bdreferencia, ger.bdcodconfirlp from vef_emp_tirlpger ger where ger.bdcodperiodo in (8,10) and ger.bdcodemp = '|| bdcodemp ||'and ger.bdreferencia >= '|| prrefini ||' and ger.bdreferencia <= '|| prreffin ||' order by ger.bdreferencia) ger ';
  wsql = wsql||' left outer join vef_emp_tirlpgerreg reg on reg.bdcodemp = ger.bdcodemp and reg.bdcodperiodo = ger.bdcodperiodo and reg.bdreferencia = ger.bdreferencia ';
  wsql = wsql||' left outer join vef_base_tconfirlpform frm on frm.bdcodconfirlp = ger.bdcodconfirlp and frm.bdcodqirlp = reg.bdcodqirlp and frm.bdnumcampoirlp = reg.bdnumcampo ';
  wsql = wsql||' left outer join sp_ref_trimestre(reg.bdreferencia) tri on tri.bdref = reg.bdreferencia ';
  --wsql = wsql||' where reg.bdnumcampo in (1,2,3,4,5,9,11,14,16,19,21,22,27,29) ';
  wsql = wsql||' where reg.bdnumcampo in (1,2,3,4,5,7,8,9,10,11,14) ';
  wsql = wsql||' group by bdcodemp, bdtrimestre, bdnumcampo, bdcodqirlp ';

  wSeqReg = 0;
  wulttrimestre = 0;
  bdvlrrecbru1_6_irlp      = 0;
  bdvlrrecbru8_irlp        = 0;
  bdvlrrecbru16_irlp       = 0;
  bdvlrrecbru32_irlp       = 0;
  bdvlrrecbru32_csll       = 0;
  bdvlrlucropresumido_irlp = 0;
  bdvlradicional_irlp      = 0;
  bdvlraliq15_irlp         = 0;
  bdvlrimpostopagar_irlp   = 0;
  bdvlrimpostoretido_irlp  = 0;
  bdvlrcsllapagar_irlp     = 0;
  bdvlrrecbru12_irlp       = 0;
  bdvlrrecbruajust_irlp    = 0;
  bdvlrcsllapurada_irlp    = 0;
  bdvlrcsllretpj           = 0;

  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodemp,
      :bdtrimestre,
      :wnumitem,
      :wcodqirlp,
      :wvalorirlpger
  DO
  BEGIN
    IF ((wulttrimestre IS NOT NULL) AND (wulttrimestre > 0) AND (wulttrimestre <> bdtrimestre)) THEN
      BEGIN
        wtrimestreaux = bdtrimestre;
        bdtrimestre = wulttrimestre;
        SUSPEND;
        bdtrimestre = wtrimestreaux;
        wultreferencia = wulttrimestre;
        bdvlrrecbru1_6_irlp      = 0;
        bdvlrrecbru8_irlp        = 0;
        bdvlrrecbru16_irlp       = 0;
        bdvlrrecbru32_irlp       = 0;
        bdvlrrecbru32_csll       = 0;
        bdvlrlucropresumido_irlp = 0;
        bdvlradicional_irlp      = 0;
        bdvlraliq15_irlp         = 0;
        bdvlrimpostopagar_irlp   = 0;
        bdvlrimpostoretido_irlp  = 0;


        bdvlrrecbru12_irlp       = 0;
        bdvlrrecbruajust_irlp    = 0;
        bdvlrcsllapurada_irlp    = 0;
        bdvlrcsllretpj           = 0;
        bdvlrcsllapagar_irlp     = 0;
      END

    IF ((:wnumitem = 1) AND (:wcodqirlp = 2)) THEN
      bdvlrrecbru1_6_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 2) AND (:wcodqirlp = 2)) THEN
      bdvlrrecbru8_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 3) AND (:wcodqirlp = 2)) THEN
      bdvlrrecbru16_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 4) AND (:wcodqirlp = 2)) THEN
      bdvlrrecbru32_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 5) AND (:wcodqirlp = 2)) THEN
      bdvlrlucropresumido_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 9) AND (:wcodqirlp = 2)) THEN
      BEGIN
        bdvlrimpostopagar_irlp = wvalorirlpger;
        bdvlraliq15_irlp = wvalorirlpger;
      END
    ELSE IF ((:wnumitem = 11) AND (:wcodqirlp = 2)) THEN
      bdvlradicional_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 14) AND (:wcodqirlp = 2)) THEN
      bdvlrimpostoretido_irlp = wvalorirlpger;

    /*sol:7885
    else if (:wnumitem = 29) then
       bdvlrrecbru12_irlp = wvalorirlpger;
    else if (:wnumitem = 27) then
      bdvlrrecbruajust_irlp = wvalorirlpger;
    else if (:wnumitem = 19) then
      bdvlrcsllapurada_irlp = wvalorirlpger;
    else if (:wnumitem = 21) then
      bdvlrcsllretpj = wvalorirlpger;
    else if (:wnumitem = 22) then
      bdvlrcsllapagar_irlp = wvalorirlpger;*/

    ELSE IF ((:wnumitem = 1) AND (:wcodqirlp = 3))  THEN
       bdvlrrecbru12_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 2) AND (:wcodqirlp = 3)) THEN
      bdvlrrecbru32_csll = wvalorirlpger;
    ELSE IF ((:wnumitem = 3) AND (:wcodqirlp = 3)) THEN
      bdvlrrecbruajust_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 7) AND (:wcodqirlp = 3)) THEN
      bdvlrcsllapurada_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 8) AND (:wcodqirlp = 3)) THEN
      bdvlrcsllretpj = wvalorirlpger;
    ELSE IF ((:wnumitem = 10) AND (:wcodqirlp = 3)) THEN
      bdvlrcsllapagar_irlp = wvalorirlpger;

    wulttrimestre = bdtrimestre;
  END

  IF ((bdtrimestre > wultreferencia) OR ((wultreferencia IS NULL) AND (bdtrimestre > 0))) THEN
    SUSPEND;

/*$$IBEC$$    for execute statement wsql
     into
       :bdcodemp,
       :bdcnpjemp,
       :bdnomemp,
       :bdcodnatjur,
       :bdcodcnae,
       :bdlogremp,
       :bdendemp,
       :bdnumemp,
       :bdcomplemp,
       :bdbaiemp,
       :bdsiglaufemp,
       :bdcodcidemp,
       :bdcepemp,
       :bddddemp,
       :bdfoneemp,
       :bddddfaxemp,
       :bdfaxemp,
       :bdemailemp,
       :bdnomsoc,
       :bdcgcceisoc,
       :bddddsoc,
       :bdtelressoc,
       :bddddfaxsoc,
       :bdfaxsoc,
       :bdcgcceisoc,
       :bdemailsoc,
       :bdcodcont,
       :bdnomecont,
       :bdcrccont,
       :bdsiglaufcont,
       :bdcpfcont,
       :bddddcont,
       :bdfonecont,
       :bddddfaxcont,
       :bdfaxcont,
       :bdemailcont,
       :wnumitem,
       :bdReferencia,
       :wvalorirlpger
     do
     begin
        wref = cast(substring(bdreferencia from 5 for 2) as integer);

--       if ((wultreferencia <> bdreferencia) and (wSeqReg <> 1)) then
        if ((wulttrimestre <> 0) and (wulttrimestre <> bdtrimestre) and (wseqreg <> 1)) then
          begin
            if (bdtrimestre is not null) then
              begin
                suspend;
                bdvlrrecbru1_6_irlp      = 0;
                bdvlrrecbru8_irlp        = 0;
                bdvlrrecbru16_irlp       = 0;
                bdvlrrecbru32_irlp       = 0;
                bdvlrrecbru32_irlp       = 0;
                bdvlrlucropresumido_irlp = 0;
                bdvlradicional_irlp      = 0;
                bdvlraliq15_irlp         = 0;
                bdvlrimpostopagar_irlp   = 0;
                bdvlrimpostoretido_irlp  = 0;
                bdvlrcsllapagar_irlp     = 0;
                bdvlrrecbru12_irlp       = 0;
                bdvlrrecbruajust_irlp    = 0;
                bdvlrcsllapurada_irlp    = 0;
                bdvlrcsllretpj           = 0;
              end
          end

       if (wref <= 3) then
          bdtrimestre = 1;
       else
       if (wref <= 6) then
          bdtrimestre = 2;
       else
       if (wref <= 9) then
          bdtrimestre = 3;
       else
       if (wref <= 12) then
          bdtrimestre = 4;

       if (wref is not null) then
          begin
            wSeqReg = wSeqReg + 1;
            wulttrimestre = bdtrimestre;
          end

       if (:wnumitem = 1) then
          bdvlrrecbru1_6_irlp = bdvlrrecbru1_6_irlp + wvalorirlpger;
       else
       if (:wnumitem = 2) then
          bdvlrrecbru8_irlp = bdvlrrecbru8_irlp + wvalorirlpger;
       else
       if (:wnumitem = 3) then
          bdvlrrecbru16_irlp = bdvlrrecbru16_irlp + wvalorirlpger;
       if (:wnumitem = 4) then
          bdvlrrecbru32_irlp = bdvlrrecbru32_irlp + wvalorirlpger;
       else
       if (:wnumitem = 5) then
          bdvlrlucropresumido_irlp = bdvlrlucropresumido_irlp + wvalorirlpger;
       else
       if (:wnumitem = 9) then
          begin
            bdvlrimpostopagar_irlp = bdvlrimpostopagar_irlp + wvalorirlpger;
            bdvlraliq15_irlp       = bdvlraliq15_irlp + wvalorirlpger;
          end
       else
       if (:wnumitem = 11) then
          bdvlradicional_irlp = bdvlradicional_irlp + wvalorirlpger;
       else
       if (:wnumitem = 14) then
          bdvlrimpostoretido_irlp = bdvlrimpostoretido_irlp + wvalorirlpger;
       else
       if (:wnumitem = 24) then
          bdvlrcsllapagar_irlp = bdvlrcsllapagar_irlp + wvalorirlpger;

       wultreferencia = BDREFERENCIA;
     end $$IBEC$$*/
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG1_3) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_3(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC DM_BDEMAIL,
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT DM_BDTELEFONE,
BDDDDFAXCONT INTEGER,
BDFAXCONT DM_BDTELEFONE,
BDEMAILCONT DM_BDEMAIL,
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);
  
/*$$IBEC$$     wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'trefemp.bdnomemp, ';
    wSql = wSql || 'trefemp.bdcodnatjur, ';
    wSql = wSql || 'trefemp.bdcodcnae, ';
    wSql = wSql || 'trefemp.bdlogremp, ';
    wSql = wSql || 'trefemp.bdendemp, ';
    wSql = wSql || 'trefemp.bdnumemp, ';
    wSql = wSql || 'trefemp.bdcomplemp, ';
    wSql = wSql || 'trefemp.bdbaiemp, ';
    wSql = wSql || 'tufemp.bdsiglauf, ';
    wSql = wSql || 'tcidemp.bdcodfed, ';
    wSql = wSql || 'trefemp.bdcepemp, ';
    wSql = wSql || 'trefemp.bddddemp, ';
    wSql = wSql || 'trefemp.bdfoneemp, ';
    wSql = wSql || 'trefemp.bddddfaxemp, ';
    wSql = wSql || 'trefemp.bdfaxemp, ';
    wSql = wSql || 'trefemp.bdemailemp, ';
    wSql = wSql || 'tsoc.bdnomsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdddsoc, ';
    wSql = wSql || 'tsoc.bdtelressoc, ';
    wSql = wSql || 'tsoc.bddddfaxsoc, ';
    wSql = wSql || 'tsoc.bdfaxsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdemailsoc, ';
    wSql = wSql || 'tcon.bdcodcont, ';
    wSql = wSql || 'tcon.bdnomecont, ';
    wSql = wSql || 'tcon.bdcrccont, ';
    wSql = wSql || 'tufcont.bdsiglauf, ';
    wSql = wSql || 'tcon.bdcpfcont, ';
    wSql = wSql || 'tcon.bddddcont, ';
    wSql = wSql || 'tcon.bdfonecont, ';
    wSql = wSql || 'tcon.bddddfaxcont, ';
    wSql = wSql || 'tcon.bdfaxcont, ';
    wSql = wSql || 'tcon.bdemailcont, ';
    wSql = wSql || 'tconfirlpform.bdnumitem, ';
    wSql = wSql || 'tirlpgerreg.bdReferencia, ';
    wSql = wSql || 'tirlpgerreg.bdvalor ';
    wSql = wSql || 'from TEMPRESAS temp ';
    wSql = wSql || 'left outer join vw_tempresas_ref trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
    wSql = wSql || 'left outer join tcidade tcidemp on (tcidemp.bdcodcid = trefemp.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
    wSql = wSql || 'left outer join TCONTADOR_PADRAO tcon on (tcon.BDCODCONT = trefemp.BDCODCONT) ';
    wSql = wSql || 'left outer join tcidade tcidcont on (tcidcont.bdcodcid = tcon.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufcont on (tufcont.bdcoduf = tcidcont.bdcoduf) ';
    wSql = wSql || 'left outer join EMPRESAS_TSOC tsoc on (tsoc.bdcodemp = temp.bdcodemp and upper(tsoc.bdresponsavelsoc) = '''||'TRUE'||''') ';
    wSql = wSql || 'left outer join VEF_EMP_TIRLPGER tirlpger on (tirlpger.bdcodperiodo in (8,9,10) and tirlpger.bdcodemp = temp.bdcodemp) and
                                                                  tirlpger.bdREFERENCIA >= '||prrefini||' and '||'tirlpger.bdREFERENCIA <= '||prreffin||' ';
    wSql = wSql || 'left outer join vef_emp_tirlpgerreg tirlpgerreg on (tirlpgerreg.bdcodemp = tirlpger.bdcodemp and tirlpgerreg.bdcodperiodo = tirlpger.bdcodperiodo and
                                                                        tirlpgerreg.bdreferencia = tirlpger.bdreferencia) ';
    wSql = wSql || 'left outer join vef_base_tconfirlpform tconfirlpform on tconfirlpform.bdcodconfirlp = tirlpger.bdcodconfirlp and tconfirlpform.bdcodqirlp = tirlpgerreg.bdcodqirlp and tconfirlpform.bdnumcampoirlp = tirlpgerreg.bdnumcampo '; $$IBEC$$*/

  wsql = ' select first 1 temp.bdcodemp, temp.bdcnpjemp, trefemp.bdnomemp, trefemp.bdcodnatjur, ';
  wsql = wsql||'          trefemp.bdcodcnae, trefemp.bdlogremp, trefemp.bdendemp, trefemp.bdnumemp, ';
  wsql = wsql||'          trefemp.bdcomplemp, trefemp.bdbaiemp, tufemp.bdsiglauf, tcidemp.bdcodfed, ';
  wsql = wsql||'          trefemp.bdcepemp, trefemp.bddddemp, trefemp.bdfoneemp, trefemp.bddddfaxemp, ';
  wsql = wsql||'          trefemp.bdfaxemp, trefemp.bdemailemp, tsoc.bdnomsoc, tsoc.bdcgcceisoc, ';
  wsql = wsql||'          tsoc.bdddsoc, tsoc.bdtelressoc, tsoc.bddddfaxsoc, tsoc.bdfaxsoc, ';
  wsql = wsql||'          tsoc.bdcgcceisoc, tsoc.bdemailsoc, tcon.bdcodcont, tcon.bdnomecont, ';
  wsql = wsql||'          tcon.bdcrccont, tufcont.bdsiglauf, tcon.bdcpfcont, tcon.bddddcont, ';
  wsql = wsql||'          tcon.bdfonecont, tcon.bddddfaxcont, tcon.bdfaxcont, tcon.bdemailcont ';
  wsql = wsql||'   from TEMPRESAS temp ';
  wsql = wsql||'   left outer join vw_tempresas_ref trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
  wsql = wsql||'   left outer join tcidade tcidemp on (tcidemp.bdcodcid = trefemp.bdcodcid) ';
  wsql = wsql||'   left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
  wsql = wsql||'   left outer join TCONTADOR_PADRAO tcon on (tcon.BDCODCONT = trefemp.BDCODCONT) ';
  wsql = wsql||'   left outer join tcidade tcidcont on (tcidcont.bdcodcid = tcon.bdcodcid) ';
  wsql = wsql||'   left outer join tuf tufcont on (tufcont.bdcoduf = tcidcont.bdcoduf) ';
  wsql = wsql||'   left outer join VW_EMPRESAS_TSOC_REF tsoc on (tsoc.bdcodemp = temp.bdcodemp and upper(tsoc.bdresponsavelsoc) = ''TRUE'') ';

  wwhere = '';
  
  IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
    wwhere = wWhere||'('||prempresas||') ';
  
  IF (wwhere <> '') THEN
    wwhere = 'where '||wwhere||' ';
  
  /*definir na aplica??o*/
--  worderby = 'order by bdcodemp, bdreferencia ';

  wsql = wsql||wwhere;--||worderby;

  EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcnpjemp,
    :bdnomemp,
    :bdcodnatjur,
    :bdcodcnae,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdcomplemp,
    :bdbaiemp,
    :bdsiglaufemp,
    :bdcodcidemp,
    :bdcepemp,
    :bddddemp,
    :bdfoneemp,
    :bddddfaxemp,
    :bdfaxemp,
    :bdemailemp,
    :bdnomsoc,
    :bdcgcceisoc,
    :bddddsoc,
    :bdtelressoc,
    :bddddfaxsoc,
    :bdfaxsoc,
    :bdcgcceisoc,
    :bdemailsoc,
    :bdcodcont,
    :bdnomecont,
    :bdcrccont,
    :bdsiglaufcont,
    :bdcpfcont,
    :bddddcont,
    :bdfonecont,
    :bddddfaxcont,
    :bdfaxcont,
    :bdemailcont;

  /*wsql = ' select ger.bdcodemp, tri.bdtrimestre, reg.bdnumcampo, sum(reg.bdvalor) bdvalor ';
  wsql = wsql||' from (select ger.bdcodemp, ger.bdcodperiodo, ger.bdreferencia, ger.bdcodconfirlp from vef_emp_tirlpger ger where ger.bdcodperiodo in (8,10) and ger.bdcodemp = '|| bdcodemp ||'and ger.bdreferencia >= '|| prrefini ||' and ger.bdreferencia <= '|| prreffin ||' order by ger.bdreferencia) ger ';
  wsql = wsql||' left outer join vef_emp_tirlpgerreg reg on reg.bdcodemp = ger.bdcodemp and reg.bdcodperiodo = ger.bdcodperiodo and reg.bdreferencia = ger.bdreferencia ';
  wsql = wsql||' left outer join vef_base_tconfirlpform frm on frm.bdcodconfirlp = ger.bdcodconfirlp and frm.bdcodqirlp = reg.bdcodqirlp and frm.bdnumcampoirlp = reg.bdnumcampo ';
  wsql = wsql||' left outer join sp_ref_trimestre(reg.bdreferencia) tri on tri.bdref = reg.bdreferencia ';
  wsql = wsql||' where reg.bdnumcampo in (1,2,3,4,5,9,11,14,16,19,21,22,27,29) ';
  wsql = wsql||' group by bdcodemp, bdtrimestre, bdnumcampo ';

  wSeqReg = 0;
  wulttrimestre = 0;
  bdvlrrecbru1_6_irlp      = 0;
  bdvlrrecbru8_irlp        = 0;
  bdvlrrecbru16_irlp       = 0;
  bdvlrrecbru32_irlp       = 0;
  bdvlrrecbru32_irlp       = 0;
  bdvlrlucropresumido_irlp = 0;
  bdvlradicional_irlp      = 0;
  bdvlraliq15_irlp         = 0;
  bdvlrimpostopagar_irlp   = 0;
  bdvlrimpostoretido_irlp  = 0;
  bdvlrcsllapagar_irlp     = 0;
  bdvlrrecbru12_irlp       = 0;
  bdvlrrecbruajust_irlp    = 0;
  bdvlrcsllapurada_irlp    = 0;
  bdvlrcsllretpj           = 0;

  for execute statement wsql
    into
      :bdcodemp,
      :bdtrimestre,
      :wnumitem,
      :wvalorirlpger
  do
  begin
    if ((wulttrimestre is not null) and (wulttrimestre > 0) and (wulttrimestre <> bdtrimestre)) then
      begin
        wtrimestreaux = bdtrimestre;
        bdtrimestre = wulttrimestre;
        suspend;
        bdtrimestre = wtrimestreaux;
        wultreferencia = wulttrimestre;
        bdvlrrecbru1_6_irlp      = 0;
        bdvlrrecbru8_irlp        = 0;
        bdvlrrecbru16_irlp       = 0;
        bdvlrrecbru32_irlp       = 0;
        bdvlrrecbru32_irlp       = 0;
        bdvlrlucropresumido_irlp = 0;
        bdvlradicional_irlp      = 0;
        bdvlraliq15_irlp         = 0;
        bdvlrimpostopagar_irlp   = 0;
        bdvlrimpostoretido_irlp  = 0;


        bdvlrrecbru12_irlp       = 0;
        bdvlrrecbruajust_irlp    = 0;
        bdvlrcsllapurada_irlp    = 0;
        bdvlrcsllretpj           = 0;
        bdvlrcsllapagar_irlp     = 0;
      end

    if (:wnumitem = 1) then
      bdvlrrecbru1_6_irlp = wvalorirlpger;
    else if (:wnumitem = 2) then
      bdvlrrecbru8_irlp = wvalorirlpger;
    else if (:wnumitem = 3) then
      bdvlrrecbru16_irlp = wvalorirlpger;
    else if (:wnumitem = 4) then
      bdvlrrecbru32_irlp = wvalorirlpger;
    else if (:wnumitem = 5) then
      bdvlrlucropresumido_irlp = wvalorirlpger;
    else if (:wnumitem = 9) then
      begin
        bdvlrimpostopagar_irlp = wvalorirlpger;
        bdvlraliq15_irlp = wvalorirlpger;
      end
    else if (:wnumitem = 11) then
      bdvlradicional_irlp = wvalorirlpger;
    else if (:wnumitem = 14) then
      bdvlrimpostoretido_irlp = wvalorirlpger;


    else if (:wnumitem = 29) then
       bdvlrrecbru12_irlp = wvalorirlpger;
    else if (:wnumitem = 27) then
      bdvlrrecbruajust_irlp = wvalorirlpger;
    else if (:wnumitem = 19) then
      bdvlrcsllapurada_irlp = wvalorirlpger;
    else if (:wnumitem = 21) then
      bdvlrcsllretpj = wvalorirlpger;
    else if (:wnumitem = 22) then
      bdvlrcsllapagar_irlp = wvalorirlpger;

    wulttrimestre = bdtrimestre;
  end

  if (bdtrimestre > wultreferencia) then*/
    SUSPEND;

/*$$IBEC$$    for execute statement wsql
     into
       :bdcodemp,
       :bdcnpjemp,
       :bdnomemp,
       :bdcodnatjur,
       :bdcodcnae,
       :bdlogremp,
       :bdendemp,
       :bdnumemp,
       :bdcomplemp,
       :bdbaiemp,
       :bdsiglaufemp,
       :bdcodcidemp,
       :bdcepemp,
       :bddddemp,
       :bdfoneemp,
       :bddddfaxemp,
       :bdfaxemp,
       :bdemailemp,
       :bdnomsoc,
       :bdcgcceisoc,
       :bddddsoc,
       :bdtelressoc,
       :bddddfaxsoc,
       :bdfaxsoc,
       :bdcgcceisoc,
       :bdemailsoc,
       :bdcodcont,
       :bdnomecont,
       :bdcrccont,
       :bdsiglaufcont,
       :bdcpfcont,
       :bddddcont,
       :bdfonecont,
       :bddddfaxcont,
       :bdfaxcont,
       :bdemailcont,
       :wnumitem,
       :bdReferencia,
       :wvalorirlpger
     do
     begin
        wref = cast(substring(bdreferencia from 5 for 2) as integer);

--       if ((wultreferencia <> bdreferencia) and (wSeqReg <> 1)) then
        if ((wulttrimestre <> 0) and (wulttrimestre <> bdtrimestre) and (wseqreg <> 1)) then
          begin
            if (bdtrimestre is not null) then
              begin
                suspend;
                bdvlrrecbru1_6_irlp      = 0;
                bdvlrrecbru8_irlp        = 0;
                bdvlrrecbru16_irlp       = 0;
                bdvlrrecbru32_irlp       = 0;
                bdvlrrecbru32_irlp       = 0;
                bdvlrlucropresumido_irlp = 0;
                bdvlradicional_irlp      = 0;
                bdvlraliq15_irlp         = 0;
                bdvlrimpostopagar_irlp   = 0;
                bdvlrimpostoretido_irlp  = 0;
                bdvlrcsllapagar_irlp     = 0;
                bdvlrrecbru12_irlp       = 0;
                bdvlrrecbruajust_irlp    = 0;
                bdvlrcsllapurada_irlp    = 0;
                bdvlrcsllretpj           = 0;
              end
          end

       if (wref <= 3) then
          bdtrimestre = 1;
       else
       if (wref <= 6) then
          bdtrimestre = 2;
       else
       if (wref <= 9) then
          bdtrimestre = 3;
       else
       if (wref <= 12) then
          bdtrimestre = 4;

       if (wref is not null) then
          begin
            wSeqReg = wSeqReg + 1;
            wulttrimestre = bdtrimestre;
          end

       if (:wnumitem = 1) then
          bdvlrrecbru1_6_irlp = bdvlrrecbru1_6_irlp + wvalorirlpger;
       else
       if (:wnumitem = 2) then
          bdvlrrecbru8_irlp = bdvlrrecbru8_irlp + wvalorirlpger;
       else
       if (:wnumitem = 3) then
          bdvlrrecbru16_irlp = bdvlrrecbru16_irlp + wvalorirlpger;
       if (:wnumitem = 4) then
          bdvlrrecbru32_irlp = bdvlrrecbru32_irlp + wvalorirlpger;
       else
       if (:wnumitem = 5) then
          bdvlrlucropresumido_irlp = bdvlrlucropresumido_irlp + wvalorirlpger;
       else
       if (:wnumitem = 9) then
          begin
            bdvlrimpostopagar_irlp = bdvlrimpostopagar_irlp + wvalorirlpger;
            bdvlraliq15_irlp       = bdvlraliq15_irlp + wvalorirlpger;
          end
       else
       if (:wnumitem = 11) then
          bdvlradicional_irlp = bdvlradicional_irlp + wvalorirlpger;
       else
       if (:wnumitem = 14) then
          bdvlrimpostoretido_irlp = bdvlrimpostoretido_irlp + wvalorirlpger;
       else
       if (:wnumitem = 24) then
          bdvlrcsllapagar_irlp = bdvlrcsllapagar_irlp + wvalorirlpger;

       wultreferencia = BDREFERENCIA;
     end $$IBEC$$*/
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG19) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG19(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18))
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL SMALLINT)
 AS
DECLARE VARIABLE worderby VARCHAR(5000);
DECLARE VARIABLE wwhere VARCHAR(5000);
DECLARE VARIABLE wsql VARCHAR(25000);
DECLARE VARIABLE wcnpjemp VARCHAR(18);
BEGIN
   wSql = 'select bdcodemp, ';
   wSql = wSql || 'bdcnpjemp ';
   wSql = wSql || 'from tempresas temp ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (wWhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplica??o*/
   worderby = 'order by bdcodemp ';

   wsql = wsql||wwhere||worderby;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcnpjemp
     DO
     BEGIN
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;
        SUSPEND;
     END
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG20) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG20(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDEXISTEMOV INTEGER,
BDPERIODO INTEGER,
BDMES INTEGER,
BDVLRSALDOCREANT NUMERIC(15,6),
BDVLRDEBITO NUMERIC(15,6),
BDVLRCREDITO NUMERIC(15,6),
BDVLRSALDO NUMERIC(15,6),
BDCREDORDEVEDOR INTEGER,
BDSEQUENCIAL INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WNUMITEM INTEGER;
DECLARE VARIABLE WULTREFERENCIA INTEGER;
DECLARE VARIABLE WULTCODPERIODO INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WVLRIPIGER NUMERIC(15,6);
DECLARE VARIABLE WSEQREG INTEGER;
DECLARE VARIABLE WVLRNUMITEM13 NUMERIC(15,6);
DECLARE VARIABLE WVLRNUMITEM14 NUMERIC(15,2);
DECLARE VARIABLE WVLRNUMITEM01 NUMERIC(15,6);
DECLARE VARIABLE WVLRNUMITEM06 NUMERIC(15,6);
DECLARE VARIABLE WVLRNUMITEM09 NUMERIC(15,6);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

    
    wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'tconfipiform.bdnumitem, ';
    wSql = wSql || 'tipigerreg.bdcodperiodo, ';
    wSql = wSql || 'tipigerreg.bdReferencia, ';
    wSql = wSql || 'tipigerreg.bdvalor ';
    wSql = wSql || 'from TEMPRESAS temp ';
    wSql = wSql || 'left outer join vef_emp_tipiger tipiger on (tipiger.bdcodemp = temp.bdcodemp and tipiger.bdREFERENCIA >= '||prrefini||' and tipiger.bdREFERENCIA <= '||prreffin||') ';
    wSql = wSql || 'left outer join vef_emp_tipigerreg tipigerreg on (tipigerreg.bdcodemp = tipiger.bdcodemp and tipigerreg.bdcodperiodo = tipiger.bdcodperiodo and
                                                                      tipigerreg.bdreferencia = tipiger.bdreferencia) ';
    wSql = wSQl || 'left outer join vef_base_tconfipiform tconfipiform on (tconfipiform.bdcodconfipi  = tipiger.bdcodconfipi and tconfipiform.bdcodqipi = tipigerreg.bdcodqipi and
                                                           tconfipiform.bdnumcampoipi = tipigerreg.bdnumcampo) ';

    wwhere = '';
  
    IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
       wwhere = wWhere||'('||prempresas||') ';
  
    IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

    worderby = 'order by temp.bdcodemp, bdreferencia, bdcodperiodo, bdnumitem ';

    wsql = wsql||wwhere||worderby;


     wSeqReg = 0;
     bdsequencial = 0;

    FOR EXECUTE STATEMENT wsql
     INTO
        :bdcodemp,
        :wcnpjemp,
        :wnumitem,
        :wcodperiodo,
        :bdreferencia,
        :wvlripiger
     DO
     BEGIN
     IF (((wultreferencia <> bdreferencia) OR (wultcodperiodo <> wcodperiodo)) AND (wSeqReg <> 1)) THEN
          BEGIN
            IF (wvlrnumitem13 > 0) THEN
               bdvlrsaldo = wvlrnumitem13;
            ELSE
               bdvlrsaldo = wvlrnumitem14;

            IF (wvlrnumitem01 > wvlrnumitem06) THEN
               bdcredordevedor = 2;
            ELSE
               bdcredordevedor = 1;

            --if ((wvlrnumitem09 - wvlrnumitem14) = 0) then
            IF ((bdvlrdebito = 0) AND (bdvlrcredito = 0)) THEN
               bdexistemov = 2;
            ELSE
               bdexistemov = 1;
            bdsequencial = bdsequencial + 1;
            SUSPEND;
            BDVLRSALDOCREANT = 0;
            BDVLRDEBITO      = 0;
            BDVLRCREDITO     = 0;
            BDVLRSALDO       = 0;
            BDCREDORDEVEDOR  = 0;
            wvlrnumitem01    = 0;
            wvlrnumitem06    = 0;
            wvlrnumitem13    = 0;
            wvlrnumitem14    = 0;
            wvlrnumitem09    = 0;
          END

       wSeqReg          = wSeqReg + 1;

       bdmes = (SUBSTRING(bdreferencia FROM 5 FOR 2));
       bdcnpjempmatriz = prcnpjmatriz;
       bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;


       -- defini??o dos valores de saldos, d?bito e cr?dito
       IF (wnumitem = 5) THEN
          bdvlrdebito = wvlripiger;
       ELSE
       IF (wnumitem = 9) THEN
          BEGIN
            bdvlrsaldocreant = wvlripiger;
            --bdvlrcredito     = wvlripiger;
            wvlrnumitem09    = wvlripiger;
          END
       ELSE
       IF (wnumitem = 11) THEN
          bdvlrcredito = wvlripiger - bdvlrsaldocreant;
       ELSE
       IF (wnumitem = 1) THEN
          wvlrnumitem01  = wvlripiger;
       ELSE
       IF (wnumitem = 6) THEN
          wvlrnumitem06  = wvlripiger;
       ELSE
       IF (wnumitem = 13) THEN
          wvlrnumitem13  = wvlripiger;
       ELSE
       IF (wnumitem = 14) THEN
          wvlrnumitem14  = wvlripiger;

       -- defini??o do per?odo
       IF (wcodperiodo = 7) THEN
           bdperiodo = 0;
       ELSE
       IF (wcodperiodo = 2) THEN
           bdperiodo = 1;
       ELSE
       IF (wcodperiodo = 3) THEN
           bdperiodo = 2;
       ELSE
       IF (wcodperiodo = 4) THEN
           bdperiodo = 3;
       wultreferencia = bdreferencia;
       wultcodperiodo = wcodperiodo;
     END

     -- ?ltimo registro - suspend
     IF (wvlrnumitem13 > 0) THEN
        bdvlrsaldo = wvlrnumitem13;
     ELSE
        bdvlrsaldo = wvlrnumitem14;

     IF (wvlrnumitem01 > wvlrnumitem06) THEN
        bdcredordevedor = 2;
     ELSE
        bdcredordevedor = 1;

     --if ((wvlrnumitem09 - wvlrnumitem14) = 0) then
     IF ((bdvlrdebito = 0) AND (bdvlrcredito = 0)) THEN
        bdexistemov = 2;
     ELSE
        bdexistemov = 1;

     bdsequencial = bdsequencial + 1;

     SUSPEND;
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG21) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG21(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRINSUMOSNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVVENDASNACIONAL NUMERIC(15,6),
BDVLROUTRASENTNACIONAL NUMERIC(15,6),
BDVLRINSUMOSEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRDEVVENDASEXTERIOR NUMERIC(15,6),
BDVLROUTRASENTEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
DECLARE VARIABLE worderby VARCHAR(5000);
DECLARE VARIABLE wwhere VARCHAR(5000);
DECLARE VARIABLE wsql VARCHAR(25000);
DECLARE VARIABLE wgroupby VARCHAR(5000);
DECLARE VARIABLE wvlrcontab NUMERIC(15,6);
DECLARE VARIABLE wvlripi NUMERIC(15,6);
DECLARE VARIABLE woutrasipi NUMERIC(15,6);
DECLARE VARIABLE wisentasipi NUMERIC(15,6);
DECLARE VARIABLE wprefixonat INTEGER;
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE i INTEGER;
BEGIN
   /*agrupar na aplica??o desta forma. Exemplo
     select bdcodemp,
            bdtipomatrizfilial,
            bdcnpjempmatriz,
            bdcnpjestab,
            bdcoluna,
            sum(bdvlrinsumosnacional),
            sum(bdvlrmercadoriasnacional),
            sum(bdvlrindustoutrasempnacional),
            sum(bdvlrdevvendasnacional),
            sum(bdvlroutrasentnacional),
            sum(bdvlrinsumosexterior),
            sum(bdvlrmercadoriasexterior),
            sum(bdvlrindustoutrasempexterior),
            sum(bdvlrdevvendasexterior),
            sum(bdvlroutrasentexterior)
            from vef_sp_exp_dipj_reg21('tnatent.bdcodemp = 1 or tnatent.bdcodemp = 2','00.190.373/0001-72', '01/01/2010', '04/30/2010', 201011)
            group by bdcodemp, bdcnpjempmatriz, BDcnpjestab, bdcoluna
            order by bdtipomatrizfilial, bdcodemp, bdcoluna
   */

   --PREMPRESAS   - empresa matriz + filiias
   --PRCNPJMATRIZ - saber o CNP da matriz previamente para atribuir para todos registros, inclusive os das filiais

   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   wSql = 'select tnatent.bdcodemp, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'tnatent.bdprefixonat, ';
   wSql = wSql || 'sum(tnatent.bdvlrcontab)  bdvlrcontab, ';
   wSql = wSql || 'sum(tnatent.bdvlripi)     bdvlripi, ';
   wSql = wSql || 'sum(tnatent.bdoutrasipi)  bdoutrasipi, ';
   wSql = wSql || 'sum(tnatent.bdisentasipi) bdisentasipi ';
   wSql = wSql || 'from vw_vef_tot_nat_ent_date tnatent ';
   wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tnatent.bdcodemp) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatent.bddataentradaent >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatent.bddataentradaent <= '||''''||prdatafin||''''||' ';
      END

   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   wGroupBy = 'group by tnatent.bdcodemp, tnatent.bdprefixonat, temp.bdcnpjemp ';
   /*definir na aplica??o*/
   worderby = '';

   wsql = wsql||wwhere||wgroupby||worderby;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcnpjemp,
       :wprefixonat,
       :wvlrcontab,
       :wvlripi,
       :woutrasipi,
       :wisentasipi
     DO
     BEGIN
        i = 1;
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        --carregar dados para cada uma das tr?s colunas do registro
        WHILE (i <= 3) DO
          BEGIN
            bdcoluna = i;
            bdvlrinsumosnacional         = 0;
            bdvlrmercadoriasnacional     = 0;
            bdvlrindustoutrasempnacional = 0;
            bdvlrdevvendasnacional       = 0;
            bdvlroutrasentnacional       = 0;
            bdvlrinsumosexterior         = 0;
            bdvlrmercadoriasexterior     = 0;
            bdvlrdevvendasexterior       = 0;
            bdvlroutrasentexterior       = 0;

            IF (wprefixonat IN (1101, 1111, 1116, 1120, 1122, 1151, 1401, 1408, 2101, 2111, 2116, 2120, 2122, 2151, 2401, 2408)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrinsumosnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrinsumosnacional = wvlrcontab;
                  ELSE
                     bdvlrinsumosnacional = wvlripi;
               END

            IF (wprefixonat IN (1102, 1113, 1117, 1118, 1121, 1152, 1403, 1409, 2102, 2113, 2117, 2118, 2121, 2152, 2403, 2409)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrmercadoriasnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrmercadoriasnacional = wvlrcontab;
                  ELSE
                     bdvlrmercadoriasnacional = wvlripi;
               END

            IF (wprefixonat IN (1124, 1125, 2124, 2125)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrindustoutrasempnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrindustoutrasempnacional = wvlrcontab;
                  ELSE
                     bdvlrindustoutrasempnacional = wvlripi;
               END

            IF (wprefixonat IN (1201, 1202, 1203, 1204, 1208, 1209, 1410, 1411, 1918, 1919, 2201, 2202, 2203, 2204, 2208, 2209, 2410, 2411, 2918, 2919)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrdevvendasnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrdevvendasnacional = wvlrcontab;
                  ELSE
                     bdvlrdevvendasnacional = wvlripi;
               END

            IF (wprefixonat IN (1126, 1154, 1207, 1252, 1256, 1302, 1352, 1356, 1406, 1407, 1414, 1415, 1452, 1501, 1503, 1504, 1505, 1506, 1551, 1552, 1553, 1554, 1555,
                                1556, 1557, 1601, 1602, 1603, 1653, 1658, 1660, 1662, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914,
                                1915, 1916, 1917, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1949, 2126, 2154, 2252, 2256, 2302, 2352, 2356, 2406, 2407, 2414, 2415, 2501,
                                2503, 2504, 2505, 2506, 2551, 2552, 2553, 2554, 2555, 2556, 2557, 2651, 2653, 2658, 2660, 2662, 2901, 2902, 2903, 2904, 2905, 2906, 2907,
                                2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2920, 2921, 2922, 2923, 2924, 2925, 2949)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlroutrasentnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlroutrasentnacional = wvlrcontab;
                  ELSE
                     bdvlroutrasentnacional = wvlripi;
               END

            IF (wprefixonat IN (3101, 3127)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrinsumosexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrinsumosexterior = wvlrcontab;
                  ELSE
                     bdvlrinsumosexterior = wvlripi;
               END

            IF (wprefixonat IN (3102)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrmercadoriasexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrmercadoriasexterior = wvlrcontab;
                  ELSE
                     bdvlrmercadoriasexterior = wvlripi;
               END

            IF (wprefixonat IN (3201, 3202, 3211, 3503, 3553)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrdevvendasexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrdevvendasexterior = wvlrcontab;
                  ELSE
                     bdvlrdevvendasexterior = wvlripi;
               END

            IF (wprefixonat IN (3126, 3352, 3356, 3551, 3556, 3651, 3653, 3930, 3949)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlroutrasentexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlroutrasentexterior = wvlrcontab;
                  ELSE
                     bdvlroutrasentexterior = wvlripi;
               END

            i = i + 1;
            SUSPEND;
          END
     END
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG22) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG22(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRPRODNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVCOMPRASNACIONAL NUMERIC(15,6),
BDVLROUTRASSAINACIONAL NUMERIC(15,6),
BDVLRPRODEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPEXTERIOR NUMERIC(15,6),
BDVLRDEVCOMPRASEXTERIOR NUMERIC(15,6),
BDVLROUTRASSAIEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
DECLARE VARIABLE worderby VARCHAR(5000);
DECLARE VARIABLE wwhere VARCHAR(5000);
DECLARE VARIABLE wsql VARCHAR(25000);
DECLARE VARIABLE wgroupby VARCHAR(5000);
DECLARE VARIABLE wvlrcontab NUMERIC(15,6);
DECLARE VARIABLE wvlripi NUMERIC(15,6);
DECLARE VARIABLE woutrasipi NUMERIC(15,6);
DECLARE VARIABLE wisentasipi NUMERIC(15,6);
DECLARE VARIABLE wprefixonat INTEGER;
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE i INTEGER;
BEGIN
   /* agrupar na aplica??o desta forma. Exemplo:
     select bdcodemp,
       bdcnpjempmatriz,
       bdcnpjestab,
       bdcoluna,
       sum(bdvlrprodnacional) bdvlrprodnacional,
       sum(bdvlrmercadoriasnacional) bdvlrmercadoriasnacional,
       sum(bdvlrindustoutrasempnacional) bdvlrindustoutrasempnacional,
       sum(bdvlrdevcomprasnacional) bdvlrdevcomprasnacional,
       sum(bdvlroutrassainacional) bdvlroutrassainacional,
       sum(bdvlrprodexterior) bdvlrprodsexterior,
       sum(bdvlrmercadoriasexterior) bdvlrmercadoriasexterior,
       sum(bdvlrindustoutrasempexterior) bdvlrindustoutrasempexterior,
       sum(bdvlrdevcomprasexterior) bdvlrdevcomprasexterior,
       sum(bdvlroutrassaiexterior) bdvlroutrassaiexterior
       from vef_sp_exp_dipj_reg22('tnatsai.bdcodemp = 1 or tnatsai.bdcodemp = 2','00.190.373/0001-72', '01/01/2010', '12/31/2010', 201011)
       group by bdcodemp, bdcnpjempmatriz, bdcnpjestab, bdcoluna
   */

   --PREMPRESAS   - empresa matriz + filiais
   --PRCNPJMATRIZ - saber o CNP da matriz previamente para atribuir para todos registros, inclusive os das filiais

   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   wSql = 'select tnatsai.bdcodemp, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'tnatsai.bdprefixonat, ';
   wSql = wSql || 'sum(tnatsai.bdvlrcontab)  bdvlrcontab, ';
   wSql = wSql || 'sum(tnatsai.bdvlripi)     bdvlripi, ';
   wSql = wSql || 'sum(tnatsai.bdoutrasipi)  bdoutrasipi, ';
   wSql = wSql || 'sum(tnatsai.bdisentasipi) bdisentasipi ';
   wSql = wSql || 'from vw_vef_tot_nat_sai_date tnatsai ';
   wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tnatsai.bdcodemp) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatsai.bddataemissao >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatsai.bddataemissao <= '||''''||prdatafin||''''||' ';
      END

   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplica??o*/
   wGroupBy = 'group by tnatsai.bdcodemp, tnatsai.bdprefixonat, temp.bdcnpjemp ';
   worderby = '';

   wsql = wsql||wwhere||wgroupby||worderby;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcnpjemp,
       :wprefixonat,
       :wvlrcontab,
       :wvlripi,
       :woutrasipi,
       :wisentasipi
     DO
     BEGIN
        i = 1;
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        --carregar dados para cada uma das tr?s colunas do registro
        WHILE (i <= 3) DO
          BEGIN
            bdcoluna = i;
            bdvlrprodnacional            = 0;
            bdvlrmercadoriasnacional     = 0;
            bdvlrindustoutrasempnacional = 0;
            bdvlrdevcomprasnacional      = 0;
            bdvlroutrassainacional       = 0;
            bdvlrprodexterior            = 0;
            bdvlrmercadoriasexterior     = 0;
            bdvlrindustoutrasempexterior = 0;
            bdvlrdevcomprasexterior      = 0;
            bdvlroutrassaiexterior       = 0;

            IF (wprefixonat IN (5101, 5103, 5105, 5109, 5111, 5113, 5116, 5118, 5122, 5151, 5155, 5401, 5402, 5408, 5501, 5904, 6101, 6103, 6105, 6107, 6109,
                                6111, 6113, 6116, 6118, 6122, 6151, 6155, 6401, 6402, 6408, 6501, 6904)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrprodnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrprodnacional = wvlrcontab;
                  ELSE
                     bdvlrprodnacional = wvlripi;
               END

            IF (wprefixonat IN (5102, 5104, 5106, 5110, 5112, 5114, 5115, 5117, 5119, 5120, 5123, 5152, 5156, 5403, 5405, 5409, 5502, 6102, 6104, 6106, 6108,
                                6110, 6114, 6115, 6117, 6119, 6120, 6123, 6152, 6156, 6403, 6404, 6409, 6502)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrmercadoriasnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrmercadoriasnacional = wvlrcontab;
                  ELSE
                     bdvlrmercadoriasnacional = wvlripi;
               END

            IF (wprefixonat IN (5124, 5125, 6124, 6125)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrindustoutrasempnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrindustoutrasempnacional = wvlrcontab;
                  ELSE
                     bdvlrindustoutrasempnacional = wvlripi;
               END

            IF (wprefixonat IN (5201, 5202, 5206, 5207, 5208, 5209, 5210, 5410, 5411, 5412, 5413, 5503, 5553, 5555, 5556, 5918, 5919, 6201, 6202, 6206, 6208, 6209,
                                6210, 6410, 6411, 6412, 6413, 6503, 6553, 6555, 6556, 6918, 6919)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrdevcomprasnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrdevcomprasnacional = wvlrcontab;
                  ELSE
                     bdvlrdevcomprasnacional = wvlripi;
               END

            IF (wprefixonat IN (5205, 5251, 5252, 5254, 5255, 5256, 5258, 5302, 5303, 5304, 5305, 5306, 5307, 5351, 5352, 5353, 5354, 5355, 5356, 5357, 5408, 5409,
                                5414, 5415, 5451, 5551, 5552, 5554, 5557, 5601, 5602, 5603, 5901, 5902, 5903, 5905, 5906, 5907, 5908, 5909, 5910, 5911, 5912, 5913,
                                5914, 5915, 5916, 5917, 5920, 5921, 5922, 5923, 5924, 5925, 5926, 5927, 5928, 5929, 5931, 5932, 5949, 6205, 6207, 6251, 6252, 6253,
                                6254, 6255, 6256, 6258, 6302, 6303, 6304, 6305, 6306, 6307, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6408, 6414, 6415, 6551, 6552,
                                6554, 6557, 6603, 6901, 6902, 6903, 6904, 6905, 6906, 6907, 6908, 6909, 6910, 6911, 6912, 6913, 6914, 6915, 6916, 6917, 6920, 6921,
                                6922, 6923, 6924, 6925, 6929, 6931, 6932, 6949)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlroutrassainacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlroutrassainacional = wvlrcontab;
                  ELSE
                     bdvlroutrassainacional = wvlripi;
               END

            IF (wprefixonat IN (7101, 7105, 7127, 7501)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrprodexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrprodexterior = wvlrcontab;
                  ELSE
                     bdvlrprodexterior = wvlripi;
               END

            IF (wprefixonat IN (7102, 7106)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrmercadoriasexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrmercadoriasexterior = wvlrcontab;
                  ELSE
                     bdvlrmercadoriasexterior = wvlripi;
               END

            IF (wprefixonat IN (7201, 7202, 7210, 7211, 7553, 7556, 7930)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrdevcomprasexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrdevcomprasexterior = wvlrcontab;
                  ELSE
                     bdvlrdevcomprasexterior = wvlripi;
               END

            IF (wprefixonat IN (7206, 7207, 7551, 7949)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlroutrassaiexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlroutrassaiexterior = wvlrcontab;
                  ELSE
                     bdvlroutrassaiexterior = wvlripi;
               END

            i = i + 1;
            SUSPEND;
          END
     END
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG23) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG23(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WVLRST NUMERIC(15,6);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN
   --PREMPRESAS   - empresa matriz + filiias
   --PRCNPJMATRIZ - saber o CNP da matriz previamente para atribuir para todos registros, inclusive os das filiais

  /* utilizar na aplica??o desta forma. Exemplo:
  select  bdcodemp,
        bdcodter,
        bdcnpjempmatriz,
        bdcnpjestab,
        bdcgcter,
        bdvalor,
        bdusast,
        bdtipomatrizfilial
  from VEF_SP_EXP_DIPJ_REG23('tnatent.bdcodemp = 1 or tnatent.bdcodemp = 2','00.190.373/0001-72','01/01/2010','04/30/2010', 201011)
  order by BDTIPOMATRIZFILIAL, bdValor desc*/


   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   IF (prlevartodos = 'TRUE') THEN
      wSql = 'select tnatent.BDCODEMP, ';
   ELSE
      wSql = 'select first 100 tnatent.BDCODEMP, ';
   wSql = wSql || 'tnatent.BDCODTER, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'tterc.bdcgcter, ';
   wSql = wSql || 'sum(tnatent.BDVLRCONTAB) - sum(tnatent.BDVLRIPI) bdVALOR, ';
   wSql = wSql || 'sum(BDVLRST) bdVALORST ';
   wSql = wSql || 'from vw_vef_tot_nat_ent_date_terc tnatent ';
   wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tnatent.BDCODEMP) ';
   wSql = wSql || 'left outer join tterceiro tterc on (tterc.bdcodter = tnatent.bdcodter) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatent.bddataentradaent >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatent.bddataentradaent <= '||''''||prdatafin||''''||' ';
      END


   IF (wWhere <> '') THEN
      wWhere = wwhere || ' and ';

   wwhere = wwhere || 'BDPREFIXONAT in (1101, 1102, 1111, 1113, 1116, 1117, 1118, 1120, 1121, 1122, 1124, 1125, 1126, 1151, 1152,
                                       1154, 1401, 1403, 1408, 1409, 1410, 1411, 1414, 1415, 1501, 1503, 1504, 1901, 1902, 1903,
                                       1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918,
                                       1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1949, 2101, 2102, 2111, 2113, 2116, 2117,
                                       2118, 2120, 2121, 2122, 2124, 2125, 2126, 2151, 2152, 2154, 2401, 2403, 2408, 2409, 2410,
                                       2411, 2414, 2415, 2501, 2503, 2504, 2901, 2902, 2903, 2904, 2905, 2906, 2907, 2908, 2909,
                                       2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924,
                                       2925, 2949, 3101, 3102, 3126, 3127, 3503, 3949)';


   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplica??o*/

   wGroupBy = 'group by tnatent.BDCODEMP, tnatent.BDCODTER, temp.bdcnpjemp, tterc.bdcgcter ';
   worderby = 'order by tnatent.BDCODEMP, BDVALOR desc ';

   wsql = wsql||wwhere||wgroupby||worderby;

   wsequencial = 0;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdcodter,
       :wcnpjemp,
       :bdcgcter,
       :bdVALOR,
       :wvlrst
     DO
     BEGIN
        wsequencial     = wSequencial + 1;
        IF (prlevartodos = 'TRUE') THEN
           bdsequencial = 101;
        ELSE
           bdsequencial = wsequencial;
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        IF (bdcgcter =   '  .   .   /    -') THEN
            bdcgcter = '00000000000000';

        IF (wvlrst > 0) THEN
           bdusast = 1;
        ELSE
           bdusast = 0;
        SUSPEND;
     END
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG24) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG24(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WVLRST NUMERIC(15,6);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN

   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   IF (prlevartodos = 'TRUE') THEN
      wSql = 'select ';
   ELSE
      wSql = 'select first 50 ';
   wSql = wSql || 'tnatprod.BDCODEMP, ';
   wSql = wSql || 'tnatprod.bdncmprod, ';
   wSql = wSql || 'tnatprod.bdcodprod, ';
   wSql = wSql || 'tnatprod.BDCODSAIDA, ';
   wSql = wSql || 'tnatprod.bdcodigoean, ';
   wSql = wSql || 'tnatprod.bddescprod, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'sum(tnatprod.bdvlritemprod - tnatprod.bdvlripi) bdvalor, ';
   wSql = wSql || 'sum(tnatprod.bdvlrstprod) bdVALORSTPROD ';
   wSql = wSql || 'from vw_vef_tot_nat_ent_date_prod tnatprod ';
   wSQl = wSQl || 'left outer join tempresas temp on (temp.bdcodemp = tnatprod.BDCODEMP) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatprod.bddataentradaent >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatprod.bddataentradaent <= '||''''||prdatafin||''''||' ';
      END


   IF (wWhere <> '') THEN
      wWhere = wwhere || ' and ';

   wwhere = wwhere || 'tnatprod.BDPREFIXONAT in (1101, 1102, 1111, 1113, 1116, 1117, 1118, 1120, 1121, 1122,
                                                 1124, 1125, 1126, 1151, 1152, 1154, 1401, 1403, 1408, 1409,
                                                 1410, 1411, 1414, 1415, 1501, 1503, 1504, 1901, 1902, 1903,
                                                 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913,
                                                 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923,
                                                 1924, 1925, 1926, 1934, 1949, 2101, 2102, 2111, 2113, 2116,
                                                 2117, 2118, 2120, 2121, 2122, 2124, 2125, 2126, 2151, 2152,
                                                 2154, 2401, 2403, 2408, 2409, 2410, 2411, 2414, 2415, 2501,
                                                 2503, 2504, 2901, 2902, 2903, 2904, 2905, 2906, 2907, 2908,
                                                 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918,
                                                 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2934, 2949, 3101,
                                                 3102, 3126, 3127, 3503, 3949)';


   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplica??o*/

   wGroupBy = 'group by tnatprod.BDCODEMP, tnatprod.bdncmprod, tnatprod.bdcodprod, tnatprod.BDCODSAIDA, tnatprod.bdcodigoean, tnatprod.bddescprod, temp.bdcnpjemp ';
   wOrderBy = 'order by tnatprod.BDCODEMP, bdvalor desc, bdncmprod ';

   wsql = wsql||wwhere||wgroupby||worderby;

   wsequencial = 0;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdncmprod,
       :bdcodprod,
       :BDCODSAIDA,
       :bdcodigoean,
       :bddescprod,
       :wcnpjemp,
       :bdVALOR,
       :wvlrst
     DO
     BEGIN
        bddescprod = SUBSTRING(bddescprod FROM 1 FOR 55);
        BDCODSAIDA = SUBSTRING(BDCODSAIDA FROM 1 FOR 20);

        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        wsequencial  = wsequencial + 1;
        IF (prlevartodos = 'TRUE') THEN
           bdsequencial = 51;
        ELSE
           bdsequencial = wsequencial;

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        IF (wvlrst > 0) THEN
           bdusast = 1;
        ELSE
           bdusast = 0;
        SUSPEND;
     END
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG25) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG25(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WVLRST NUMERIC(15,6);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN
   --PREMPRESAS   - empresa matriz + filiias
   --PRCNPJMATRIZ - saber o CNP da matriz previamente para atribuir para todos registros, inclusive os das filiais

  /* utilizar na aplica??o desta forma. Exemplo:
  select bdcodemp,
         bdcodter,
         bdcnpjempmatriz,
         bdcnpjestab,
         bdcgcter,
         bdvalor,
         bdusast,
         bdtipomatrizfilial
  from VEF_SP_EXP_DIPJ_REG25('tnatsai.bdcodemp = 1 or tnatsai.bdcodemp = 2','00.190.373/0001-72','01/01/2010','04/30/2010', 201011)
  order by BDTIPOMATRIZFILIAL, bdValor desc*/
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  IF (prlevartodos = 'TRUE') THEN
      wSql = 'select ';
   ELSE
      wSql = 'select first 100 ';
  wSql = wSql || 'tnatsai.bdcodemp, ';
  wSql = wSql || 'tnatsai.bdcodter, ';
  wSql = wSql || 'temp.bdcnpjemp, ';
  wSql = wSql || 'tterc.bdcgcter, ';
  wSql = wSql || 'sum(tnatsai.BDVLRCONTAB) - sum(tnatsai.BDVLRIPI) bdVALOR, ';
  wSql = wSql || 'sum(BDVLRST) bdVALORST ';
  wSql = wSql || 'from vw_vef_tot_nat_sai_date_terc tnatsai ';
  wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tnatsai.BDCODEMP) ';
  wSql = wSql || 'left outer join tterceiro tterc on (tterc.bdcodter = tnatsai.bdcodter) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatsai.bddataemissao >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatsai.bddataemissao <= '||''''||prdatafin||''''||' ';
      END


   IF (wWhere <> '') THEN
      wWhere = wwhere || ' and ';

   wwhere = wwhere || 'tnatsai.BDPREFIXONAT in (5101, 5102, 5103, 5104, 5105, 5106, 5109, 5110, 5111, 5112,
                                                5113, 5114, 5115, 5116, 5117, 5118, 5119, 5120, 5122, 5123,
                                                5124, 5125, 5151, 5152, 5155, 5156, 5401, 5402, 5403, 5405,
                                                5408, 5409, 5414, 5415, 5501, 5502, 5503, 5667, 5901, 5902,
                                                5903, 5904, 5905, 5906, 5907, 5908, 5909, 5910, 5911, 5912,
                                                5913, 5914, 5915, 5916, 5917, 5918, 5919, 5920, 5921, 5922,
                                                5923, 5924, 5925, 5934, 5949, 6101, 6102, 6103, 6104, 6105,
                                                6106, 6107, 6108, 6109, 6110, 6111, 6112, 6113, 6114, 6115,
                                                6116, 6117, 6118, 6119, 6120, 6122, 6123, 6124, 6125, 6151,
                                                6152, 6155, 6156, 6401, 6402, 6403, 6404, 6408, 6409, 6502,
                                                6503, 6505, 6667, 6901, 6902, 6903, 6904, 6905, 6906, 6907,
                                                6908, 6909, 6910, 6911, 6912, 6913, 6914, 6915, 6916, 6917,
                                                6918, 6919, 6920, 6921, 6922, 6923, 6924, 6925, 6934, 6949,
                                                7101, 7102, 7105, 7106, 7127, 7501, 7667, 7949)';


   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplica??o*/
   wgroupby = 'group by tnatsai.bdcodemp, tnatsai.bdcodter, temp.bdcnpjemp, tterc.bdcgcter ';
   worderby = 'order by tnatsai.bdcodemp, bdvalor desc ';

   wsql = wsql||wwhere||wgroupby||worderby;

   wsequencial = 0;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdcodter,
       :wcnpjemp,
       :bdcgcter,
       :bdvalor,
       :wvlrst
     DO
     BEGIN
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);
        wsequencial  = wsequencial + 1;
        IF (prlevartodos = 'TRUE') THEN
           bdsequencial = 101;
        ELSE
           bdsequencial = wsequencial;

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        IF (bdcgcter =   '  .   .   /    -') THEN
            bdcgcter = '00000000000000';

        IF (wvlrst > 0) THEN
           bdusast = 1;
        ELSE
           bdusast = 0;
        SUSPEND;
     END
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG26) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG26(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WVLRST NUMERIC(15,6);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN

   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   IF (prlevartodos = 'TRUE') THEN
      wSql = 'select ';
   ELSE
      wSql = 'select first 50 ';
   wSql = wSql || 'tnatprod.bdcodemp, ';
   wSql = wSql || 'tnatprod.bdncmprod, ';
   wSql = wSql || 'tnatprod.bdcodprod, ';
   wSql = wSql || 'tnatprod.BDCODSAIDA, ';
   wSql = wSql || 'tnatprod.bdcodigoean, ';
   wSql = wSql || 'tnatprod.bddescprod, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'sum(tnatprod.bdvlritemprod - tnatprod.bdvlripi) bdvalor, ';
   wSql = wSql || 'sum(tnatprod.bdvlrstprod) bdvalorstprod ';
   wSql = wSql || 'from vw_vef_tot_nat_sai_date_prod tnatprod ';
   wSQl = wSQl || 'left outer join tempresas temp on (temp.bdcodemp = tnatprod.BDCODEMP) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatprod.bddataemissao >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatprod.bddataemissao <= '||''''||prdatafin||''''||' ';
      END


   IF (wWhere <> '') THEN
      wWhere = wwhere || ' and ';

   wwhere = wwhere || 'tnatprod.BDPREFIXONAT in (5101, 5102, 5103, 5104, 5105, 5106, 5109, 5110, 5111, 5112, 5113, 5114, 5115,
                                                 5116, 5117, 5118, 5119, 5120, 5122, 5123, 5124, 5125, 5151, 5152, 5155, 5156,
                                                 5401, 5402, 5403, 5405, 5408, 5409, 5414, 5415, 5501, 5502, 5503, 5901, 5902,
                                                 5903, 5904, 5905, 5906, 5907, 5908, 5909, 5910, 5911, 5912, 5913, 5914, 5915,
                                                 5916, 5917, 5918, 5919, 5920, 5921, 5922, 5923, 5924, 5925, 5949, 6101, 6102,
                                                 6103, 6104, 6105, 6106, 6107, 6108, 6109, 6110, 6111, 6112, 6113, 6114, 6115,
                                                 6116, 6117, 6118, 6119, 6120, 6122, 6123, 6124, 6125, 6151, 6152, 6155, 6156,
                                                 6401, 6402, 6403, 6404, 6408, 6409, 6502, 6503, 6505, 6901, 6902, 6903, 6904,
                                                 6905, 6906, 6907, 6908, 6909, 6910, 6911, 6912, 6913, 6914, 6915, 6916, 6917,
                                                 6918, 6919, 6920, 6921, 6922, 6923, 6924, 6925, 6949, 7101, 7102, 7105, 7106,
                                                 7127, 7501, 7949)';

   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplica??o*/

   wGroupBy = 'group by tnatprod.BDCODEMP, tnatprod.bdncmprod, tnatprod.bdcodprod, tnatprod.BDCODSAIDA, tnatprod.bdcodigoean, tnatprod.bddescprod, temp.bdcnpjemp ';
   wOrderBy = 'order by tnatprod.BDCODEMP, bdvalor desc, bdncmprod ';

   wsql = wsql||wwhere||wgroupby||worderby;

   wsequencial = 0;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdncmprod,
       :bdcodprod,
       :BDCODSAIDA,
       :bdcodigoean,
       :bddescprod,
       :wcnpjemp,
       :bdVALOR,
       :wvlrst
     DO
     BEGIN
        bddescprod = SUBSTRING(bddescprod FROM 1 FOR 55);
        BDCODSAIDA = SUBSTRING(BDCODSAIDA FROM 1 FOR 20);

        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        wsequencial  = wsequencial + 1;
        IF (prlevartodos = 'TRUE') THEN
           bdsequencial = 51;
        ELSE
           bdsequencial = wsequencial;


        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        IF (wvlrst > 0) THEN
           bdusast = 1;
        ELSE
           bdusast = 0;
        SUSPEND;
     END
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG54) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG54(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRREFERENCIA INTEGER,
PRREFINI INTEGER = 0,
PRREFFIN INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCNAEPREP INTEGER,
BDTIPOMATRIZFILIAL INTEGER,
BDRECEITA NUMERIC(15,6))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
BEGIN
   wSql = 'select temp.bdcodemp, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'tempref.BDCODCNAE ';
   wSql = wSql || 'from tempresas temp ';
   wsql = wSql || 'left outer join SP_CONSULTAEMPRESAS('||prReferencia||', 0,  NULL) tempref on (tempref.bdCodemp =  temp.bdcodemp) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (wWhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   worderby = 'order by bdcodemp ';

   wsql = wsql||wwhere||worderby;
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcnpjemp,
       :bdcnaeprep
     DO
     BEGIN
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        --somar campos 1,2,3,4 da apura??o IRLP
        wwhere = '';

        IF (((prrefini IS NOT NULL) AND (prrefini > 0)) AND ((prreffin IS NOT NULL) AND (prreffin >= prrefini))) THEN
          BEGIN
            IF ((bdcodemp IS NOT NULL) AND (bdcodemp > 0)) THEN
              wwhere = wwhere||' ger.bdcodemp = '||bdcodemp||' ';

            IF ((wwhere IS NOT NULL) AND (prempresas <> '')) THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||' ger.bdreferencia between '||prrefini||' and '||prreffin||' ';
          END

        IF ((wwhere IS NOT NULL) AND (wwhere <> '')) THEN
          wwhere = ' and '||wwhere||' ';

        wsql = ' select sum(reg.bdvalor) bdreceita ';
        wsql = wsql||' from (select * from vef_emp_tirlpger ger where ger.bdcodperiodo in (8, 10) '||wwhere||' ) ger ';
        wsql = wsql||' left outer join vef_emp_tirlpgerreg reg on reg.bdcodemp = ger.bdcodemp and reg.bdcodperiodo = ger.bdcodperiodo and reg.bdreferencia = ger.bdreferencia ';
        wsql = wsql||' where reg.bdnumcampo between 1 and 4 ';

        IF ((wwhere IS NOT NULL) AND (wwhere <> '')) THEN
          EXECUTE STATEMENT wsql INTO :bdreceita;
        ELSE
          bdreceita = 0;

        SUSPEND;
     END
END
^

/* Alter (VEF_SP_EXP_DIPJ_REG60_61A) */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG60_61A(PREMPRESAS VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRCODPAISBRASIL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODFED INTEGER,
BDTIPOPESSOA INTEGER,
BDCGCCEISOC VARCHAR(18),
BDCODSOC INTEGER,
BDNOMSOC VARCHAR(200),
BDEXPQUALISOC INTEGER,
BDCAPTOTCOTA NUMERIC(15,6),
BDCAPVOLCOTA NUMERIC(15,6),
BDCPFRESPLEGALSOC VARCHAR(14),
BDEXPQUALIRESPSOC INTEGER,
BDREMTRACOTA NUMERIC(15,6),
BDRENISECOTA NUMERIC(15,6),
BDRENTRICOTA NUMERIC(15,6),
BDDEMRENCOTA NUMERIC(15,6),
BDIRFONTCOTA NUMERIC(15,6),
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

    wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSQl = wsql || 'tsoc.bdcodsoc, ';
    wSql = wSql || 'tsoc.bdnomsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdcpfresplegalsoc, ';
    wSql = wSql || 'tqsoc.BDEXPQUALISOC, ';
    wSql = wSql || 'tqrespsoc.BDEXPQUALISOC BDEXPQUALIRESPSOC, ';
    wSql = wSql || 'tsoccotas.bdcaptotcota, ';
    wSql = wSql || 'tsoccotas.bdcapvolcota, ';
    wSql = wSql || 'tsoccotas.bdremtracota, ';
    wSql = wSql || 'tsoccotas.bdrenisecota, ';
    wSql = wSql || 'tsoccotas.bdrentricota, ';
    wSql = wSql || 'tsoccotas.bddemrencota, ';
    wSql = wSql || 'tsoccotas.bdirfontcota, ';
    wSql = wSql || 'tpais.bdcodfed ';
    wSql = wSql || 'from vw_empresas_tsoc_ref tsoc ';
    wSql = wSql || 'left outer join tpais on (tpais.bdcodpais = tsoc.bdcodpais) ';
    wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tsoc.bdcodemp) ';
    wSql = wSql || 'left outer join tqualificacaosoc tqsoc on (tqsoc.bdqualificacaosoc = tsoc.BDQUALILEGALDIPJSOC) and character_length(tsoc.bdcgcceisoc) = 14 '; --and (tsoc.bdcodpais is null or tsoc.bdcodpais = 30)
    wSql = wSql || 'left outer join tqualificacaosoc tqrespsoc on (tqrespsoc.bdqualificacaosoc = tsoc.BDQUALIRESPLEGALSOC) and character_length(tsoc.bdcpfresplegalsoc) = 14 ';
    wSql = wSql || 'left outer join vw_empresas_tsoccotas tsoccotas on (tsoccotas.bdcodemp = tsoc.bdcodemp and tsoccotas.bdcodsoc = tsoc.bdcodsoc) ';

    wwhere = '';
  
    IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
       wwhere = wWhere||'('||prempresas||') ';

    IF (wWhere <> '') THEN
       wWhere = wWhere || ' and ';

    wWhere = wWhere || '((tsoc.bddatasaisoc is null) or (tsoc.bddatasaisoc >= '||''''||prdataini||''''||')) ';

    IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

    worderby = 'order by tsoc.bdcodemp, tsoc.bdcodsoc ';

    wsql = wsql||wwhere||worderby;

    wSequencial = 0;
 
    FOR EXECUTE STATEMENT wsql
      INTO
        :bdcodemp,
        :bdcnpjemp,
        :bdcodsoc,
        :bdnomsoc,
        :bdcgcceisoc,
        :bdcpfresplegalsoc,
        :bdexpqualisoc,
        :bdexpqualirespsoc,
        :bdcaptotcota,
        :bdcapvolcota,
        :bdremtracota,
        :bdrenisecota,
        :bdrentricota,
        :bddemrencota,
        :bdirfontcota,
        :bdcodfed
      DO
      BEGIN
        IF (CHARACTER_LENGTH(bdcgcceisoc) > 14) THEN
           bdtipopessoa = 1;
        ELSE
           bdtipopessoa = 2;

        wsequencial  = wsequencial + 1;
        bdsequencial = wsequencial;

        IF (BDCODFED IS NULL OR BDCODFED = 0) THEN
           SELECT FIRST 1 p.bdcodfed FROM tpais p WHERE p.bdcodpais = :prcodpaisbrasil INTO bdcodfed;

        IF (bdcpfresplegalsoc = '000.000.000-00') THEN
           bdcpfresplegalsoc = '';
        SUSPEND;
      END
END
^

/* Alter (VEF_SP_EXP_GIASP) */
ALTER PROCEDURE VEF_SP_EXP_GIASP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCFORM VARCHAR(150),
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDVLRCONT NUMERIC(18,6),
BDBASEICMS NUMERIC(18,6),
BDVLRICMS NUMERIC(18,6),
BDISENTASICMS NUMERIC(18,6),
BDOUTRASICMS NUMERIC(18,6),
BDVLRST NUMERIC(18,6),
BDIMPSUBSTITUTO NUMERIC(18,6),
BDIMPSUBSTITUIDO NUMERIC(18,6),
BDOUTROSIMPOSTOS NUMERIC(18,6),
BDUF_R14 VARCHAR(2),
BDVALOR_CONTABIL_1_R14 NUMERIC(18,6),
BDBASECALCULO_1_R14 NUMERIC(18,6),
BDVALOR_CONTABIL_2_R14 NUMERIC(18,6),
BDBASECALCULO_2_R14 NUMERIC(18,6),
BDIMPOSTO_R14 NUMERIC(18,6),
BDOUTRAS_R14 NUMERIC(18,6),
BDICMSCOBRADOST_R14 NUMERIC(18,6),
BDPETROLEOENERGIA_R14 NUMERIC(18,6),
BDOUTROS_PRODUTOS_R14 NUMERIC(18,6),
BDCODIGO_R20 INTEGER,
BDOPERACAO_R20 INTEGER,
BDFUNLEGAL_R20 VARCHAR(150),
BDDESCRICAO_R20 VARCHAR(250),
BDINSCESTREM_R25 VARCHAR(15),
BDCODAUTORIZACAO_R28 VARCHAR(14),
BDVLRCONT1 NUMERIC(18,6),
BDBASEICMS1 NUMERIC(18,6),
BDVLRCONT2 NUMERIC(18,6),
BDBASEICMS2 NUMERIC(18,6),
BDNRDOC INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQLOCO VARCHAR(32700);
DECLARE VARIABLE WSQLR14 VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCONTADOR INTEGER;
DECLARE VARIABLE WCODNATANT INTEGER;
DECLARE VARIABLE WCODNATAUT INTEGER;
DECLARE VARIABLE WVLRCONT NUMERIC(18,6);
DECLARE VARIABLE WBASEICMS NUMERIC(18,6);
DECLARE VARIABLE WVLRICMS NUMERIC(18,6);
DECLARE VARIABLE WISENTASICMS NUMERIC(18,6);
DECLARE VARIABLE WOUTRASICMS NUMERIC(18,6);
DECLARE VARIABLE WVLRST NUMERIC(18,6);
DECLARE VARIABLE WIMPSUBSTITUTO NUMERIC(18,6);
DECLARE VARIABLE WIMPSUBSTITUIDO NUMERIC(18,6);
DECLARE VARIABLE WOUTROSIMPOSTOS NUMERIC(18,6);
DECLARE VARIABLE WTIPORETENT INTEGER;
DECLARE VARIABLE WVALOR_CONTABIL_1_R14 NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_1_R14 NUMERIC(18,6);
DECLARE VARIABLE WVALOR_CONTABIL_2_R14 NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_2_R14 NUMERIC(18,6);
DECLARE VARIABLE WIMPOSTO_R14 NUMERIC(18,6);
DECLARE VARIABLE WOUTRAS_R14 NUMERIC(18,6);
DECLARE VARIABLE WICMSCOBRADOST_R14 NUMERIC(18,6);
DECLARE VARIABLE WPETROLEOENERGIA_R14 NUMERIC(18,6);
DECLARE VARIABLE WOUTROS_PRODUTOS_R14 NUMERIC(18,6);
DECLARE VARIABLE WVALOR_CONTABIL_1_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_1_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WVALOR_CONTABIL_2_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_2_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WIMPOSTO_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WOUTRAS_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WICMSCOBRADOST_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WPETROLEOENERGIA_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WOUTROS_PRODUTOS_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WUFAUX VARCHAR(2);
DECLARE VARIABLE WUFAUXANT VARCHAR(2);
DECLARE VARIABLE WPASSOUUF INTEGER;
DECLARE VARIABLE WCODEMPOCO INTEGER;
DECLARE VARIABLE WREFOCO INTEGER;
DECLARE VARIABLE WCODEMPBKP INTEGER;
DECLARE VARIABLE WNOMEMPBKP DM_BDNOMEMP;
DECLARE VARIABLE WCODCONFBKP INTEGER;
DECLARE VARIABLE WREFERENCIABKP INTEGER;
DECLARE VARIABLE WNUMCAMPOBKP INTEGER;
DECLARE VARIABLE WCODQUADROBKP INTEGER;
DECLARE VARIABLE WCLASSIFICACAOBKP VARCHAR(5);
DECLARE VARIABLE WDESCFORMBKP VARCHAR(150);
DECLARE VARIABLE WCODNATBKP INTEGER;
DECLARE VARIABLE WVALORBKP NUMERIC(18,6);
DECLARE VARIABLE WVLRCONTBKP NUMERIC(18,6);
DECLARE VARIABLE WBASEICMSBKP NUMERIC(18,6);
DECLARE VARIABLE WVLRICMSBKP NUMERIC(18,6);
DECLARE VARIABLE WISENTASICMSBKP NUMERIC(18,6);
DECLARE VARIABLE WOUTRASICMSBKP NUMERIC(18,6);
DECLARE VARIABLE WVLRSTBKP NUMERIC(18,6);
DECLARE VARIABLE WIMPSUBSTITUTOBKP NUMERIC(18,6);
DECLARE VARIABLE WIMPSUBSTITUIDOBKP NUMERIC(18,6);
DECLARE VARIABLE WOUTROSIMPOSTOSBKP NUMERIC(18,6);
DECLARE VARIABLE WUF_R14BKP VARCHAR(2);
DECLARE VARIABLE WVALOR_CONTABIL_1_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_1_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WVALOR_CONTABIL_2_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_2_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WIMPOSTO_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WOUTRAS_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WICMSCOBRADOST_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WPETROLEOENERGIA_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WOUTROS_PRODUTOS_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WCODIGO_R20BKP INTEGER;
DECLARE VARIABLE WOPERACAO_R20BKP INTEGER;
DECLARE VARIABLE WFUNLEGAL_R20BKP VARCHAR(150);
DECLARE VARIABLE WDESCRICAO_R20BKP VARCHAR(250);
DECLARE VARIABLE WINSCESTREM_R25BKP VARCHAR(12);
DECLARE VARIABLE WCODAUTORIZACAO_R28BKP VARCHAR(250);
DECLARE VARIABLE WVALORESEXTRAIDOS INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wwhere = '';

  wcodempOCO = 0;
  wrefOCO = 0;

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = 'where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (wwhere = '') THEN
    wwhere = 'where ';

  wsql = 'select T.BDCODEMP, empresas.BDNOMEMP, empresas.BDCODCONFGIASP bdCODCONF,T.BDREFERENCIA, T.BDNUMCAMPO, T.BDCODQUADRO,TCONF.bdclassificacao, TCONFGIASPFORM.bddescform,T.BDPREFIXONAT BDCODNAT, SUM(T.BDVALOR) BDVALOR,';
  wsql = wsql || ' NULL BDVLRCONT,NULL BDBASEICMS,NULL BDVLRICMS,NULL BDISENTASICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL BDIMPSUBSTITUTO,NULL BDIMPSUBSTITUIDO,NULL BDOUTROSIMPOSTOS, ';
  wsql = wsql || ' null BDUF_R14,NULL BDTIPORETENT,null BDVALOR_CONTABIL_1_R14,null BDBASECALCULO_1_R14,null BDVALOR_CONTABIL_2_R14,null BDBASECALCULO_2_R14,null BDIMPOSTO_R14,null BDOUTRAS_R14,null BDICMSCOBRADOST_R14,null BDPETROLEOENERGIA_R14,null BDOUTROS_PRODUTOS_R14, ';
  wsql = wsql || ' NULL bdcodigo_R20, NULL bdoperacao_R20, NULL bdfunlegal_R20, NULL bddescricao_R20, NULL BDINSCESTREM_R25, NULL BDCODAUTORIZACAO_R28 ';

  wsql = wsql || ' from VEF_EMP_TGIASPGERNAT T, VW_EMP_REF_TOTAL empresas, VEF_ESTADOS_TCONFGIASPQ TCONF, VEF_ESTADOS_TCONFGIASPFORM TCONFGIASPFORM ';
  IF (wwhere <> '') THEN
    wwhere = wwhere||' and ';
  wsql = wsql || wwhere;
  wsql = wsql || ' (empresas.bdcodemp = t.bdcodemp) ';
  wsql = wsql || ' and (TCONF.bdcodquadro = t.bdcodquadro)';
  wsql = wsql || ' and (TCONFGIASPFORM.bdcodconf = empresas.BDCODCONFGIASP and  TCONFGIASPFORM.bdcodquadro = T.BDCODQUADRO and TCONFGIASPFORM.bdnumcampo = T.BDNUMCAMPO)';
  wsql = wsql || ' group by T.BDCODEMP,empresas.BDNOMEMP, BDCODCONF,T.BDREFERENCIA,BDCODNAT, TCONFGIASPFORM.bddescform, T.BDCODQUADRO,TCONF.BDCLASSIFICACAO, t.bdnumcampo';
  wsql = wsql || ' order by T.BDCODEMP,BDCODCONF,T.BDREFERENCIA,BDCODNAT, T.bdnumcampo, TCONFGIASPFORM.bddescform, T.BDCODQUADRO,TCONF.BDCLASSIFICACAO';

  wcontador = 1;

  wVLRCONT = 0;
  wBASEICMS = 0;
  wVLRICMS = 0;
  wISENTASICMS = 0;
  wOUTRASICMS = 0;
  wVLRST = 0;
  wIMPSUBSTITUTO = 0;
  wIMPSUBSTITUIDO = 0;
  wOUTROSIMPOSTOS = 0;

  WVALOR_CONTABIL_1_R14 = 0;
  WBASECALCULO_1_R14 = 0;
  WVALOR_CONTABIL_2_R14 = 0;
  WBASECALCULO_2_R14 = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp, 
    BDCODCONF ,
    BDREFERENCIA ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCFORM ,
    BDCODNAT,
    BDVALOR,
    BDVLRCONT,
    BDBASEICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDVLRST,
    BDIMPSUBSTITUTO,
    BDIMPSUBSTITUIDO,
    BDOUTROSIMPOSTOS,
    BDUF_R14 ,
    WTIPORETENT,
    BDVALOR_CONTABIL_1_R14 ,
    BDBASECALCULO_1_R14,
    BDVALOR_CONTABIL_2_R14,
    BDBASECALCULO_2_R14,
    BDIMPOSTO_R14,
    BDOUTRAS_R14,
    BDICMSCOBRADOST_R14,
    BDPETROLEOENERGIA_R14,
    BDOUTROS_PRODUTOS_R14,
    BDCODIGO_R20,
    BDOPERACAO_R20,
    BDFUNLEGAL_R20,
    BDDESCRICAO_R20,
    BDINSCESTREM_R25,
    BDCODAUTORIZACAO_R28
  DO
  BEGIN

    wcodnataut = BDCODNAT;
    wValoresExtraidos = 0;
    IF (BDCODQUADRO = 2) THEN
       BEGIN
        IF (wcontador = 1) THEN wVLRCONT = BDVALOR;     ELSE
        IF (wcontador = 2) THEN wBASEICMS = BDVALOR;    ELSE
        IF (wcontador = 3) THEN wVLRICMS = BDVALOR;     ELSE
        IF (wcontador = 4) THEN wISENTASICMS = BDVALOR; ELSE
        IF (wcontador = 5) THEN wOUTRASICMS = BDVALOR;  ELSE
        IF (wcontador = 6) THEN wVLRST = BDVALOR;       ELSE
        IF (wcontador = 7) THEN wIMPSUBSTITUTO = BDVALOR; ELSE
        IF (wcontador = 8) THEN wIMPSUBSTITUIDO = BDVALOR; ELSE
        IF (wcontador = 9) THEN
           wValoresExtraidos = 1;
      END
    ELSE
       BEGIN
        IF (wcontador = 1) THEN wVLRCONT = BDVALOR;     ELSE
        IF (wcontador = 2) THEN wBASEICMS = BDVALOR;    ELSE
        IF (wcontador = 3) THEN wVLRICMS = BDVALOR;     ELSE
        IF (wcontador = 4) THEN wISENTASICMS = BDVALOR; ELSE
        IF (wcontador = 5) THEN wOUTRASICMS = BDVALOR;  ELSE
        IF (wcontador = 6) THEN wVLRST = BDVALOR;       ELSE
        IF (wcontador = 7) THEN wIMPSUBSTITUTO = BDVALOR; ELSE
        IF (wcontador = 8) THEN wIMPSUBSTITUIDO = BDVALOR; ELSE
        IF (wcontador = 9) THEN
           wValoresExtraidos = 1;
      END

    IF (wValoresExtraidos = 1) THEN
    BEGIN
      wcontador = 0;
      wOUTROSIMPOSTOS = BDVALOR;

      WCODEMPBKP = BDCODEMP;
      WNOMEMPBKP = BDNOMEMP;
      WCODCONFBKP = BDCODCONF;
      WREFERENCIABKP = BDREFERENCIA;
      WNUMCAMPOBKP = BDNUMCAMPO;
      WCODQUADROBKP = BDCODQUADRO;
      WCLASSIFICACAOBKP = BDCLASSIFICACAO;
      WDESCFORMBKP = BDDESCFORM;
      WCODNATBKP = BDCODNAT;
      WVALORBKP = BDVALOR;
      WVLRCONTBKP = BDVLRCONT;
      WBASEICMSBKP = BDBASEICMS;
      WVLRICMSBKP = BDVLRICMS;
      WISENTASICMSBKP = BDISENTASICMS;
      WOUTRASICMSBKP = BDOUTRASICMS;
      WVLRSTBKP = BDVLRST;
      WIMPSUBSTITUTOBKP = BDIMPSUBSTITUTO;
      WIMPSUBSTITUIDOBKP = BDIMPSUBSTITUIDO;
      WOUTROSIMPOSTOSBKP = BDOUTROSIMPOSTOS;
      WUF_R14BKP = BDUF_R14;
      WVALOR_CONTABIL_1_R14BKP = BDVALOR_CONTABIL_1_R14;
      WBASECALCULO_1_R14BKP = BDBASECALCULO_1_R14;
      WVALOR_CONTABIL_2_R14BKP = BDVALOR_CONTABIL_2_R14;
      WBASECALCULO_2_R14BKP = BDBASECALCULO_2_R14;
      WIMPOSTO_R14BKP = BDIMPOSTO_R14;
      WOUTRAS_R14BKP = BDOUTRAS_R14;
      WICMSCOBRADOST_R14BKP = BDICMSCOBRADOST_R14;
      WPETROLEOENERGIA_R14BKP = BDPETROLEOENERGIA_R14;
      WOUTROS_PRODUTOS_R14BKP = BDOUTROS_PRODUTOS_R14;
      WCODIGO_R20BKP = BDCODIGO_R20;
      WOPERACAO_R20BKP = BDOPERACAO_R20;
      WFUNLEGAL_R20BKP = BDFUNLEGAL_R20;
      WDESCRICAO_R20BKP = BDDESCRICAO_R20;
      WINSCESTREM_R25BKP = BDINSCESTREM_R25;
      WCODAUTORIZACAO_R28BKP = BDCODAUTORIZACAO_R28;

      IF ((wcodempOCO > 0) AND ((wcodempOCO <> bdcodemp) OR (wrefOCO <> bdreferencia))) THEN
        BEGIN
          wsqloco = 'select t.BDCODEMP, NULL BDNOMEMP,NULL bdCODCONF,t.BDREFERENCIA, NULL BDNUMCAMPO, NULL BDCODQUADRO,NULL bdclassificacao, NULL bddescform,NULL BDCODNAT, BDVALOR,';
          wsqloco = wsqloco||' NULL BDVLRCONT,NULL BDBASEICMS,NULL BDVLRICMS,NULL BDISENTASICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL BDIMPSUBSTITUTO,NULL BDIMPSUBSTITUIDO,NULL BDOUTROSIMPOSTOS, ';
          wsqloco = wsqloco||' NULL BDSIGLAUF,NULL BDTIPORETENT,NULL BDVLRCONTAB,null BDVLRCONTAB2,NULL BDBASEICMS,NULL BDBASEICMS2,NULL BDVLRICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL bdicmsret,NULL BDOUTROSIMPOSTOS, ';
          wsqloco = wsqloco||'l.bdcodigo, l.bdoperacao -1 bdoperacao, l.bdfunlegal, l.bddescricao, T.BDINSCESTREM, T.BDCODAUTORIZACAO ';
          wsqloco = wsqloco||' from ( ';
          wsqloco = wsqloco||'       select BDCODEMP,BDCODTIPOOCOGIA,BDCODLISOCOGIASP,BDREFERENCIA,BDINSCESTREM,BDCODAUTORIZACAO,sum(BDVALOR) bdvalor ';
          wsqloco = wsqloco||'       from VEF_EMP_TMOVOCO_GIASP ';
          wsqloco = wsqloco||'       where bdcodemp = '||wcodempOCO;
          wsqloco = wsqloco||'       and bdreferencia = '||wrefOCO;
          wsqloco = wsqloco||'       group by BDCODEMP,BDCODTIPOOCOGIA,BDCODLISOCOGIASP,BDREFERENCIA,BDINSCESTREM,BDCODAUTORIZACAO ';
          wsqloco = wsqloco||' ) t, VEF_BASE_TTAB_LISTAOCO_GIASP l ';
          wsqloco = wsqloco||' where bdcodemp = '||wcodempOCO;
          wsqloco = wsqloco||' and bdreferencia = '||wrefOCO;
          wsqloco = wsqloco||' and (t.bdcodlisocogiasp = l.bdcodlisocogiasp) ';
          wsqloco = wsqloco||' order by t.bdcodemp, t.bdreferencia,l.bdcodigo,t.BDINSCESTREM ';

          FOR EXECUTE STATEMENT wsqloco
          INTO
            BDCODEMP,
            bdnomemp,
            BDCODCONF ,
            BDREFERENCIA ,
            BDNUMCAMPO ,
            BDCODQUADRO,
            BDCLASSIFICACAO ,
            BDDESCFORM ,
            BDCODNAT,
            BDVALOR,
            BDVLRCONT,
            BDBASEICMS,
            BDVLRICMS,
            BDISENTASICMS,
            BDOUTRASICMS,
            BDVLRST,
            BDIMPSUBSTITUTO,
            BDIMPSUBSTITUIDO,
            BDOUTROSIMPOSTOS,
            BDUF_R14 ,
            WTIPORETENT,
            BDVALOR_CONTABIL_1_R14 ,
            BDBASECALCULO_1_R14,
            BDVALOR_CONTABIL_2_R14,
            BDBASECALCULO_2_R14,
            BDIMPOSTO_R14,
            BDOUTRAS_R14,
            BDICMSCOBRADOST_R14,
            BDPETROLEOENERGIA_R14,
            BDOUTROS_PRODUTOS_R14,
            BDCODIGO_R20,
            BDOPERACAO_R20,
            BDFUNLEGAL_R20,
            BDDESCRICAO_R20,
            BDINSCESTREM_R25,
            BDCODAUTORIZACAO_R28
          DO
          BEGIN
            bddescform = 'R20';
        
            SUSPEND;
        
            IF ((BDCODIGO_R20 = 218) OR (BDCODIGO_R20 = 219) OR (BDCODIGO_R20 = 225) OR (BDCODIGO_R20 = 704) OR (BDCODIGO_R20 = 705) OR
                (BDCODIGO_R20 = 706) OR (BDCODIGO_R20 = 707) OR (BDCODIGO_R20 = 729) OR (BDCODIGO_R20 = 730) OR (BDCODIGO_R20 = 747)) THEN
               BEGIN
                  bddescform = 'R25';
                  SUSPEND;
               END
        
            IF ((BDCODIGO_R20 = 220) OR (BDCODIGO_R20 = 221) OR (BDCODIGO_R20 = 223) OR (BDCODIGO_R20 = 740) OR (BDCODIGO_R20 = 741) OR (BDCODIGO_R20 = 744) OR (BDCODIGO_R20 = 745)) THEN
               BEGIN
                  bddescform = 'R28';
                  SUSPEND;
               END
          END

          BDCODEMP = WCODEMPBKP;
          bdnomemp = wnomempbkp;
          BDCODCONF = WCODCONFBKP;
          BDREFERENCIA = WREFERENCIABKP;
          BDNUMCAMPO = WNUMCAMPOBKP;
          BDCODQUADRO = WCODQUADROBKP;
          BDCLASSIFICACAO = WCLASSIFICACAOBKP;
          BDDESCFORM = WDESCFORMBKP;
          BDCODNAT = WCODNATBKP;
          BDVALOR = WVALORBKP;
          BDVLRCONT = WVLRCONTBKP;
          BDBASEICMS = WBASEICMSBKP;
          BDVLRICMS = WVLRICMSBKP;
          BDISENTASICMS = WISENTASICMSBKP;
          BDOUTRASICMS = WOUTRASICMSBKP;
          BDVLRST = WVLRSTBKP;
          BDIMPSUBSTITUTO = WIMPSUBSTITUTOBKP;
          BDIMPSUBSTITUIDO = WIMPSUBSTITUIDOBKP;
          BDOUTROSIMPOSTOS = WOUTROSIMPOSTOSBKP;
          BDUF_R14 = WUF_R14BKP;
          BDVALOR_CONTABIL_1_R14 = WVALOR_CONTABIL_1_R14BKP;
          BDBASECALCULO_1_R14 = WBASECALCULO_1_R14BKP;
          BDVALOR_CONTABIL_2_R14 = WVALOR_CONTABIL_2_R14BKP;
          BDBASECALCULO_2_R14 = WBASECALCULO_2_R14BKP;
          BDIMPOSTO_R14 = WIMPOSTO_R14BKP;
          BDOUTRAS_R14 = WOUTRAS_R14BKP;
          BDICMSCOBRADOST_R14 = WICMSCOBRADOST_R14BKP;
          BDPETROLEOENERGIA_R14 = WPETROLEOENERGIA_R14BKP;
          BDOUTROS_PRODUTOS_R14 = WOUTROS_PRODUTOS_R14BKP;
          BDCODIGO_R20 = WCODIGO_R20BKP;
          BDOPERACAO_R20 = WOPERACAO_R20BKP;
          BDFUNLEGAL_R20 = WFUNLEGAL_R20BKP;
          BDDESCRICAO_R20 = WDESCRICAO_R20BKP;
          BDINSCESTREM_R25 = WINSCESTREM_R25BKP;
          BDCODAUTORIZACAO_R28 = WCODAUTORIZACAO_R28BKP;
        END

      wcodempOCO = bdcodemp;
      wrefOCO = bdreferencia;

      BDCODNAT = wcodnatant;
      BDVLRCONT = wVLRCONT;
      BDBASEICMS = wBASEICMS;
      BDVLRICMS = wVLRICMS;
      BDISENTASICMS = wISENTASICMS;
      BDOUTRASICMS = wOUTRASICMS;
      BDVLRST = wVLRST;
      BDIMPSUBSTITUTO = wIMPSUBSTITUTO;
      BDIMPSUBSTITUIDO = wIMPSUBSTITUIDO;
      BDOUTROSIMPOSTOS = wOUTROSIMPOSTOS;
      bddescform = 'R10';
      SUSPEND;

      wPassouUF = 0;

      IF (((wcodnatant >= 2000) AND (wcodnatant < 2999)) OR ((wcodnatant >= 6000) AND (wcodnatant < 6999))) THEN
        BEGIN

          WSQLR14 = 'select BDCODEMP, NULL BDNOMEMP, NULL bdCODCONF,BDREFERENCIA, NULL BDNUMCAMPO, NULL BDCODQUADRO,NULL bdclassificacao, NULL bddescform,NULL BDCODNAT, 0 BDVALOR,';
          WSQLR14 = WSQLR14||' BDVLRCONTAB,BDBASEICMS,0 BDVLRICMS,0 BDISENTASICMS,0 BDOUTRASICMS,0 BDVLRST, BDIMPSUBSTITUTO, BDIMPSUBSTITUIDO,0 BDOUTROSIMPOSTOS, ';
          WSQLR14 = WSQLR14||' BDSIGLAUF,BDTIPORETENT,0 BDVLRCONTAB,0 BDVLRCONTAB2,0 BDBASEICMS,0 BDBASEICMS2,BDVLRICMS,BDOUTRASICMS,BDVLRST,BDVLRST, BDVLRST, ';--BDOUTROSIMPOSTOS, ';
          WSQLR14 = WSQLR14||' NULL bdcodigo_R20, NULL bdoperacao_R20, NULL bdfunlegal_R20, NULL bddescricao_R20, NULL BDINSCESTREM_R25, NULL BDCODAUTORIZACAO_R28 ';

          IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN
             WSQLR14 = WSQLR14||' , NULL BDVLRCONT1, NULL BDBASEICMS1, NULL BDVLRCONT2, NULL BDBASEICMS2 FROM ';
          ELSE
             WSQLR14 = WSQLR14||' , BDVLRCONT1, BDBASEICMS1, BDVLRCONT2, BDBASEICMS2 FROM ';
    
          IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN -- Alt.: 15863 - Ver c?digo abaixo da mesma solicita??o, deve sempre verificar entradas...
            BEGIN
             WSQLR14 = WSQLR14||' VW_VEF_TOTEXP_UF_ENT_GIASP ';
             WSQLR14 = WSQLR14||' where bdcodemp = '||bdcodemp||' and bdreferencia = '||bdreferencia||' and bdSIGLAUF <> '''||'SP'||''' and BDPREFIXONAT = '||wcodnatant;
            END
          ELSE
            BEGIN
--             WSQLR14 = WSQLR14||' VW_VEF_TOTEXP_UF_GIASP ';
--             WSQLR14 = WSQLR14||' where bdcodemp = '||bdcodemp||' and bdreferencia = '||bdreferencia||' and bdSIGLAUF <> '''||'SP'||''' and BDPREFIXONAT = '||wcodnatant;
            --ALT:16719 - FEITO PEGAR O D160 O PARTICIPNATE QUANDO HOUVER
             WSQLR14 = WSQLR14||' ( ';
             /* Quando a cidade do lan?amento for de fora de SP ent?o pega essa cidade do lan?amento.
                Verifica a inscri??o estadual do participante para saber se lan?a o valor como contribuinte ou n?o contribuinte. */
             WSQLR14 = WSQLR14||'                SELECT  MOV.bdcodemp,mov.bdreflan BDREFERENCIA ,mov.bdsiglauf,mov.BDTIPORETENT, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdvlrcontab,0)) BDVLRCONTAB, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.BDBASEICMS,0)) BDBASEICMS, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdvlricms,0)) bdvlricms, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.BDOUTRASICMS,0)) BDOUTRASICMS, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdvlrst,0)) BDVLRST, ';
             WSQLR14 = WSQLR14||'                        SUM(0) bdicmsret, ';
             WSQLR14 = WSQLR14||'                        SUM(0) BDOUTROSIMPOSTOS, ';
             WSQLR14 = WSQLR14||'                        SUM(0) BDVLRCONT1, ';
             WSQLR14 = WSQLR14||'                        SUM(0) BDBASEICMS1, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdvlrcontab,0)) BDVLRCONT2, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.BDBASEICMS,0)) BDBASEICMS2, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdIMPSUBSTITUTO,0)) BDIMPSUBSTITUTO, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdIMPSUBSTITUIDO,0)) BDIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                FROM ( ';
             WSQLR14 = WSQLR14||'                      select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdordem,MOV.BDPREFIXONAT,null BDTIPORETENT, ';
             WSQLR14 = WSQLR14||'                             UF.BDSIGLAUF, mov.bdvlrcontab,mov.BDBASEICMS,mov.bdvlricms,mov.BDOUTRASICMS,MOV.bdvlrst, ';
             WSQLR14 = WSQLR14||'                             coalesce(impret.bdIMPSUBSTITUTO,0) bdIMPSUBSTITUTO,coalesce(impret.bdIMPSUBSTITUIDO,0) bdIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                      from ( ';
             WSQLR14 = WSQLR14||'                              select sai.bdcodemp,sai.bdchave,sai.bdcodter,sai.bdreflan,itens.bdordem,d160.bdcodterdestinatario,ITENS.BDPREFIXONAT, ';
             WSQLR14 = WSQLR14||'                                     ITENS.bdvlrcontab,ITENS.BDBASEICMS,ITENS.bdvlricms,ITENS.BDOUTRASICMS,ITENS.bdvlrst, SAI.BDCODCID, d160.bdCODCIDDESTINATARIO ';
             WSQLR14 = WSQLR14||'                              from ( ';
             WSQLR14 = WSQLR14||'                                    select sai.bdcodemp,sai.bdchave,sai.bdcodter,sai.bdreflan, SAI.BDCODCID ';
             WSQLR14 = WSQLR14||'                                    from vef_emp_tmovsai sai ';
             WSQLR14 = WSQLR14||'                                    where sai.bdcodemp = '||bdcodemp;
             WSQLR14 = WSQLR14||'                                    and  sai.bdcodsitnf not in (2,3,4,5) ';
             WSQLR14 = WSQLR14||'                                    and sai.BDREFLAN =  '||bdreferencia;
             WSQLR14 = WSQLR14||'                                    ) sai ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_td160cargatrans d160 ON (SAI.bdcodemp = d160.bdcodemp AND SAI.bdchave = D160.bdchave) ';
             WSQLR14 = WSQLR14||'                              where itens.BDPREFIXONAT = '||wcodnatant ;
             WSQLR14 = WSQLR14||'                            ) mov ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = MOV.bdcodemp AND impret.bdchave = MOV.bdchave AND impret.bdordem = MOV.bdordem) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = MOV.bdcodter) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = mov.bdcodcid) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        WHERE ((ter.bdIETER IS NULL) OR (ter.bdIETER = '''') OR (UPPER(ter.bdIETER) = ''ISENTO'')) AND (uf.bdSIGLAUF <> ''SP'') ';
             WSQLR14 = WSQLR14||'                          AND (uf.bdSIGLAUF <> ''SP'') ';
             WSQLR14 = WSQLR14||'                        UNION ALL ';
             /* Quando a cidade do lan?amento for de SP ent?o pega essa cidade do destinatario no D160.
                Verifica a inscri??o estadual do destinatario para saber se lan?a o valor como contribuinte ou n?o contribuinte. */
             WSQLR14 = WSQLR14||'                      select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdordem,MOV.BDPREFIXONAT,null BDTIPORETENT, ';
             WSQLR14 = WSQLR14||'                             UFD.BDSIGLAUF, mov.bdvlrcontab,mov.BDBASEICMS,mov.bdvlricms,mov.BDOUTRASICMS,MOV.bdvlrst, ';
             WSQLR14 = WSQLR14||'                             coalesce(impret.bdIMPSUBSTITUTO,0) bdIMPSUBSTITUTO,coalesce(impret.bdIMPSUBSTITUIDO,0) bdIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                      from ( ';
             WSQLR14 = WSQLR14||'                              select sai.bdcodemp,sai.bdchave,sai.bdcodter,sai.bdreflan,itens.bdordem,d160.bdcodterdestinatario,ITENS.BDPREFIXONAT, ';
             WSQLR14 = WSQLR14||'                                     ITENS.bdvlrcontab,ITENS.BDBASEICMS,ITENS.bdvlricms,ITENS.BDOUTRASICMS,ITENS.bdvlrst, SAI.BDCODCID, d160.bdCODCIDDESTINATARIO ';
             WSQLR14 = WSQLR14||'                              from ( ';
             WSQLR14 = WSQLR14||'                                    select sai.bdcodemp,sai.bdchave,sai.bdcodter,sai.bdreflan, SAI.BDCODCID ';
             WSQLR14 = WSQLR14||'                                    from vef_emp_tmovsai sai ';
             WSQLR14 = WSQLR14||'                                    where sai.bdcodemp = '||bdcodemp;
             WSQLR14 = WSQLR14||'                                    and  sai.bdcodsitnf not in (2,3,4,5) ';
             WSQLR14 = WSQLR14||'                                    and sai.BDREFLAN =  '||bdreferencia;
             WSQLR14 = WSQLR14||'                                    ) sai ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_td160cargatrans d160 ON (SAI.bdcodemp = d160.bdcodemp AND SAI.bdchave = D160.bdchave) ';
             WSQLR14 = WSQLR14||'                              where itens.BDPREFIXONAT = '||wcodnatant ;
             WSQLR14 = WSQLR14||'                            ) mov ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = MOV.bdcodemp AND impret.bdchave = MOV.bdchave AND impret.bdordem = MOV.bdordem) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = mov.bdcodcid) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VW_TTERCEIRO td ON (td.bdCODTER = mov.bdCODTERDESTINATARIO) '; -- Alt.: 23787 - Deve usar o participante do destinat?rio do D160 e n?o do lan?amento...
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TCIDADE cidd ON (cidd.bdCODCID = mov.bdCODCIDDESTINATARIO) '; -- Alt.: 23787 - Deve usar a cidade do destinat?rio do D160 e n?o do lan?amento...
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF ufD ON (ufD.bdcoduf = CIDD.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        WHERE ((td.bdIETER IS NULL) OR (td.bdIETER = '''') OR (UPPER(td.bdIETER) = ''ISENTO'')) ';
             WSQLR14 = WSQLR14||'                          AND (ufd.bdSIGLAUF <> ''SP'') AND (uf.bdSIGLAUF = ''SP'')';
             WSQLR14 = WSQLR14||'                    ) MOV ';
             WSQLR14 = WSQLR14||'                GROUP BY MOV.bdcodemp, mov.bdreflan,mov.bdsiglauf,mov.BDTIPORETENT ';
             WSQLR14 = WSQLR14||'                union ';   
             WSQLR14 = WSQLR14||'                select MOV.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, MOV.BDSIGLAUF, MOV.BDTIPORETENT,';
             WSQLR14 = WSQLR14||'                        sum(MOV.BDVLRCONTAB) BDVLRCONTAB, sum(MOV.BDBASEICMS) BDBASEICMS, sum(MOV.BDVLRICMS) BDVLRICMS, sum(MOV.BDOUTRASICMS) BDOUTRASICMS, ';
             WSQLR14 = WSQLR14||'                        sum(MOV.BDVLRST) BDVLRST, sum(0) BDICMSRET, sum(0) BDOUTROSIMPOSTOS, sum(MOV.BDVLRCONTAB) BDVLRCONT1, ';
             WSQLR14 = WSQLR14||'                        sum(MOV.BDBASEICMS) BDBASEICMS1, sum(0) BDVLRCONT2, sum(0) BDBASEICMS2, ';
             WSQLR14 = WSQLR14||'                        sum(MOV.BDIMPSUBSTITUTO) BDIMPSUBSTITUTO, sum(MOV.BDIMPSUBSTITUIDO) BDIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                FROM ( ';
             /* Quando a cidade do lan?amento for de fora de SP ent?o pega essa cidade do lan?amento.
                Verifica a inscri??o estadual do participante para saber se lan?a o valor como contribuinte ou n?o contribuinte. */
             WSQLR14 = WSQLR14||'                       select MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDORDEM, MOV.BDPREFIXONAT, null BDTIPORETENT, UF.BDSIGLAUF, ';
             WSQLR14 = WSQLR14||'                             MOV.BDVLRCONTAB, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDOUTRASICMS, MOV.BDVLRST,';
             WSQLR14 = WSQLR14||'                             coalesce(IMPRET.BDIMPSUBSTITUTO, 0) BDIMPSUBSTITUTO, coalesce(IMPRET.BDIMPSUBSTITUIDO, 0) BDIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                       from ( ';
             WSQLR14 = WSQLR14||'                              select SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDCODTER, SAI.BDREFLAN, ITENS.BDORDEM, D160.BDCODTERDESTINATARIO, ';
             WSQLR14 = WSQLR14||'                                     ITENS.BDPREFIXONAT, ITENS.BDVLRCONTAB, ITENS.BDBASEICMS, ITENS.BDVLRICMS, ITENS.BDOUTRASICMS, ITENS.BDVLRST, ';
             WSQLR14 = WSQLR14||'                                     SAI.BDCODCID, d160.bdCODCIDDESTINATARIO ';
             WSQLR14 = WSQLR14||'                              from ( ';
             WSQLR14 = WSQLR14||'                                    select SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDCODTER, SAI.BDREFLAN, SAI.BDCODCID ';
             WSQLR14 = WSQLR14||'                                    from vef_emp_tmovsai sai ';
             WSQLR14 = WSQLR14||'                                    where sai.bdcodemp = '||bdcodemp;
             WSQLR14 = WSQLR14||'                                    and  sai.bdcodsitnf not in (2,3,4,5) ';
             WSQLR14 = WSQLR14||'                                    and sai.BDREFLAN =  '||bdreferencia;
             WSQLR14 = WSQLR14||'                                    ) sai ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_td160cargatrans d160 ON (SAI.bdcodemp = d160.bdcodemp AND SAI.bdchave = D160.bdchave) ';
        /*Sol. 19711 Gabriel Ariel (11/08/17) - Nao estava exportando R14 com notas de valor contabil zerado*/
             WSQLR14 = WSQLR14||'                              where /*ITENS.BDVLRCONTAB > 0 and*/ itens.BDPREFIXONAT = '||wcodnatant ;
             WSQLR14 = WSQLR14||'                            ) mov ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = MOV.bdcodemp AND impret.bdchave = MOV.bdchave AND impret.bdordem = MOV.bdordem) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = MOV.bdcodter) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = MOV.bdcodcid) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        WHERE ((ter.bdIETER IS NOT NULL) AND (ter.bdIETER <> '''') AND (UPPER(ter.bdIETER) <> ''ISENTO'')) ';
             WSQLR14 = WSQLR14||'                          AND (uf.bdSIGLAUF <> ''SP'') ';
             WSQLR14 = WSQLR14||'                       union all ';
             /* Quando a cidade do lan?amento for de SP ent?o pega essa cidade do destinatario no D160.
                Verifica a inscri??o estadual do destinatario para saber se lan?a o valor como contribuinte ou n?o contribuinte. */
             WSQLR14 = WSQLR14||'                       select MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDORDEM, MOV.BDPREFIXONAT, null BDTIPORETENT, UFD.BDSIGLAUF,';
             WSQLR14 = WSQLR14||'                             MOV.BDVLRCONTAB, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDOUTRASICMS, MOV.BDVLRST, ';
             WSQLR14 = WSQLR14||'                             coalesce(IMPRET.BDIMPSUBSTITUTO, 0) BDIMPSUBSTITUTO, coalesce(IMPRET.BDIMPSUBSTITUIDO, 0) BDIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                       from ( ';
             WSQLR14 = WSQLR14||'                              select SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDCODTER, SAI.BDREFLAN, ITENS.BDORDEM, D160.BDCODTERDESTINATARIO, ';
             WSQLR14 = WSQLR14||'                                     ITENS.BDPREFIXONAT, ITENS.BDVLRCONTAB, ITENS.BDBASEICMS, ITENS.BDVLRICMS, ITENS.BDOUTRASICMS, ITENS.BDVLRST, ';
             WSQLR14 = WSQLR14||'                                     SAI.BDCODCID, d160.bdCODCIDDESTINATARIO ';
             WSQLR14 = WSQLR14||'                              from ( ';
             WSQLR14 = WSQLR14||'                                    select SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDCODTER, SAI.BDREFLAN, SAI.BDCODCID ';
             WSQLR14 = WSQLR14||'                                    from vef_emp_tmovsai sai ';
             WSQLR14 = WSQLR14||'                                    where sai.bdcodemp = '||bdcodemp;
             WSQLR14 = WSQLR14||'                                    and  sai.bdcodsitnf not in (2,3,4,5) ';
             WSQLR14 = WSQLR14||'                                    and sai.BDREFLAN =  '||bdreferencia;
             WSQLR14 = WSQLR14||'                                    ) sai ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_td160cargatrans d160 ON (SAI.bdcodemp = d160.bdcodemp AND SAI.bdchave = D160.bdchave) ';
             WSQLR14 = WSQLR14||'                              where itens.BDPREFIXONAT = '||wcodnatant ;
             WSQLR14 = WSQLR14||'                            ) mov ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = MOV.bdcodemp AND impret.bdchave = MOV.bdchave AND impret.bdordem = MOV.bdordem) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = MOV.bdcodcid) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VW_TTERCEIRO td ON (td.bdCODTER = mov.bdCODTERDESTINATARIO) '; -- Alt.: 23787 - Deve usar o participante do destinat?rio do D160 e n?o do lan?amento...
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TCIDADE cidd ON (cidd.bdCODCID = mov.bdCODCIDDESTINATARIO) '; -- Alt.: 23787 - Deve usar a cidade do destinat?rio do D160 e n?o do lan?amento...
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF ufD ON (ufD.bdcoduf = CIDD.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        WHERE ((td.bdIETER IS NOT NULL) AND (td.bdIETER <> '''') AND (UPPER(td.bdIETER) <> ''ISENTO'')) ';
             WSQLR14 = WSQLR14||'                          AND (ufd.bdSIGLAUF <> ''SP'') AND (uf.bdSIGLAUF = ''SP'')';
             WSQLR14 = WSQLR14||'                    ) MOV ';
             WSQLR14 = WSQLR14||'                group by MOV.BDCODEMP, MOV.BDREFLAN, MOV.BDSIGLAUF, MOV.BDTIPORETENT ';
             WSQLR14 = WSQLR14||'  )';
            END

          wufaux = '';
          wufauxAnt = '';

          wVALOR_CONTABIL_1_R14 = 0;
          wBASECALCULO_1_R14 = 0;
          wVALOR_CONTABIL_2_R14 = 0;
          wBASECALCULO_2_R14 = 0;
          wIMPOSTO_R14 = 0;
          wOUTRAS_R14 = 0;
          wICMSCOBRADOST_R14 = 0;
          wPETROLEOENERGIA_R14 = 0;
          wOUTROS_PRODUTOS_R14 = 0;
    
          FOR EXECUTE STATEMENT WSQLR14
          INTO
            BDCODEMP,
            bdnomemp, 
            BDCODCONF,
            BDREFERENCIA,
            BDNUMCAMPO ,
            BDCODQUADRO,
            BDCLASSIFICACAO ,
            BDDESCFORM ,
            BDCODNAT,
            BDVALOR,
            BDVLRCONT,
            BDBASEICMS,
            BDVLRICMS,
            BDISENTASICMS,
            BDOUTRASICMS,
            BDVLRST,
            BDIMPSUBSTITUTO,
            BDIMPSUBSTITUIDO,
            BDOUTROSIMPOSTOS,
            BDUF_R14 ,
            WTIPORETENT,
            BDVALOR_CONTABIL_1_R14 ,
            BDBASECALCULO_1_R14,
            BDVALOR_CONTABIL_2_R14,
            BDBASECALCULO_2_R14,
            BDIMPOSTO_R14,
            BDOUTRAS_R14,
            BDICMSCOBRADOST_R14,
            BDPETROLEOENERGIA_R14,
            BDOUTROS_PRODUTOS_R14,
            BDCODIGO_R20,
            BDOPERACAO_R20,
            BDFUNLEGAL_R20,
            BDDESCRICAO_R20,
            BDINSCESTREM_R25,
            BDCODAUTORIZACAO_R28,
            BDVLRCONT1,
            BDBASEICMS1,
            BDVLRCONT2,
            BDBASEICMS2
          DO
          BEGIN
            bddescform = 'R14';
            bdcodnat = wcodnatant;
            wPassouUF = 1;

            IF ((wufaux <> '') AND (wufaux <> BDUF_R14)) THEN
               BEGIN
                  /*wVALOR_CONTABIL_1_R14Aux = 0;
                  wBASECALCULO_1_R14Aux = 0;
                  wVALOR_CONTABIL_2_R14Aux = 0;
                  wBASECALCULO_2_R14Aux = 0;*/

                  IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN
                     BEGIN
                        wVALOR_CONTABIL_1_R14Aux = BDVLRCONT;
                        wBASECALCULO_1_R14Aux = BDBASEICMS;
                     END
                  ELSE
                     BEGIN
                        --if ((wIETER is null) or (wieter = '') or (Upper(wieter) = 'ISENTO')) then
                           BEGIN
                             wVALOR_CONTABIL_2_R14Aux = BDVLRCONT2;
                             wBASECALCULO_2_R14Aux = BDBASEICMS2;
                           /*end
                        else
                           begin*/
                             wVALOR_CONTABIL_1_R14Aux = BDVLRCONT1;
                             wBASECALCULO_1_R14Aux = BDBASEICMS1;
                           END
                     END

                  wIMPOSTO_R14Aux = BDIMPOSTO_R14;
                  wOUTRAS_R14Aux = BDOUTRAS_R14;
                  wICMSCOBRADOST_R14Aux = BDICMSCOBRADOST_R14;
                  wPETROLEOENERGIA_R14Aux = BDPETROLEOENERGIA_R14;
                  wOUTROS_PRODUTOS_R14Aux = BDOUTROS_PRODUTOS_R14;

                  wufauxant = BDUF_R14;
                  BDUF_R14 = wufaux;
                  BDVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14;
                  BDBASECALCULO_1_R14 = wBASECALCULO_1_R14;
                  BDVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14;
                  BDBASECALCULO_2_R14 = wBASECALCULO_2_R14;
                  BDIMPOSTO_R14 = wIMPOSTO_R14;
                  BDOUTRAS_R14 = wOUTRAS_R14;
                  BDICMSCOBRADOST_R14 = wICMSCOBRADOST_R14;
                  BDPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14;
                  BDOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14;

                  SUSPEND;

                  --Adilson - sol. 5664 - inicializado vari?vies para o R14
                  wVALOR_CONTABIL_1_R14 = 0;
                  wBASECALCULO_1_R14 = 0;
                  wVALOR_CONTABIL_2_R14 = 0;
                  wBASECALCULO_2_R14 = 0;
                  wIMPOSTO_R14 = 0;
                  wOUTRAS_R14 = 0;
                  wICMSCOBRADOST_R14 = 0;
                  wPETROLEOENERGIA_R14 = 0;
                  wOUTROS_PRODUTOS_R14 = 0;

                  BDUF_R14 = wufauxant;
                  BDVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14Aux;
                  BDBASECALCULO_1_R14 = wBASECALCULO_1_R14Aux;
                  BDVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14Aux;
                  BDBASECALCULO_2_R14 = wBASECALCULO_2_R14Aux;
                  BDIMPOSTO_R14 = wIMPOSTO_R14Aux;
                  BDOUTRAS_R14 = wOUTRAS_R14Aux;
                  BDICMSCOBRADOST_R14 = wICMSCOBRADOST_R14Aux;
                  BDPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14Aux;
                  BDOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14Aux;

               END

            wufaux = BDUF_R14;

            /*wVALOR_CONTABIL_1_R14 = 0;
            wBASECALCULO_1_R14 = 0;
            wVALOR_CONTABIL_2_R14 = 0;
            wBASECALCULO_2_R14 = 0;*/

            IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN
               BEGIN
                  --Adilson - sol. 5664
                  --wVALOR_CONTABIL_1_R14 = /*wVALOR_CONTABIL_1_R14 + */BDVLRCONT;
                  --wBASECALCULO_1_R14 = /*wBASECALCULO_1_R14 + */BDBASEICMS;
                  wVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14 + BDVLRCONT;
                  wBASECALCULO_1_R14 = wBASECALCULO_1_R14 + BDBASEICMS;
               END
            ELSE
               BEGIN
                  --if ((wIETER is null) or (wieter = '') or (Upper(wieter) = 'ISENTO')) then
                     BEGIN
                       --Adilson - sol. 5664
                       --wVALOR_CONTABIL_2_R14 = /*wVALOR_CONTABIL_2_R14 + */BDVLRCONT2;
                       --wBASECALCULO_2_R14 = /*wBASECALCULO_2_R14 + */BDBASEICMS2;
                       wVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14 + BDVLRCONT2;
                       wBASECALCULO_2_R14 = wBASECALCULO_2_R14 + BDBASEICMS2;
                     /*end
                  else
                     begin*/
                       --Adilson - sol. 5664
                       --wVALOR_CONTABIL_1_R14 = /*wVALOR_CONTABIL_1_R14 + */BDVLRCONT1;
                       --wBASECALCULO_1_R14 = /*wBASECALCULO_1_R14 + */BDBASEICMS1;
                       wVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14 + BDVLRCONT1;
                       wBASECALCULO_1_R14    = wBASECALCULO_1_R14 + BDBASEICMS1;
                     END
               END
            --Adilson - sol. 5664
            --wIMPOSTO_R14 = /*wIMPOSTO_R14 + */BDIMPOSTO_R14;
            --wOUTRAS_R14 = /*wOUTRAS_R14 +*/ BDOUTRAS_R14;
            wIMPOSTO_R14 = wIMPOSTO_R14 + BDIMPOSTO_R14;
            wOUTRAS_R14  = wOUTRAS_R14  + BDOUTRAS_R14;

            IF ((wcodnatant >= 6000) AND (wcodnatant < 6999)) THEN
               --Adilson - sol. 5664
               --wICMSCOBRADOST_R14 = /*wICMSCOBRADOST_R14 + */BDICMSCOBRADOST_R14;
               wICMSCOBRADOST_R14 = wICMSCOBRADOST_R14 + BDICMSCOBRADOST_R14;

            --alt:15582 - elizeu - 31-08-16 - n?o tendo o tiporet n?o jogava o valor em nada, deve jogar em outros
            IF ((WTIPORETENT IS NOT NULL) OR ((wcodnatant >= 2000) AND (wcodnatant < 2999))) THEN -- Alt.: 15863 - Deve sempre verificar as entradas ou se tem reten??o
               BEGIN
                IF ((WTIPORETENT = 0) OR (WTIPORETENT = 1)) THEN
                  BEGIN
                    IF (BDIMPSUBSTITUIDO > 0) THEN
                       --Adilson - sol. 5664
                       --wpetroleoenergia_r14 = BDIMPSUBSTITUIDO;
                       wpetroleoenergia_r14 = wpetroleoenergia_r14 + BDIMPSUBSTITUIDO;
                    ELSE
                    IF (BDIMPSUBSTITUTO > 0) THEN
                       --Adilson - sol. 5664
                       --wpetroleoenergia_r14 = BDIMPSUBSTITUTO;
                       wpetroleoenergia_r14 = wpetroleoenergia_r14 + BDIMPSUBSTITUTO;
                    wOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14;
                  END
                ELSE
                  BEGIN
                    --wOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14 + BDOUTROS_PRODUTOS_R14;
                    IF (BDIMPSUBSTITUIDO > 0) THEN
                       --Adilson - sol. 5664
                       --woutros_produtos_r14 = BDIMPSUBSTITUIDO;
                       woutros_produtos_r14 = woutros_produtos_r14 + BDIMPSUBSTITUIDO;
                    ELSE
                    IF (BDIMPSUBSTITUTO > 0) THEN
                       --Adilson - sol. 5664
                       --woutros_produtos_r14 = BDIMPSUBSTITUTO;
                       woutros_produtos_r14 = woutros_produtos_r14 + BDIMPSUBSTITUTO;
                    wPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14;
                  END
              END
          END
        END

      IF (wPassouUF = 1) THEN
        BEGIN

          /*wVALOR_CONTABIL_1_R14Aux = 0;
          wBASECALCULO_1_R14Aux = 0;
          wVALOR_CONTABIL_2_R14Aux = 0;
          wBASECALCULO_2_R14Aux = 0;*/

          IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN
             BEGIN
                wVALOR_CONTABIL_1_R14Aux = BDVLRCONT;
                wBASECALCULO_1_R14Aux = BDBASEICMS;
             END
          ELSE
             BEGIN
                --if ((wIETER is null) or (wieter = '') or (Upper(wieter) = 'ISENTO')) then
                   BEGIN
                     wVALOR_CONTABIL_2_R14Aux = BDVLRCONT2;
                     wBASECALCULO_2_R14Aux = BDBASEICMS2;
                   /*end
                else
                   begin*/
                     wVALOR_CONTABIL_1_R14Aux = BDVLRCONT1;
                     wBASECALCULO_1_R14Aux = BDBASEICMS1;
                   END
             END

          wIMPOSTO_R14Aux = BDIMPOSTO_R14;
          wOUTRAS_R14Aux = BDOUTRAS_R14;
          wICMSCOBRADOST_R14Aux = BDICMSCOBRADOST_R14;
          wPETROLEOENERGIA_R14Aux = BDPETROLEOENERGIA_R14;
          wOUTROS_PRODUTOS_R14Aux = BDOUTROS_PRODUTOS_R14;

          wufauxant = BDUF_R14;
          BDUF_R14 = wufaux;
          BDVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14;
          BDBASECALCULO_1_R14 = wBASECALCULO_1_R14;
          BDVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14;
          BDBASECALCULO_2_R14 = wBASECALCULO_2_R14;
          BDIMPOSTO_R14 = wIMPOSTO_R14;
          BDOUTRAS_R14 = wOUTRAS_R14;
          BDICMSCOBRADOST_R14 = wICMSCOBRADOST_R14;
          BDPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14;
          BDOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14;

          SUSPEND;

          BDUF_R14 = wufauxant;
          BDVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14Aux;
          BDBASECALCULO_1_R14 = wBASECALCULO_1_R14Aux;
          BDVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14Aux;
          BDBASECALCULO_2_R14 = wBASECALCULO_2_R14Aux;
          BDIMPOSTO_R14 = wIMPOSTO_R14Aux;
          BDOUTRAS_R14 = wOUTRAS_R14Aux;
          BDICMSCOBRADOST_R14 = wICMSCOBRADOST_R14Aux;
          BDPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14Aux;
          BDOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14Aux;
        END

      BDCODEMP = WCODEMPBKP;
      bdnomemp = wnomempbkp;
      BDCODCONF = WCODCONFBKP;
      BDREFERENCIA = WREFERENCIABKP;
      BDNUMCAMPO = WNUMCAMPOBKP;
      BDCODQUADRO = WCODQUADROBKP;
      BDCLASSIFICACAO = WCLASSIFICACAOBKP;
      BDDESCFORM = WDESCFORMBKP;
      BDCODNAT = WCODNATBKP;
      BDVALOR = WVALORBKP;
      BDVLRCONT = WVLRCONTBKP;
      BDBASEICMS = WBASEICMSBKP;
      BDVLRICMS = WVLRICMSBKP;
      BDISENTASICMS = WISENTASICMSBKP;
      BDOUTRASICMS = WOUTRASICMSBKP;
      BDVLRST = WVLRSTBKP;
      BDIMPSUBSTITUTO = WIMPSUBSTITUTOBKP;
      BDIMPSUBSTITUIDO = WIMPSUBSTITUIDOBKP;
      BDOUTROSIMPOSTOS = WOUTROSIMPOSTOSBKP;
      BDUF_R14 = WUF_R14BKP;
      BDVALOR_CONTABIL_1_R14 = WVALOR_CONTABIL_1_R14BKP;
      BDBASECALCULO_1_R14 = WBASECALCULO_1_R14BKP;
      BDVALOR_CONTABIL_2_R14 = WVALOR_CONTABIL_2_R14BKP;
      BDBASECALCULO_2_R14 = WBASECALCULO_2_R14BKP;
      BDIMPOSTO_R14 = WIMPOSTO_R14BKP;
      BDOUTRAS_R14 = WOUTRAS_R14BKP;
      BDICMSCOBRADOST_R14 = WICMSCOBRADOST_R14BKP;
      BDPETROLEOENERGIA_R14 = WPETROLEOENERGIA_R14BKP;
      BDOUTROS_PRODUTOS_R14 = WOUTROS_PRODUTOS_R14BKP;
      BDCODIGO_R20 = WCODIGO_R20BKP;
      BDOPERACAO_R20 = WOPERACAO_R20BKP;
      BDFUNLEGAL_R20 = WFUNLEGAL_R20BKP;
      BDDESCRICAO_R20 = WDESCRICAO_R20BKP;
      BDINSCESTREM_R25 = WINSCESTREM_R25BKP;
      BDCODAUTORIZACAO_R28 = WCODAUTORIZACAO_R28BKP;

      --wcontador = 1;
      BDCODNAT = wcodnataut;
      wVLRCONT = BDVALOR;
      wBASEICMS = 0;
      wVLRICMS = 0;
      wISENTASICMS = 0;
      wOUTRASICMS = 0;
      wVLRST = 0;
      wIMPSUBSTITUTO = 0;
      wIMPSUBSTITUIDO = 0;
      wOUTROSIMPOSTOS = 0;
    END

    wcontador = wcontador + 1;
    wcodnatant = BDCODNAT;

  END

  wsqloco = 'select t.BDCODEMP, NULL BDNOMEMP,NULL bdCODCONF,t.BDREFERENCIA, NULL BDNUMCAMPO, NULL BDCODQUADRO,NULL bdclassificacao, NULL bddescform,NULL BDCODNAT, BDVALOR,';
  wsqloco = wsqloco||' NULL BDVLRCONT,NULL BDBASEICMS,NULL BDVLRICMS,NULL BDISENTASICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL BDIMPSUBSTITUTO,NULL BDIMPSUBSTITUIDO,NULL BDOUTROSIMPOSTOS, ';
  wsqloco = wsqloco||' NULL BDSIGLAUF,NULL BDTIPORETENT,NULL BDVLRCONTAB,null BDVLRCONTAB2,NULL BDBASEICMS,NULL BDBASEICMS2,NULL BDVLRICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL bdicmsret,NULL BDOUTROSIMPOSTOS, ';
  wsqloco = wsqloco||'l.bdcodigo, l.bdoperacao -1 bdoperacao, l.bdfunlegal, l.bddescricao, T.BDINSCESTREM, T.BDCODAUTORIZACAO, T.BDNRDOC ';

  wsqloco = wsqloco||' from ( ';
  wsqloco = wsqloco||'       select BDCODEMP,BDCODTIPOOCOGIA,BDCODLISOCOGIASP,BDREFERENCIA,BDINSCESTREM,BDCODAUTORIZACAO,sum(BDVALOR) bdvalor, BDNRDOC ';
  wsqloco = wsqloco||'       from VEF_EMP_TMOVOCO_GIASP t ';
  IF (WCODEMPBKP IS NOT NULL) THEN
     wsqloco = wsqloco||' where t.bdcodemp = '||WCODEMPBKP;
  ELSE
  IF (:PRCODEMP IS NOT NULL) THEN
     wsqloco = wsqloco||' where '||:PRCODEMP;

  IF (WREFERENCIABKP IS NOT NULL) THEN
     wsqloco = wsqloco||' and t.bdreferencia = '||WREFERENCIABKP;
  ELSE
  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       wsqloco = wsqloco||' and t.BDREFERENCIA >= '||:pranomesinicial;
       wsqloco = wsqloco||' and t.BDREFERENCIA <= '||:pranomesfinal;
     END
  wsqloco = wsqloco||'       group by BDCODEMP,BDCODTIPOOCOGIA,BDCODLISOCOGIASP,BDREFERENCIA,BDINSCESTREM,BDCODAUTORIZACAO, BDNRDOC ';

  wsqloco = wsqloco|| ') t, VEF_BASE_TTAB_LISTAOCO_GIASP l ';
  wsqloco = wsqloco||' where (t.bdcodlisocogiasp = l.bdcodlisocogiasp) ';

  IF (WCODEMPBKP IS NOT NULL) THEN
     wsqloco = wsqloco||' and t.bdcodemp = '||WCODEMPBKP;
  ELSE
  IF (:PRCODEMP IS NOT NULL) THEN
     wsqloco = wsqloco||' and '||:PRCODEMP;

  IF (WREFERENCIABKP IS NOT NULL) THEN
     wsqloco = wsqloco||' and t.bdreferencia = '||WREFERENCIABKP;
  ELSE
  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       wsqloco = wsqloco||' and t.BDREFERENCIA >= '||:pranomesinicial;
       wsqloco = wsqloco||' and t.BDREFERENCIA <= '||:pranomesfinal;
     END

  wsqloco = wsqloco||' and (t.bdcodlisocogiasp = l.bdcodlisocogiasp) ';
  wsqloco = wsqloco||' order by t.bdcodemp, t.bdreferencia, l.bdcodigo, l.bdoperacao, t.BDINSCESTREM, t.BDNRDOC ';

  FOR EXECUTE STATEMENT wsqloco
  INTO
    BDCODEMP,
    bdnomemp,
    BDCODCONF ,
    BDREFERENCIA ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCFORM ,
    BDCODNAT,
    BDVALOR,
    BDVLRCONT,
    BDBASEICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDVLRST,
    BDIMPSUBSTITUTO,
    BDIMPSUBSTITUIDO,
    BDOUTROSIMPOSTOS,
    BDUF_R14 ,
    WTIPORETENT,
    BDVALOR_CONTABIL_1_R14 ,
    BDBASECALCULO_1_R14,
    BDVALOR_CONTABIL_2_R14,
    BDBASECALCULO_2_R14,
    BDIMPOSTO_R14,
    BDOUTRAS_R14,
    BDICMSCOBRADOST_R14,
    BDPETROLEOENERGIA_R14,
    BDOUTROS_PRODUTOS_R14,
    BDCODIGO_R20,
    BDOPERACAO_R20,
    BDFUNLEGAL_R20,
    BDDESCRICAO_R20,
    BDINSCESTREM_R25,
    BDCODAUTORIZACAO_R28,
    BDNRDOC
  DO
  BEGIN
    bddescform = 'R20';

    SUSPEND;

    IF ((BDCODIGO_R20 = 218) OR (BDCODIGO_R20 = 219) OR (BDCODIGO_R20 = 225) /*OR (BDCODIGO_R20 = 704)*/ OR (BDCODIGO_R20 = 705) OR
        (BDCODIGO_R20 = 706) OR (BDCODIGO_R20 = 707) OR (BDCODIGO_R20 = 729) OR (BDCODIGO_R20 = 730) OR (BDCODIGO_R20 = 747)) THEN
       BEGIN
          bddescform = 'R25';
          SUSPEND;
       END

    IF ((BDCODIGO_R20 IN (701, 702)) AND (BDOPERACAO_R20 = 1)) THEN /*ST*/
       BEGIN
          bddescform = 'R27';
          SUSPEND;
       END

    IF ((BDCODIGO_R20 = 220) OR (BDCODIGO_R20 = 221) OR (BDCODIGO_R20 = 223) OR (BDCODIGO_R20 = 740) OR (BDCODIGO_R20 = 741) OR (BDCODIGO_R20 = 744) OR (BDCODIGO_R20 = 745)) THEN
       BEGIN
          bddescform = 'R28';
          SUSPEND;
       END
  END
END
^

/* Alter (VEF_SP_EXP_GISSONLINE) */
ALTER PROCEDURE VEF_SP_EXP_GISSONLINE(PREMPRESAS VARCHAR(10000),
PRTIPOLANC SMALLINT,
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODCIDEMP INTEGER,
BDNUMDOCINI VARCHAR(15),
BDNUMDOCFIN VARCHAR(15),
BDSERIE VARCHAR(6),
BDDATAEMISSAO DATE,
BDVLRCONTAB NUMERIC(15,6),
BDCODMUNATVM VARCHAR(20),
BDCODLOCEXP VARCHAR(1),
BDCODTPNFEXP VARCHAR(2),
BDCODOBRA VARCHAR(10),
BDCONSTCIVIL VARCHAR(5),
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDNOMETER VARCHAR(100),
BDCEPTER VARCHAR(9),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER VARCHAR(10),
BDCOMPTER DM_BDCOMPENDERECO,
BDBAITER VARCHAR(60),
BDCODCIDTER INTEGER,
BDIMTER VARCHAR(16),
BDIETER VARCHAR(20),
BDSIGLAUFTER VARCHAR(2),
BDNOMCIDTER VARCHAR(40),
BDCODENQFEDTER INTEGER,
BDTIPOREG VARCHAR(1),
BDTIPLAN VARCHAR(1),
BDCODSITNF INTEGER,
BDBCISSSER NUMERIC(15,2))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
BEGIN
    /* BDTIPOREG
       1 : Servi?o emitido para peessoa f?sica
       2 : Servi?o emitido para tomador fora do pa?s
       3 : Servi?o emitido para pessoa jur?dica
       4 : Servi?o tomado de prestador residente no pa?s com nota fiscal*/
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);
  
    wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'trefemp.bdnomemp, ';
    wSql = wSql || 'trefemp.bdcodcid, ';
    wSql = wSql || 'tmovser.bdnumdocini, ';
    wSql = wSql || 'tmovser.bdnumdocfim, ';
    wSql = wSql || 'tmovser.bdserie, ';
    wSql = wSql || 'tmovser.bddataemissao, ';
    wSql = wSql || 'tmovseritens.bdvlrcontab, ';
    wSql = wSql || 'tatvm.bdcodmunatvm, ';
    WSQL = WSQL || 'coalesce(ttablocpreser.bdcodlocexp, case when trefemp.bdcodcid = tmovser.bdcodcid then ''D'' else ''F'' end) bdcodlocexp, ';
    wSql = wSql || 'ttabtpnf.bdcodtpnfexp, ';
    wSql = wSql || 'tgisson.bdcodobra, ';
    wSql = wSql || 'tgisson.bdconstcivil, ';
    wSql = wSql || 'vwterc.bdcodter, ';
    wSql = wSql || 'vwterc.bdcgcter, ';
    wSql = wSql || 'vwterc.bdnometer, ';
    wSql = wSql || 'vwterc.bdcepter, ';
    wSql = wSql || 'vwterc.bdlogrter, ';
    wSql = wSql || 'vwterc.bdendter, ';
    wSql = wSql || 'vwterc.bdnumter, ';
    wSql = wSql || 'vwterc.bdcompter, ';
    wSql = wSql || 'vwterc.bdbaiter, ';
    wSql = wSql || 'vwterc.bdcodcid, ';
    wSql = wSql || 'vwterc.bdimter, ';
    wSql = wSql || 'vwterc.bdieter, ';
    wSql = wSql || 'tufterc.bdsiglauf, ';
    wSql = wSql || 'tcidterc.bdnomcid, ';
    wSql = wSql || 'vwterc.bdenqsimplesfedter, ';
    wSql = wsql || 'tmovser.bdtiplan, ';
    wsql = wsql || ''''||'0'||''' as bdtiporeg, ';
    wSql = wSql || 'ttabtpnf.BDTIPONF, ';
    wSql = wSql || 'tmovseritens.BDBCISSSER ';
    wSql = wSql || 'from tempresas temp ';
    wSql = wSql || 'left outer join vw_empresas_ref_atual trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
    wSql = wSql || 'left outer join vef_emp_tmovser tmovser on (tmovser.bdcodemp = temp.bdCODEMP) ';
    wSql = wSql || 'left outer join vef_emp_tmovseritens tmovseritens on (tmovseritens.bdcodemp = tmovser.bdcodemp and tmovseritens.bdchave = tmovser.bdchave) ';
    wSql = wSql || 'left outer join vef_emp_tmovsergissonline tgisson on (tgisson.bdcodemp = tmovser.bdCodemp and tgisson.bdchave = tmovser.bdchave) ';
    wSql = wSql || 'left outer join vef_base_ttablocpreser ttablocpreser on (ttablocpreser.bdcodlocpreser = tgisson.bdcodlocpreser) ';
    wSql = wSql || 'left outer join vef_base_ttabtpnf ttabtpnf on (ttabtpnf.bdcodtpnf = tmovser.bdcodtpnf) ';
    wSql = wSql || 'left outer join vw_tterceiro vwterc on (vwterc.bdcodter = tmovser.bdcodter) ';
    wSql = wSql || 'left outer join tcidade tcidterc on (tcidterc.bdcodcid = vwterc.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufterc on (tufterc.bdcoduf = tcidterc.bdcoduf) ';
    wSql = wSql || 'left outer join tatvmunicipal tatvm on (tatvm.bdcodatvm = tmovseritens.bdcodatvm) ';

    --alt:7633 - n?o exportar notas que foram lan?adas pela folha e n?o foram conferidas pela escrita
    wSql = wSql || 'left outer join ( ';
    wSql = wSql || '                 select statusaux.* from VEF_EMP_TMOVSERSTATUS statusaux ';
    wSql = wSql || '                 where exists( ';
    wSql = wSql || '                              select MAX(aux.bdordemstatus) bdmaxordem from VEF_EMP_TMOVSERSTATUS aux ';
    wSql = wSql || '                              where statusaux.bdcodemp = aux.bdcodemp and statusaux.bdchave = aux.bdchave ';
    wSql = wSql || '                              having statusaux.bdordemstatus = MAX(aux.bdordemstatus) ';
    wSql = wSql || '                             ) ';
    wSql = wSql || '                ) status on (status.bdcodemp = tmovser.bdcodemp and status.bdchave = tmovser.bdchave) ';
    wwhere = '((status.bdcodjus is null) or (status.bdcodjus <> 25)) and ';
  

    IF (prempresas IS NOT NULL) THEN
       wwhere = wWhere||prempresas||' ';
  
    IF (prdataini IS NOT NULL) THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
  
         wwhere = wwhere||'tmovser.bddataemissao >= '||''''||prdataini||''''||' ';
       END
  
    IF (prdatafin IS NOT NULL) THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
  
         wwhere = wwhere||'tmovser.bddataemissao <= '||''''||prdatafin||''''||' ';
       END
  

   /*prtipolanc       : 0- ambos     ; 1 - emitido  ; 2 - recebidos
     tmovser.bdtiplan : 0 - emitidos ; 1 - recebidos*/
   IF ((prtipolanc IS NOT NULL) AND (prTipoLanc > 0)) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         IF (prtipolanc = 1) THEN
            wwhere = wWhere||' tmovser.bdtiplan = 0 ';
         ELSE
         IF (prtipolanc = 2) THEN
            wwhere = wWhere||' tmovser.bdtiplan = 1 ';
      END


   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplica??o*/
   worderby = '';

   wsql = wsql||wwhere||worderby;
 
   FOR EXECUTE STATEMENT wsql
     INTO
        :bdcodemp,
        :bdcnpjemp,
        :bdnomemp,
        :bdcodcidemp,
        :bdnumdocini,
        :bdnumdocfin,
        :bdserie,
        :bddataemissao,
        :bdvlrcontab,
        :bdcodmunatvm,
        :bdcodlocexp,
        :bdcodtpnfexp,
        :bdcodobra,
        :bdconstcivil,
        :bdcodter,
        :bdcgcter,
        :bdnometer,
        :bdcepter,
        :bdlogrter,
        :bdendter,
        :bdnumter,
        :bdcompter,
        :bdbaiter,
        :bdcodcidter,
        :bdimter,
        :bdieter,
        :bdsiglaufter,
        :bdnomcidter,
        :bdcodenqfedter,
        :bdtiplan,
        :bdtiporeg,
        :BDCODSITNF,
        :BDBCISSSER
     DO
      BEGIN
        IF (bdcodsitnf IN (2,3,4,5)) THEN
           BEGIN
              BDVLRCONTAB = 0;
              BDBCISSSER = 0;
           END

        IF ((strlen(bdcgcter) = 14) AND (UPPER(bdsiglaufter) <> 'EX') AND (bdtiplan = 0)) THEN
           bdtiporeg = 1;
        ELSE
        IF ((UPPER(bdsiglaufter) = 'EX') AND (bdtiplan = 0)) THEN
           bdtiporeg = 2;
        ELSE
        IF ((strlen(bdcgcter) = 18) AND (UPPER(bdsiglaufter) <> 'EX') AND (bdtiplan = 0)) THEN
           bdtiporeg = 3;
        ELSE
        IF ((UPPER(bdsiglaufter) <> 'EX') AND (bdtiplan = 1)) THEN
           bdtiporeg = 4;
        SUSPEND;
      END
END
^

/* Alter (VEF_SP_EXP_SPEDCONTRIBUICAO) */
ALTER PROCEDURE VEF_SP_EXP_SPEDCONTRIBUICAO(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIN DATE)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODBEM INTEGER,
NAT_BC_CRED VARCHAR(2),
IDENT_BEM_IMOB VARCHAR(2),
IND_ORIG_CRED INTEGER,
IND_UTIL_BEM_IMOB INTEGER,
MES_OPER_AQUIS VARCHAR(6),
VL_OPER_AQUIS NUMERIC(18,2),
VL_OPER_DEP NUMERIC(18,2),
PARC_OPER_NAO_BC_CRED NUMERIC(18,2),
VL_BC_CRED NUMERIC(18,2),
IND_NR_PARC INTEGER,
CST_PIS VARCHAR(2),
VL_BC_PIS NUMERIC(18,2),
ALIQ_PIS NUMERIC(18,4),
VL_PIS NUMERIC(18,2),
CST_COFINS VARCHAR(2),
VL_BC_COFINS NUMERIC(18,2),
ALIQ_COFINS NUMERIC(18,4),
VL_COFINS NUMERIC(18,2),
COD_CTA VARCHAR(255),
COD_PLAPADRAO INTEGER,
ANO INTEGER,
COD_CCUS VARCHAR(1000),
DESC_BEM_IMOB VARCHAR(300),
BDDATABAIXA DATE,
BDDATORIAQUIBEM DATE,
COD_CTA_REF VARCHAR(60),
COD_PLAPADRAOREF INTEGER,
NUMPARC INTEGER,
BDCODCCSPED INTEGER,
BDDEPDIARIA VARCHAR(5),
BDNUMDIAS INTEGER,
BDDEPDIADATA INTEGER,
BDDEPMESBAIXABEM VARCHAR(5),
BDCALCPATRIMONIO VARCHAR(5),
BDCTALON VARCHAR(40))
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSUBSELECT VARCHAR(30000);
DECLARE VARIABLE WVALORBASECALCATIVA NUMERIC(18,2);
DECLARE VARIABLE WDATAAUX VARCHAR(10);
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIN VARCHAR(10);
DECLARE VARIABLE WSEPARADOR VARCHAR(1);
DECLARE VARIABLE WTIPOAPROCRED INTEGER;
DECLARE VARIABLE WCOD_PLA_PADRAO_REF INTEGER;
DECLARE VARIABLE WCODNRPARC INTEGER;
BEGIN
  WDATAAUX = CAST(PRDATAINI AS VARCHAR(10));
  EXECUTE PROCEDURE sp_seta_competencia(CAST(SUBSTRING(WDATAAUX FROM 1 FOR 4) || SUBSTRING(WDATAAUX FROM 6 FOR 2) AS INTEGER));
  --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
  WSEPARADOR = '/';
  WDATAINI = SUBSTRING(WDATAAUX FROM 6 FOR 2) || WSEPARADOR || SUBSTRING(WDATAAUX FROM 9 FOR 2) || WSEPARADOR || SUBSTRING(WDATAAUX FROM 1 FOR 4);

  WDATAAUX = CAST(PRDATAFIN AS VARCHAR(10));
  WDATAFIN = SUBSTRING(WDATAAUX FROM 6 FOR 2) || WSEPARADOR || SUBSTRING(WDATAAUX FROM 9 FOR 2) || WSEPARADOR || SUBSTRING(WDATAAUX FROM 1 FOR 4);

  WSUBSELECT = ' select tbem.*, ';
  --Sol. 22905 - Pega a data da primeira e ultima parcela, para verificar se o bem est? no primeiro ou ?ltimo m?s, onde o c?lculo ? diferente
  WSUBSELECT = WSUBSELECT||   'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
  WSUBSELECT = WSUBSELECT||        'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT||        'else DATEADD(tbem.BDNUMPARC MONTH to tbem.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT||    'end)) BDDTFIM,';
  WSUBSELECT = WSUBSELECT||   'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
  WSUBSELECT = WSUBSELECT||        'WHEN ((BDDEPMESAQUIBEM = ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
  WSUBSELECT = WSUBSELECT||        'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT||    'end)) BDDTINI ';
  WSUBSELECT = WSUBSELECT||  ' from empresas_tbem tbem where ' || PRCODEMP;
  /*sol:15691 - deve trazer os registros sem data de baixa OU
               (se tiver baixa) todos que a baixa seja posterior ao periodo de apura??o OU
               (se a baixa for menor que a data final da apura??o) os registros em que o mes da baixa seja igual ao da apura??o E estiver parametrizado para depreciar no mes da baixa
  WSUBSELECT = WSUBSELECT || ' and ((tbem.bddatabaixa is null) or (tbem.bddatabaixa > ''' || WDATAFIN || ''')) ';*/
  WSUBSELECT = WSUBSELECT || ' and ((tbem.bddatabaixa is null) or ';
  WSUBSELECT = WSUBSELECT || '      (tbem.bddatabaixa > ''' || WDATAFIN || ''') or ';
  WSUBSELECT = WSUBSELECT || '      ((BDDEPMESBAIXABEM = '||'''TRUE'''||') and (EXTRACT(MONTH FROM tbem.bddatabaixa) = EXTRACT(MONTH FROM cast(''' || WDATAFIN || ''' as date))) and ';
  WSUBSELECT = WSUBSELECT || '       (tbem.bdtipoaprocred <> 0))) '; --sol:15691 - n?o levar no mes da baixa se for bdtipoaprocred = 0(10), que ? do F130
--sol:15691 - obedecer o parametro BDDEPMESAQUIBEM que diz se deve depreciar no mes da aquisi??o ou no pr?ximo
--WSUBSELECT = WSUBSELECT || ' and ((dateadd(tbem.bdnumparc - 1 month to tbem.bddatoriaquibem) >= ''' || WDATAINI || ''') and (tbem.bddatoriaquibem <= ''' || WDATAFIN || ''')) ';
  WSUBSELECT = WSUBSELECT || ' and (((case ';
  WSUBSELECT = WSUBSELECT || '          when ((BDDEPMESAQUIBEM = '||'''TRUE'''||') and (BDDEPDIARIA <> ''TRUE'')) or  (tbem.bdtipoaprocred = 0) then dateadd(TBEM.BDNUMPARC - 1 month to TBEM.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT || '          else dateadd(TBEM.BDNUMPARC - 1 + 1 month to TBEM.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT || '        end) >= ''' || WDATAINI || ''') ';
  WSUBSELECT = WSUBSELECT || ' and ((case ';
  WSUBSELECT = WSUBSELECT || '         when (BDDEPMESAQUIBEM = '||'''TRUE'''||') or (tbem.bdtipoaprocred = 0) then TBEM.BDDATORIAQUIBEM ';
  WSUBSELECT = WSUBSELECT || '         else dateadd(1 month to TBEM.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT || '       end) <= ''' || WDATAFIN || ''')) ';
  --sol:15653 - somente se cst for diferente de 70
  WSUBSELECT = WSUBSELECT || ' and (tbem.bdcodcstpis <> 70) and (tbem.bdcodcstcof <> 70) ';


 /* WSQL = 'SELECT FIRST 1 tbem.BDCODPLAPADRAOREF ';
  WSQL = WSQL || '  FROM TEMPRESAS_REF tbem ';
  WSQL = WSQL || '  WHERE tbem.BDCODPLAPADRAOREF IS NOT NULL AND ';
  WSQL = WSQL || '    '||PRCODEMP||' AND ';
  WSQL = WSQL || '    tbem.BDREFEMP <= cast(''' || CAST(EXTRACT(YEAR FROM PRDATAINI) AS VARCHAR(4) ) || '''|| substring(''0''||'''||CAST(EXTRACT(MONTH FROM PRDATAINI) AS VARCHAR(2))||''' from (char_length(''0''||'''||CAST(EXTRACT(MONTH FROM PRDATAINI) AS VARCHAR(2))||''')-1)) as integer)';
  WSQL = WSQL || '  ORDER BY tbem.BDREFEMP DESC';*/
/*  WSQL = 'Select BDCODPLAPADRAOREF FROM vw_tempresas_ref tbem where ' || PRCODEMP;*/

  /*Sol: 21960 Patrick T. S? 21/03/2018. Estava dando erro com o select acima porque o
    :PRCODEMP vinha com a matriz e filial, dando erro de multiple rows no into do select.
    Conforme visto com o Elizeu, deve pegar o plano da matriz*/
  wSQL =          'SELECT VW.BDCODPLAPADRAOREF ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ ';
  wSQL = :wSQL || '      FROM vw_tempresas_ref tbem ';
  wSQL = :wSQL || '      JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP) ';
  wSQL = :wSQL || '      WHERE '||:PRCODEMP;
  wSQL = :wSQL || '      GROUP BY BDCODMATRIZ ';
  wSQL = :wSQL || '     ) EMP ';
  wSQL = :wSQL || 'JOIN VW_TEMPRESAS_REF VW ON(VW.BDCODEMP = EMP.BDCODMATRIZ) ';

  EXECUTE STATEMENT WSQL INTO WCOD_PLA_PADRAO_REF;

  WSQL = ' select ';
  WSQL = WSQL || '     bem.bdcodemp, ';
  WSQL = WSQL || '     emp.bdcnpjemp, ';
  WSQL = WSQL || '     bem.bdcodbem, ';

  WSQL = WSQL || '     case bem.bdtipoaprocred ';
  WSQL = WSQL || '         when 0 then ''10'' ';
  WSQL = WSQL || '         when 1 then ''09'' ';
  WSQL = WSQL || '         when 2 then ''11'' ';
  WSQL = WSQL || '     end NAT_BC_CRED, ';

  WSQL = WSQL || '     case bem.bdcodtipbem ';
  WSQL = WSQL || '         when 0 then ''01'' ';
  WSQL = WSQL || '         when 1 then ''03'' ';
  WSQL = WSQL || '         when 2 then ''04'' ';
  WSQL = WSQL || '         when 3 then ''05'' ';
  WSQL = WSQL || '         when 4 then ''06'' ';
  WSQL = WSQL || '         when 5 then ''99'' ';
  WSQL = WSQL || '     end IDENT_BEM_IMOB, ';

  WSQL = WSQL || '     case ';
  WSQL = WSQL || '         when bem.bdcodpais = 30 then 0 ';
  WSQL = WSQL || '         when bem.bdcodpais <> 30 and bem.bdcodpais is not null then 1 ';
  WSQL = WSQL || '     end IND_ORIG_CRED, ';

  WSQL = WSQL || '     case bem.bdcodutilbem ';
  WSQL = WSQL || '         when 0 then 1 ';
  WSQL = WSQL || '         when 1 then 2 ';
  WSQL = WSQL || '         when 2 then 3 ';
  WSQL = WSQL || '         when 3 then 9 ';
  WSQL = WSQL || '     end IND_UTIL_BEM_IMOB, ';

  WSQL = WSQL || '     substring(''0''||cast(extract(month from bem.bddatoriaquibem) as varchar(2)) from (char_length(''0''||cast(extract(month from bem.bddatoriaquibem) as varchar(2)))-1))||cast(extract(year from bem.bddatoriaquibem) as varchar(4)) MES_OPER_AQUIS, ';

  WSQL = WSQL || '    case bem.bdtipoaprocred ';
  WSQL = WSQL || '         when 0 then bem.BDVALAQUIBEMORIGINAL '; -- 1 - Valor da aquisi??o
  WSQL = WSQL || '         else bem.bdvalaquibem ';
  WSQL = WSQL || '    end VL_OPER_AQUIS, ';
  
--WSQL = WSQL || '     bem.bdbasecalc VL_OPER_DEP, ';   
  --Sol. 22905 - Faz a proporcao para o primeiro e ultimo mes, que depender? dos par?metros do bem, antes era feito na aplica??o
  wSQL = wSQL||               'CASE WHEN (BDDEPDIARIA = ''TRUE'') THEN CASE WHEN ('||EXTRACT(YEAR FROM :PRDATAINI) || EXTRACT(MONTH FROM :PRDATAINI)||' = extract(year from BDDTINI) || extract(month from BDDTINI)) then cast(cast(BEM.BDBASECALC * (iif(BDNUMDIAS <= 1, 30, (select ULTDIA  from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) - iif((BDNUMDIAS <= 1) and ((extract(day from BDDTINI) ) > 30), 30, (extract(day from BDDTINI) ))) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) as numeric(15,2))';
  wSQL = wSQL||               '                                             WHEN ('||EXTRACT(YEAR FROM :PRDATAFIN) || EXTRACT(MONTH FROM :PRDATAFIN)||' = extract(year from BDDTFIM) || extract(month from BDDTFIM)) then cast(cast(BEM.BDBASECALC * (iif((BDNUMDIAS <= 1) and (extract(day from BDDTFIM) > 30), 30, extract(day from BDDTFIM) )) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTFIM), extract(year from BDDTFIM)))) as numeric(15,2))';
  wSQL = wSQL||               '                                             ELSE BEM.BDBASECALC ';
  wSQL = wSQL||               '                                        END ';
  wSQL = wSQL||               '     ELSE BEM.BDBASECALC ';
  wSQL = wSQL||               'END VL_OPER_DEP, ';

  WSQL = WSQL || '     bem.bdexcbase PARC_OPER_NAO_BC_CRED, ';
  WSQL = WSQL || '     bem.bdbasecalc VL_BC_CRED, ';

  WSQL = WSQL || '     case bem.bdcodnrparc ';
  WSQL = WSQL || '         when 0 then 1 ';
  WSQL = WSQL || '         when 1 then 2 ';
  WSQL = WSQL || '         when 2 then 3 ';
  WSQL = WSQL || '         when 3 then 4 ';
  WSQL = WSQL || '         when 4 then 5 ';
  WSQL = WSQL || '         when 5 then 9 ';
  WSQL = WSQL || '     end IND_NR_PARC, ';

  WSQL = WSQL || '     pis.bdcstpis CST_PIS, ';
  WSQL = WSQL || '     0 vl_bc_pis, ';
  WSQL = WSQL || '     coalesce(bem.bdaliqpis, 0) ALIQ_PIS, ';
  WSQL = WSQL || '     0 vl_pis, ';

  WSQL = WSQL || '     cof.bdcstcof CST_COFINS, ';
  WSQL = WSQL || '     0 vl_bc_cofins, ';
  WSQL = WSQL || '     coalesce(bem.bdaliqcofins, 0) ALIQ_COFINS, ';
  WSQL = WSQL || '     0 vl_cofins, ';
                                                    
  WSQL = WSQL || '     bem.bdcodtpla as COD_CTA, ';
  WSQL = WSQL || '     bem.bdcodplapadrao as COD_PLAPADRAO, ';
--alt22357 - ajuste para pegar a data da tela ao inves da data de aquisi??o do bem
  WSQL = WSQL || '     ' || CAST(EXTRACT(YEAR FROM PRDATAINI) AS INTEGER ) || ' as ANO, ';
--  WSQL = WSQL || '     coalesce(ccle.bdano, cast(extract(year from bem.bddatoriaquibem) as Integer)) 2017 as ANO, ';
  WSQL = WSQL || '     bem.bdcodtpcc COD_CCUS, ';
  WSQL = WSQL || '     bem.bdnombem DESC_BEM_IMOB, ';
  WSQL = WSQL || '     bem.bddatabaixa, ';
  WSQL = WSQL || '     bem.bddatoriaquibem, ';   
  WSQL = WSQL || '     (cclep.bdcodtplaref) COD_CTA_REF, ';
  WSQL = WSQL || '     (cclep.bdcodplapadraoref) COD_PLAPADRAOREF, ';

  WSQL = WSQL || '     case ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 0) then 1 ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 1) then 12 ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 2) then 24 ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 3) then 48 ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 4) then 6 ';
  WSQL = WSQL || '         else bem.bdnumparc ';
  WSQL = WSQL || '     end numparc, ';

  WSQL = WSQL || '     vefbem.bdcodccsped, ';
  WSQL = WSQL || '     bem.bdtipoaprocred, ';

  WSQL = WSQL || '     bem.BDDEPDIARIA, ';
  WSQL = WSQL || '     bem.BDNUMDIAS, ';
  WSQL = WSQL || '     bem.BDDEPDIADATA, ';
  WSQL = WSQL || '     bem.BDDEPMESBAIXABEM, ';
  WSQL = WSQL || '     CASE WHEN (exists (select dep.bdcodemp from EMPRESAS_TDEPRECIACAO dep where dep.bdcodemp = BEM.BDCODEMP and dep.bdcodbem = BEM.BDCODBEM)) THEN ''TRUE'' ELSE ''FALSE'' END bdcalcpatrimonio, ';
  WSQL = WSQL || '     bem.BDCODNRPARC, ';
  WSQL = WSQL || '     CCL.BDCTALON ';

  WSQL = WSQL || ' from (' || WSUBSELECT || ') bem ';
  WSQL = WSQL || ' join tempresas emp on emp.bdcodemp = bem.bdcodemp ';

  WSQL = WSQL || ' left outer join planos_tpla ccl on (bem.BDCODPLAPADRAO = ccl.bdcodplapadrao and bem.bdcodtpla = ccl.bdcodtpla)';
  WSQL = WSQL || ' left outer join PLANOS_TPLA_ECF ccle on (ccle.bdcodplapadrao = ccl.bdcodplapadrao and ccle.bdcodtpla = ccl.bdcodtpla and ccle.bdcodplapadraoref '||IIF((WCOD_PLA_PADRAO_REF IS NULL), ' IS NULL ', ' = ' || WCOD_PLA_PADRAO_REF)||' and ';
  WSQL = WSQL || '                    ccle.bdano = (SELECT FIRST 1 BDANO ';
  WSQL = WSQL || '                                  FROM  PLANOS_TPLA_ECF ';
  --alt22357 - ajuste para pegar a data da tela ao inves da data de aquisi??o do bem
  WSQL = WSQL || '                                  WHERE BDANO <= ' || CAST(EXTRACT(YEAR FROM PRDATAINI) AS INTEGER ) || ' AND ';
--  WSQL = WSQL || '                                  WHERE BDANO <= cast(extract(year from bem.bddatoriaquibem) as Integer) AND ';
  WSQL = WSQL || '                                    BDCODTPLAREF IS NOT NULL AND ';
  WSQL = WSQL || '                                    CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO AND ';
  WSQL = WSQL || '                                    CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND ';
  WSQL = WSQL || '                                    CCLE.BDCODTPLA = BDCODTPLA ';
  WSQL = WSQL || '                                  ORDER BY BDANO DESC)';
  WSQL = WSQL || '                                 ) ';
  WSQL = WSQL || ' left outer join vef_emp_tbem vefbem on ((vefbem.bdcodemp = bem.bdcodemp) and (vefbem.bdcodbem = bem.bdcodbem)) ';
  WSQL = WSQL || ' left outer join PLANOS_TPLA_ECF_PADRAO cclep on (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF and ccle.BDCODTPLAREF = cclep.BDCODTPLAREF)';
  WSQL = WSQL || ' left outer join vef_base_ttabcstpis pis on (pis.bdcodcstpis = bem.bdcodcstpis) ';
  WSQL = WSQL || ' left outer join vef_base_ttabcstcof cof on (cof.bdcodcstcof = bem.bdcodcstcof) ';

  FOR EXECUTE STATEMENT WSQL 
  INTO
    :BDCODEMP,
    :BDCNPJEMP,
    :BDCODBEM,
    :NAT_BC_CRED,
    :IDENT_BEM_IMOB,
    :IND_ORIG_CRED,
    :IND_UTIL_BEM_IMOB,
    :MES_OPER_AQUIS,
    :VL_OPER_AQUIS,
    :VL_OPER_DEP,
    :PARC_OPER_NAO_BC_CRED,
    :VL_BC_CRED,
    :IND_NR_PARC,
    :CST_PIS,
    :VL_BC_PIS,
    :ALIQ_PIS,
    :VL_PIS,
    :CST_COFINS,
    :VL_BC_COFINS,
    :ALIQ_COFINS,
    :VL_COFINS,
    :COD_CTA,
    :COD_PLAPADRAO,
    :ANO,
    :COD_CCUS,
    :DESC_BEM_IMOB,
    :BDDATABAIXA,
    :BDDATORIAQUIBEM,
    :COD_CTA_REF,
    :COD_PLAPADRAOREF,
    :NUMPARC,
    :BDCODCCSPED,
    :WTIPOAPROCRED,
    :BDDEPDIARIA,
    :BDNUMDIAS,
    :BDDEPDIADATA,
    :BDDEPMESBAIXABEM,
    :BDCALCPATRIMONIO,
    :wCODNRPARC,
    :BDCTALON
  DO
    BEGIN
      /*pega o valor do calculo de deprecia??o do ATIVA para o registro F120*/
      WSQL = 'select coalesce(PRDEPRECIACAOPERIODO, 0) PRDEPRECIACAOPERIODO from ';
      WSQL = WSQL || 'sp_cons_calc_dep(' || :BDCODEMP || ', ' || :BDCODBEM || ', ''' || :PRDATAINI || ''', ''' || :PRDATAFIN || ''', 0,0)';
      EXECUTE STATEMENT WSQL 
          INTO WVALORBASECALCATIVA;
  
      /*se for registro do F130*/
      IF (:NAT_BC_CRED = '10') THEN
        BEGIN
          IF (:wtipoaprocred <> 0) THEN
            BEGIN
              VL_BC_CRED = :VL_OPER_AQUIS - :PARC_OPER_NAO_BC_CRED;
              VL_BC_PIS = VL_BC_CRED;
              VL_BC_COFINS = VL_BC_CRED;
            END
        END
      ELSE
        BEGIN
          /*se for F120 verifica qual valor esta preenchido, bdbasecalc (cadbem) ou o calculo do ATIVA para a deprecia??o*/
          /*Sol. 22905 Gabriel Ariel (06/03/2018) - Estava levando o valor da depreciacao apenas quando fosse menor que o valor da base, o que n?o ? correto*/
          if (BDCALCPATRIMONIO = 'TRUE') then
            VL_OPER_DEP = WVALORBASECALCATIVA;

          IF (:VL_OPER_DEP = :WVALORBASECALCATIVA) THEN
            BDCALCPATRIMONIO = 'TRUE';
    
          /*exclus?o da base dividido pelo numero de parcelas*/
          PARC_OPER_NAO_BC_CRED = :PARC_OPER_NAO_BC_CRED / :NUMPARC;
    
          /*Base de calculo dividido pelo numero de parcelas menos a exclus?o da base*/
          VL_BC_CRED =(:VL_OPER_DEP / :NUMPARC) - :PARC_OPER_NAO_BC_CRED;
        END 
  
      /*Base de calc PIS e Cofins dividido pelo numero de parcelas (para ambos os registros F120, F130)*/
      VL_BC_PIS = :VL_BC_CRED / :NUMPARC;
      VL_BC_COFINS = /*:VL_BC_COFINS*/:VL_BC_CRED / :NUMPARC;
  
      IF ((wTIPOAPROCRED = 0) AND (wCODNRPARC = 4)) THEN -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
        BEGIN
          VL_PIS    = :VL_BC_PIS * :ALIQ_PIS;
          VL_COFINS = :VL_BC_COFINS * :ALIQ_COFINS;
        END
      ELSE
        BEGIN
      VL_PIS = :VL_BC_PIS * :ALIQ_PIS / 100;
      VL_COFINS = :VL_BC_COFINS * :ALIQ_COFINS / 100;
        END

      /*se o centro de custos da aba EFD PIS/Cofins estiver vazio pegar o CC da aba EFD Fiscal*/
      COD_CCUS = IIF(:COD_CCUS IS NOT NULL, :COD_CCUS, 'i' ||(:BDCODCCSPED + 1));
      SUSPEND;
    END
END
^

/* Alter (VEF_SP_EXP_TERCEIRO) */
ALTER PROCEDURE VEF_SP_EXP_TERCEIRO(PREMPRESA VARCHAR(2048),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER VARCHAR(10),
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2))
 AS
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WSQLTER VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQLCAD VARCHAR(10240);
BEGIN
    IF (pranomesfinal IS NOT NULL) THEN
        EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal,NULL,NULL);

    wsqlemp = 'select distinct(t.bdcodemp) ';
    wsqlemp = wsqlemp||' from tempresas t ';


  IF (:prempresa IS NOT NULL) THEN
     wsqlemp =   wsqlemp|| ' where ' || :prempresa;

    wsqlemp = wsqlemp||' order by t.bdcodemp asc ';

-- executa o sql das empresas
FOR EXECUTE STATEMENT wsqlemp
    INTO :bdcodemp  DO
  BEGIN

  wsqlter = '';
  wsqlter = wsqlter || ' select ENT.BDCODTER ';
  wsqlter = wsqlter || ' from vef_emp_tmovent ent ';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' ENT.bdcodTER = '||prcodter;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'ENT.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'ENT.BDREFLAN <= '||:pranomesfinal;

     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'ENT.BDCODEMP = '||:bdcodemp;

  IF (wwhere <> '') THEN
     wsqlter = wsqlter||' where '||wwhere;


-- inicio saidas.....................................

  wsqlter = wsqlter || ' union select SAI.BDCODTER ';
  wsqlter = wsqlter || ' from vef_emp_tmovsai sai ';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' SAI.bdcodTER = '||prcodter;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SAI.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SAI.BDREFLAN <= '||:pranomesfinal;

     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'SAI.BDCODEMP = '||:bdcodemp;

  IF (wwhere <> '') THEN
     wsqlter = wsqlter||' where '||wwhere;

-- inicio servicos.............................

  wsqlter = wsqlter || ' union select SER.BDCODTER ';
  wsqlter = wsqlter || ' from vef_emp_tmovser ser ';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' SER.bdcodTER = '||prcodter;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SER.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SER.BDREFLAN <= '||:pranomesfinal;

     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'SER.BDCODEMP = '||:bdcodemp;

  IF (wwhere <> '') THEN
     wsqlter = wsqlter||' where '||wwhere;

  FOR EXECUTE STATEMENT wsqlter
  INTO :BDCODTER DO

  BEGIN

    wsqlcad = '';
    wsqlcad = wsqlcad || ' select distinct ';
    wsqlcad = wsqlcad || ' TER.BDCODPLAPADRAO, ';
    wsqlcad = wsqlcad || ' TER.BDCODTPLA, ';
    wsqlcad = wsqlcad || ' TER.BDCGCTER, ';
    wsqlcad = wsqlcad || ' TER.BDREFEMP, ';
    wsqlcad = wsqlcad || ' TER.BDAPELIDOTER, ';
    wsqlcad = wsqlcad || ' TER.BDNOMETER, ';
    wsqlcad = wsqlcad || ' TER.BDLOGRTER, ';
    wsqlcad = wsqlcad || ' TER.BDENDTER, ';
    wsqlcad = wsqlcad || ' TER.BDNUMTER, ';
    wsqlcad = wsqlcad || ' TER.BDCOMPTER, ';
    wsqlcad = wsqlcad || ' TER.BDCEPTER, ';
    wsqlcad = wsqlcad || ' TER.BDBAITER, ';
    wsqlcad = wsqlcad || ' TER.BDDDDTER, ';
    wsqlcad = wsqlcad || ' TER.BDFONETER, ';
    wsqlcad = wsqlcad || ' TER.BDFAXTER, ';
    wsqlcad = wsqlcad || ' TER.BDEMAILTER, ';
    wsqlcad = wsqlcad || ' TER.BDIETER, ';
    wsqlcad = wsqlcad || ' TER.BDDATACADTER, ';
    wsqlcad = wsqlcad || ' TER.BDIMTER, ';
    wsqlcad = wsqlcad || ' TER.BDPRURALTER, ';
    wsqlcad = wsqlcad || ' TER.BDENQSIMPLESFEDTER, ';
    wsqlcad = wsqlcad || ' TER.BDINSCSUFRAMATER, ';
    wsqlcad = wsqlcad || ' TER.BDCODGPS, ';
    wsqlcad = wsqlcad || ' TER.BDCODCID, ';
    wsqlcad = wsqlcad || ' CID.bdnomcid, ';
    wsqlcad = wsqlcad || ' TER.BDCODPAIS, ';
    wsqlcad = wsqlcad || ' TER.BDDESCPAIS, ';
    wsqlcad = wsqlcad || ' TER.BDDDDFAXTER, ';
    wsqlcad = wsqlcad || ' CID.BDCODUF, ';
    wsqlcad = wsqlcad || ' UF.BDSIGLAUF ';
    wsqlcad = wsqlcad || ' from VW_TTERCEIRO ter ';
    wsqlcad = wsqlcad || ' left outer join tcidade CID';
    wsqlcad = wsqlcad || ' on (TER.BDCODCID = CID.bdCODCID)';
    wsqlcad = wsqlcad || ' left outer join tuf UF';
    wsqlcad = wsqlcad || ' on (CID.BDCODUF = UF.bdCODUF)';

    wwhere = '';
    wwhere = wwhere||'BDCODTER = '||:bdcodter;

    IF (wwhere <> '') THEN
       wsqlcad = wsqlcad||' where '||wwhere;

    FOR EXECUTE STATEMENT wsqlcad
    INTO
      :BDCODPLAPADRAO,
      :BDCODTPLA,
      :BDCGCTER,
      :BDREFEMP,
      :BDAPELIDOTER,
      :BDNOMETER,
      :BDLOGRTER,
      :BDENDTER,
      :BDNUMTER,
      :BDCOMPTER,
      :BDCEPTER,
      :BDBAITER,
      :BDDDDTER,
      :BDFONETER,
      :BDFAXTER,
      :BDEMAILTER,
      :BDIETER,
      :BDDATACADTER,
      :BDIMTER,
      :BDPRURALTER,
      :BDENQSIMPLESFEDTER,
      :BDINSCSUFRAMATER,
      :BDCODGPS,
      :BDCODCID,
      :bdnomcid,
      :BDCODPAIS,
      :bddescpais,
      :BDDDDFAXTER,
      :BDCODUF,
      :BDSIGLAUF
    DO
    SUSPEND;
  END

  END
END
^

/* Alter (VEF_SP_EXP_TNATOP) */
ALTER PROCEDURE VEF_SP_EXP_TNATOP(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255))
 AS
DECLARE VARIABLE wsqlnat VARCHAR(10240);
DECLARE VARIABLE wwhere VARCHAR(20000);
DECLARE VARIABLE wsqlcad VARCHAR(10240);
BEGIN


  IF (pranomesfinal IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal,NULL,NULL);


  -- naturezas usadas no movimento de ENTRADAS...

  wsqlnat = '';
  wsqlnat = wsqlnat || ' select t.bdcodemp, t.bdcodnat  ';
  wsqlnat = wsqlnat || ' from vef_emp_tmoventitens t, vef_emp_tmovent mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wsqlnat = wsqlnat||' where '||wwhere ;

  -- naturezas usadas no movimento de SAIDAS...

  wsqlnat = wsqlnat || ' union select t.bdcodemp, t.bdcodnat  ';
  wsqlnat = wsqlnat || ' from vef_emp_tmovsaiitens t, vef_emp_tmovsai mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wsqlnat = wsqlnat||' where '||wwhere ;

  -- naturezas usadas no movimento de SERVICOS...

  wsqlnat = wsqlnat || ' union select t.bdcodemp, t.bdcodnat  ';
  wsqlnat = wsqlnat || ' from vef_emp_tmovseritens t, vef_emp_tmovser mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wsqlnat = wsqlnat||' where '||wwhere ;


  FOR EXECUTE STATEMENT wsqlnat
  INTO :bdcodemp, :bdcodnat DO

  BEGIN

    wsqlcad = '';
    wsqlcad = wsqlcad || ' select  ';
    wsqlcad = wsqlcad || ' tnatop.bdnomenat ';
    wsqlcad = wsqlcad || ' from vef_base_tnatop tnatop';

    wwhere = '';

    wwhere = wwhere||'TNATOP.BDCODNAT = '||:bdcodnat;

    IF (wwhere <> '') THEN
       wsqlcad = wsqlcad||' where '||wwhere;

    FOR EXECUTE STATEMENT wsqlcad
    INTO
      :bdnomenat
    DO

    SUSPEND;


  END

END
^

/* Alter (VEF_SP_EXP_TPRODUTOS) */
ALTER PROCEDURE VEF_SP_EXP_TPRODUTOS(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255))
 AS
DECLARE VARIABLE WSQLPRO VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQLCAD VARCHAR(10240);
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WAUX INTEGER;
BEGIN


  IF (pranomesfinal IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal,NULL,NULL);

 wmes = CAST(SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 5) AS SMALLINT);
 wano = CAST(SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
 SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;

 wdataini = SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM 1 FOR 4);
 wdatafim = SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 5)||'/'||
             waux|| '/'||SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 1 FOR 4);



  -- produtos usados no movimento de ENTRADAS...

  wsqlpro = '';
  wsqlpro = wsqlpro || ' select t.bdcodemp, t.bdcodprod  ';
  wsqlpro = wsqlpro || ' from vef_emp_tmovproent t,  vef_emp_tmovent mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and (MOV.bdcodsitnf not in (2,3,4,5)) ';
  ELSE
    wwhere = wwhere||' (MOV.bdcodsitnf not in (2,3,4,5)) ';

  IF (wwhere <> '') THEN
     wsqlpro = wsqlpro||' where '||wwhere ;

  -- produtos usados no movimento de saidas...

  wsqlpro = wsqlpro || ' union select t.bdcodemp, t.bdcodprod  ';
  wsqlpro = wsqlpro || ' from vef_emp_tmovprosai t, vef_emp_tmovsai mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and (MOV.bdcodsitnf not in (2,3,4,5)) ';
  ELSE
    wwhere = wwhere||' (MOV.bdcodsitnf not in (2,3,4,5)) ';

  IF (wwhere <> '') THEN
     wsqlpro = wsqlpro||' where '||wwhere ;


  -- produtos usados no movimento de reducao z...

  wsqlpro = wsqlpro || ' union select t.bdcodemp, t.bdcodprod     ';
  wsqlpro = wsqlpro || ' from VW_VEF_EMP_TREDZ_EXP_SVA t  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere|| ' BDDATAREDZ between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wsqlpro = wsqlpro||' where '||wwhere ;


  FOR EXECUTE STATEMENT wsqlpro
  INTO :bdcodemp, :bdcodprod DO

  BEGIN

    wsqlcad = '';
    wsqlcad = wsqlcad || ' select  ';
    wsqlcad = wsqlcad || ' bddescprod ';
    wsqlcad = wsqlcad || ' from TCADPRO_VINC ';

    wwhere = '';

    wwhere = wwhere||'BDCODEMP = '||:bdcodemp;

    wwhere = wwhere||' AND bdcodprod = '||:bdcodprod;

    IF (wwhere <> '') THEN
       wsqlcad = wsqlcad||' where '||wwhere;

    FOR EXECUTE STATEMENT wsqlcad
    INTO
      :bdnomeprod
    DO

    SUSPEND;
  END
END
^

/* Alter (VEF_SP_LANCAMENTOS) */
ALTER PROCEDURE VEF_SP_LANCAMENTOS(PRREFMICRO INTEGER,
PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDPERCISS NUMERIC(15,6),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODPLANOONLINE INTEGER,
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDLANBCICMSISEOUT INTEGER,
BDALIQINSS NUMERIC(7,4))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';

  wSql = wsql || 'Tref.BDCODEMP, ';
  wSql = wsql || 'trefsis.BDPERCISS, ';
  wSql = wsql || 'trefsis.BDALIQINSS, ';
  wSql = wsql || 'trefsis.BDRETINSS, ';
  wSql = wsql || 'trefsis.BDVLRMININSS, ';
  wSql = wsql || 'Tref.BDCODPLANOONLINE, ';
  wSql = wsql || 'trefsis.BDLANPROENT, ';
  wSql = wsql || 'trefsis.BDLANPROSAI, ';
  wSql = wsql || 'trefsis.BDLANBCICMSISEOUT ';

  WPAR = 'from vw_tempresas_ref tref';

  wSql = wsql || wpar;

  wSql = wsql || ' left outer join vw_VEF_BASE_TEMPPARGER TREFSIS on (TREFSIS.bdcodemp = tref.bdcodemp) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' tref.bdcodemp = '||prcodemp;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By tref.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDPERCISS,
    :bdaliqinss,
    :BDRETINSS,
    :BDVLRMININSS,
    :BDCODPLANOONLINE,
    :BDLANPROENT,
    :BDLANPROSAI,
    :BDLANBCICMSISEOUT
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VEF_SP_RETORNA_DIME_Q47) */
ALTER PROCEDURE VEF_SP_RETORNA_DIME_Q47(PRCODEMP VARCHAR(2048),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSIMPLIFICADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDVALOR NUMERIC(15,2),
BDCODCIDTOT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WWHERE VARCHAR(10480);
DECLARE VARIABLE VTOTCIDREF NUMERIC(15,2);
DECLARE VARIABLE WREFAUX INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WCODEMPANT INTEGER;
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE WCODCIDANT INTEGER;
DECLARE VARIABLE WNOMCIDANT VARCHAR(40);
DECLARE VARIABLE WVALORANT NUMERIC(15,2);
BEGIN

  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);

  IF (prsimplificado  IS NULL OR prsimplificado = 0) THEN
    BEGIN



      wsql = 'select ent.BDCODEMP, ent.BDREFLAN, ter.BDCODCID, CID.BDNOMCID, sum(ent.BDVLRCONTAB) BDVLRCONTAB ';
      wsql = wsql||' from ( ';
      wsql = wsql||'       select ent.bdcodemp,ent.bdreflan,ent.bdcodter,ITENS.BDVLRCONTAB ';
      wsql = wsql||'       FROM ( ';
      wsql = wsql||'           select bdcodemp,bdchave,bdreflan,bdcodter ';
      wsql = wsql||'           from VEF_EMP_TMOVENT ';
      IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN --Alt.: #6420 n?o estava validando se prcodemp era dif. de vazio, quando gerava DIME de todas as empresas n?o funcionava
         wwhere = wwhere|| ' where ' || :PRCODEMP;

      IF (wwhere <> '') THEN
         wwhere = wwhere||' and (BDREFLAN between '||prrefini||' and '||prreffim||') ';
      ELSE
         wwhere = wwhere||' where (BDREFLAN between '||prrefini||' and '||prreffim||') ';
--          where BDCODEMP = 67 and (BDREFLAN between 201607 and 201607)
      wsql = wsql||'           ) ENT ';
      wsql = wsql||'       LEFT OUTER JOIN VEF_EMP_TMOVENTITENS ITENS ON ENT.BDCODEMP = ITENS.BDCODEMP AND ENT.BDCHAVE = ITENS.BDCHAVE ';
      wsql = wsql||'       where substring(itens.BDCODNAT from 1 for 4) in (1101, 1102, 1151, 1451, 1556, 1116, 1152) ';
      wsql = wsql||'     ) ent ';
      wsql = wsql||' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = ent.BDCODTER) ';
      wsql = wsql||' LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = TER.BDCODCID) ';
      wsql = wsql||' where TER.BDPRURALTER = ''TRUE'' and cid.bdcoduf = 24 ';
      wsql = wsql||' GROUP BY ENT.BDCODEMP, ENT.BDREFLAN, TER.BDCODCID, CID.BDNOMCID ';
      wsql = wsql||' order by BDCODEMP, BDREFLAN, BDCODCID  ';

      vtotcidref = 0;
      wrefant = 0;
      wrefaux = 0;
      wcodempaux = 0;
      FOR EXECUTE STATEMENT wsql
          INTO :bdcodemp, :bdref, : bdcodcid, :bdnomcid, :bdvalor  DO
          BEGIN

            IF ((wrefaux <> bdref AND wrefaux > 0) OR (wcodempaux <> bdcodemp AND wcodempaux > 0))  THEN
              BEGIN
                wcodempant = bdcodemp;
                wrefant = bdref;
                wcodcidant = BDCODCID;
                wnomcidant = bdnomcid;
                wvalorant = bdvalor;

                bdcodemp = wcodempaux;
                bdref = wrefaux;
                bdcodcid = NULL;
                bdcodcidtot = 99999;
                bdnomcid = 'TOTALIZADOR';
                bdvalor = vtotcidref;
                SUSPEND;

                vtotcidref = 0;
                bdcodemp = wcodempant;
                bdref = wrefant;
                bdcodcid = wcodcidant;
                bdnomcid = wnomcidant;
                bdvalor = wvalorant;
                bdcodcidtot = NULL;

              END

            bdcodcidtot = NULL;
            wrefaux = bdref;
            wcodempaux = bdcodemp;
            vtotcidref = vtotcidref + bdvalor;

            SUSPEND;

          END

      IF (vtotcidref > 0) THEN
          BEGIN
            bdcodemp = bdcodemp;
            bdref = wrefaux;
            bdcodcid = NULL;
            bdcodcidtot = 99999;
            bdnomcid = 'TOTALIZADOR';
            bdvalor = vtotcidref;
            SUSPEND;
            vtotcidref = 0;
          END

    END
END
^

/* Alter (VEF_SP_RETORNA_DIME_Q48) */
ALTER PROCEDURE VEF_SP_RETORNA_DIME_Q48(PRCODEMP VARCHAR(2048),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSIMPLIFICADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODCIDTOT INTEGER,
BDALIMPREP VARCHAR(5),
BDCODEXP VARCHAR(3),
BDCODATIVQ48 VARCHAR(3),
BDVALOR NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE VTOTCIDREF NUMERIC(15,2);
DECLARE VARIABLE WREFAUX INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WCODEMPANT INTEGER;
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE WCODCIDANT INTEGER;
DECLARE VARIABLE WNOMCIDANT VARCHAR(40);
DECLARE VARIABLE WVALORANT NUMERIC(15,2);
DECLARE VARIABLE WBDALIMPREPANT VARCHAR(5);
DECLARE VARIABLE WBDCODEXPANT VARCHAR(3);
DECLARE VARIABLE WBDCODATIVQ48ANT VARCHAR(3);
BEGIN


  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);

  IF (prsimplificado  IS NULL OR prsimplificado = 0) THEN
    BEGIN

       wsql = '        select SAID.BDCODEMP, SAID.BDREFLAN, SAID.BDCODCID, SAID.BDNOMCID, null BDCODCIDTOT, BDALIMPREP, BDCODEXP, BDCODATIVQ48, ';
       wsql = wsql||'               sum(SAID.BDVLRCONTAB) BDVLRCONTAB ';
       wsql = wsql||'        from ( ';
       wsql = wsql||'             select S.BDCODEMP, S.BDREFLAN, s.BDCODCID, s.BDNOMCID, s.BDCODUF,S.BDVLRCONTAB, ALIM.BDALIMPREP, ';
       wsql = wsql||'                     case ';
       wsql = wsql||'                       when ALIM.BDALIMPREP = ''TRUE''then ''008''';
       wsql = wsql||'                       else Q48.BDCODEXP ';
       wsql = wsql||'                     end BDCODEXP, ';
       wsql = wsql||'                     Q48.BDCODATIVQ48 ';
       wsql = wsql||'              from ( ';
       wsql = wsql||'                     select mov.BDCODEMP, mov.BDREFLAN, Coalesce(Q48.BDCODCID,mov.BDCODCID) BDCODCID, CID.BDNOMCID, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT,nat.BDCODATIVQ48, ';
       wsql = wsql||'                             sum(Coalesce(Q48.BDVLRTOTALLIQUIDO,ITENS.BDVLRCONTAB)) BDVLRCONTAB ';
        
       wsql = wsql||'                      from ( ';
       wsql = wsql||'                            select BDCODEMP, BDCHAVE, BDREFLAN, BDCODTER, BDCODCID ';
       wsql = wsql||'                            from VEF_EMP_TMOVSAI ';
       wsql = wsql||'where (bdcodsitnf not in (2,3,4,5)) and (BDREFLAN between '||prrefini||' and '||prreffim||') ';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          wsql = wsql||'and '||:prcodemp||'';
       wsql = wsql||'                            ) mov ';
       wsql = wsql||'                      join VEF_EMP_TMOVSAIITENS ITENS on (mov.BDCODEMP = ITENS.BDCODEMP and mov.BDCHAVE = ITENS.BDCHAVE) ';  
       wsql = wsql||'                      left outer join VEF_EMP_TMOVSAIQ48 Q48 on (Q48.BDCODEMP = ITENS.BDCODEMP AND Q48.BDCHAVE = ITENS.BDCHAVE AND Q48.BDORDEM = ITENS.BDORDEM) ';
       wsql = wsql||'                      left outer join VW_TTERCEIRO TER on (TER.BDCODTER = mov.BDCODTER) ';
       wsql = wsql||'                      join TCIDADE CID on (CID.BDCODCID = Coalesce(Q48.BDCODCID,mov.BDCODCID) AND BDCODUF = 24 /* estado de SC*/) ';
       wsql = wsql||'                      left outer join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = ITENS.BDCODNAT) ';
       wsql = wsql||'                      group by mov.BDCODEMP, mov.BDREFLAN,ITENS.BDCODNAT,ITENS.BDPREFIXONAT,CID.BDCODUF, BDCODCID, CID.BDNOMCID,nat.BDCODATIVQ48 ';
       wsql = wsql||'                   )s ';
       wsql = wsql||'              left outer join VEF_BASE_TTABATIVQ48 Q48 on (s.BDCODATIVQ48 = Q48.BDCODATIVQ48) ';
       wsql = wsql||'              left outer join VW_VEF_BASE_TEMPPARESTSC ALIM on (ALIM.BDCODEMP = S.BDCODEMP) ';
       wsql = wsql||'              ) SAID ';
       wsql = wsql||'        group by SAID.BDCODEMP, SAID.BDREFLAN, SAID.BDCODCID, SAID.BDNOMCID, SAID.BDCODEXP, SAID.BDALIMPREP, BDCODCIDTOT, BDALIMPREP, BDCODEXP, BDCODATIVQ48 ';


      vtotcidref = 0;
      wrefaux = 0;
      wrefant = 0;
      wcodempaux = 0;

      FOR EXECUTE STATEMENT wsql
      INTO
        bdcodemp,
        bdref,
        bdcodcid,
        bdnomcid,
        bdcodcidtot,
        bdalimprep,
        bdcodexp,
        bdcodativq48,
        bdvalor DO
      BEGIN

        IF ((wrefaux <> bdref AND wrefaux > 0) OR (wcodempaux <> bdcodemp AND wcodempaux > 0))  THEN
          BEGIN
            wcodempant = bdcodemp;
            wrefant = bdref;
            wcodcidant = BDCODCID;
            wnomcidant = bdnomcid;
            wvalorant = bdvalor;
            wBDALIMPREPant = bdalimprep;
            wBDCODEXPant   = bdcodexp;
            wBDCODATIVQ48ant = bdcodativq48;


            bdcodemp = wcodempaux;
            bdref = wrefaux;
            bdcodcid = NULL;
            bdcodcidtot = 99999;
            bdnomcid = 'TOTALIZADOR';
            bdvalor = vtotcidref;
            IF (bdvalor > 0) THEN
              SUSPEND;

            vtotcidref = 0;
            bdcodemp = wcodempant;
            bdref = wrefant;
            bdcodcid = wcodcidant;
            bdnomcid = wnomcidant;
            bdvalor = wvalorant;
            bdalimprep = wBDALIMPREPant;
            bdcodexp = wBDCODEXPant;
            bdcodativq48 = wBDCODATIVQ48ant;
            bdcodcidtot = NULL;

          END

        bdcodcidtot = NULL;
        wrefaux = bdref;
        wcodempaux = bdcodemp;
        IF (bdcodexp IS NOT NULL) THEN
          vtotcidref = vtotcidref + bdvalor;

        SUSPEND;
      END

      IF (vtotcidref > 0) THEN
          BEGIN
            bdcodexp = 999;
            bdcodemp = bdcodemp;
            bdref = wrefaux;
            bdcodcid = NULL;
            bdcodcidtot = 99999;
            bdnomcid = 'TOTALIZADOR';
            bdvalor = vtotcidref;
            SUSPEND;
            vtotcidref = 0;
          END



    END
END
^

/* Alter (VEF_SP_RETORNA_DIME_VENC_PRODEC) */
ALTER PROCEDURE VEF_SP_RETORNA_DIME_VENC_PRODEC(PRCODEMP INTEGER,
PRREF INTEGER)
 RETURNS(BDDATAVENC DATE)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WNRPARPRODEC INTEGER;
DECLARE VARIABLE WDIAVCTOEMPSC INTEGER;
DECLARE VARIABLE WCONTPRODEC VARCHAR(5);
DECLARE VARIABLE WDATA DATE;
BEGIN

/* giovanni */


  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  --select BDNRPARPRODEC, BDDIAVCTOEMPSC, BDCONTPRODEC from SP_CONSULTAEMPRESAS_SIS...
  wsql = 'select BDNRPARPRODEC, BDCONTPRODEC from SP_CONSULTAEMPRESAS_SIS('|| prref || ', '|| prcodemp || ', null) ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
      wnrparprodec,
      --wdiavctoempsc,
      wcontprodec

  DO
    BEGIN
     IF (wdiavctoempsc > 0) THEN
        BEGIN
         wdata = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2)||'-'||15||'-'||SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS DATE);
    
    
         IF ((UPPER(wcontprodec) = 'TRUE') OR (wnrparprodec > 0)) THEN
           BEGIN
              wdata = addmonth(wdata, wnrparprodec);
              bddatavenc = wdata;
           END
         ELSE
           BEGIN
              wdata = addmonth(wdata, 1);
              bddatavenc = wdata;
           END
    
          SUSPEND;
        END
    END
END
^

/* Alter (VEF_SP_RETORNA_TOTAIS_ENT) */
ALTER PROCEDURE VEF_SP_RETORNA_TOTAIS_ENT(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTOTALLANC INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRCSOCIAL NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
BEGIN


  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';

  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
/*
        wSqllanc =  'select count (BDCHAVE) BDTOTALLANC , SUM(BDVLRCONTAB) BDVLRCONTAB , SUM(BDBASEST) BDBASEST , SUM(BDVLRST) BDVLRST, ' ||
                    'SUM(BDVLRPIS) BDVLRPIS, SUM(BDBASEICMS) BDBASEICMS, SUM(BDVLRICMS) BDVLRICMS, SUM(BDISENTASICMS) BDISENTASICMS, SUM(BDOUTRASICMS), ' ||
                    'SUM(BDVLRCOFINS) BDVLRCOFINS, SUM(BDBASEIPI) BDBASEIPI, SUM(BDVLRIPI) BDVLRIPI, SUM(BDISENTASIPI) BDISENTASIPI, SUM(BDOUTRASIPI) BDOUTRASIPI, ' ||
                    'SUM(BDVLRCSOCIAL) BDVLRCSOCIAL  ' ||
                    'from VW_VEF_EMP_TMOVENT_E_ITENS LAN ' ||
                    ' where bdcodemp = ' || :bdcodemp;
*/
        wSqllanc =  'select count (BDCHAVE) BDTOTALLANC , SUM(BDVLRCONTAB) BDVLRCONTAB , SUM(BDBASEST) BDBASEST , SUM(BDVLRST) BDVLRST, ' ||
                    'SUM(BDVLRPIS) BDVLRPIS, SUM(BDBASEICMS) BDBASEICMS, SUM(BDVLRICMS) BDVLRICMS, SUM(BDISENTASICMS) BDISENTASICMS, SUM(BDOUTRASICMS), ' ||
                    'SUM(BDVLRCOFINS) BDVLRCOFINS, SUM(BDBASEIPI) BDBASEIPI, SUM(BDVLRIPI) BDVLRIPI, SUM(BDISENTASIPI) BDISENTASIPI, SUM(BDOUTRASIPI) BDOUTRASIPI, ' ||
                    'SUM(BDVLRCSOCIAL) BDVLRCSOCIAL  ' ||
                    'from VW_VEF_EMP_TMOVENT_E_ITENS ENT ' ||
                    ' where bdcodemp = ' || :bdcodemp;

        IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
           wsqllanc = wsqllanc ||' and (BDDATAENTRADAENT between '''||wdatini||''' and '''||wdatfin||''') ';

        IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
            wsqllanc = wsqllanc || ' and  ' || prwhere;

        FOR EXECUTE STATEMENT wsqllanc
           INTO  :BDTOTALLANC, :BDVLRCONTAB, :bdbasest, :bdvlrst, :bdvlrpis, :BDBASEICMS, :BDVLRICMS, :BDISENTASICMS, :BDOUTRASICMS, :BDVLRCOFINS, :BDBASEIPI,
                 :BDVLRIPI, :BDISENTASIPI, :BDOUTRASIPI, BDVLRCSOCIAL  DO
           BEGIN
             SUSPEND;
           END



      END

END
^

/* Alter (VEF_SP_RETORNA_TOTAIS_SAI) */
ALTER PROCEDURE VEF_SP_RETORNA_TOTAIS_SAI(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTOTALLANC INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRCSOCIAL NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
BEGIN


  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';

  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
/*
        wSqllanc =  'select count (BDCHAVE) BDTOTALLANC , SUM(BDVLRCONTAB) BDVLRCONTAB , SUM(BDBASEST) BDBASEST , SUM(BDVLRST) BDVLRST, ' ||
                    'SUM(BDVLRPIS) BDVLRPIS, SUM(BDBASEICMS) BDBASEICMS, SUM(BDVLRICMS) BDVLRICMS, SUM(BDISENTASICMS) BDISENTASICMS, SUM(BDOUTRASICMS), ' ||
                    'SUM(BDVLRCOFINS) BDVLRCOFINS, SUM(BDBASEIPI) BDBASEIPI, SUM(BDVLRIPI) BDVLRIPI, SUM(BDISENTASIPI) BDISENTASIPI, SUM(BDOUTRASIPI) BDOUTRASIPI, ' ||
                    'SUM(BDVLRCSOCIAL) BDVLRCSOCIAL  ' ||
                    'from VW_VEF_EMP_TMOVSAI_E_ITENS LAN ' ||
                    ' where bdcodemp = ' || :bdcodemp;
*/

         wsqllanc = 'select count (BDCHAVE) BDTOTALLANC , SUM(BDVLRCONTAB) BDVLRCONTAB , SUM(BDBASEST) BDBASEST , SUM(BDVLRST) BDVLRST, ' ||
                    'SUM(BDVLRPIS) BDVLRPIS, SUM(BDBASEICMS) BDBASEICMS, SUM(BDVLRICMS) BDVLRICMS, SUM(BDISENTASICMS) BDISENTASICMS, SUM(BDOUTRASICMS), ' ||
                    'SUM(BDVLRCOFINS) BDVLRCOFINS, SUM(BDBASEIPI) BDBASEIPI, SUM(BDVLRIPI) BDVLRIPI, SUM(BDISENTASIPI) BDISENTASIPI, SUM(BDOUTRASIPI) BDOUTRASIPI, ' ||
                    'SUM(BDVLRCSOCIAL) BDVLRCSOCIAL  ' ||
                    'from VW_VEF_EMP_TMOVSAI_E_ITENS SAI ' ||
                    ' where bdcodemp = ' || :bdcodemp;

        IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
           wsqllanc = wsqllanc ||' and (BDDATASAIDA between '''||wdatini||''' and '''||wdatfin||''') ';

        IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
            wsqllanc = wsqllanc || ' and  ' || prwhere;

        FOR EXECUTE STATEMENT wsqllanc
           INTO  :BDTOTALLANC, :BDVLRCONTAB, :bdbasest, :bdvlrst, :bdvlrpis, :BDBASEICMS, :BDVLRICMS, :BDISENTASICMS, :BDOUTRASICMS, :BDVLRCOFINS, :BDBASEIPI,
                 :BDVLRIPI, :BDISENTASIPI, :BDOUTRASIPI, BDVLRCSOCIAL  DO
           BEGIN
             SUSPEND;
           END



      END

END
^

/* Alter (VEF_SP_RETORNA_TOTAIS_SER) */
ALTER PROCEDURE VEF_SP_RETORNA_TOTAIS_SER(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTOTALLANC INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBCISSSER NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRISSSER NUMERIC(15,6),
BDISENTASISSSER NUMERIC(15,6),
BDOUTRASISSSER NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDBCIRSER NUMERIC(15,6),
BDVLRIRSER NUMERIC(15,6),
BDACREDEDUIRSER NUMERIC(15,6),
BDVLRCSOCIAL NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
BEGIN


  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';

  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
/*
        wSqllanc =  'select count (BDCHAVE) BDTOTALLANC , SUM(BDVLRCONTAB) BDVLRCONTAB , SUM(BDBCISSSER) BDBCISSSER , SUM(BDVLRPIS) BDVLRPIS ,' ||
                    'SUM(BDVLRISSSER) BDVLRISSSER,  SUM(BDISENTASISSSER) BDISENTASISSSER ,' ||
                    'SUM(BDOUTRASISSSER) BDOUTRASISSSER, SUM(BDVLRCOFINS) BDVLRCOFINS, ' ||
                    'SUM(BDBCIRSER) BDBCIRSER, SUM(BDVLRIRSER) BDVLRIRSER, SUM(BDACREDEDUIRSER) BDACREDEDUIRSER, ' ||
                    'SUM(BDVLRCSOCIAL) BDVLRCSOCIAL  ' ||
                    'from VW_VEF_EMP_TMOVSER_E_ITENS LAN ' ||
                    ' where bdcodemp = ' || :bdcodemp;
*/

        wSqllanc =  'select count (BDCHAVE) BDTOTALLANC , SUM(BDVLRCONTAB) BDVLRCONTAB , SUM(BDBCISSSER) BDBCISSSER , SUM(BDVLRPIS) BDVLRPIS ,' ||
                    'SUM(BDVLRISSSER) BDVLRISSSER,  SUM(BDISENTASISSSER) BDISENTASISSSER ,' ||
                    'SUM(BDOUTRASISSSER) BDOUTRASISSSER, SUM(BDVLRCOFINS) BDVLRCOFINS, ' ||
                    'SUM(BDBCIRSER) BDBCIRSER, SUM(BDVLRIRSER) BDVLRIRSER, SUM(BDACREDEDUIRSER) BDACREDEDUIRSER, ' ||
                    'SUM(BDVLRCSOCIAL) BDVLRCSOCIAL  ' ||
                    'from VW_VEF_EMP_TMOVSER_E_ITENS ser ' ||
                    ' where bdcodemp = ' || :bdcodemp;

        IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
           wsqllanc = wsqllanc ||' and (BDDATAEMISSAO between '''||wdatini||''' and '''||wdatfin||''') ';

        IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
            wsqllanc = wsqllanc || ' and  ' || prwhere;

        FOR EXECUTE STATEMENT wsqllanc
           INTO  :BDTOTALLANC,
                 :BDVLRCONTAB,
                 :BDBCISSSER,
                 :bdvlrpis,
                 :BDVLRISSSER,
                 :BDISENTASISSSER,
                 :BDOUTRASISSSER,
                 :BDVLRCOFINS,
                 :BDBCIRSER,
                 :BDVLRIRSER,
                 :BDACREDEDUIRSER,
                 :BDVLRCSOCIAL  DO
           BEGIN
             SUSPEND;
           END



      END

END
^

/* Alter (VEF_SP_RETVLRSTSP) */
ALTER PROCEDURE VEF_SP_RETVLRSTSP(PRCODEMP VARCHAR(30000),
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDVLRSTSAI NUMERIC(15,2),
BDVLRSTENT NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WEMP VARCHAR(30000);
BEGIN
  wemp = '';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> ''))  THEN
     wemp = ' and '||prcodemp;

   wSql = 'select m.bdcodemp, m.bdreflan, SUM(i.bdimpsubstituto) bdvlrstsai, SUM(0) bdvlrstent from vef_emp_tmovsai m, vef_emp_tmovsaiimpretsp i, vw_tterceiro t, tcidade c, tuf u'||
          ' where (m.bdcodemp = i.bdcodemp and m.bdchave = i.bdchave) and (m.bdcodsitnf not in (2,3,4,5)) and (bdimpsubstituto > 0) and (m.bdreflan = '||:prreferencia||')'|| --Sol. 18329 Gabriel Ariel (11/09/17) - Adicionada verifica??o para notas canceladas
          ' and (m.bdcodter = t.bdcodter and t.bdcodcid = c.bdcodcid and c.bdcoduf = u.bdcoduf and u.bdsiglauf = '||''''||'SP'||''''||') '||:wemp||
          ' group by m.bdcodemp, m.bdreflan'||
          ' union all '||
          ' select m.bdcodemp, m.bdreflan, SUM(0) bdvlrstsai, SUM(i.bdimpsubstituto) bdvlrstent from vef_emp_tmovent m, vef_emp_tmoventimpretsp i, vw_tterceiro t, tcidade c, tuf u'||
          ' where (m.bdcodemp = i.bdcodemp and m.bdchave = i.bdchave) and (bdimpsubstituto > 0) and (m.bdreflan = '||:prreferencia||')'||
          ' and (m.bdcodter = t.bdcodter and t.bdcodcid = c.bdcodcid and c.bdcoduf = u.bdcoduf and u.bdsiglauf = '||''''||'SP'||''''||') '||:wemp||
          ' group by m.bdcodemp, m.bdreflan';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFERENCIA,
    :BDVLRSTSAI,
    :BDVLRSTENT
  DO
  SUSPEND;

END
^

/* Alter (VEF_SP_SPED_LAN_ENT_PRO) */
ALTER PROCEDURE VEF_SP_SPED_LAN_ENT_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDAPEUNIMEDFAT VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN

    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

    wSql = ' select ';
    wSql = wSql || 'ENT.BDCODEMP ,';
    wSql = wSql || 'ENT.BDCHAVE ,';
    wSql = wSql || 'ENTITENS.BDORDEM ,';
    wSql = wSql || 'ENTPRO.BDORDEMPRO ,';
    wSql = wSql || 'ENTPRO.BDCODCTA ,';
    wSql = wSql || 'ENTPRO.BDCODPROD  ,';
    wSql = wSql || 'ENTPRO.BDCODCSTCOF  ,';
    wSql = wSql || 'ENTPRO.BDCODCSTICMS  ,';
    wSql = wSql || 'ENTPRO.BDCODCSTPIS  ,';
    wSql = wSql || 'ENTPRO.BDCODCSTIPI  ,';
    wSql = wSql || 'ENTPRO.BDMOVFISICO  ,';
    wSql = wSql || 'ENTPRO.BDQTDITEM  ,';
    wSql = wSql || 'ENTPRO.BDVLRITEM  ,';
    wSql = wSql || 'ENTPRO.BDVLRDESC  ,';
    wSql = wSql || 'ENTPRO.BDVLRDESPACESSORIA  ,';
    wSql = wSql || 'ENTPRO.BDREDBCICMS  ,';
    wSql = wSql || 'ENTPRO.BDBCICMS  ,';
    wSql = wSql || 'ENTPRO.BDBCPIS  ,';
    wSql = wSql || 'ENTPRO.BDBCST  ,';
    wSql = wSql || 'ENTPRO.BDBCIPI  ,';
    wSql = wSql || 'ENTPRO.BDBCCOFINS  ,';
    wSql = wSql || 'ENTPRO.BDBCISSQN  ,';
    wSql = wSql || 'ENTPRO.BDALIQICMS  ,';
    wSql = wSql || 'ENTPRO.BDALIQPIS  ,';
    wSql = wSql || 'ENTPRO.BDALIQST  ,';
    wSql = wSql || 'ENTPRO.BDALIQIPI  ,';
    wSql = wSql || 'ENTPRO.BDALIQCOFINS  ,';
    wSql = wSql || 'ENTPRO.BDALIQISSQN  ,';
    wSql = wSql || 'ENTPRO.BDVLRICMS  ,';
    wSql = wSql || 'ENTPRO.BDVLRPIS  ,';
    wSql = wSql || 'ENTPRO.BDVLRST   ,';
    wSql = wSql || 'ENTPRO.BDVLRIPI  ,';
    wSql = wSql || 'ENTPRO.BDVLRCOFINS  ,';
    wSql = wSql || 'ENTPRO.BDVLRISSQN  ,';
    wSql = wSql || 'PRO.BDDESCPROD, ';
    wSql = wSql || 'ENTPRO.BDCSTICMS, ';
    wSql = wSql || 'ENTPRO.BDCODEXPCSTIPI, ';
    wSql = wSql || 'ENTPRO.BDAPEUNIMEDFAT ';


    wSql = wsql || ' FROM vw_vef_emp_tmovent_pro_expnfp ENTPRO , vw_vef_emp_tmovent_itens ENTITENS , vw_vef_emp_tmovent ENT ,  tcadpro_VINC PRO ';

    wSql = wsql || ' where (ENTPRO.BDCODEMP = ENTITENS.BDCODEMP AND ENTPRO.bdchave = ENTITENS.BDCHAVE AND ENTPRO.bdordem = ENTITENS.BDORDEM) ';
    wsql = wsql || ' and (ENTITENS.BDCODEMP = ENT.BDCODEMP AND ENTITENS.BDCHAVE = ENT.BDCHAVE) ';
    wsql = wsql || ' and (ENTPRO.BDCODEMP = PRO.BDCODEMP AND ENTPRO.BDCODPROD = PRO.BDCODPROD)';


  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wwhere = wwhere || ' AND ENT.bdcodemp = '||prcodemp;

  IF (prwhereemp IS NOT NULL AND prwhereemp = '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereemp;
    END

  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'ENT.BDDATAENTRADAENT between '||''''||prdataini||''' and '||''''||prdatafim||'''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||wwhere;

  wSql = wsql || ' order By ENT.bdCODEMP,ENT.bdCHAVE, ENTITENS.BDORDEM, ENTPRO.BDORDEMPRO';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdchave,
    :BDORDEM,
    :BDORDEMPRO,
    :BDCODCTA ,
    :BDCODPROD ,
    :BDCODCSTCOF ,
    :BDCODCSTICMS ,
    :BDCODCSTPIS ,
    :BDCODCSTIPI ,
    :BDMOVFISICO ,
    :BDQTDITEM ,
    :BDVLRITEM ,
    :BDVLRDESC ,
    :BDVLRDESPACESSORIA ,
    :BDREDBCICMS ,
    :BDBCICMS ,
    :BDBCPIS ,
    :BDBCST ,
    :BDBCIPI ,
    :BDBCCOFINS ,
    :BDBCISSQN ,
    :BDALIQICMS ,
    :BDALIQPIS ,
    :BDALIQST ,
    :BDALIQIPI ,
    :BDALIQCOFINS ,
    :BDALIQISSQN ,
    :BDVLRICMS ,
    :BDVLRPIS ,
    :BDVLRST  ,
    :BDVLRIPI ,
    :BDVLRCOFINS ,
    :BDVLRISSQN ,
    :BDDESCPROD,
    :BDCSTICMS,
    :BDCODEXPCSTIPI,
    :BDAPEUNIMEDFAT

  DO
  BEGIN
   SUSPEND;
  END

END
^

/* Alter (VEF_SP_SPED_LAN_SAI_PRO) */
ALTER PROCEDURE VEF_SP_SPED_LAN_SAI_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDCODCLAENETEL INTEGER,
BDINDREC INTEGER,
BDCODCLAENETELGAS INTEGER,
BDINDRECGAS INTEGER,
BDCODSELOIPI INTEGER,
BDQTDSELOIPI INTEGER,
BDCODCLASSEIPI VARCHAR(5),
BDVLRUNIDADE NUMERIC(15,6),
BDQTDUNIDADE NUMERIC(15,6),
BDAPEUNIMEDFAT VARCHAR(5),
BDCODSAIDA VARCHAR(60))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN

    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

    wSql = ' select ';
    wSql = wSql || 'SAI.BDCODEMP ,';
    wSql = wSql || 'SAI.BDCHAVE ,';
    wSql = wSql || 'SAIITENS.BDORDEM ,';
    wSql = wSql || 'SAIPRO.BDORDEMPRO ,';
    wSql = wSql || 'SAIPRO.BDCODCTA ,';
    wSql = wSql || 'SAIPRO.BDCODPROD  ,';
    wSql = wSql || 'SAIPRO.BDCODCSTCOF  ,';
    wSql = wSql || 'SAIPRO.BDCODCSTICMS  ,';
    wSql = wSql || 'SAIPRO.BDCODCSTPIS  ,';
    wSql = wSql || 'SAIPRO.BDCODCSTIPI  ,';
    wSql = wSql || 'SAIPRO.BDMOVFISICO  ,';
    wSql = wSql || 'SAIPRO.BDQTDITEM  ,';
    wSql = wSql || 'SAIPRO.BDVLRITEM  ,';
    wSql = wSql || 'SAIPRO.BDVLRDESC  ,';
    wSql = wSql || 'SAIPRO.BDVLRDESPACESSORIA  ,';
    wSql = wSql || 'SAIPRO.BDREDBCICMS  ,';
    wSql = wSql || 'SAIPRO.BDBCICMS  ,';
    wSql = wSql || 'SAIPRO.BDBCPIS  ,';
    wSql = wSql || 'SAIPRO.BDBCST  ,';
    wSql = wSql || 'SAIPRO.BDBCIPI  ,';
    wSql = wSql || 'SAIPRO.BDBCCOFINS  ,';
    wSql = wSql || 'SAIPRO.BDBCISSQN  ,';
    wSql = wSql || 'SAIPRO.BDALIQICMS  ,';
    wSql = wSql || 'SAIPRO.BDALIQPIS  ,';
    wSql = wSql || 'SAIPRO.BDALIQST  ,';
    wSql = wSql || 'SAIPRO.BDALIQIPI  ,';
    wSql = wSql || 'SAIPRO.BDALIQCOFINS  ,';
    wSql = wSql || 'SAIPRO.BDALIQISSQN  ,';
    wSql = wSql || 'SAIPRO.BDVLRICMS  ,';
    wSql = wSql || 'SAIPRO.BDVLRPIS  ,';
    wSql = wSql || 'SAIPRO.BDVLRST   ,';
    wSql = wSql || 'SAIPRO.BDVLRIPI  ,';
    wSql = wSql || 'SAIPRO.BDVLRCOFINS  ,';
    wSql = wSql || 'SAIPRO.BDVLRISSQN  ,';
    wSql = wSql || 'PRO.BDDESCPROD, ';
    wSql = wSql || 'SAIPRO.BDCSTICMS, ';
    wSql = wSql || 'SAIPRO.BDCODEXPCSTIPI , ';

    wSql = wSql || 'SAIPRO.BDCODCLAENETEL  ,';
    wSql = wSql || 'SAIPRO.BDINDREC  ,';
    wSql = wSql || 'SAIPRO.BDCODCLAENETELGAS  ,';
    wSql = wSql || 'SAIPRO.BDINDRECGAS, ';

    wSql = wSql || 'SAIPRO.BDCODSELOIPI, ';
    wSql = wSql || 'SAIPRO.BDQTDSELOIPI, ';
    wSql = wSql || 'SAIPRO.BDCODCLASSEIPI, ';
    wSql = wSql || 'SAIPRO.BDVLRUNIDADE, ';
    wSql = wSql || 'SAIPRO.BDQTDUNIDADE, ';

--    wSql = wSql || 'SAIPRO.bdapeunimed, ';
    wSql = wSql || 'SAIPRO.BDAPEUNIMEDFAT, ';
    wSql = wSql || 'PRO.BDCODSAIDA ';


    wSql = wsql || ' FROM vw_vef_emp_tmovsai SAI , vw_vef_emp_tmovsai_itens SAIITENS, VW_VEF_EMP_TMOVSAI_PRO_EXPNFP SAIPRO , tcadpro_VINC PRO ';

    wSql = wsql || ' where (SAIPRO.BDCODEMP = PRO.BDCODEMP AND SAIPRO.BDCODPROD = PRO.BDCODPROD) AND (SAI.BDCODEMP = SAIITENS.BDCODEMP AND SAI.BDCHAVE = SAIITENS.BDCHAVE) ';
    wsql = wsql || ' and (SAI.BDCODEMP = SAIPRO.BDCODEMP AND SAI.BDCHAVE = SAIPRO.bdchave AND SAIITENS.BDORDEM = SAIPRO.bdordem)';

  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wwhere = wwhere || ' AND SAI.bdcodemp = '||prcodemp;

  IF (prwhereemp IS NOT NULL AND prwhereemp = '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereemp;
    END

  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SAI.BDDATAEMISSAO between '||''''||prdataini||''' and '||''''||prdatafim||'''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||wwhere;

  wSql = wsql || ' order By SAI.bdCODEMP,SAI.bdCHAVE, SAIITENS.BDORDEM, SAIPRO.BDORDEMPRO';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdchave,
    :BDORDEM,
    :BDORDEMPRO,
    :BDCODCTA ,
    :BDCODPROD ,
    :BDCODCSTCOF ,
    :BDCODCSTICMS ,
    :BDCODCSTPIS ,
    :BDCODCSTIPI ,
    :BDMOVFISICO ,
    :BDQTDITEM ,
    :BDVLRITEM ,
    :BDVLRDESC ,
    :BDVLRDESPACESSORIA ,
    :BDREDBCICMS ,
    :BDBCICMS ,
    :BDBCPIS ,
    :BDBCST ,
    :BDBCIPI ,
    :BDBCCOFINS ,
    :BDBCISSQN ,
    :BDALIQICMS ,
    :BDALIQPIS ,
    :BDALIQST ,
    :BDALIQIPI ,
    :BDALIQCOFINS ,
    :BDALIQISSQN ,
    :BDVLRICMS ,
    :BDVLRPIS ,
    :BDVLRST  ,
    :BDVLRIPI ,
    :BDVLRCOFINS ,
    :BDVLRISSQN ,
    :BDDESCPROD,
    :BDCSTICMS,
    :BDCODEXPCSTIPI,

    :BDCODCLAENETEL ,
    :BDINDREC       ,
    :BDCODCLAENETELGAS ,
    :BDINDRECGAS,

    :BDCODSELOIPI,
    :BDQTDSELOIPI,
    :BDCODCLASSEIPI,
    :BDVLRUNIDADE,
    :BDQTDUNIDADE,
--    :bdapeunimed,
    :BDAPEUNIMEDFAT,
    :BDCODSAIDA


  DO
  BEGIN
   SUSPEND;
  END

END
^

/* Alter (VEF_SP_SVA_431) */
ALTER PROCEDURE VEF_SP_SVA_431(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDMODELOAUX VARCHAR(15),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDVLRFRETEC100 NUMERIC(15,6),
BDVLRSEGUROC100 NUMERIC(15,6),
BDVLROUTDESPC100 NUMERIC(15,6),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDVLRIR NUMERIC(15,2),
BDINSSRET NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDORDEMPRO INTEGER,
BDTIPOREG VARCHAR(10),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
BDBINSSRET NUMERIC(15,2),
BDRETVAZIO VARCHAR(1),
BDVLRCONTAB2 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

 IF (UPPER(PRENTRADA) = 'TRUE') THEN
    BEGIN

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.BDMODELOSTR, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,
         coalesce(RET.bdvlrpis,0.0) BDVLRPIS,
         coalesce(RET.bdvlrcofins,0.0) BDVLRCOFINS,
         coalesce(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL,
         coalesce(0,0.0)  BDVLRIR,
         coalesce(0,0.0)  BDINSSRET ,
         ter.bdcgcter,

         sum(pro.BDVLRITEM) BDVLRITEMPRO, sum(pro.BDVLRDESC) BDVLRDESCPRO, sum(pro.bdvlripi) bdvlripipro,
         sum(pro.bdvlricms) bdvlricmspro, sum(C100.bdvlrfrete) bdvlrfretec100, sum(C100.bdvlrseguro) bdvlrseguroc100, sum(C100.bdvlroutdesp) bdvlroutdespc100';

  wsql = wsql || ' from VW_VEF_EMP_TMOVENT_EXP_SVA T';

  wsql = wsql || ' left outer join vef_emp_tmovproENT pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';

  wsql = wsql || ' left outer join vef_emp_tc100ENT C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';

  /*wsql = wsql || ' left outer join VEF_EMP_TMOVENTRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave and ret.bdordem = t.bdordem) ';*/
  wsql = wsql || ' left outer join VEF_EMP_TMOVENTRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave) ';

  wsql = wsql || ' left outer join TTERCEIRO ter on (ter.bdcodter = t.bdcodter) ';



  wwhere = ' where bdemitente = 0 ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere || ' group by t.BDCODEMP,  t.BDCHAVE,  t.BDREFLAN, t.bdtipomov, t.BDMODELO, t.BDMODELOSTR, t.BDSERIE,
                           BDNUMDOCINI, BDDATAEMISSAO, BDDATAENTSAI, t.BDCODTER,
                           BDESPECIE, BDEMITENTE, BDCODSITNF, BDCIFFOB, t.bdordem,
                           BDVLRCONTAB, BDBASEICMS, BDBASEIPI, BDBASEST, BDISENTASICMS, BDISENTASIPI, BDOUTRASICMS,
                           BDOUTRASIPI, BDVLRICMS, BDVLRIPI, BDVLRST, BDIMPEXCLUIDAS, BDOUTROSIMP, BDDESCONTO,
                           BDICMSRETENTSAI, bdcondpgto, bdvlrpis, bdvlrcofins, bdvlrcsocial, BDVLRIR, BDINSSRET,bdcgcter ' ;

--  wsql = wsql || ' order by t.bdcodemp, t.bdreflan, t.bdtipomov ';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    bdmodelostr, 
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,
    BDVLRIR,
    BDINSSRET,
    bdcgcter,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100
  DO
  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
          bdvlrcsocial = 0;
          BDVLRIR = 0;
          BDINSSRET = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
       END

     bdtiporeg = '4_3_1';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
       bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (bdmodelo IN (7,8)) THEN
       bdmodeloaux = 'RODOVIARIO';
    ELSE
    IF (bdmodelo = 9) THEN
       bdmodeloaux = 'AQUAVIARIO';
    ELSE
    IF (bdmodelo = 10) THEN
       bdmodeloaux = 'AEREO';
    ELSE
    IF (bdmodelo = 11) THEN
       bdmodeloaux = 'FERROVIARIO';
    ELSE
       bdmodeloaux = ' ';


    IF (bdvlrcontab <> 0) THEN
      BEGIN
        bdaliqpis = (bdvlrpis * 100) / bdvlrcontab;
        bdaliqcofins = (bdvlrcofins * 100) / bdvlrcontab;
        bdaliqir = (bdvlrir * 100) / bdvlrcontab;
        bdaliqcsocial = (bdvlrcsocial * 100) / bdvlrcontab;
      END
    ELSE
      BEGIN
        bdaliqpis = 0;
        bdaliqcofins = 0;
        bdaliqir = 0;
        bdaliqcsocial = 0;

      END

    IF (bdinssret <> 0) THEN
       bdbinssret = bdvlrcontab;
    ELSE
       bdbinssret = 0;

    IF (BDVLRITEMPRO IS NULL) THEN
       BDVLRITEMPRO = 0;
    IF (BDVLRDESC IS NULL) THEN
       BDVLRDESC = 0;
    IF (bdvlrfretec100 IS NULL) THEN
       bdvlrfretec100 = 0;
    IF (bdvlrseguroc100 IS NULL) THEN
       bdvlrseguroc100 = 0;
    IF (bdvlroutdespc100 IS NULL) THEN
       bdvlroutdespc100 = 0;
    IF (bdvlripipro IS NULL) THEN
       bdvlripipro = 0;
    IF (BDVLRST IS NULL) THEN
       BDVLRST = 0;
    BDVLRCONTAB2 = (BDVLRITEMPRO + BDVLRDESC + bdvlrfretec100 + bdvlrseguroc100 + bdvlroutdespc100 + bdvlripipro + BDVLRST);

    SUSPEND;
  END

    END

 IF (UPPER(PRSAIDA) = 'TRUE') THEN
    BEGIN

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.bdmodelostr, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,
         coalesce(RET.bdvlrpis,0.0) BDVLRPIS,
         coalesce(RET.bdvlrcofins,0.0) BDVLRCOFINS,
         coalesce(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL,
         coalesce(RET.BDVLRIR,0.0) BDVLRIR,
         coalesce(RET.BDINSSRET,0.0) BDINSSRET,
         ter.bdcgcter,

         sum(pro.BDVLRITEM) BDVLRITEMPRO, sum(pro.BDVLRDESC) BDVLRDESCPRO, sum(pro.bdvlripi) bdvlripipro,
         sum(pro.bdvlricms) bdvlricmspro, sum(C100.bdvlrfrete) bdvlrfretec100, sum(C100.bdvlrseguro) bdvlrseguroc100, sum(C100.bdvlroutdesp) bdvlroutdespc100 ';


  wsql = wsql || ' from VW_VEF_EMP_TMOVSAI_EXP_SVA T';

  wsql = wsql || ' left outer join vef_emp_tmovprosai pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';

  wsql = wsql || ' left outer join vef_emp_tc100SAI C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';

  /*wsql = wsql || ' left outer join VEF_EMP_TMOVSAIRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave and ret.bdordem = t.bdordem) ';*/
  wsql = wsql || ' left outer join VEF_EMP_TMOVSAIRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave) ';

  wsql = wsql || ' left outer join TTERCEIRO ter on (ter.bdcodter = t.bdcodter) ';


  wwhere = ' where bdemitente = 0 ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere || ' group by t.BDCODEMP,  t.BDCHAVE,  t.BDREFLAN, t.bdtipomov, t.BDMODELO, t.bdmodelostr, t.BDSERIE,
                           BDNUMDOCINI, BDDATAEMISSAO, BDDATAENTSAI, t.BDCODTER,
                           BDESPECIE, BDEMITENTE, BDCODSITNF, BDCIFFOB, t.bdordem,
                           BDVLRCONTAB, BDBASEICMS, BDBASEIPI, BDBASEST, BDISENTASICMS, BDISENTASIPI, BDOUTRASICMS,
                           BDOUTRASIPI, BDVLRICMS, BDVLRIPI, BDVLRST, BDIMPEXCLUIDAS, BDOUTROSIMP, BDDESCONTO,
                           BDICMSRETENTSAI, bdcondpgto , bdvlrpis, bdvlrcofins, bdvlrcsocial ,BDVLRIR, BDINSSRET, bdcgcter ' ;
                                   

--  wsql = wsql || ' order by t.bdcodemp, t.bdreflan, t.bdtipomov ';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    bdmodelostr, 
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,
    BDVLRIR,
    BDINSSRET,
    bdcgcter,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100
  DO
  BEGIN

     IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
          bdvlrcsocial = 0;
          BDVLRIR = 0;
          BDINSSRET = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
       END


     bdtiporeg = '4_3_1';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (bdmodelo IN (7,8)) THEN
       bdmodeloaux = 'RODOVIARIO';
    ELSE
    IF (bdmodelo = 9) THEN
       bdmodeloaux = 'AQUAVIARIO';
    ELSE
    IF (bdmodelo = 10) THEN
       bdmodeloaux = 'AEREO';
    ELSE
    IF (bdmodelo = 11) THEN
       bdmodeloaux = 'FERROVIARIO';
    ELSE
       bdmodeloaux = ' ';


    IF (bdvlrcontab <> 0) THEN
      BEGIN
        bdaliqpis = (bdvlrpis * 100) / bdvlrcontab;
        bdaliqcofins = (bdvlrcofins * 100) / bdvlrcontab;
        bdaliqir = (bdvlrir * 100) / bdvlrcontab;
        bdaliqcsocial = (bdvlrcsocial * 100) / bdvlrcontab;
      END
    ELSE
      BEGIN
        bdaliqpis = 0;
        bdaliqcofins = 0;
        bdaliqir = 0;
        bdaliqcsocial = 0;

      END

    IF (bdinssret <> 0) THEN
       bdbinssret = bdvlrcontab;
    ELSE
       bdbinssret = 0;

    IF (BDVLRITEMPRO IS NULL) THEN
       BDVLRITEMPRO = 0;
    IF (BDVLRDESC IS NULL) THEN
       BDVLRDESC = 0;
    IF (bdvlrfretec100 IS NULL) THEN
       bdvlrfretec100 = 0;
    IF (bdvlrseguroc100 IS NULL) THEN
       bdvlrseguroc100 = 0;
    IF (bdvlroutdespc100 IS NULL) THEN
       bdvlroutdespc100 = 0;
    IF (bdvlripipro IS NULL) THEN
       bdvlripipro = 0;
    IF (BDVLRST IS NULL) THEN
       BDVLRST = 0;
    BDVLRCONTAB2 = (BDVLRITEMPRO + BDVLRDESC + bdvlrfretec100 + bdvlrseguroc100 + bdvlroutdespc100 + bdvlripipro + BDVLRST);

    SUSPEND;
  END

    END

END
^

/* Alter (VEF_SP_SVA_4310_TREDZ) */
ALTER PROCEDURE VEF_SP_SVA_4310_TREDZ(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAREDZ DATE,
BDCODPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDALIQICMS NUMERIC(15,2),
BDCAMPO8 NUMERIC(15,2),
BDVLRTOTPRO NUMERIC(15,2),
BDALIQPIS NUMERIC(15,4),
BDVLRPIS NUMERIC(15,2),
BDALIQCOFINS NUMERIC(15,4),
BDVLRCOFINS NUMERIC(15,2),
BDNCMPROD INTEGER,
BDTIPOREG VARCHAR(10))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
BEGIN
  /* Procedure Text */

  /* giovanni ultimo dia...*/

 EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

 wmes = CAST(SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 5) AS SMALLINT);
 wano = CAST(SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
 SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;

 wdataini = SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM 1 FOR 4);
 wdatafim = SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 5)||'/'||
             waux|| '/'||SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 1 FOR 4);

 wsql = ' select t.BDCODEMP, t.BDDATAREDZ, t.BDCODPROD, CADPRO.bdncmprod, t.BDQTDITEM, t.BDALIQICMS, t.bdvlrtotpro  ';

 wsql = wsql || ' from VW_VEF_EMP_TREDZ_EXP_SVA T,  tcadpro_VINC CADPRO ';


 wwhere = '';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || :prempresa;

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere|| ' (CADPRO.BDCODEMP = T.BDCODEMP AND cadpro.bdcodprod = t.bdcodprod) ';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere|| ' BDDATAREDZ between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

     END


  IF (wwhere <> TRIM('')) THEN
     wsql = wsql||' where ' || wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDDATAREDZ,
    BDCODPROD,
    bdncmprod,
    BDQTDITEM,
    BDALIQICMS,
    bdvlrtotpro
  DO

  BEGIN
    IF ((bdvlrtotpro > 0) AND (bdaliqicms > 0)) THEN
       bdcampo8 = bdvlrtotpro * bdaliqicms / 100;
    ELSE
       bdcampo8 = 0;

    bdreflan = EXTRACT(YEAR FROM bddataredz)||SUBSTRING(bddataredz FROM 6 FOR 2);
    bdtiporeg = '4_3_10';

    bdaliqpis = 0.65;

    bdvlrpis =  bdvlrtotpro * bdaliqpis / 100;

    bdaliqcofins = 3;

    bdvlrcofins = bdvlrtotpro * bdaliqcofins / 100;

    SUSPEND;
  END
END
^

/* Alter (VEF_SP_SVA_432) */
ALTER PROCEDURE VEF_SP_SVA_432(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5),
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(3),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCSTPIS VARCHAR(3),
BDCSTCOF VARCHAR(3),
BDVLRUNITARIO NUMERIC(15,4),
BDVLRCOFINSEXP NUMERIC(15,2),
BDVLRCOFINSTRIBINT NUMERIC(15,2),
BDVLRCOFINSNTRIBINT NUMERIC(15,2),
BDVLRPISEXP NUMERIC(15,2),
BDVLRPISTRIBINT NUMERIC(15,2),
BDVLRPISNTRIBINT NUMERIC(15,2),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
DECLARE VARIABLE WLANBCICMSISEOUT INTEGER;
DECLARE VARIABLE WCODNATAUX CHAR(1);
DECLARE VARIABLE WCSTIPI VARCHAR(2);
DECLARE VARIABLE WCSTIPIAUX VARCHAR(1);
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

 BDPRODFRETE = 'FALSE';
 BDPRODENERGIA  = 'FALSE';
 BDPRODAGUA  = 'FALSE';
 BDPRODTELECOM  = 'FALSE';
 BDPRODGENERICO  = 'FALSE';

 IF (UPPER(PRENTRADA) = 'TRUE') THEN
    BEGIN

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.bdmodelostr, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,

         pro.BDVLRITEM BDVLRITEMPRO, pro.BDVLRDESC BDVLRDESCPRO, pro.bdvlripi bdvlripipro, pro.bdvlricms bdvlricmspro,
         c100.bdvlrfrete, c100.bdvlrseguro, c100.bdvlroutdesp,

         pro.bdordempro , pro.BDCODPROD, CADPRO.BDDESCPROD, bdcodnat, BDNCMPROD, BDQTDITEM, BDAPEUNIMED, pro.BDALIQIPI, BDBCIPI,
         CSTICMS.BDCSTICMS, pro.BDALIQICMS, BDBCICMS, bdbcst, pro.BDVLRST BDVLRSTMOVPRO, bdmovfisico, CSTIPI.BDCODEXPCSTIPI,
         pro.BDCODCSTPIS, pro.BDALIQPIS, BDBCPIS, BDVLRPIS, pro.BDCODCSTCOF , BDALIQCOFINS , BDBCCOFINS, BDVLRCOFINS, pis.bdcstpis, cof.bdcstcof ';

  wsql = wsql || ' from VW_VEF_EMP_TMOVENT_EXP_SVA T';
  wsql = wsql || ' left outer join vef_emp_tmovproENT pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTIPI CSTIPI ON ( PRO.bdcodcstipi = CSTIPI.bdcodcstipi) ';
  wsql = wsql || ' left outer join vef_emp_tc100ENT C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';
  wsql = wsql || ' left outer join TCADPRO_VINC CADPRO on (CADPRO.BDCODEMP = PRO.BDCODEMP AND cadpro.bdcodprod = pro.bdcodprod)';
  wsql = wsql || ' left outer join tunidademedida UM on (UM.bdcodunimed = CADPRO.bdcodunimed) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTPIS pis on (pis.BDCODCSTPIS = pro.BDCODCSTPIS) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTCOF cof on (cof.BDCODCSTCOF = pro.BDCODCSTCOF) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTICMS CSTICMS ON ( PRO.bdcodcstICMS = CSTICMS.bdcodcstICMS) ';

  wwhere = ' where bdemitente = 0 and bdordempro is not null ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere; --|| ' order by bdcodemp, bdreflan, bdtipomov  ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    BDMODELOSTR,
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100,
    bdordempro,
    bdcodprod,
    BDDESCPROD,
    bdcodnat,
    BDNCMPROD,
    BDQTDITEM,
    BDAPEUNIMED,
    bdaliqipipro,
    bdbcipipro,
    BDCODCSTICMS,
    bdaliqicmspro,
    bdbcicmspro,
    bdbcstpro,
    bdvlrstmovpro,
    bdmovfisico,
    BDCODEXPCSTIPI,
    BDCODCSTPIS,
    BDALIQPIS,
    BDBCPIS,
    BDVLRPIS,
    BDCODCSTCOF ,
    BDALIQCOFINS ,
    BDBCCOFINS,
    BDVLRCOFINS,
    bdcstpis,
    bdcstcof

  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
          BDQTDITEM = 0;
          bdaliqipipro = 0;
          bdbcipipro = 0;
          bdaliqicmspro = 0;
          bdbcicmspro = 0;
          bdbcstpro = 0;
          bdvlrstmovpro = 0;
          BDALIQPIS = 0;
          BDBCPIS = 0;
          BDVLRPIS = 0;
          BDALIQCOFINS  = 0;
          BDBCCOFINS = 0;
          BDVLRCOFINS = 0;
       END

    IF (UPPER(bdmovfisico) = 'TRUE') THEN
       bdmovfisico = 'S';
    ELSE
       bdmovfisico = 'N';

    IF (bdqtditem > 0)  THEN
       bdvlrunitario = bdvlritempro / bdqtditem;

    bdtiporeg = '4_3_2';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

--    if (wlanbcicmsiseout is null) then
--      begin
--        wsqlaux = 'select bdlanbcicmsiseout from VW_VEF_BASE_TEMPPARGER where bdcodemp = ' || :bdcodemp;
--        execute statement wsqlaux into wlanbcicmsiseout;
--      end

    IF (bdaliqipipro > 0) THEN
       wlanbcicmsiseout = 1;
    ELSE
      BEGIN
        IF (wlanbcicmsiseout = 0) THEN
           wlanbcicmsiseout = 1;
        ELSE
           wlanbcicmsiseout = 2;
      END

    bdlanbcicmsiseout = wlanbcicmsiseout;
    wcodnataux =  SUBSTRING(CAST(bdcodnat AS VARCHAR(10)) FROM 1 FOR 1);

    bdvlrcofinsexp = 0;
    IF (((bdcodcstcof IN (52,62)) OR (bdcodcstcof IN (54,55,56,64,65,66,73,75,67,98)) AND  wcodnataux = '3')) THEN
       bdvlrcofinsexp = bdvlrcofins;

    BDVLRCOFINSTRIBINT = 0;
    IF (((bdcodcstcof IN (50,53,60,63)) OR (bdcodcstcof IN (54,64,73,75,56,66,67,98)) AND  (wcodnataux <> '3'))) THEN
       BDVLRCOFINSTRIBINT = bdvlrcofins;

    BDVLRCOFINSNTRIBINT = 0;
    IF (((bdcodcstcof IN (51,61,70,71,72,74,53,63)) OR (bdcodcstcof IN (55,65,56,66,67,98)) AND  (wcodnataux <> '3'))) THEN
       BDVLRCOFINSNTRIBINT = bdvlrcofins;


    bdvlrpisexp = 0;
    IF (((bdcodcstcof IN (52,62)) OR (bdcodcstcof IN (54,55,56,64,65,66,73,75,67,98)) AND  wcodnataux = '3')) THEN
       bdvlrpisexp = bdvlrpis;

    bdvlrpistribint = 0;
    IF (((bdcodcstcof IN (50,53,60,63)) OR (bdcodcstcof IN (54,64,73,75,56,66,67,98)) AND  (wcodnataux <> '3'))) THEN
       bdvlrpistribint = bdvlrpis;

    bdvlrpisntribint = 0;
    IF (((bdcodcstcof IN (51,61,70,71,72,74,53,63)) OR (bdcodcstcof IN (55,65,56,66,67,98)) AND  (wcodnataux <> '3'))) THEN
       bdvlrpisntribint = bdvlrpis;

    --rotina usada no suprema...
    WCSTIPI = CAST(BDCODEXPCSTIPI AS VARCHAR(2));
    IF (WCSTIPI IS NULL) THEN
       WCSTIPI = '00';
    WCSTIPIaux = SUBSTRING(WCSTIPI FROM 1 FOR 1);
    IF (WCSTIPIaux <> '0' AND WCSTIPIaux <> '4')  THEN
       BEGIN
         IF (WCSTIPIaux = '5') THEN
            WCSTIPIaux = '0';
         ELSE
            WCSTIPIaux = '4';
       END
    WCSTIPI = WCSTIPIaux || SUBSTRING(WCSTIPI FROM 2 FOR 1);
    BDCODEXPCSTIPI = CAST(WCSTIPI AS INTEGER);

    -- se produto for vazio, deve lan?ar o produto default informado na tela do sva
    IF (bdcodprod IS NULL) THEN
       BEGIN
         IF (bdmodelo IN (21,22)) THEN -- telecom
            BEGIN
              IF (PRODTELECOM IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODTELECOM;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODTELECOM  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (7,8,9,10,11,12,13,14,15,16,27,27,57)) THEN -- frete
            BEGIN
              IF (PRODFRETE IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = '|| :PRODFRETE;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODFRETE = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo = 6) THEN -- energia
            BEGIN
              IF (PRODENERGIA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODENERGIA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODENERGIA  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (28,29)) THEN -- agua
            BEGIN
              IF (PRODAGUA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODAGUA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODAGUA  = 'TRUE';
                 END
            END

         IF (bdcodprod IS NULL) THEN -- generico
            BEGIN
              IF (PRODGENERICO IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODGENERICO;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODGENERICO  = 'TRUE';
                 END
            END

         bdapeunimed = 'UN';
         bdordempro = 1;
         bdqtditem = 1;
         bdvlritempro = bdvlrcontab;
         bdvlrunitario = bdvlritempro;
         bdvlrdesc = bddesconto;
         bdbcicmspro = bdbaseicms;
         bdbcipipro = bdbaseipi;
         bdbcstpro = bdbasest;
         bdvlricmspro = bdvlricms;
         bdvlripipro = bdvlripi;
         bdvlrstmovpro = bdvlrst;
       END


    SUSPEND;


  END

    END

 IF (UPPER(PRSAIDA) = 'TRUE') THEN
    BEGIN

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.bdmodelostr, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,

         pro.BDVLRITEM BDVLRITEMPRO, pro.BDVLRDESC BDVLRDESCPRO, pro.bdvlripi bdvlripipro, pro.bdvlricms bdvlricmspro,
         c100.bdvlrfrete, c100.bdvlrseguro, c100.bdvlroutdesp,

         pro.bdordempro , pro.BDCODPROD, CADPRO.BDDESCPROD, bdcodnat, BDNCMPROD, BDQTDITEM, BDAPEUNIMED, pro.BDALIQIPI, BDBCIPI,
         CSTICMS.BDCSTICMS, pro.BDALIQICMS, BDBCICMS, bdbcst, pro.BDVLRST BDVLRSTMOVPRO, bdmovfisico , CSTIPI.BDCODEXPCSTIPI,
         pro.BDCODCSTPIS, pro.BDALIQPIS, BDBCPIS, BDVLRPIS, pro.BDCODCSTCOF , BDALIQCOFINS , BDBCCOFINS, BDVLRCOFINS, pis.bdcstpis, cof.bdcstcof ';


  wsql = wsql || ' from VW_VEF_EMP_TMOVSAI_EXP_SVA T';

  wsql = wsql || ' left outer join vef_emp_tmovproSAI pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTIPI CSTIPI ON ( PRO.bdcodcstipi = CSTIPI.bdcodcstipi) ';
  wsql = wsql || ' left outer join vef_emp_tc100SAI C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';
  wsql = wsql || ' left outer join TCADPRO_vinc CADPRO on (cadpro.bdcodemp = pro.bdcodemp and cadpro.bdcodprod = pro.bdcodprod)';
  wsql = wsql || ' left outer join tunidademedida UM on (UM.bdcodunimed = CADPRO.bdcodunimed) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTPIS pis on (pis.BDCODCSTPIS = pro.BDCODCSTPIS) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTCOF cof on (cof.BDCODCSTCOF = pro.BDCODCSTCOF) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTICMS CSTICMS ON ( PRO.bdcodcstICMS = CSTICMS.bdcodcstICMS) ';

  wwhere = ' where bdemitente = 0 and bdordempro is not null ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere; --|| ' order by bdcodemp, bdreflan, bdtipomov  ' ;

  wlanbcicmsiseout = NULL;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    BDMODELOSTR,
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100,
    bdordempro,
    bdcodprod,
    BDDESCPROD,
    bdcodnat,
    BDNCMPROD,
    BDQTDITEM,
    BDAPEUNIMED,
    bdaliqipipro,
    bdbcipipro,
    BDCODCSTICMS,
    bdaliqicmspro,
    bdbcicmspro,
    bdbcstpro,
    bdvlrstmovpro,
    bdmovfisico,
    BDCODEXPCSTIPI,
    BDCODCSTPIS,
    BDALIQPIS,
    BDBCPIS,
    BDVLRPIS,
    BDCODCSTCOF ,
    BDALIQCOFINS ,
    BDBCCOFINS,
    BDVLRCOFINS,
    bdcstpis,
    bdcstcof

  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
          BDQTDITEM = 0;
          bdaliqipipro = 0;
          bdbcipipro = 0;
          bdaliqicmspro = 0;
          bdbcicmspro = 0;
          bdbcstpro = 0;
          bdvlrstmovpro = 0;
          BDALIQPIS = 0;
          BDBCPIS = 0;
          BDVLRPIS = 0;
          BDALIQCOFINS  = 0;
          BDBCCOFINS = 0;
          BDVLRCOFINS = 0;
       END


    IF (UPPER(bdmovfisico) = 'TRUE') THEN
       bdmovfisico = 'S';
    ELSE
       bdmovfisico = 'N';

    IF (bdqtditem > 0) THEN
       bdvlrunitario = bdvlritempro / bdqtditem;

    bdtiporeg = '4_3_2';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

--    if (wlanbcicmsiseout is null)  then
--      begin
--        wsqlaux = 'select bdlanbcicmsiseout from VW_VEF_BASE_TEMPPARGER where bdcodemp = ' || :bdcodemp;
--        execute statement wsqlaux into wlanbcicmsiseout;
--      end

    IF (bdaliqipipro > 0) THEN
       wlanbcicmsiseout = 1;
    ELSE
      BEGIN
        IF (wlanbcicmsiseout = 0) THEN
           wlanbcicmsiseout = 1;
        ELSE
           wlanbcicmsiseout = 2;
      END

    bdlanbcicmsiseout = wlanbcicmsiseout;
    wcodnataux =  SUBSTRING(CAST(bdcodnat AS VARCHAR(10)) FROM 1 FOR 1);

    bdvlrcofinsexp = 0;
    IF (wcodnataux = '7') THEN
       bdvlrcofinsexp = bdvlrcofins;

    BDVLRCOFINSTRIBINT = 0;

    BDVLRCOFINSNTRIBINT = 0;
    IF (wcodnataux <> '7') THEN
       BDVLRCOFINSNTRIBINT = bdvlrcofins;


    bdvlrpisexp = 0;
    IF (wcodnataux = '7') THEN
       bdvlrpisexp = bdvlrpis;

    bdvlrpistribint = 0;

    bdvlrpisntribint = 0;
    IF (wcodnataux <> '7') THEN
       bdvlrpisntribint = bdvlrpis;

    --rotina usada no suprema...
    WCSTIPI = CAST(BDCODEXPCSTIPI AS VARCHAR(2));
    IF (WCSTIPI IS NULL) THEN
       WCSTIPI = '00';
    WCSTIPIaux = SUBSTRING(WCSTIPI FROM 1 FOR 1);
    IF (WCSTIPIaux <> '5' AND WCSTIPIaux <> '9')  THEN
       BEGIN
         IF (WCSTIPIaux = '0') THEN
            WCSTIPIaux = '5';
         ELSE
            WCSTIPIaux = '9';
       END
    WCSTIPI = WCSTIPIaux || SUBSTRING(WCSTIPI FROM 2 FOR 1);
    BDCODEXPCSTIPI = CAST(WCSTIPI AS INTEGER);

    -- se produto for vazio, deve lan?ar o produto default informado na tela do sva
    IF (bdcodprod IS NULL) THEN
       BEGIN
         IF (bdmodelo IN (21,22)) THEN -- telecom
            BEGIN
              IF (PRODTELECOM IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODTELECOM;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODTELECOM  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (7,8,9,10,11,12,13,14,15,16,27,27,57)) THEN -- frete
            BEGIN
              IF (PRODFRETE IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODFRETE;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODFRETE = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo = 6) THEN -- energia
            BEGIN
              IF (PRODENERGIA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODENERGIA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODENERGIA  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (28,29)) THEN -- agua
            BEGIN
              IF (PRODAGUA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODAGUA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODAGUA  = 'TRUE';
                 END
            END

         IF (bdcodprod IS NULL) THEN -- generico
            BEGIN
              IF (PRODGENERICO IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODGENERICO;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODGENERICO  = 'TRUE';
                 END
            END

         bdapeunimed = 'UN';
         bdordempro = 1;
         bdqtditem = 1;
         bdvlritempro = bdvlrcontab;
         bdvlrunitario = bdvlritempro;
         bdvlrdesc = bddesconto;
         bdbcicmspro = bdbaseicms;
         bdbcipipro = bdbaseipi;
         bdbcstpro = bdbasest;
         bdvlricmspro = bdvlricms;
         bdvlripipro = bdvlripi;
         bdvlrstmovpro = bdvlrst;
       END


    SUSPEND;
  END
    END
END
^

/* Alter (VEF_SP_SVA_433) */
ALTER PROCEDURE VEF_SP_SVA_433(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIAPRO NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
BDVLRIR NUMERIC(15,2),
BDINSSRET NUMERIC(15,2),
BDVLRPISRET NUMERIC(15,2),
BDVLRCOFINSRET NUMERIC(15,2),
BDVLRCSLLRET NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);




  wsql =  'select mov.BDCODEMP, mov.BDCHAVE, mov.BDREFLAN, ''ENT'', BDMODELO, mov.BDMODELOSTR, BDSERIE, BDNUMDOCINI, BDDATAEMISSAO, ';
  wsql = wsql || '       BDDATAENTRADAENT BDDATAENTSAI, mov.BDCODTER, TER.BDCGCTER, BDESPECIE, BDEMITENTE, BDCODSITNF, BDCIFFOB, ';
  wsql = wsql || '       sum(BDVLRCONTAB) BDVLRCONTAB, sum(BDBASEICMS) BDBASEICMS, sum(BDBASEIPI) BDBASEIPI, sum(BDBASEST) BDBASEST, ';
  wsql = wsql || '       sum(BDISENTASICMS) BDISENTASICMS, sum(BDISENTASIPI) BDISENTASIPI, sum(BDOUTRASICMS) BDOUTRASICMS, ';
  wsql = wsql || '       sum(BDOUTRASIPI) BDOUTRASIPI, sum(BDVLRICMS) BDVLRICMS, sum(BDVLRIPI) BDVLRIPI, sum(BDVLRST) BDVLRST, ';
  wsql = wsql || '       sum(BDIMPEXCLUIDAS) BDIMPEXCLUIDAS, sum(BDOUTROSIMP) BDOUTROSIMP, sum(BDDESCONTO) BDDESCONTO, ';
  wsql = wsql || '       sum(BDICMSRETENT) BDICMSRETENTSAI, BDCONDPGTO, coalesce(RET.BDVLRPIS, 0.0) BDVLRPIS, ';
  wsql = wsql || '       coalesce(RET.BDVLRCOFINS, 0.0) BDVLRCOFINS, coalesce(RET.BDVLRCSOCIAL, 0.0) BDVLRCSOCIAL, ';
  wsql = wsql || '       coalesce(0, 0.0) BDVLRIR, coalesce(0, 0.0) BDINSSRET, ';

  wsql = wsql || '       sum(mov.BDVLRITEMPRO) BDVLRITEMPRO, sum(mov.BDVLRDESCPRO) BDVLRDESCPRO, ';
  wsql = wsql || '       sum(mov.BDVLRDESPACESSORIAPRO) BDVLRDESPACESSORIAPRO, sum(mov.BDVLRIPIPRO) BDVLRIPIPRO, ';
  wsql = wsql || '       sum(mov.BDVLRICMSPRO) BDVLRICMSPRO ';
  wsql = wsql || 'from ( ';
  wsql = wsql || '        select mov.bdcodemp,mov.bdchave,mov.BDCODTER,mov.BDREFLAN,modlan.BDMODELOSTR,mov.bDMODELO, ';
  wsql = wsql || '               mov.BDSERIE, mov.BDNUMDOCINI, mov.BDDATAEMISSAO,mov.BDCONDPGTO, ';
  wsql = wsql || '               mov.BDDATAENTRADAENT, mov.BDESPECIE, mov.BDEMITENTE, mov.BDCODSITNF, mov.BDCIFFOB, ';

  wsql = wsql || '               sum(PRO.BDVLRITEM) BDVLRITEMPRO, sum(PRO.BDVLRDESC) BDVLRDESCPRO, ';
  wsql = wsql || '               sum(PRO.BDVLRDESPACESSORIA) BDVLRDESPACESSORIAPRO, sum(PRO.BDVLRIPI) BDVLRIPIPRO, ';
  wsql = wsql || '               sum(PRO.BDVLRICMS) BDVLRICMSPRO ';
  wsql = wsql || '        from ( ';
  wsql = wsql || '                select * FROM vef_emp_tmovent t ';
              -- SOMENTE TERCEIROS ENTRADAS...
  wsql = wsql || '                where bdemitente = 1 ';
            
              IF (:prempresa IS NOT NULL) THEN
                   wsql = wsql || ' and '||:prempresa;
            
              IF (:pranomesinicial IS NOT NULL) THEN
                 BEGIN
                   wsql = wsql ||'AND T.BDREFLAN >= '||:pranomesinicial;
                   wsql = wsql ||'AND T.BDREFLAN <= '||:pranomesfinal;
                 END
  wsql = wsql || '              ) mov ';
  wsql = wsql || '        LEFT OUTER JOIN vef_emp_tmoventitens i ON (mov.bdcodemp = i.bdcodemp AND mov.bdchave = i.bdchave) ';
  wsql = wsql || '        LEFT OUTER JOIN vef_base_ttabmodelolan modlan ON (modlan.bdmodelo = mov.bdmodelo) ';
  wsql = wsql || '        left outer join VEF_EMP_TMOVPROENT PRO on (PRO.BDCODEMP = mov.BDCODEMP and PRO.BDCHAVE = mov.BDCHAVE and PRO.BDORDEM = i.BDORDEM) ';
  wsql = wsql || '        group by mov.bdcodemp,mov.bdchave,mov.BDCODTER,mov.BDREFLAN,modlan.BDMODELOSTR,mov.bDMODELO, ';
  wsql = wsql || '                 mov.BDSERIE, mov.BDNUMDOCINI, mov.BDDATAEMISSAO,mov.BDCONDPGTO, mov.BDDATAENTRADAENT, mov.BDESPECIE, mov.BDEMITENTE, mov.BDCODSITNF, mov.BDCIFFOB ';

  wsql = wsql || ') mov ';
  wsql = wsql || 'LEFT OUTER JOIN vef_emp_tmoventitens i ON (mov.bdcodemp = i.bdcodemp AND mov.bdchave = i.bdchave) ';
  wsql = wsql || 'left outer join VW_TTERCEIRO TER on (TER.BDCODTER = mov.BDCODTER) ';
  wsql = wsql || 'left outer join VEF_EMP_TMOVENTRET RET on (RET.BDCODEMP = mov.BDCODEMP and RET.BDCHAVE = mov.BDCHAVE) ';
  wsql = wsql || 'group by BDCODEMP, BDCHAVE, BDREFLAN, ''ENT'', BDMODELO, mov.BDMODELOSTR, BDSERIE, BDNUMDOCINI, BDDATAEMISSAO, BDDATAENTRADAENT, mov.BDCODTER, TER.BDCGCTER, BDESPECIE, BDEMITENTE, BDCODSITNF, BDCIFFOB, BDCONDPGTO, BDVLRPIS, BDVLRCOFINS, BDVLRCSOCIAL ';
  wsql = wsql || 'order by BDCODEMP, BDREFLAN ';



  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    BDMODELOSTR,
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    bdcgcter,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    --bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST ,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,
    bdvlrir,
    bdinssret,

    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlrdespacessoriapro,
    bdvlripipro,
    bdvlricmspro
  DO
  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST  = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
          bdvlrcsocial = 0;
          bdvlrir = 0;
          bdinssret = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlrdespacessoriapro = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
       END

    bdtiporeg = '4_3_3';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (bdvlrcontab <> 0) THEN
      BEGIN
        bdaliqpis = (bdvlrpis * 100) / bdvlrcontab;
        bdaliqcofins = (bdvlrcofins * 100) / bdvlrcontab;
        bdaliqir = (bdvlrir * 100) / bdvlrcontab;
        bdaliqcsocial = (bdvlrcsocial * 100) / bdvlrcontab;
      END
    ELSE
      BEGIN
        bdaliqpis = 0;
        bdaliqcofins = 0;
        bdaliqir = 0;
        bdaliqcsocial = 0;
      END

    IF (bdvlrpis = 0) THEN
       bdvlrpisret = 0;
    ELSE
       bdvlrpisret = bdvlrcontab;

    IF (bdvlrcofins = 0) THEN
       bdvlrcofinsret = 0;
    ELSE
       bdvlrcofinsret = bdvlrcontab;

    IF (bdvlrcsocial = 0) THEN
       bdvlrcsllret = 0;
    ELSE
       bdvlrcsllret = bdvlrcontab;

    SUSPEND;
  END
END
^

/* Alter (VEF_SP_SVA_434) */
ALTER PROCEDURE VEF_SP_SVA_434(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(5),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDCAMPO10 NUMERIC(15,2),
BDCAMPO11 NUMERIC(15,2),
BDCAMPO12 NUMERIC(15,2),
BDCAMPO17 NUMERIC(15,2),
BDCAMPO18 NUMERIC(15,2),
BDCAMPO19 NUMERIC(15,2),
BDVLRUNITARIO NUMERIC(15,4),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
DECLARE VARIABLE WLANBCICMSISEOUT INTEGER;
DECLARE VARIABLE WCSTIPI VARCHAR(2);
DECLARE VARIABLE WCSTIPIAUX VARCHAR(1);
DECLARE VARIABLE WCSTPIS VARCHAR(2);
DECLARE VARIABLE WCSTPISAUX VARCHAR(1);
DECLARE VARIABLE WCSTCOF VARCHAR(2);
DECLARE VARIABLE WCSTCOFAUX VARCHAR(1);
DECLARE VARIABLE WVLRITEMPRO NUMERIC(15,2);
DECLARE VARIABLE WSERIE VARCHAR(6);
DECLARE VARIABLE WNUMDOC INTEGER;
DECLARE VARIABLE WDATAEMISSAO DATE;
DECLARE VARIABLE WORDEMPRO INTEGER;
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

 BDPRODFRETE = 'FALSE';
 BDPRODENERGIA  = 'FALSE';
 BDPRODAGUA  = 'FALSE';
 BDPRODTELECOM  = 'FALSE';
 BDPRODGENERICO  = 'FALSE';

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.bdMODELOSTR, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,

         pro.BDVLRITEM BDVLRITEMPRO, pro.BDVLRDESC BDVLRDESCPRO, pro.bdvlripi bdvlripipro, pro.bdvlricms bdvlricmspro,
         c100.bdvlrfrete, c100.bdvlrseguro, c100.bdvlroutdesp,

         pro.bdordempro , pro.BDCODPROD, CADPRO.BDDESCPROD, bdcodnat, BDNCMPROD, BDQTDITEM, BDAPEUNIMED, pro.BDALIQIPI, BDBCIPI,
         CSTICMS.BDCSTICMS, pro.BDALIQICMS, BDBCICMS, bdbcst, pro.BDVLRST BDVLRSTMOVPRO, bdmovfisico, CSTIPI.BDCODEXPCSTIPI ,
         BDCODCSTPIS , pro.BDALIQPIS, BDBCPIS, BDVLRPIS, BDCODCSTCOF , BDALIQCOFINS , BDBCCOFINS, BDVLRCOFINS, ter.bdcgcter ';

  wsql = wsql || ' from VW_VEF_EMP_TMOVENT_EXP_SVA T';
  wsql = wsql || ' left outer join vef_emp_tmovproENT pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTIPI CSTIPI ON ( PRO.bdcodcstipi = CSTIPI.bdcodcstipi) ';
  wsql = wsql || ' left outer join vef_emp_tc100ENT C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';
  wsql = wsql || ' left outer join TCADPRO_VINC CADPRO on (cadpro.bdcodemp = pro.bdcodemp and cadpro.bdcodprod = pro.bdcodprod)';
  wsql = wsql || ' left outer join tunidademedida UM on (UM.bdcodunimed = CADPRO.bdcodunimed) ';
  wsql = wsql || ' left outer join TTERCEIRO ter on (ter.bdcodter = t.bdcodter) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTICMS CSTICMS ON ( PRO.bdcodcstICMS = CSTICMS.bdcodcstICMS) ';

  /*wwhere = ' where bdemitente = 1 and bdordempro is not null';*/
  wwhere = ' where bdemitente = 1 ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreflan, bdtipomov  ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    bdmodelostr, 
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100,
    bdordempro,
    bdcodprod,
    BDDESCPROD,
    bdcodnat,
    BDNCMPROD,
    BDQTDITEM,
    BDAPEUNIMED,
    bdaliqipipro,
    bdbcipipro,
    BDCODCSTICMS,
    bdaliqicmspro,
    bdbcicmspro,
    bdbcstpro,
    bdvlrstmovpro,
    bdmovfisico,
    BDCODEXPCSTIPI,
    BDCODCSTPIS,
    BDALIQPIS,
    BDBCPIS,
    BDVLRPIS,
    BDCODCSTCOF ,
    BDALIQCOFINS ,
    BDBCCOFINS,
    BDVLRCOFINS,
    BDCGCTER

  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
          BDQTDITEM = 0;
          bdaliqipipro = 0;
          bdbcipipro = 0;
          bdaliqicmspro = 0;
          bdbcicmspro = 0;
          bdbcstpro = 0;
          bdvlrstmovpro = 0;
          BDALIQPIS = 0;
          BDBCPIS = 0;
          BDVLRPIS = 0;
          BDALIQCOFINS  = 0;
          BDBCCOFINS = 0;
          BDVLRCOFINS = 0;
       END

    IF (((wSERIE <> bdserie) AND (wNUMDOC <> bdnumdoc) AND (wdataemissao <> bddataemissao)) OR ((wSERIE IS NULL) AND (wNUMDOC IS NULL) AND (wdataemissao IS NULL)))  THEN
       BEGIN
         wSERIE = bdserie;
         wNUMDOC = bdnumdoc;
         wdataemissao = bddataemissao;

         wordempro = 1;
       END
    ELSE
       wordempro = wordempro + 1;

    bdordempro = wordempro;

    wvlritempro = 0;

    IF (UPPER(bdmovfisico) = 'TRUE') THEN
       bdmovfisico = 'S';
    ELSE
       bdmovfisico = 'N';

    bdvlrunitario = bdvlritempro / bdqtditem;

    bdtiporeg = '4_3_4';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (wlanbcicmsiseout IS NULL) THEN
      BEGIN
        wsqlaux = 'select bdlanbcicmsiseout from VW_VEF_BASE_TEMPPARGER where bdcodemp = ' || :bdcodemp;
        EXECUTE STATEMENT wsqlaux INTO wlanbcicmsiseout;
      END

    IF (bdaliqipipro > 0) THEN
       wlanbcicmsiseout = 1;
    ELSE
      BEGIN
        IF (wlanbcicmsiseout = 0) THEN
           wlanbcicmsiseout = 2;
        ELSE
           wlanbcicmsiseout = 3;
      END

    bdlanbcicmsiseout = wlanbcicmsiseout;


    /*if (bdcodcstpis = 7) then
       bdcampo10 = BDVLRPIS;
    else
       bdcampo10 =  0;

    if ((bdcodcstpis = 50) or (bdcodcstpis = 53) or (bdcodcstpis = 54)) then
       bdcampo11 = BDVLRPIS;
    else
       bdcampo11 =  0;

    if ((bdcodcstpis = 51) or (bdcodcstpis = 55) or (bdcodcstpis = 56)) then
       bdcampo12 = BDVLRPIS;
    else
       bdcampo12 =  0;

    if (BDCODCSTCOF = 52) then
       bdcampo17 = BDVLRCOFINS;
    else
       bdcampo17 =  0;

    if ((BDCODCSTCOF = 50) or (bdcodcstpis = 53) or (bdcodcstpis = 54)) then
       bdcampo18 = BDVLRPIS;
    else
       bdcampo18 =  0;

    if ((BDCODCSTCOF = 51) or (bdcodcstpis = 55) or (bdcodcstpis = 56)) then
       bdcampo19 = BDVLRPIS;
    else
       bdcampo19 =  0;*/


    --rotina usada no suprema...
    WCSTIPI = CAST(BDCODEXPCSTIPI AS VARCHAR(2));
    IF (WCSTIPI IS NULL) THEN
       WCSTIPI = '00';
    WCSTIPIaux = SUBSTRING(WCSTIPI FROM 1 FOR 1);
    IF (WCSTIPIaux <> '0' AND WCSTIPIaux <> '4')  THEN
       BEGIN
         IF (WCSTIPIaux = '5') THEN
            WCSTIPIaux = '0';
         ELSE
            WCSTIPIaux = '4';
       END
    WCSTIPI = WCSTIPIaux || SUBSTRING(WCSTIPI FROM 2 FOR 1);
    BDCODEXPCSTIPI = CAST(WCSTIPI AS INTEGER);

    -- se produto for vazio, deve lan?ar o produto default informado na tela do sva
    IF (bdcodprod IS NULL) THEN
       BEGIN
         IF (bdmodelo IN (21,22)) THEN -- telecom
            BEGIN
              IF (PRODTELECOM IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODTELECOM;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODTELECOM  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (7,8,9,10,11,12,13,14,15,16,27,27,57)) THEN -- frete
            BEGIN
              IF (PRODFRETE IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODFRETE;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODFRETE = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo = 6) THEN -- energia
            BEGIN
              IF (PRODENERGIA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODENERGIA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODENERGIA  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (28,29)) THEN -- agua
            BEGIN
              IF (PRODAGUA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODAGUA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODAGUA  = 'TRUE';
                 END
            END

         IF (bdcodprod IS NULL) THEN -- generico
            BEGIN
              IF (PRODGENERICO IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODGENERICO;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODGENERICO  = 'TRUE';
                 END
            END

         bdapeunimed = 'UN';
         bdordempro = 1;
         bdqtditem = 1;
         wvlritempro = bdvlrcontab;
         bdvlrunitario = bdvlritempro;
         bdvlrdesc = bddesconto;
         bdbcicmspro = bdbaseicms;
         bdbcipipro = bdbaseipi;
         bdbcstpro = bdbasest;
         bdvlricmspro = bdvlricms;
         bdvlripipro = bdvlripi;
         bdvlrstmovpro = bdvlrst;
       END


    WCSTPIS = CAST(bdcodcstpis AS VARCHAR(2));
    IF ((WCSTpis IS NULL) OR (TRIM(WCSTpis) = '')) THEN
       WCSTpis = '00';
    WCSTpisaux = SUBSTRING(WCSTpis FROM 1 FOR 1);
    IF (WCSTpisaux <> '9') THEN
        WCSTpisaux = '5';
    WCSTpis = WCSTpisaux || SUBSTRING(WCSTpis FROM 2 FOR 1);
    BDCODCSTPIS = CAST(WCSTpis AS INTEGER);

    IF ((BDCODCSTPIS = '50') AND ((bdbcpis = 0) OR (bdbcpis IS NULL))) THEN
       BDCODCSTPIS = '98';

    IF (BDCODCSTPIS = '57') THEN
       BDCODCSTPIS = '71';


    WCSTcof = CAST(bdcodcstcof AS VARCHAR(2));
    IF ((WCSTcof IS NULL) OR (TRIM(WCSTcof) = '')) THEN
       WCSTcof = '00';
    WCSTcofaux = SUBSTRING(WCSTcof FROM 1 FOR 1);
    IF (WCSTcofaux <> '9') THEN
        WCSTcofaux = '5';
    WCSTcof = WCSTcofaux || SUBSTRING(WCSTcof FROM 2 FOR 1);
    BDCODCSTcof = CAST(WCSTcof AS INTEGER);

    IF ((BDCODCSTcof = '50') AND ((bdbccofins = 0) OR (bdbccofins IS NULL))) THEN
       BDCODCSTcof = '98';

    IF (BDCODCSTcof = '57') THEN
       BDCODCSTcof = '71';


    IF ((bdbcpis IS NULL) OR (bdbcpis = 0)) THEN
       bdbcpis = BDVLRITEMPRO;

    IF ((bdaliqpis IS NULL) OR (bdaliqpis = 0)) THEN
       bdaliqpis = 0.65;

    IF ((bdvlrpis IS NULL) OR (bdvlrpis = 0)) THEN
       bdvlrpis = (bdbcpis * bdaliqpis / 100);

    IF ((bdbccofins IS NULL) OR (bdbccofins = 0)) THEN
       bdbccofins = BDVLRITEMPRO;

    IF ((bdaliqcofins IS NULL) OR (bdaliqcofins = 0)) THEN
       bdaliqcofins = 3;

    IF ((bdvlrcofins IS NULL) OR (bdvlrcofins = 0)) THEN
       bdvlrcofins = (bdbccofins * bdaliqcofins / 100);


    IF (bdcodcstpis = 52) THEN
       bdcampo10 = BDVLRPIS;
    ELSE
       bdcampo10 =  0;

    IF ((bdcodcstpis = 50) OR (bdcodcstpis = 53) OR (bdcodcstpis = 54)) THEN
       bdcampo11 = BDVLRPIS;
    ELSE
       bdcampo11 =  0;

    IF ((bdcodcstpis = 51) OR (bdcodcstpis = 55) OR (bdcodcstpis = 56)) THEN
       bdcampo12 = BDVLRPIS;
    ELSE
       bdcampo12 =  0;

    IF (BDCODCSTCOF = 52) THEN
       bdcampo17 = BDVLRCOFINS;
    ELSE
       bdcampo17 =  0;

    IF ((BDCODCSTCOF = 50) OR (BDCODCSTCOF = 53) OR (BDCODCSTCOF = 54)) THEN
       bdcampo18 = BDVLRCOFINS;
    ELSE
       bdcampo18 =  0;

    IF ((BDCODCSTCOF = 51) OR (BDCODCSTCOF = 55) OR (BDCODCSTCOF = 56)) THEN
       bdcampo19 = BDVLRCOFINS;
    ELSE
       bdcampo19 =  0;

    IF ((wvlritempro IS NOT NULL) AND (wvlritempro > 0)) THEN
    BDVLRITEMPRO = wvlritempro;

    SUSPEND;
  END

END
^

/* Alter (VEF_SP_SVA_491) */
ALTER PROCEDURE VEF_SP_SVA_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDDATACADTER DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDIMTER VARCHAR(16),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDENDEXPTER DM_BDENDERECO,
BDNUMTER VARCHAR(10),
BDCOMPTER DM_BDCOMPENDERECO,
BDBAITER VARCHAR(60),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCEPTER VARCHAR(9),
BDDESCPAIS VARCHAR(60),
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDCODCGCTER VARCHAR(18))
 AS
DECLARE VARIABLE WAUX VARCHAR(1000);
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDDATACADTER, ';
  wSql = wSql || 'BDCODTER, ';
  wSql = wSql || 'BDCGCTER, ';
  wSql = wSql || 'BDIETER, ';
  wSql = wSql || 'BDIMTER, ';
  wSql = wSql || 'BDNOMETER, ';
  wSql = wSql || 'BDLOGRTER, ';
  wSql = wSql || 'BDENDTER, ';
  wSql = wSql || 'BDNUMTER, ';
  wSql = wSql || 'BDCOMPTER, ';
  wSql = wSql || 'BDBAITER, ';
  wSql = wSql || 'bdnomcid, ';
  wSql = wSql || 'BDSIGLAUF, ';
  wSql = wSql || 'BDCEPTER, ';
  wSql = wSql || 'bddescpais ';


  wsql = wsql || ' from VEF_SP_EXP_TERCEIRO(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   IF (prcodter IS NULL) THEN
      wparsqlcalc = wparsqlcalc||',null';
   ELSE
      wparsqlcalc = wparsqlcalc||','||''''||prcodter||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wparsqlcalc = wparsqlcalc||',null';

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bddatacadter,
       :bdcodter,
       :bdcgcter,
       :bdieter,
       :bdimter,
       :bdnometer,
       :bdlogrter,
       :bdendter,
       :bdnumter,
       :bdcompter,
       :bdbaiter,
       :bdnomcid,
       :bdsiglauf,
       :bdcepter,
       :bddescpais
     DO
     BEGIN
       bdordemreg = 4;
       bdtiporeg = '4_9_1';
       bdreflan = NULL;
       bdendexpter = bdlogrter || ' ' || bdendter || ' ' || bdnumter || ' ' || bdcompter ;

       IF (UPPER(bddescpais) = 'BRASIL') THEN
          bddescpais = '';

       IF (UPPER(bdsiglauf) = 'EX') THEN
          bdcodcgcter = bdcodter;
       ELSE
          bdcodcgcter = bdcgcter;

       IF (UPPER(bdsiglauf) = 'EX') THEN
          bdsiglauf = '';

       BDDATACADTER = CAST((SUBSTRING((CAST(PRANOMESINICIAL AS VARCHAR(6))) FROM 5 FOR 2)||'/'||'01/'||SUBSTRING((CAST(PRANOMESINICIAL AS VARCHAR(6))) FROM 1 FOR 4)) AS DATE);

       SUSPEND;
     END
END
^

/* Alter (VEF_SP_SVA_494) */
ALTER PROCEDURE VEF_SP_SVA_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select distinct ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'CAST(substring(BDCODNAT FROM 1 FOR 6) as Integer), ';
  wSql = wSql || 'substring(BDNOMENAT FROM 1 FOR 45) ';

  wsql = wsql || ' from VEF_SP_EXP_TNATOP(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdcodnat,
       :bdnomenat
     DO
     BEGIN
       bdordemreg = 5;
       bdtiporeg = '4_9_4';
       bdreflan = NULL;

       SUSPEND;

      END

END
^

/* Alter (VEF_SP_SVA_495) */
ALTER PROCEDURE VEF_SP_SVA_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRPROD VARCHAR(10000))
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WEMP INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDCODPROD, ';
  wSql = wSql || 'BDNOMEPROD ';

  wsql = wsql || ' from VEF_SP_EXP_TPRODUTOS(';

  wparsqlcalc = '';

  IF (prempresa IS NULL) THEN
     wparsqlcalc = wparsqlcalc||'null';
  ELSE
     wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

  wparsqlcalc = wparsqlcalc||','||pranomesinicial;
  wparsqlcalc = wparsqlcalc||','||pranomesfinal;

  wsql = wsql||wparsqlcalc||')';

  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodemp,
      :bdcodprod,
      :bdnomeprod
    DO
    BEGIN
      bdordemreg = 6;
      bdtiporeg = '4_9_5';
      bdreflan = NULL;
  
      wemp = bdcodemp;

      SUSPEND;

    END

  IF (prprod <> '') THEN
     BEGIN
       wsql = 'select bdcodprod, bddescprod from TCADPRO_vinc where bdcodemp = '||:PREMPRESA||' bdcodprod in (' || :PRPROD || ')';

       FOR EXECUTE STATEMENT wsql
         INTO
           :bdcodprod,
           :bdnomeprod
         DO
         BEGIN
           bdcodemp = wemp; --0
           bdordemreg = 6;
           bdtiporeg = '4_9_5';
           bdreflan = NULL;

           SUSPEND;

         END
     END
END
^

/* Alter (VEF_SP_SVA_EXP_491) */
ALTER PROCEDURE VEF_SP_SVA_EXP_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
DECLARE VARIABLE WAUX VARCHAR(1000);
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WDATACADTER DATE;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCGCTER VARCHAR(18);
DECLARE VARIABLE WIETER VARCHAR(20);
DECLARE VARIABLE WIMTER VARCHAR(16);
DECLARE VARIABLE WNOMETER VARCHAR(100);
DECLARE VARIABLE WLOGRTER VARCHAR(15);
DECLARE VARIABLE WENDTER VARCHAR(60);
DECLARE VARIABLE WNUMTER VARCHAR(10);
DECLARE VARIABLE WCOMPTER VARCHAR(60);
DECLARE VARIABLE WBAITER VARCHAR(60);
DECLARE VARIABLE WNOMCID VARCHAR(40);
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE WCEPTER VARCHAR(9);
DECLARE VARIABLE WDESCPAIS VARCHAR(60);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDDATACADTER, ';
  wSql = wSql || 'BDCODTER, ';
  wSql = wSql || 'BDCGCTER, ';
  wSql = wSql || 'BDIETER, ';
  wSql = wSql || 'BDIMTER, ';
  wSql = wSql || 'BDNOMETER, ';
  wSql = wSql || 'BDLOGRTER, ';
  wSql = wSql || 'BDENDTER, ';
  wSql = wSql || 'BDNUMTER, ';
  wSql = wSql || 'BDCOMPTER, ';
  wSql = wSql || 'BDBAITER, ';
  wSql = wSql || 'bdnomcid, ';
  wSql = wSql || 'BDSIGLAUF, ';
  wSql = wSql || 'BDCEPTER, ';
  wSql = wSql || 'bddescpais ';

  wsql = wsql || ' from VEF_SP_EXP_TERCEIRO(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   IF (prcodter IS NULL) THEN
      wparsqlcalc = wparsqlcalc||',null';
   ELSE
      wparsqlcalc = wparsqlcalc||','||''''||prcodter||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wparsqlcalc = wparsqlcalc||',null';

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wdatacadter,
       :wcodter,
       :wcgcter,
       :wieter,
       :wimter,
       :wnometer,
       :wlogrter,
       :wendter,
       :wnumter,
       :wcompter,
       :wbaiter,
       :wnomcid,
       :wsiglauf,
       :wcepter,
       :wdescpais
     DO
     BEGIN
       wRetorno = '';
       bdordemreg = 4;
       bdtiporeg = '4_9_1';
       bdreflan = NULL;

       -- Ord   Inicio / Fim / Tamanho

       --  01 -    001 a 008   008 Data de Data de Atualiza??o
       IF (wdatacadter IS NULL) THEN
          SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
       ELSE
          waux = SUBSTRING(CAST(wdatacadter AS VARCHAR(10)) FROM 9 FOR 2)||SUBSTRING(CAST(wdatacadter AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(wdatacadter AS VARCHAR(10)) FROM 1 FOR 4);
       wRetorno = wRetorno||waux;

       --  02 -    009 a 022   014 C?digo do Participante
       wsql = 'select bdretorno from preenche_direita('||''''||wcodter||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  03 -    023 a 036   014 CNPJ / CPF
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcgcter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||TRIM(waux)||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  04 -    037 a 050   014 Inscri??o Estadual
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wieter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||TRIM(waux)||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  05 -    051 a 064   014 Inscri??o Municipal
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wimter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||TRIM(waux)||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  06 -    065 a 134   070 Nome ou Raz?o Socia
       wsql = 'select bdretorno from preenche_direita('||''''||wnometer||''''||',70,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  07 -    135 a 194   070 Endere?o
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wlogrter||' '|| wendter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',60,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  08 -    195 a 214   020 Bairro
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wbaiter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  09 -    215 a 234   020 Municipio
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomcid||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  10 -    235 a 236   002 Unidade da Federa??o
       IF (wsiglauf = 'EX') THEN
          wsiglauf = ' ';
       wsql = 'select bdretorno from preenche_direita('||''''||wsiglauf||''''||',2,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  11 -    237 a 256   020 Pa?s
       IF (wdescpais = 'BRASIL') THEN
          wdescpais = ' ';
       wsql = 'select bdretorno from preenche_direita('||''''||wdescpais||''''||',20,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  12 -    257 a 264   008 Cep
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcepter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',8,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       bdreg = wretorno;
       SUSPEND;
      END
END
^

/* Alter (VEF_SP_SVA_EXP_494) */
ALTER PROCEDURE VEF_SP_SVA_EXP_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
DECLARE VARIABLE WAUX VARCHAR(1000);
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WDATACADNAT VARCHAR(8);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WNOMENAT VARCHAR(255);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDCODNAT, ';
  wSql = wSql || 'BDNOMENAT ';

  wsql = wsql || ' from VEF_SP_EXP_TNATOP(';


  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcodnat,
       :wnomenat
     DO
     BEGIN
       wRetorno = '';
       bdordemreg = 5;
       bdtiporeg = '4_9_4';
       bdreflan = NULL;

       -- Ord   Inicio / Fim / Tamanho

       --  01 -    001 a 008   008 Data de Atualiza??o
       wdatacadnat = '01'||SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM  5 FOR 2)||SUBSTRING(CAST(pranomesinicial AS VARCHAR(10)) FROM 1 FOR 4);  --pranomesinicial || '01';
       IF (wdatacadnat IS NULL) THEN
          SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
       ELSE
          waux = wdatacadnat;
       wRetorno = wRetorno||waux;

       --  02 -    009 a 014   006 C?digo da Natureza da Opera??o
       wsql = 'select bdretorno from preenche_direita('||''''||wcodnat||''''||',6,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  03 -    015 a 059   045 Descri??o
       wsql = 'select bdretorno from preenche_direita('||''''||wnomenat||''''||',44,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;
       wRetorno = wRetorno||' ';


       bdreg = wretorno;
       SUSPEND;


      END

END
^

/* Alter (VEF_SP_SVA_EXP_495) */
ALTER PROCEDURE VEF_SP_SVA_EXP_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
DECLARE VARIABLE WAUX VARCHAR(1000);
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WDATACADPROD VARCHAR(8);
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WNOMEPROD VARCHAR(255);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDCODPROD, ';
  wSql = wSql || 'BDNOMEPROD ';

  wsql = wsql || ' from VEF_SP_EXP_TPRODUTOS(';


  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcodprod,
       :wnomeprod
     DO
     BEGIN
       wRetorno = '';
       bdordemreg = 6;
       bdtiporeg = '4_9_5';
       bdreflan = NULL;

       -- Ord   Inicio / Fim / Tamanho

       --  01 -    001 a 008   008 Data de Atualiza??o
       wdatacadprod =  '01'||SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM  5 FOR 2)||SUBSTRING(CAST(pranomesinicial AS VARCHAR(10)) FROM 1 FOR 4);  --pranomesinicial || '01'; --pranomesinicial || '01';
       IF (wdatacadprod IS NULL) THEN
          SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
       ELSE
          waux = wdatacadprod;
       wRetorno = wRetorno||waux;

       --  02 -    009 a 014   020 C?digo da Mercadoria /Produto /
       wsql = 'select bdretorno from preenche_direita('||''''||wcodprod||''''||',20,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  03 -    015 a 059   045 Descri??o
       wsql = 'select bdretorno from preenche_direita('||''''||wnomeprod||''''||',45,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;


       bdreg = wretorno;
       SUSPEND;


      END

END
^

/* Alter (VEF_SP_SVA_EXP_CAD) */
ALTER PROCEDURE VEF_SP_SVA_EXP_CAD(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
DECLARE VARIABLE waux VARCHAR(1000);
DECLARE VARIABLE wretorno VARCHAR(1000);
DECLARE VARIABLE wparsqlcalc VARCHAR(32700);
DECLARE VARIABLE wsql VARCHAR(32700);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  -- Inicio do registro 4.9.1 --------------------------------------------------------------------------------------------------------

  wsql = 'select bdcodemp, bdreflan, bdtiporeg, bdordemreg,  bdreg ';
  wsql = wsql || ' from VEF_SP_SVA_EXP_491(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||',null';
   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;
   wparsqlcalc = wparsqlcalc||','||prtipoexp;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdreflan,
       :bdtiporeg,
       :bdordemreg,
       :bdreg
     DO

    SUSPEND;

  -- Inicio do registro 4.9.4 --------------------------------------------------------------------------------------------------------

  wsql = 'select bdcodemp, bdreflan, bdtiporeg, bdordemreg,  bdreg ';
  wsql = wsql || ' from VEF_SP_SVA_EXP_494(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;
   wparsqlcalc = wparsqlcalc||','||prtipoexp;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdreflan,
       :bdtiporeg,
       :bdordemreg,
       :bdreg
     DO

    SUSPEND;

  -- Inicio do registro 4.9.5 --------------------------------------------------------------------------------------------------------

  wsql = 'select bdcodemp, bdreflan, bdtiporeg, bdordemreg,  bdreg ';
  wsql = wsql || ' from VEF_SP_SVA_EXP_495(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;
   wparsqlcalc = wparsqlcalc||','||prtipoexp;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdreflan,
       :bdtiporeg,
       :bdordemreg,
       :bdreg
     DO

    SUSPEND;
END
^

/* Alter (VEF_SP_SVA_SERVICOS_ITENS) */
ALTER PROCEDURE VEF_SP_SVA_SERVICOS_ITENS(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODSERVICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDCODCID INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(6),
BDSERIE VARCHAR(5),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDORDEM INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDCODOBS INTEGER,
BDIDCST INTEGER,
BDCONDPGTO INTEGER,
BDCONDPGTOAUX VARCHAR(1),
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDCODCSTPIS VARCHAR(2),
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDCODCSTCOF VARCHAR(2),
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDCAMPO07_4106 NUMERIC(15,2),
BDCAMPO14_4106 NUMERIC(15,2),
BDVLRCONTAB_4106 NUMERIC(15,3),
BDCAMPO10_4106 NUMERIC(15,2),
BDCAMPO17_4106 NUMERIC(15,2),
BDDESCPROD VARCHAR(45),
BDPRODSERVICO VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

 BDPRODSERVICO = 'FALSE';

 wsql = 'SELECT  t.BDCODEMP, t.BDCHAVE, BDREFLAN, BDCODCIC, bddataemissao, bdcodter, bdnumdocini, bdtiplan, bdespecie, bdserie, bdcodsitnf, t.bdordem,
        bdcodnat, bdvlrcontab, BDDESCONTO, bdaliqirser, bdbcirser, bdvlrirser, bdvlrissser, bdidcfps, bdcodrec, bdcodobs, bdidcst, bdcondpgto, bdaliqredbcissser,
        bdbcissser, bdaliqredissser, bdisentasissser, bdoutrasissser, bdacrededuirser, bdacrecfinser, bddigopernat, bdprefixonat, bdcodatvm,
        coalesce(RET.bdvlrpis,0.0) BDVLRPIS, coalesce(RET.bdvlrcofins,0.0) BDVLRCOFINS, BDTIPOMOV ';

  wsql = wsql || ' from VW_VEF_EMP_TMOVSER_EXP_SVA T';
  /*wsql = wsql || ' left outer join VEF_EMP_TMOVSERRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave and ret.bdordem = t.bdordem) ';*/
  wsql = wsql || ' left outer join VEF_EMP_TMOVSERRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave) ';

  wwhere = '';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || :prempresa;

  IF (prtipolan IS NOT NULL) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         IF (prtipolan = 0) THEN
            wwhere = wWhere||' bdtiplan = 0 ';
         ELSE
         IF (prtipolan = 1) THEN
            wwhere = wWhere||' bdtiplan = 1 ';
      END

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql|| ' where ' || wwhere || ' order by bdcodemp, bdreflan, bdtiplan ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdcodcid,
    bddataemissao,
    bdcodter,
    bdnumdoc,
    bdtiplan,
    bdespecie,
    bdserie,
    bdcodsitnf,

    bdordem,
    bdcodnat,
    bdvlrcontab,
    BDDESCONTO,
    bdaliqirser,
    bdbcirser,
    bdvlrirser,
    bdvlrissser,
    bdidcfps,
    bdcodrec,
    bdcodobs,
    bdidcst,
    bdcondpgto,
    bdaliqredbcissser,
    bdbcissser,
    bdaliqredissser,
    bdisentasissser,
    bdoutrasissser,
    bdacrededuirser,
    bdacrecfinser,
    bddigopernat,
    bdprefixonat,
    bdcodatvm,
    bdvlrpis,
    bdvlrcofins,

    BDTIPOMOV
  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          bdvlrcontab = 0;
          BDDESCONTO = 0;
          bdaliqirser = 0;
          bdbcirser = 0;
          bdvlrirser = 0;
          bdvlrissser = 0;
          bdaliqredbcissser = 0;
          bdbcissser = 0;
          bdaliqredissser = 0;
          bdisentasissser = 0;
          bdoutrasissser = 0;
          bdacrededuirser = 0;
          bdacrecfinser = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
       END

    IF (bdtiplan = 0) THEN
       bdtiporeg = '4_3_6';
    ELSE
       bdtiporeg = '4_3_9';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
       bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (((bdvlrcontab = 0) OR (bdvlrcontab IS NULL)) AND ((bdvlrirser = 0) OR (bdvlrissser IS NULL)))   THEN
        bdcampo10 = 'S';
    ELSE
        bdcampo10 = 'N';

    IF (bdvlrpis <> 0) THEN
      BEGIN
        bdcodcstpis = '01';
        bdbcpis = bdvlrcontab;
        IF (bdvlrcontab > 0) THEN
           bdaliqpis = bdvlrpis * 100 / bdvlrcontab;
        ELSE
           bdaliqpis = bdvlrpis * 100 / 1;
      END
    ELSE
      BEGIN
        bdcodcstpis = '07';
        bdbcpis = 0;
        bdaliqpis = 0;
      END

    IF (bdvlrcofins <> 0) THEN
      BEGIN
        bdcodcstcof = '01';
        bdbccofins = bdvlrcontab;
        IF (bdvlrcontab > 0) THEN
           bdaliqcofins = bdvlrcofins * 100 / bdvlrcontab;
        ELSE
           bdaliqcofins = bdvlrcofins * 100 / 1;
      END
    ELSE
      BEGIN
        bdcodcstcof = '07';
        bdbccofins = 0;
        bdaliqcofins = 0;
      END

    bdvlrcontab_4106 = bdvlrcontab;


    bdcampo07_4106 = 0.65;
    bdcampo14_4106 = 3;

    bdcampo10_4106 = bdvlrcontab_4106 * bdcampo07_4106 / 100;
    bdcampo17_4106 = bdvlrcontab_4106 * bdcampo14_4106 / 100;

    IF (bdcodatvm IS NULL) THEN
       IF (PRODSERVICO IS NOT NULL) THEN
          BEGIN
            wsqlaux = 'select bdcodprod, bddescprod from TCADPRO_vinc where bdcodemp = '||:BDCODEMP||' and bdcodprod = ' || :PRODSERVICO;
            EXECUTE STATEMENT wsqlaux INTO bdcodatvm, bddescprod;
            BDPRODSERVICO = 'TRUE';
          END


    SUSPEND;
  END
END
^

/* Alter (VEF_SP_SVA_SERVICOS_MOV) */
ALTER PROCEDURE VEF_SP_SVA_SERVICOS_MOV(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDIDCST INTEGER,
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
DECLARE VARIABLE WLANBCICMSISEOUT INTEGER;
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);


 wsql = 'SELECT  T.BDCODEMP, T.BDCHAVE, T.BDREFLAN, T.BDTIPOMOV , T.bddataemissao, T.bdcodter, T.bdnumdocini, T.bdtiplan, T.bdespecie, T.bdserie, T.bdcodsitnf, T.bdaliqirser,
         sum(coalesce(RET.bdvlrpis,0.0)) BDVLRPIS,
         sum(coalesce(RET.bdvlrcofins,0.0)) BDVLRCOFINS,
         sum(coalesce(RET.bdvlrcsocial,0.0)) BDVLRCSOCIAL,
         sum(T.bdvlrcontab) bdvlrcontab, sum(T.BDDESCONTO) BDDESCONTO, sum(T.bdbcirser) bdbcirser , sum(T.bdvlrirser) bdvlrirser, sum(T.bdvlrissser) bdvlrissser ';

 wsql = wsql || ' from VW_VEF_EMP_TMOVSER_EXP_SVA T';

 /*wsql = wsql || ' left outer join VEF_EMP_TMOVSERRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave and ret.bdordem = t.bdordem) ';*/
 wsql = wsql || ' left outer join VEF_EMP_TMOVSERRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave) ';

 wwhere = '';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || :prempresa;

  IF (prtipolan IS NOT NULL) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         IF (prtipolan = 0) THEN
            wwhere = wWhere||' bdtiplan = 0 ';
         ELSE
         IF (prtipolan = 1) THEN
            wwhere = wWhere||' bdtiplan = 1 ';
      END

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||' where ' || wwhere || ' group by BDCODEMP, BDCHAVE, BDREFLAN, BDTIPOMOV , bddataemissao, bdcodter, bdnumdocini, bdtiplan, bdespecie, bdserie, bdcodsitnf, bdaliqirser
                                        order by bdcodemp, bdreflan, bdtiplan ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    BDTIPOMOV ,
    bddataemissao,
    bdcodter,
    bdnumdoc,
    bdtiplan,
    bdespecie,
    bdserie,
    bdcodsitnf,
    bdaliqirser,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,

    bdvlrcontab,
    BDDESCONTO,
    bdbcirser,
    bdvlrirser,
    bdvlrissser

  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          bdaliqirser = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
          bdvlrcsocial = 0;
          bdvlrcontab = 0;
          BDDESCONTO = 0;
          bdbcirser = 0;
          bdvlrirser = 0;
          bdvlrissser = 0;
       END

    IF (bdtiplan = 0) THEN
       bdtiporeg = '4_3_5';
    ELSE
       bdtiporeg = '4_3_8';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
       bdcodsitnfaux = 'N';

    IF (((bdvlrcontab = 0) OR (bdvlrcontab IS NULL)) AND ((bdvlrirser = 0) OR (bdvlrissser IS NULL)))   THEN
        bdcampo10 = 'S';
    ELSE
        bdcampo10 = 'N';

    IF (bdvlrcontab <> 0) THEN
      BEGIN
        bdaliqpis = (bdvlrpis * 100) / bdvlrcontab;
        bdaliqcofins = (bdvlrcofins * 100) / bdvlrcontab;
        bdaliqcsocial = (bdvlrcsocial * 100) / bdvlrcontab;
      END
    ELSE
      BEGIN
        bdaliqpis = 0;
        bdaliqcofins = 0;
        bdaliqcsocial = 0;

      END



    SUSPEND;
  END


END
^

/* Alter (VEF_SP_TREEVIEW_CONS_ANUAL_CONF) */
ALTER PROCEDURE VEF_SP_TREEVIEW_CONS_ANUAL_CONF(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODPLANO INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDCODMATRIZ INTEGER,
BDREGAUX INTEGER)
 AS
DECLARE VARIABLE WCODEMPANTERIOR INTEGER;
DECLARE VARIABLE WNOMEEMPANTERIOR DM_BDNOMEMP;
DECLARE VARIABLE WREFANTERIOR INTEGER;
DECLARE VARIABLE WCODQUADROANTERIOR INTEGER;
DECLARE VARIABLE WDESCQUADROANTERIOR VARCHAR(80);
DECLARE VARIABLE WORDEMANTERIOR INTEGER;
DECLARE VARIABLE WDESCRICAOANTERIOR VARCHAR(80);
DECLARE VARIABLE WCODMATRIZANTERIOR INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WNOMEEMPAUX DM_BDNOMEMP;
DECLARE VARIABLE WREFAUX INTEGER;
DECLARE VARIABLE WCODQUADROAUX INTEGER;
DECLARE VARIABLE WDESCQUADROAUX VARCHAR(80);
DECLARE VARIABLE WORDEMAUX INTEGER;
DECLARE VARIABLE WDESCRICAOAUX VARCHAR(80);
DECLARE VARIABLE WCODMATRIZAUX INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WWHERE VARCHAR(32000);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WORDEMTOT NUMERIC(15,6);
DECLARE VARIABLE WORDEMJAN NUMERIC(15,6);
DECLARE VARIABLE WORDEMFEV NUMERIC(15,6);
DECLARE VARIABLE WORDEMMAR NUMERIC(15,6);
DECLARE VARIABLE WORDEMABR NUMERIC(15,6);
DECLARE VARIABLE WORDEMMAI NUMERIC(15,6);
DECLARE VARIABLE WORDEMJUN NUMERIC(15,6);
DECLARE VARIABLE WORDEMJUL NUMERIC(15,6);
DECLARE VARIABLE WORDEMAGO NUMERIC(15,6);
DECLARE VARIABLE WORDEMSET NUMERIC(15,6);
DECLARE VARIABLE WORDEMOUT NUMERIC(15,6);
DECLARE VARIABLE WORDEMNOV NUMERIC(15,6);
DECLARE VARIABLE WORDEMDEZ NUMERIC(15,6);
DECLARE VARIABLE WCODQUADROANTERIOR_CONTROLE INTEGER;
DECLARE VARIABLE WCODEMPANTERIOR_CONTROLE INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql||'empresas.BDNOMEMP, ';
  wsql = wsql||'T.BDREF, ';
  wsql = wsql||'T.BDCODQPLACONSCONF, ';
  wsql = wsql||'QUADRO.BDDESCRICAO, ';
  wsql = wsql||'T.BDORDEM, ';
  wsql = wsql||'T.BDDESCRICAO, ';
  wsql = wsql||'T.BDVALOR, ';
  wsql = wsql||'T.BDCODMATRIZ ';
  wsql = wsql||'from VEF_REL_CONS_ANUAL_CONF T '; --tabela por sess?o
  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas on (empresas.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join TPLANOCONSCONF_Q QUADRO on (QUADRO.BDCODQPLACONSCONF = t.BDCODQPLACONSCONF AND QUADRO.BDCODPLACONSCONF = T.BDCODPLACONSCONF) ';

  wwhere = '';

  IF (:prcodemp IS NOT NULL) THEN
    wwhere = :prcodemp;

  IF ((:prCodPlano IS NOT NULL) AND (:prCodPlano > 0)) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
      ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'T.BDCODPLACONSCONF  = '||:prCodPlano;
    END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDCODQPLACONSCONF  = '||:prcodquadro;
    END

  IF (:prRef IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDREF Between '||SUBSTRING(:prRef FROM 1 FOR 4)||'01 and '||SUBSTRING(:prRef FROM 1 FOR 4)||'12 ';
    END

  IF (wwhere <> '') THEN
    wwhere = 'where '||wwhere||' and QUADRO.bdcodsis = 3';
  ELSE
    wwhere = wwhere||' where QUADRO.bdcodsis = 3';

  wsql = wsql||wwhere||' order by t.bdcodmatriz, t.bdcodemp, t.bdcodqplaconsconf, t.bdordem, t.bdref ';

  /*inicializa variaveis*/
  wcodmatrizanterior = 0;
  wcodempanterior = 0;
  wcodquadroanterior = 0;
  wordemanterior = 0;
  wcodquadroanterior_controle = 0;
  wcodempanterior_controle = 0;

  wordemtot = 0;
  wordemjan = 0;
  wordemfev = 0;
  wordemmar = 0;
  wordemabr = 0;
  wordemmai = 0;
  wordemjun = 0;
  wordemjul = 0;
  wordemago = 0;
  wordemset = 0;
  wordemout = 0;
  wordemnov = 0;
  wordemdez = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP,
    BDREF,
    BDCODQUADRO,
    BDDESCQUADRO,
    BDORDEM,
    BDDESCRICAO,
    BDVALOR,
    BDCODMATRIZ
  DO
    BEGIN
      IF ((wcodempanterior_controle = 0) OR (wcodempanterior_controle <> wcodempanterior)) THEN
        BEGIN
         wordemaux = :bdordem;
         wdescricaoaux = :bddescricao;
 
         bdordem = NULL;
         bddescricao = LPAD(:bdcodemp||' - '||:bdnomemp, 80);
 
         bdregaux = 2;
         SUSPEND;
 
         wcodempanterior_controle = :bdcodemp;
         bdordem = wordemaux;
         bddescricao = wdescricaoaux;
        END
 
      IF ((wcodquadroanterior_controle = 0) OR (wcodquadroanterior_controle <> wcodquadroanterior) ) THEN
        BEGIN
          wordemaux = :bdordem;
          wdescricaoaux = :bddescricao;
 
          bdordem = NULL;
          bddescricao = :bddescquadro;
 
          bdregaux = 1;
          SUSPEND;
 
          wcodquadroanterior_controle = :bdcodquadro;
          bdordem = wordemaux;
          bddescricao = wdescricaoaux;
        END

      IF ((wordemanterior <> :bdordem) OR (wcodquadroanterior <> :bdcodquadro) OR (wcodempanterior <> :bdcodemp) OR (wcodmatrizanterior <> :bdcodmatriz)) THEN
        BEGIN
          IF (wordemanterior <> 0) THEN
            BEGIN
              --guarda o conteudo em uma variavel auxiliar
              wcodempaux = :bdcodemp;
              wnomeempaux = :bdnomemp;
              wrefaux = :bdref;
              wcodquadroaux = :bdcodquadro;
              wdescquadroaux = :bddescquadro;
              wordemaux = :bdordem;
              wdescricaoaux = :bddescricao;
              wcodmatrizaux = :bdcodmatriz;

              --pega o valor anterior e aplica nos campos de sa?da
              bdcodemp = wcodempanterior;
              bdnomemp = wnomeempanterior;
              bdref = wrefanterior;
              bdcodquadro = wcodquadroanterior;
              bddescquadro = wdescquadroanterior;
              bdordem = wordemanterior;
              bddescricao = wdescricaoanterior;
              bdcodmatriz = wcodmatrizanterior;

              --passa os totalizadores para os campos de sa?da
              bdtotal = wordemtot;
              bdjan = wordemjan;
              bdfev = wordemfev;
              bdmar = wordemmar;
              bdabr = wordemabr;
              bdmai = wordemmai;
              bdjun = wordemjun;
              bdjul = wordemjul;
              bdago = wordemago;
              bdset = wordemset;
              bdout = wordemout;
              bdnov = wordemnov;
              bddez = wordemdez;

              bdregaux = 0;
              SUSPEND;

              bdtotal = NULL;
              bdjan = NULL;
              bdfev = NULL;
              bdmar = NULL;
              bdabr = NULL;
              bdmai = NULL;
              bdjun = NULL;
              bdjul = NULL;
              bdago = NULL;
              bdset = NULL;
              bdout = NULL;
              bdnov = NULL;
              bddez = NULL;

              --retorna os valores originais dos campos de saida
              bdcodemp = wcodempaux;
              bdnomemp = wnomeempaux;
              bdref = wrefaux;
              bdcodquadro = wcodquadroaux;
              bddescquadro = wdescquadroaux;
              bdordem = wordemaux;
              bddescricao = wdescricaoaux;
              bdcodmatriz = wcodmatrizaux;
            END

          wcodempanterior = :bdcodemp;
          wnomeempanterior = :bdnomemp;
          wrefanterior = :bdref;
          wcodquadroanterior = :bdcodquadro;
          wdescquadroanterior = :bddescquadro;
          wordemanterior = :bdordem;
          wdescricaoanterior = :bddescricao;
          wcodmatrizanterior = :bdcodmatriz;

          wordemtot = 0;
          wordemjan = 0;
          wordemfev = 0;
          wordemmar = 0;
          wordemabr = 0;
          wordemmai = 0;
          wordemjun = 0;
          wordemjul = 0;
          wordemago = 0;
          wordemset = 0;
          wordemout = 0;
          wordemnov = 0;
          wordemdez = 0;
        END

      wmes = CAST(SUBSTRING(:bdref FROM 5 FOR 2) AS INTEGER);

      wordemtot = wordemtot + :bdvalor;

      IF (wmes = 1) THEN
        wordemjan = :bdvalor;
      ELSE IF (wmes = 2) THEN
        wordemfev = :bdvalor;
      ELSE IF (wmes = 3) THEN
        wordemmar = :bdvalor;
      ELSE IF (wmes = 4) THEN
        wordemabr = :bdvalor;
      ELSE IF (wmes = 5) THEN
        wordemmai = :bdvalor;
      ELSE IF (wmes = 6) THEN
        wordemjun = :bdvalor;
      ELSE IF (wmes = 7) THEN
        wordemjul = :bdvalor;
      ELSE IF (wmes = 8) THEN
        wordemago = :bdvalor;
      ELSE IF (wmes = 9) THEN
        wordemset = :bdvalor;
      ELSE IF (wmes = 10) THEN
        wordemout = :bdvalor;
      ELSE IF (wmes = 11) THEN
        wordemnov = :bdvalor;
      ELSE IF (wmes = 12) THEN
        wordemdez = :bdvalor;
    END

    IF (:bdordem IS NOT NULL) THEN
      BEGIN
        IF (wcodempanterior_controle <> :bdcodemp) THEN
          BEGIN
            wordemaux = :bdordem;
            wdescricaoaux = :bddescricao;

            bdordem = NULL;
            bddescricao = :bdnomemp;

            bdregaux = 2;
            SUSPEND;

            bdordem = wordemaux;
            bddescricao = wdescricaoaux;
          END

        IF (wcodquadroanterior_controle <> :bdcodquadro) THEN
          BEGIN
            wordemaux = :bdordem;
            wdescricaoaux = :bddescricao;

            bdordem = NULL;
            bddescricao = :bddescquadro;

            bdregaux = 1;
            SUSPEND;

            bdordem = wordemaux;
            bddescricao = wdescricaoaux;
          END

        bdtotal = wordemtot;
        bdjan = wordemjan;
        bdfev = wordemfev;
        bdmar = wordemmar;
        bdabr = wordemabr;
        bdmai = wordemmai;
        bdjun = wordemjun;
        bdjul = wordemjul;
        bdago = wordemago;
        bdset = wordemset;
        bdout = wordemout;
        bdnov = wordemnov;
        bddez = wordemdez;

        bdregaux = 0;
        SUSPEND;
      END
END
^

/* Alter (VEF_TOTAIS_EXPORTACAO_SEFINNET) */
ALTER PROCEDURE VEF_TOTAIS_EXPORTACAO_SEFINNET(PREMP VARCHAR(9),
PRDATAINI VARCHAR(12),
PRDATAFIM VARCHAR(12),
PRINDICADORISS VARCHAR(1),
PRTIPOLANC VARCHAR(1))
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDIDCNAE VARCHAR(12),
BDCODCFPS VARCHAR(9),
BDCODCST INTEGER,
BDQTDENFS INTEGER,
BDNFS VARCHAR(4000),
BDNFSCANC VARCHAR(4000),
BDVLRCONTABTOTAL NUMERIC(15,2),
BDBCISSSERTOTAL NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,6),
BDVLRISSTOTAL NUMERIC(15,2))
 AS
DECLARE WSQL VARCHAR(10000);
BEGIN

   wSQL =         'select BDCODEMP,  ';
   wSQL = wSQL || '       BDREFLAN,  ';
   wSQL = wSQL || '       BDIDCNAE,  ';
   wSQL = wSQL || '       BDCODCFPS,  ';
   wSQL = wSQL || '       BDCODCST,  ';
   wSQL = wSQL || '       SUM(BDQTDENFS) BDQTDENFS,  ';
   wSQL = wSQL || '       LIST(BDNFS) BDNFS,  ';
   wSQL = wSQL || '       LIST(BDNFSCANC) BDNFSCANC,  ';
   wSQL = wSQL || '       SUM(BDVLRCONTABTOTAL) as BDVLRCONTABTOTAL,  ';
   wSQL = wSQL || '       SUM(BDBCISSSERTOTAL) as BDBCISSSERTOTAL,  ';
   wSQL = wSQL || '       BDALIQREDISSSER, ';
   wSQL = wSQL || '       SUM(BDVLRISSTOTAL) as BDVLRISSTOTAL  ';
   wSQL = wSQL || 'from (  ';
   wSQL = wSQL || '       select BDCODEMP, BDREFLAN, BDIDCNAE, BDCODCFPS, BDCODCST,  ';
   wSQL = wSQL || '              Count(*) BDQTDENFS,  ';
   wSQL = wSQL || '              LIST(BDNUMDOCINI) BDNFS,  ';
   wSQL = wSQL || '              null BDNFSCANC,  ';
   wSQL = wSQL || '              SUM(BDVLRCONTAB) as BDVLRCONTABTOTAL, ';
   wSQL = wSQL || '              SUM(BDBCISSSER) as BDBCISSSERTOTAL, ';
   wSQL = wSQL || '              BDALIQREDISSSER, ';
   wSQL = wSQL || '              ((SUM(BDBCISSSER)*BDALIQREDISSSER)/100) BDVLRISSTOTAL  ';
   wSQL = wSQL || '       from (  ';
   wSQL = wSQL || '              select SER.BDCODEMP, SER.BDCHAVE, SER.BDTIPLAN, SER.BDESPECIE, SER.BDSERIE, SER.BDREFLAN, SER.BDDATAEMISSAO, ';
   wSQL = wSQL || '                     SER.BDNUMDOCINI, SER.BDNUMDOCFIM, SUM(ITENS.BDVLRCONTAB) as BDVLRCONTAB, SUM(ITENS.BDBCISSSER) as BDBCISSSER, ITENS.BDOBSERVACAO, ';
   wSQL = wSQL || '                     ATV.BDCODMUNATVM as BDIDCNAE, ';
   wSQL = wSQL || '                     iif(ITENS.BDALIQREDISSSER <> 0, ITENS.BDALIQREDISSSER, ATV.BDALIQATVM) as BDALIQREDISSSER, ';
   wSQL = wSQL || '                     SUM(((ITENS.BDBCISSSER * (iif(ITENS.BDALIQREDISSSER <> 0, ITENS.BDALIQREDISSSER, ATV.BDALIQATVM))) / 100)) as BDVLRISS, ';
   wSQL = wSQL || '                     coalesce(CFPS.BDCODCFPS, '''') as BDCODCFPS, coalesce(CST.BDCODCST, 0) as BDCODCST ';

   wSQL = wSQL || '               from ( select *  ';
   wSQL = wSQL || '                      from vef_emp_tmovser s  ';
   wSQL = wSQL || '                      where (s.bdcodemp = '||PREMP||') ';
   IF (PRTIPOLANC = '1') THEN /* Tipo do Lan?amento */
     wSQL = wSQL || '                        AND s.BDTIPLAN = 0 ';
   ELSE
   IF (PRTIPOLANC = '2') THEN
     wSQL = wSQL || '                        AND s.BDTIPLAN = 1 ';
   wSQL = wSQL || '                        and (s.bddataemissao between '''||PRDATAINI||''' and '''||PRDATAFIM||''') ';
   wSQL = wSQL || '                        and (S.BDCODSITNF not in (2, 3, 4, 5))   ) ser ';
   wSQL = wSQL || '               left outer join VEF_EMP_TMOVSERITENS itens on ( itens.BDCODEMP = ser.BDCODEMP and itens.BDCHAVE = ser.BDCHAVE )  ';
   wSQL = wSQL || '               left outer join TATVMUNICIPAL atv on ( atv.BDCODATVM = itens.BDCODATVM )  ';
   wSQL = wSQL || '               join VEF_EMP_TMOVSERINDISS iss on ( iss.BDCODEMP = ser.BDCODEMP and iss.BDCHAVE = ser.BDCHAVE and iss.BDINDICADORISS = '||PRINDICADORISS||' ) ';
   wSQL = wSQL || '               left outer join VEF_BASE_TCST cst on ( cst.BDID = iss.BDIDCST )  ';
   wSQL = wSQL || '               left outer join VEF_BASE_TCFPS cfps on ( cfps.BDID = iss.BDIDCFPS ) ';
   wSQL = wSQL || '               group by ser.BDCODEMP,ser.BDCHAVE,ser.BDTIPLAN,ser.BDESPECIE,ser.BDSERIE,ser.BDREFLAN,ser.BDDATAEMISSAO,ser.BDNUMDOCINI,ser.BDNUMDOCFIM, ';
   wSQL = wSQL || '                        itens.BDOBSERVACAO,BDIDCNAE,BDALIQREDISSSER,BDCODCFPS,BDCODCST ';
   wSQL = wSQL || '               order by ser.BDCODEMP, ser.BDREFLAN, ser.BDDATAEMISSAO, ser.BDNUMDOCINI  ';
   wSQL = wSQL || '             ) Group by BDCODEMP, BDREFLAN, BDIDCNAE, BDCODCFPS, BDCODCST, BDALIQREDISSSER ';
   wSQL = wSQL || '       UNION ALL ';
   wSQL = wSQL || '       select BDCODEMP, BDREFLAN, BDIDCNAE, BDCODCFPS, BDCODCST, ';
   wSQL = wSQL || '              0 BDQTDENFS,  ';
   wSQL = wSQL || '              null BDNFS,  ';
   wSQL = wSQL || '              LIST(BDNUMDOCINI) BDNFSCANC,  ';
   wSQL = wSQL || '              SUM(BDVLRCONTAB) as BDVLRCONTABTOTAL, ';
   wSQL = wSQL || '              SUM(BDBCISSSER) as BDBCISSSERTOTAL, ';
   wSQL = wSQL || '              BDALIQREDISSSER, ';
   wSQL = wSQL || '              ((SUM(BDBCISSSER)*BDALIQREDISSSER)/100) BDVLRISSTOTAL  ';
   wSQL = wSQL || '       from ( ';
   wSQL = wSQL || '              select ser.BDCODEMP, ser.BDTIPLAN, ser.BDESPECIE, ser.BDSERIE, ser.BDREFLAN, ser.BDDATAEMISSAO, ser.BDNUMDOCINI, ser.BDNUMDOCFIM,  ';
   wSQL = wSQL || '                     itens.BDVLRCONTAB, itens.BDBCISSSER, itens.BDOBSERVACAO, ';
   wSQL = wSQL || '                     0 as BDIDCNAE, ';
   wSQL = wSQL || '                     0 as BDALIQREDISSSER, ';
   wSQL = wSQL || '                     0 as BDVLRISS, ';
   wSQL = wSQL || '                     '''' as BDCODCFPS, ';
   wSQL = wSQL || '                     0 as BDCODCST ';

   wSQL = wSQL || '              from ( select *  ';
   wSQL = wSQL || '                     from vef_emp_tmovser s  ';
   wSQL = wSQL || '                     where (s.bdcodemp = '||PREMP||') ';
   IF (PRTIPOLANC = '1') THEN /* Tipo do Lan?amento */
     wSQL = wSQL || '                        AND s.BDTIPLAN = 0 ';
   ELSE
   IF (PRTIPOLANC = '2') THEN
     wSQL = wSQL || '                        AND s.BDTIPLAN = 1 ';
   wSQL = wSQL || '                       and (s.bddataemissao between '''||PRDATAINI||''' and '''||PRDATAFIM||''') ) ser ';
   wSQL = wSQL || '              left outer join VEF_EMP_TMOVSERITENS itens on ( itens.BDCODEMP = ser.BDCODEMP and itens.BDCHAVE = ser.BDCHAVE )  ';
   wSQL = wSQL || '              left outer join TATVMUNICIPAL atv on ( atv.BDCODATVM = itens.BDCODATVM )  ';
   wSQL = wSQL || '              join VEF_EMP_TMOVSERINDISS iss on ( iss.BDCODEMP = ser.BDCODEMP and iss.BDCHAVE = ser.BDCHAVE and iss.BDINDICADORISS = '||PRINDICADORISS||' ) ';
   wSQL = wSQL || '              left outer join VEF_BASE_TCST cst on ( cst.BDID = iss.BDIDCST )  ';
   wSQL = wSQL || '              left outer join VEF_BASE_TCFPS cfps on ( cfps.BDID = iss.BDIDCFPS ) ';
   wSQL = wSQL || '              where ser.bdcodsitnf in (2,3,4,5) ';
   wSQL = wSQL || '              order by ser.BDCODEMP, ser.BDREFLAN, ser.BDDATAEMISSAO, ser.BDNUMDOCINI  ';
   wSQL = wSQL || '             ) group by BDCODEMP, BDREFLAN, BDIDCNAE, BDCODCFPS, BDCODCST, BDALIQREDISSSER  ';
   wSQL = wSQL || '      ) group by BDCODEMP,BDREFLAN,BDIDCNAE,BDCODCFPS,BDCODCST, BDALIQREDISSSER ';

   FOR EXECUTE STATEMENT WSQL
   INTO :BDCODEMP,
        :BDREFLAN,
        :BDIDCNAE,
        :BDCODCFPS,
        :BDCODCST,
        :BDQTDENFS,
        :BDNFS,
        :BDNFSCANC,
        :BDVLRCONTABTOTAL,
        :BDBCISSSERTOTAL,
        :BDALIQREDISSSER,
        :BDVLRISSTOTAL
   DO
   SUSPEND;

END
^

/* Alter (VFIN_INSERT_CLIENTE_ONLINE) */
ALTER PROCEDURE VFIN_INSERT_CLIENTE_ONLINE(PRCODCLI INTEGER)
 AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLACLIONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    wplano
  DO
    BEGIN
      --classifica??o dos clientes na ONLINE
      wSql = 'select BDCODTIPOCONTA from TTIPOCONTAONLINE tc where BDCLASSIFICACAO = '''||'08.001.000000001.000000001'||'''';
      EXECUTE STATEMENT wsql INTO wCodTipoConta;

      wsql = PRCODCLI;
      wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';
      EXECUTE STATEMENT wsql INTO WCLACLIONLINE;

      WCLACLIONLINE = '08.001.000000001.000000001'||'.'||WCLACLIONLINE;

      wformula = 'CLIFIXFIN('||PRCODCLI||')';
      wformula = ''''||wformula||'''';
      wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodcli,bdclassificacao,bdformula) values('||
                                              wplano||','||wCodTipoConta||','||PRCODCLI||','||''''||WCLACLIONLINE||''''||','||wformula||')';
      EXECUTE STATEMENT wsql;
    END

--  suspend;
END
^

/* Alter (VFIN_INSERT_CONTABAN_ONLINE) */
ALTER PROCEDURE VFIN_INSERT_CONTABAN_ONLINE(PRCHAVECTABAN INTEGER)
 AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLACONTABANONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    wplano
  DO
    BEGIN
      --classifica??o das contas bancarias na ONLINE
      wSql = 'select BDCODTIPOCONTA from TTIPOCONTAONLINE tc where BDCLASSIFICACAO = '''||'08.001.000000004'||'''';
      EXECUTE STATEMENT wsql INTO wCodTipoConta;

      wsql = PRCHAVECTABAN;
      wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';
      EXECUTE STATEMENT wsql INTO WCLACONTABANONLINE;

      WCLACONTABANONLINE = '08.001.000000004'||'.'||WCLACONTABANONLINE;

      wformula = 'CTABANFIN('||PRCHAVECTABAN||')';
      wformula = ''''||wformula||'''';
      wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdchavectaban,bdclassificacao,bdformula) values('||
                                              wplano||','||wCodTipoConta||','||PRCHAVECTABAN||','||''''||WCLACONTABANONLINE||''''||','||wformula||')';
      EXECUTE STATEMENT wsql;
    END

--  suspend;
END
^

/* Alter (VFIN_INSERT_NOVO_SERVICO_ONLINE) */
ALTER PROCEDURE VFIN_INSERT_NOVO_SERVICO_ONLINE(PRCLASSIFICACAO VARCHAR(100),
PRCODOBRSER INTEGER)
 AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLASERONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    wplano
  DO
    BEGIN
      --classifica??o dos servi?os na ONLINE
      wSql = 'select BDCODTIPOCONTA from TTIPOCONTAONLINE tc where BDCLASSIFICACAO = '''||'08.001.000000002'||'''';
      EXECUTE STATEMENT wsql INTO wCodTipoConta;

      IF (wCodTipoConta > 0) THEN
        BEGIN
          wsql = 'select x.BDCLANOVASERVICO from VFIN_CLASSIFSERVICO_ONLINE(null,'||''''||prclassificacao||''''||') x';
          EXECUTE STATEMENT wsql INTO wClaSerOnline;
    
          wformula = 'SERFIN('||PRCODOBRSER||')';
          wformula = ''''||wformula||'''';
          wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodobrser,bdclassificacao,bdformula) values('||
                                                  wplano||','||wCodTipoConta||','||PRCODOBRSER||','||''''||wClaSerOnline||''''||','||wformula||')';
          EXECUTE STATEMENT wsql;
        END
    END

--  suspend;
END
^

/* Alter (VFIN_SP_CONSFORNECEDORES) */
ALTER PROCEDURE VFIN_SP_CONSFORNECEDORES(PRCODFOR INTEGER,
PRREF INTEGER,
PRWHEREFOR VARCHAR(20000))
 RETURNS(BDCODFOR INTEGER,
BDCNPJFOR VARCHAR(18),
BDREFFOR INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDNOMEFOR DM_BDNOMEMP,
BDAPEFOR DM_BDAPEMP,
BDCEPFOR VARCHAR(9),
BDLOGRFOR DM_LOGRADOURO,
BDENDFOR DM_BDENDERECO,
BDNUMENDFOR DM_BDENDERECO_NR,
BDBAIFOR DM_BDBAIRRO,
BDCOMPLENDFOR DM_BDCOMPENDERECO,
BDIEFOR VARCHAR(20),
BDIMFOR VARCHAR(20),
BDDDDFONEFOR INTEGER,
BDFONEFOR DM_BDTELEFONE,
BDDDDFAXFOR INTEGER,
BDFAXFOR DM_BDTELEFONE,
BDEMAILFOR DM_BDEMAIL,
BDDATACADFOR DATE)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

    wSql = ' select ';
    wSql = wSql || 'forn.BDCODFOR, ';
    wSql = wSql || 'forn.BDCNPJFOR, ';
    wSql = wSql || 'forn.BDREFFOR, ';
    wSql = wsql || 'forn.bdcodcid, ';
    wSql = wSql || 'cid.bdnomcid, ';
    wSql = wSql || 'uf.bdsiglauf, ';
    wSql = wSql || 'forn.bdcodpais, ';
    wSql = wSql || 'pais.bddescpais, ';
    wSql = wSql || 'forn.BDNOMEFOR, ';
    wSql = wSql || 'forn.BDAPEFOR, ';
    wSql = wSql || 'forn.BDCEPFOR, ';
    wSql = wSql || 'forn.BDLOGRFOR, ';
    wSql = wSql || 'forn.BDENDFOR, ';
    wSql = wSql || 'forn.BDNUMENDFOR, ';
    wSql = wSql || 'forn.BDBAIFOR, ';
    wSql = wSql || 'forn.BDCOMPLENDFOR, ';
    wSql = wSql || 'forn.BDIEFOR, ';
    wSql = wSql || 'forn.BDIMFOR, ';
    wSql = wSql || 'forn.BDDDDFONEFOR, ';
    wSql = wSql || 'forn.BDFONEFOR, ';
    wSql = wSql || 'forn.BDDDDFAXFOR, ';
    wSql = wSql || 'forn.BDFAXFOR, ';
    wSql = wSql || 'forn.BDEMAILFOR, ';
    wSql = wSql || 'forn.BDDATACADFOR ';
    wSql = wsql || 'FROM VW_VFIN_BASE_TFORNECEDOR forn ';
    wSql = wsql || 'left outer join tcidade CID on (CID.bdCODCID = forn.BDCODCID) ';
    wSql = wsql || 'left outer join tuf UF on (UF.bdCODUF = CID.BDCODUF) ';
    wSql = wSql || 'left outer join tpais pais on (pais.bdCODPAIS = forn.bdcodpais) ';

  wwhere = '';
  IF (prcodfor IS NOT NULL AND prcodfor <> 0) THEN
    wwhere = wwhere || ' forn.bdcodfor = '||prcodfor;

  IF (prwherefor IS NOT NULL AND prwherefor <> '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwherefor;
    END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By forn.bdcodfor';

  FOR EXECUTE STATEMENT wsql
  INTO
     :BDCODFOR,
     :BDCNPJFOR,
     :BDREFFOR,
     :BDCODCID,
     :BDNOMCID,
     :BDSIGLAUF,
     :BDCODPAIS,
     :BDDESCPAIS,
     :BDNOMEFOR,
     :BDAPEFOR,
     :BDCEPFOR,
     :BDLOGRFOR,
     :BDENDFOR,
     :BDNUMENDFOR,
     :BDBAIFOR,
     :BDCOMPLENDFOR,
     :BDIEFOR,
     :BDIMFOR,
     :BDDDDFONEFOR,
     :BDFONEFOR,
     :BDDDDFAXFOR,
     :BDFAXFOR,
     :BDEMAILFOR,
     :BDDATACADFOR
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VFIN_UPDATE_SERVICO_ONLINE) */
ALTER PROCEDURE VFIN_UPDATE_SERVICO_ONLINE(PRCLAANT VARCHAR(1000),
PRCLANOVA VARCHAR(1000),
PRCODOBRSER INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLAANT VARCHAR(100);
DECLARE VARIABLE WCLANOVA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN
  /* Procedure Text */
  --classifica??o dos servi?os na ONLINE
  wSql = 'select BDCODTIPOCONTA from TTIPOCONTAONLINE tc where BDCLASSIFICACAO = '''||'08.001.000000002'||'''';
  EXECUTE STATEMENT wsql INTO wCodTipoConta;

  IF (wCodTipoConta > 0) THEN
     BEGIN
       wsql = 'select x.BDCLAANTSERVICO, x.BDCLANOVASERVICO from VFIN_CLASSIFSERVICO_ONLINE('||
              ''''||prclaant||''''||
              ','||''''||prclanova||''''||') x';
        
       EXECUTE STATEMENT wsql INTO wclaant, wclanova;
       UPDATE tconf_contas_online SET bdclassificacao = :wclanova WHERE BDCODobrser = :PRCODOBRSER AND BDCODTIPOCONTA = :wCodTipoConta;
     END
END
^

/* Alter (VLAL_COPIA_PARTEA_PLANO) */
ALTER PROCEDURE VLAL_COPIA_PARTEA_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WAPELPA VARCHAR(20);
DECLARE VARIABLE WCTALONLPA VARCHAR(40);
DECLARE VARIABLE WNOMLPA VARCHAR(60);
DECLARE VARIABLE WTIPCTALPA SMALLINT;
DECLARE VARIABLE WFORLPA VARCHAR(200);
DECLARE VARIABLE WCONLPA VARCHAR(200);
DECLARE VARIABLE WCOLLPA INTEGER;
DECLARE VARIABLE WIMPZEROLPA VARCHAR(5);
DECLARE VARIABLE WIMPNEGROLPA VARCHAR(5);
DECLARE VARIABLE WSOTEXTOLPA VARCHAR(5);
DECLARE VARIABLE WZERASALDOLPA VARCHAR(5);
DECLARE VARIABLE WNAOACUMULALPA VARCHAR(5);
DECLARE VARIABLE WTIPOCONTA INTEGER;
DECLARE VARIABLE WTIPOTRIBUTO INTEGER;
declare variable WCODLPA integer;
BEGIN
  DELETE FROM VLAL_PLANOS_TLPA WHERE BDCODPARTEA = :codigonovo;

  IF ((codigonovo IS NULL) OR (codigonovo = 0))  THEN
     BEGIN
       --#alt:85809 . Estava pegando o c?digo a partir do apelido, mas o apelido n?o estava sendo tratado para ser exclusivo. Ana - 22/06/2018
       SELECT MAX(BDCODPARTEA) FROM VLAL_BASE_LALUR_PARTEA INTO codigonovo;
     END
  --#alt:85809 . Inclu?do campo do c?digo, pois o c?digo deve ser o mesmo para as f?rmulas. Ana - 22/06/2018
  --Incluido campos "Tipo tributo" e "Tipo conta ECF" - Carlos Machado - 12/06/2018 - Sol. 84867
  FOR SELECT BDCODLPA, bdctalonlpa,bdnomlpa,bdapelpa,bdtipctalpa,bdforlpa,bdconlpa,
             bdcollpa,bdimpzerolpa,bdimpnegrolpa,bdsotextolpa,bdzerasaldolpa,bdnaoacumulalpa,BDTIPOTRIBUTO,BDTIPOCONTA FROM VLAL_PLANOS_TLPA
             WHERE BDCODPARTEA = : codigocopiar INTO
             :WCODLPA, :wctalonlpa,:wnomlpa,:wapelpa,:wtipctalpa,:wforlpa,:wconlpa,
             :wcollpa,:wimpnegrolpa,:wimpnegrolpa,:wsotextolpa,:wzerasaldolpa,:wnaoacumulalpa,:wtipotributo,wtipoconta DO
     BEGIN
        INSERT INTO VLAL_PLANOS_TLPA (BDCODPARTEA,BDCODLPA, bdctalonlpa,bdnomlpa,bdapelpa,
                                 bdtipctalpa,bdforlpa,bdconlpa,
                                 bdcollpa,bdimpzerolpa,bdimpnegrolpa,bdsotextolpa,bdzerasaldolpa,bdnaoacumulalpa,BDTIPOTRIBUTO,BDTIPOCONTA) VALUES
                                 (:codigonovo,:WCODLPA, :wctalonlpa,:wnomlpa,:wapelpa,:wtipctalpa,:wforlpa,:wconlpa,
                                  :wcollpa,:wimpzerolpa,:wimpnegrolpa,:wsotextolpa,:wzerasaldolpa,:wnaoacumulalpa,:wtipotributo,:wtipoconta);
     END

  SUSPEND;
END
^

/* Alter (VLAL_SP_LAN_PARTEA) */
ALTER PROCEDURE VLAL_SP_LAN_PARTEA(PREMPRESA INTEGER,
PRCODLLA INTEGER,
PRCODUSU INTEGER,
PRANOBASE INTEGER,
PRCODPARTEA INTEGER,
PRCODLPA INTEGER,
PRCODTPHI INTEGER,
PRANUALACUMULADO SMALLINT,
PRVALOR1 NUMERIC(15,2),
PRCOMPL1 VARCHAR(200),
PRVALOR2 NUMERIC(15,2),
PRCOMPL2 VARCHAR(200),
PRVALOR3 NUMERIC(15,2),
PRCOMPL3 VARCHAR(200),
PRVALOR4 NUMERIC(15,2),
PRCOMPL4 VARCHAR(200),
PRVALOR5 NUMERIC(15,2),
PRCOMPL5 VARCHAR(200),
PRVALOR6 NUMERIC(15,2),
PRCOMPL6 VARCHAR(200),
PRVALOR7 NUMERIC(15,2),
PRCOMPL7 VARCHAR(200),
PRVALOR8 NUMERIC(15,2),
PRCOMPL8 VARCHAR(200),
PRVALOR9 NUMERIC(15,2),
PRCOMPL9 VARCHAR(200),
PRVALOR10 NUMERIC(15,2),
PRCOMPL10 VARCHAR(200),
PRVALOR11 NUMERIC(15,2),
PRCOMPL11 VARCHAR(200),
PRVALOR12 NUMERIC(15,2),
PRCOMPL12 VARCHAR(200),
PRREFEMP INTEGER)
 AS
DECLARE VARIABLE wanolan INTEGER;
DECLARE VARIABLE wcodpartea INTEGER;
DECLARE VARIABLE wcodhist INTEGER;
DECLARE VARIABLE wdia INTEGER;
DECLARE VARIABLE wmes INTEGER;
DECLARE VARIABLE wano INTEGER;
DECLARE VARIABLE wdatalanc DATE;
DECLARE VARIABLE wcodusu INTEGER;
BEGIN
  --SELECT BDCODPARTEA FROM VLAL_BASE_TEMP WHERE BDCODEMP = :PREMPRESA INTO :WCODPARTEA;
  SELECT TEMP.BDCODPARTEA, TREF.BDCODHIST FROM VLAL_BASE_TEMP TEMP
  INNER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
  WHERE TEMP.BDCODEMP = :PREMPRESA
  AND tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                       WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                       AND tempresas_ref.bdrefemp <= :prrefemp
                       ORDER BY tempresas_ref.bdrefemp)
  INTO WCODPARTEA, WCODHIST;

  WANO = :PRANOBASE;

  --alt:11995 - 21/08/2015 - Carrega o c?digo do usu?rio para ser inserido nos lan?amentos. Pedro
  SELECT BDCODUSU FROM SP_GET_USUARIO INTO :wCodUsu;

  /*SELECT CAST(SUBSTRING(LLA.BDDATLLA FROM 1 FOR 4) AS INTEGER) AS ANO FROM VLAL_EMPRESAS_TLLA LLA
  WHERE (SUBSTRING(LLA.BDDATLLA FROM 1 FOR 4) = :PRANOBASE)
  AND   (LLA.BDCODPARTEA = :WCODPARTEA)
  AND   (LLA.BDCODLPA = :PRCODLPA)
  GROUP BY ANO
  INTO WANOLAN;

  IF ((:WANOLAN IS NOT NULL) AND (WANOLAN <> 0)) THEN
    EXCEPTION EX_DATE;*/

  /* M?S 01 */
  IF (PRVALOR1 <> 0) THEN
    BEGIN
      WMES = 1;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR1, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL1);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR1, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL1);
        END
    END

  /* M?S 02 */
  IF (PRVALOR2 <> 0) THEN
    BEGIN
      WMES = 2;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR2, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL2);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR2, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL2);
        END
    END

  /* M?S 03 */
  IF (PRVALOR3 <> 0) THEN
    BEGIN
      WMES = 3;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR3, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL3);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR3, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL3);
        END
    END

  /* M?S 04 */
  IF (PRVALOR4 <> 0) THEN
    BEGIN
      WMES = 4;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR4, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL4);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR4, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL4);
        END
    END

  /* M?S 05 */
  IF (PRVALOR5 <> 0) THEN
    BEGIN
      WMES = 5;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR5, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL5);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR5, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL5);
        END
    END

  /* M?S 06 */
  IF (PRVALOR6 <> 0) THEN
    BEGIN
      WMES = 6;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR6, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL6);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR6, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL6);
        END
    END

  /* M?S 07 */
  IF (PRVALOR7 <> 0) THEN
    BEGIN
      WMES = 7;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR7, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL7);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR7, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL7);
        END
    END

  /* M?S 08 */
  IF (PRVALOR8 <> 0) THEN
    BEGIN
      WMES = 8;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR8, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL8);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR8, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL8);
        END
    END

  /* M?S 09 */
  IF (PRVALOR9 <> 0) THEN
    BEGIN
      WMES = 9;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR9, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL9);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR9, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL9);
        END
    END

  /* M?S 10 */
  IF (PRVALOR10 <> 0) THEN
    BEGIN
      WMES = 10;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR10, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL10);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR10, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL10);
        END
    END

  /* M?S 11 */
  IF (PRVALOR11 <> 0) THEN
    BEGIN
      WMES = 11;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR11, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL11);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR11, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL11);
        END
    END

  /* M?S 12 */
  IF (PRVALOR12 <> 0) THEN
    BEGIN
      WMES = 12;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR12, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL12);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR12, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL12);
        END
    END

  SUSPEND;
END
^

/* Alter (VLAL_SP_RETORNA_INT_CONTABLALUR) */
ALTER PROCEDURE VLAL_SP_RETORNA_INT_CONTABLALUR(PRCODEMP VARCHAR(2048),
PRMATRIZFILIAL VARCHAR(2048),
PRCODCONTABLALUR INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRACUMULADO INTEGER,
PRDATALANC DATE,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRTIPOLANC INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRREFERENCIA INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA VARCHAR(7),
BDMESANO INTEGER,
BDDATA DATE,
BDCONTA INTEGER,
BDNOMLPA VARCHAR(60),
BDVALOR NUMERIC(15,2),
BDTIPOLANC INTEGER,
BDCODTPLA INTEGER,
BDCHAVELAN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WEXPORTAR INTEGER;
DECLARE VARIABLE WINVERTESINAL INTEGER;
DECLARE VARIABLE WCLASSINI VARCHAR(50);
DECLARE VARIABLE WCLASSFIN VARCHAR(50);
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WSALDOATUAL NUMERIC(15,2);
DECLARE VARIABLE WMOVIMENTO NUMERIC(15,2);
BEGIN
  /* se for mensal */
  IF (pracumulado = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafim FROM 1 FOR 4)||SUBSTRING(prdatafim FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- acumulado _____________________________________________________________________
     BEGIN
       wtotal = 1;
     END

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao =  (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prreferencia
                                    ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  AND planos_tpla.bdcodtpla = :prcontainicial
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao =  (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prreferencia
                                    ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  AND planos_tpla.bdcodtpla = :prcontafinal
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao =  (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prreferencia
                                    ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdcodplapadrao DESC, planos_tpla.bdctalon DESC
  INTO :wclassfin;

  --alt:15116 - 26/08/2016 - Alterado join para corrigir erro na integra??o, estava trazendo Lucro Real e Presumido juntos quando h? uma conta preparada com ambos mesmo que selecionado na filtragem apenas um dos dois. Pedro
  --wSql = ' select integra.bdcodtpla, planoA.BDNOMLPA, integra.BDCODLPALEST, planoReal.BDCODLPA as BDCODLPALR, integra.bdexportar, integra.bdinvertesinal ';
  wSql = ' select distinct integra.bdcodtpla, planoA.BDNOMLPA, PlanoA.BDCODLPA, PlanoPadraoA.BDTIPO, integra.bdexportar, integra.bdinvertesinal ';
  wSql = wSql || ' from VLAL_BASE_TCONTAS_CONTAB_LALUR Integra ';
  wSql = wSql || ' left outer join PLANOS_TPLA tpla on tpla.bdcodplapadrao = Integra.bdcodplapadrao and tpla.bdcodtpla = Integra.bdcodtpla ';
  wSql = wSql || ' left outer join VLAL_BASE_TCONF_CONTAB_LALUR IntegraConf on IntegraConf.BDCODCONTABLALUR = Integra.BDCODCONTABLALUR ';
  --alt:13903 - 31/03/2016 - Alterado join, um apenas para as informa??es da conta do lalur e outro apenas para trazer o IR e CSLL na mesma coluna (ambos s?o Lucro Real). Pedro
  wSql = wSql || ' left outer join VLAL_PLANOS_TLPA PlanoReal on PlanoReal.BDCODPARTEA = IntegraConf.BDCODPARTEALR and ((PlanoReal.BDCODLPA = Integra.BDCODLPALRIR) or (PlanoReal.BDCODLPA = Integra.BDCODLPALRCSLL))';
  wSql = wSql || ' join VLAL_BASE_LALUR_PARTEA PlanoPadraoA on (PlanoPadraoA.BDCODPARTEA = IntegraConf.BDCODPARTEALR) or (PlanoPadraoA.BDCODPARTEA = IntegraConf.BDCODPARTEALP) ';
  --alt:15116 - 26/08/2016 - Alterado join para corrigir erro na integra??o, estava trazendo Lucro Real e Presumido juntos quando h? uma conta preparada com ambos mesmo que selecionado na filtragem apenas um dos dois. Pedro
  --wSql = wSql || ' join VLAL_PLANOS_TLPA PlanoA on ((PlanoA.BDCODPARTEA = IntegraConf.BDCODPARTEALR) and (PlanoA.BDCODLPA = PLANOREAL.BDCODLPA)) or ((PlanoA.BDCODPARTEA = IntegraConf.BDCODPARTEALP) and (PlanoA.BDCODLPA = Integra.BDCODLPALEST))';
  wSql = wSql || ' join VLAL_PLANOS_TLPA PlanoA on (PlanoA.BDCODPARTEA = PlanoPadraoA.BDCODPARTEA) and '||
                                                  '(((PlanoA.BDCODLPA = PlanoReal.BDCODLPA) and (PlanoPadraoA.BDTIPO = 0)) or'||
                                                  ' ((PlanoA.BDCODLPA = Integra.BDCODLPALEST) and (PlanoPadraoA.BDTIPO = 1)))';
  wSql = wSql || ' where (integra.BDCODCONTABLALUR = '||prcodcontablalur||')';
  wSql = wSql || '   and (tpla.bdctalon between '''||:wclassini||''' and  '''||:wclassfin||''')';
  wSQL = wSQL || '   and (integra.bdexportar is not null)';
  wSql = wSql || ' order by tpla.bdctalon ';
  --FOR EXECUTE STATEMENT wsql INTO :wcodtpla, :bdnomlpa, :wcodlpalest, :wcodlpalr, :wexportar, :winvertesinal DO
  FOR EXECUTE STATEMENT wSQL INTO :BDCODTPLA, :BDNOMLPA, :BDCONTA, :BDTIPOLANC, :wexportar, :winvertesinal DO
    BEGIN
      wcount = 1;
      WHILE (wcount -1 < wtotal) DO
        BEGIN
          -- Mensal ________________________________________________________
          IF (pracumulado = 0) THEN
            BEGIN
              wdata_inicial = addmonth(prdataini, wcount-1);
              wdata_final   = addmonth(prdataini, wcount)-1;
            END
          ELSE
            BEGIN
              wdata_inicial = prdataini;
              wdata_final   = prdatafim;
            END

          bdvalor = 0;
          --alt:11995 - 12/08/2015 - Adicionados novos par?metros e vari?veis de retorno (CHAVELAN e CODEMP). Pedro
          FOR SELECT SUM(SALDO_ANTERIOR), SUM(SALDO_DEB), SUM(SALDO_CRE), SUM(SALDO_ATUAL),
              CASE WHEN (:printcontabillalur = 1) THEN CHAVELAN ELSE NULL END AS CHAVELAN,
              CASE WHEN (:printcontabillalur = 1) THEN CODEMP ELSE NULL END AS CODEMP
              FROM SP_RETORNA_SALDO_MATRIZFILIAL_X(:prcodemp, :prmatrizfilial, :BDCODTPLA, :wdata_inicial, :wdata_final, :prignorazeramento,NULL,NULL,
                                                   :prreferencia, 0, :prcontabilizacao, :prmatrizfilialconsolidado, :prIntContabilLalur) tsal
              GROUP BY CHAVELAN, CODEMP
              INTO :wanterior, :wdebito, :wcredito, :wsaldoatual, :BDCHAVELAN, :BDCODEMP DO
           BEGIN
             wmovimento = :wsaldoatual - :wanterior;

             --alt:15116 - 26/08/2016 - Alterado m?todo de tratamento dos dados. Mais simples e corrigindo erro de estar integrando Lucro
             --Real e Presumido juntos quando h? uma conta preparada com ambos mesmo que selecionado na filtragem apenas um dos dois. Pedro
             BDDATA = CASE WHEN prAcumulado = 0 THEN wData_Final ELSE prDataLanc END;
             BDREFERENCIA = SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                            SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4);
             BDMESANO = SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2);

             IF (wexportar = 0) THEN
                bdvalor = wmovimento;
             ELSE
             IF (wexportar = 1) THEN
                bdvalor = wdebito;
             ELSE
             IF (wexportar = 2) THEN
                bdvalor = wcredito;
             ELSE
             IF (wexportar = 3) THEN
                bdvalor = wsaldoatual;
             ELSE
             IF (wexportar = 4) THEN
                bdvalor = wanterior;

             IF (winvertesinal = 0) THEN
                bdvalor = bdvalor * -1;

             --alt:18994 - 07/06/2017 - Se for integra??o do Lalur, tamb?m deve retornar o registro, porque sempre ter? o valor zerado. Pedro
             --alt:15116 - 26/08/2016 - Adicionado filtro para a forma de apura??o do lucro. Pedro
             --alt:13903 - 31/03/2016 - S? deve integrar se tiver algum valor. Pedro
             IF (((prIntContabilLalur = 1) OR (BDVALOR <> 0)) AND ((BDTIPOLANC = prTipoLanc) OR (prTipoLanc = 2))) THEN
               SUSPEND;

             --alt:15116 - In?cio do m?todo antigo. Pedro
             /*--alt:11995 - 12/08/2015 - Passa o valor de retorno para os novos campos. Pedro
             bdcodtpla = :wcodtpla;
             if (wcodemp > 0) then
               bdcodemp = wcodemp;

             -- Lucro Real
             IF  (((prtipolanc = 0) OR (prtipolanc = 2)) AND (((wcodlpalr <> 0) AND ((:wdebito) <> 0 OR (:wcredito<>0) OR (:wsaldoatual <> 0))) or (printcontabillalur = 1)) ) THEN --alt:11995 - 12/08/2015 - Adicionada excess?o para o prIntContabilLalur. Pedro
               BEGIN
                 BDCONTA = wCodlpalr;
                 IF (pracumulado = 0) THEN
                    bddata = wdata_final;
                 ELSE
                    bddata = prdatalanc;

                 bdtipolanc = 0;
                 bdreferencia = SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                                SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4);
                 bdmesano = SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2);

                 IF (wexportar = 0) THEN
                    bdvalor = wmovimento;
                 ELSE
                 IF (wexportar = 1) THEN
                    bdvalor = wdebito;
                 ELSE
                 IF (wexportar = 2) THEN
                    bdvalor = wcredito;
                 ELSE
                 IF (wexportar = 3) THEN
                    bdvalor = wsaldoatual;
                 ELSE
                 IF (wexportar = 4) THEN
                    bdvalor = wanterior;


                 IF (winvertesinal = 0) THEN
                    bdvalor = bdvalor * -1;

                 if (bdvalor <> 0) then --alt:13903 - 31/03/2016 - S? deve integrar se tiver algum valor. Pedro
                   SUSPEND;
               END

             -- Lucro Presumido
             IF  (((prtipolanc = 1) OR (prtipolanc = 2)) AND (((wcodlpalest <> 0) AND (((:wdebito) <> 0 OR (:wcredito<>0) OR (:wsaldoatual <> 0))))  or (printcontabillalur = 1)) ) THEN --alt:11995 - 12/08/2015 - Adicionada excess?o para o prIntContabilLalur. Pedro
               BEGIN
                 IF (pracumulado = 0) THEN
                    bddata = wdata_final;
                 ELSE
                    bddata = prdatalanc;
                 bdconta = wcodlpalest;
                 bdtipolanc = 1;
                 bdreferencia = SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                                SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4);

                 bdmesano = SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2);

                 IF (wexportar = 0) THEN
                    bdvalor = wmovimento;
                 ELSE
                 IF (wexportar = 1) THEN
                    bdvalor = wdebito;
                 ELSE
                 IF (wexportar = 2) THEN
                    bdvalor = wcredito;
                 ELSE
                 IF (wexportar = 3) THEN
                    bdvalor = wsaldoatual;
                 ELSE
                 IF (wexportar = 4) THEN
                    bdvalor = wanterior;

                 IF (winvertesinal = 0) THEN
                    bdvalor = bdvalor * -1;

                 if (bdvalor <> 0) then --alt:13903 - 31/03/2016 - S? deve integrar se tiver algum valor. Pedro
                   SUSPEND;
               END*/
             --alt:15116 - Fim
           END

          wcount = wcount + 1;
        END
    END
END
^

/* Alter (VRH_SP_ALTERACAOSALARIAL) */
ALTER PROCEDURE VRH_SP_ALTERACAOSALARIAL(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(15000),
PRDATAINICIAL DATE,
PRDATAFINAL DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATACOL DATE,
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDDESCMAS VARCHAR(50),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDCODCBO INTEGER,
BDTIPOCOL INTEGER,
BDSALINICOL NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WORDERBY VARCHAR(15000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WCODCOLAUX INTEGER;
DECLARE VARIABLE WCODTFUC INTEGER;
DECLARE VARIABLE WSALBASECOLAUX NUMERIC(18,6);
BEGIN
   /*wSql = 'select ';
   wSql = wSql || 'colcon_dia.bdcodemp, ';
   wSql = wSql || 'colcon_dia.bdcodcol, ';
   wSql = wSql || 'colcon_dia.bddatacol, ';
   wSql = wSql || 'colcon_dia.bdcodmas, ';
   wSql = wSql || 'colcon_dia.bdsalbasecol, ';
   wSql = wSql || 'tmotaumsal.bddescmas, ';
   wSql = wSql || 'tcolfunc.bdcodtfuc, ';
   wSql = wSql || 'tcolfunc.bddesctfuc, ';
   wSql = wSql || 'tcolfunc.bdcodcbo, ';
   wSql = wSql || 'tcolcalc.bdtipocol ';


   wSql = wSql || 'from VRH_SP_COLCON_DIA ('||prEmpresa||','||prColaborador||','||prdatainicial||','||prdatafinal||') colcon_dia ';
   wSql = wSql || 'left outer join vrh_base_tmotaumsal tmotaumsal on (tmotaumsal.bdcodmas = colcon_dia.bdcodmas) ';
   wSql = wSql || 'left outer join VRH_FUNCOES_TFUC tcolfunc on (tcolfunc.bdcodplafuc = colcon_dia.bdcodplafuc and tcolfunc.bdcodtfuc = colcon_dia.bdcodtfuc) ';
   wSql = wSql || 'left outer join vrhf_emp_tcol_calc tcolcalc on (tcolcalc.BDCODEMP = colcon_dia.BDCODEMP and tcolcalc.BDCODCOL = colcon_dia.BDCODCOL and
                                                                   tcolcalc.bdrefcol = substring(cast(colcon_dia.bddatacol as VarChar(10)) from 1 for 4) ||
                                                                   substring(cast(colcon_dia.bddatacol as VarChar(10)) from 6 for 2)) ';

   wWhere = '';
   wOrderBy = 'order by colcon_dia.bddatacol ';

   wSql = wSql||wwhere||worderby;*/
   wcodempaux = 0;
   wcodcolaux = 0;
   wsalbasecolaux = 0;

 FOR SELECT 
  colcon_dia.bdcodemp,
  colcon_dia.bdcodcol,
  vw_col.bdnomcol,
  IIF(COALESCE(tcolshe.bddatashe,'') <> '', tcolshe.bddatashe, colcon_dia.bddatacol), -- 17420 | Marcelo B. M. | 05/06/2017
  colcon_dia.bdcodmas,
  IIF(COALESCE(tcolshe.bdsalshe,0) <> 0, tcolshe.bdsalshe, colcon_dia.bdsalbasecol),  -- 17420 | Marcelo B. M. | 05/06/2017
  IIF(COALESCE(tcolshe.bdcodmas,0) <> 0, tmothoresp.bddescmas, tmotaumsal.bddescmas), -- 17420 | Marcelo B. M. | 05/06/2017
  tcolfunc.bdcodtfuc,
  tcolfunc.bddesctfuc,
  tcolfunc.bdcodcbo,
  tcolcalc.bdtipocol,
  vw_col.bdsalinicol

 FROM 
  VRH_SP_COLCON_DIA(:prempresa, :prcolaborador, :prdatainicial, :prdatafinal) colcon_dia
 LEFT OUTER JOIN  
  vw_colaboradores vw_col ON (vw_col.bdcodemp = colcon_dia.BDCODEMP AND vw_col.bdcodcol = colcon_dia.BDCODCOL)
 LEFT OUTER JOIN 
  vrh_base_tmotaumsal tmotaumsal ON (tmotaumsal.bdcodmas = colcon_dia.bdcodmas)
 LEFT OUTER JOIN 
  VRH_FUNCOES_TFUC tcolfunc ON (tcolfunc.bdcodplafuc = colcon_dia.bdcodplafuc AND 
           tcolfunc.bdcodtfuc = colcon_dia.bdcodtfuc)
 LEFT OUTER JOIN 
  vrhf_emp_tcol_calc tcolcalc ON (tcolcalc.BDCODEMP = colcon_dia.BDCODEMP AND tcolcalc.BDCODCOL = colcon_dia.BDCODCOL AND
          tcolcalc.bdrefcol = (select first 1 bdrefcol from vrhf_emp_tcol_calc where BDCODEMP = colcon_dia.BDCODEMP
          AND BDCODCOL = colcon_dia.BDCODCOL and bdrefcol <= extract(year from colcon_dia.bddatacol) || lpad(extract(month from COLCON_DIA.BDDATACOL),2,0) order by BDREFCOL desc)
          )
 LEFT OUTER JOIN -- 17420 | Marcelo B. M. | 31/05/2017
  VRH_EMP_TCOL_SHE tcolshe ON (tcolshe.bdcodemp = colcon_dia.BDCODEMP AND tcolshe.BDCODCOL = colcon_dia.BDCODCOL)
 LEFT OUTER JOIN -- 17420 | Marcelo B. M. | 05/06/2017
  vrh_base_tmotaumsal tmothoresp ON (tmothoresp.bdcodmas = tcolshe.bdcodmas)

   INTO
    :bdcodemp,
    :bdcodcol,
    :bdnomcol,
    :bddatacol,
    :bdcodmas,
    :bdsalbasecol,
    :bddescmas,
    :bdcodtfuc,
    :bddesctfuc,
    :bdcodcbo,
    :bdtipocol,
    :bdsalinicol DO
   BEGIN
     IF ((bdcodemp <> wcodempaux) OR (bdcodcol <> wcodcolaux) OR (bdsalbasecol <> wsalbasecolaux) OR (WCODTFUC <> bdcodtfuc)) THEN --Caso o mesmo colaborador tenha 2 ou mais vezes 'altera??o salarial' com o mesmo sal?rio.
        BEGIN
            wcodempaux = bdcodemp;
            wcodcolaux = bdcodcol;
            wsalbasecolaux = bdsalbasecol;
   WCODTFUC = bdcodtfuc;
            SUSPEND;
        END
   END
END
^

/* Alter (VRH_SP_AUMENTOSALARIO) */
ALTER PROCEDURE VRH_SP_AUMENTOSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDDATACOL DATE,
BDSALBASECOLANT NUMERIC(15,2),
BDSALBASECOLATU NUMERIC(15,2),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDHORASMENSAISCOL NUMERIC(15,2),
BDTIPOCOL INTEGER)
 AS
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WULTDIA VARCHAR(10);
BEGIN

--  execute procedure sp_seta_competencia(PRANOMES, null, null);

  wmes = CAST(SUBSTRING(CAST(:pranomes AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:pranomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;


  wwhere = 'select COL.bdcodemp, empresas.bdnomemp, COL.bdcodcol , COL.bdnomcol , COL.bddataadmcol, col.bdcodcla, classe.BDDESCCLA, col.bdcodtfuc, colfunc.BDDESCTFUC, col.bdHORASMENSAISCOL, col.bdTIPOCOL ';
  wwhere = wwhere||'from vrh_sp_colcon(null,null,null,null,null, ' || pranomes || ' , '''||wultdia||''' , 1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0) col ';
  wwhere = wwhere||'join VRH_BASE_TCLASSE classe on (col.bdcodcla = classe.bdcodcla)';
  wwhere = wwhere||'left outer join VRH_FUNCOES_TFUC colfunc on  (col.BDCODPLAFUC = colfunc.BDCODPLAFUC and col.BDCODTFUC = colfunc.BDCODTFUC) ';

  IF (prcodemp > 0) THEN
    BEGIN
      wwhere = wwhere||'left outer join sp_consultaempresas(' || pranomes || ' , ' || prCodEmp || '  ,null) empresas on (col.bdcodemp = empresas.bdcodemp)';
      wwhere = wwhere||'where col.bdcodemp in ('||prcodemp||') ';
    END
  ELSE
      wwhere = wwhere||'left outer join sp_consultaempresas(' || pranomes || ' , ' || ' null ' || '  ,null) empresas on (col.bdcodemp = empresas.bdcodemp)';

  IF (prcodcol > 0) THEN
     wwhere = wwhere||'and col.bdcodcol in ('||prcodcol||') ';

  FOR EXECUTE STATEMENT wwhere
      INTO :bdcodemp, :bdnomemp,  :bdcodcol , :bdnomcol , :bddataadmcol, :bdcodcla , :bddesccla, :bdcodtfuc, :bddesctfuc, :bdhorasmensaiscol, :bdtipocol  DO
      BEGIN
        bdsalbasecolant = 0;
        bdsalbasecolatu = 0;

        FOR SELECT FIRST 2 COLDIA.bddatacol,  COLDIA.bdsalbasecol, COLDIA.bdcodmas, codmas.bddescmas
            FROM VRH_EMP_TCOLCON_CALCDIA COLDIA
            LEFT OUTER JOIN VRH_BASE_TMOTAUMSAL codmas ON (coldia.bdcodmas = codmas.bdcodmas)
            WHERE coldia.bdcodemp = :bdcodemp
            AND coldia.bdcodcol = :bdcodcol
            AND coldia.bddatacol <= :wultdia
            ORDER BY coldia.bddatacol DESC
            INTO :bddatacol, :wvalor, :bdcodmas, :bddescmas DO
            BEGIN
              IF (bdsalbasecolatu = 0) THEN
                 bdsalbasecolatu = wvalor;
              ELSE
                 bdsalbasecolant = wvalor;
            END

         IF (bdsalbasecolant <> 0) THEN
            BEGIN


              SUSPEND;
            END
      END
END
^

/* Alter (VRH_SP_CAD_TERC) */
ALTER PROCEDURE VRH_SP_CAD_TERC(PRCODCOL VARCHAR(32700),
PRCODCLA VARCHAR(1000),
PRREF INTEGER,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOLCON_DIA SMALLINT)
 RETURNS(BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL VARCHAR(10),
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODCBO INTEGER,
BDCODCBOTSIN INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255))
 AS
DECLARE VARIABLE WCAM VARCHAR(20000);
DECLARE VARIABLE WWHE VARCHAR(10000);
DECLARE VARIABLE WV VARCHAR(30);
DECLARE VARIABLE WI VARCHAR(3);
DECLARE VARIABLE WD VARCHAR(30);
DECLARE VARIABLE WB VARCHAR(30);
DECLARE VARIABLE WN VARCHAR(30);
DECLARE VARIABLE WTRUE VARCHAR(5);
DECLARE VARIABLE WDATA VARCHAR(10);
BEGIN
   -- Seta a compet?ncia atual.
   -- Algumas View's utilizam essas vari?veis de contexto para filtrar e agrupar tabelas.
   wdata = CAST(prref AS VARCHAR(6));
   wdata = SUBSTRING(wdata FROM 5 FOR 2)||'-01-'||SUBSTRING(wdata FROM 1 FOR 4);
   EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wdata AS DATE), CAST(wdata AS DATE));

   /* Retorna o usu?rio logado */
--   for select BDCODUSU from sp_get_usuario
--     into
--       :wcodusu
--     do

   wtrue = '(0=0)';
   prcodcol = COALESCE(prcodcol,wtrue);
   prcodcla = COALESCE(prcodcla,wtrue);

   wv = ', CAST(NULL AS varchar(1))';
   wi = ', 0';
   wd = ', CAST(NULL AS DATE)';
   wb = ', CAST(NULL AS BLOB)';
   wn = ', CAST(NULL AS NUMERIC(15,6))';

   wcam = 'select COLCON.BDCODTER ';

   -- CAMPOS
   IF (:PRCOLCON = 0) THEN
      wcam = wcam||wi||wi||wi||wi||
                   wi||wi||wv||wv||wv||
                   wi||wv||wv||wv||wi||
                   wv||wv||wv||wi||
                   wd||wd||wi||wi||
                   wd||wd;
   ELSE
      wcam = wcam||wi||', COLCON.BDCODCID'||wi||wi||
                   ', COLCON.BDCODCIDNASCTER'||wi||', COLCON.BDNOMTER, COLCON.BDLOGRTER, COLCON.BDENDTER '||
                   ', COLCON.BDNUMTER, COLCON.BDCOMPLTER, COLCON.BDBAITER, COLCON.BDCEPTER, COLCON.BDDDDTER '||
                   ', COLCON.BDFONETER, COLCON.BDCELTER, COLCON.BDEMAILTER, COLCON.BDSEXOTER '||
                   ', COLCON.BDDATANASCTER, COLCON.BDDATACADTER, TTERCREF.bdgrauinstrucao, TTERCREF.bdestadocivil '||
                   wd||wd;

   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wd||
                   wv||wv||wv||wd;
   ELSE
      wcam = wcam||', COLCON_DOC.bdrgter, COLCON_DOC.BDORGEMIRGTER, COLCON_DOC.BDDATAEMIRGTER '||
                   ', COLCON_DOC.BDCPFTER, COLCON_DOC.BDRESERVISTATER, COLCON_DOC.BDPISTER'||wd;

   /*Dados n?o existentes no terceiro
   if (:PRCOL_DOC = 0) then*/
      wcam = wcam||wi||wv||
                   wi||wi||wi||wi||
                   wv||wd||wv||wd||
                   wv;

/* Dados nao existentes para o terceiro
   if (:PRCOL_HIST = 0) then*/
      wcam = wcam||wi||wi||wv||wd;

--   if (:PRCOL_PARENT = 0) then
      wcam = wcam||wi||wv||wv||wv||wd;

--   if (:PRCOL_FIS = 0) then
      wcam = wcam||wi||wi||wi||wn||wn||wv||wi||wi;

--   if (:PRCON_DOC = 0) then
   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wv;
   ELSE
      wcam = wcam||', COLCON_DOC.BDNROCONSPROTER, COLCON_DOC.BDSIGLACONSPROTER, COLCON_DOC.BDCODCCMPROTER';

   IF (:PRCOLCON_VINC = 0 AND :PRCODCLA IS NULL) THEN
      wcam = wcam||wi||wi;
   ELSE
      wcam = wcam||', COLCON_VINC.BDCODCLA, CLASSE.BDGRUPOCLA';

   /*SINDICATO terceiro nao possui*/
   wcam = wcam||wi||wi;

   IF (:PRCOLCON_BANCO = 0) THEN
      wcam = wcam||wi||wi||wv||wv||wi||wi||wv;
   ELSE
      wcam = wcam||', COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPCOL, COLCON_BANCO.BDDIGCTADEPCOL '||
                   ', COLCON_BANCO.BDTIPOCTACOL, COLCON_BANCO.BDMODOPAGTOCOL, COLCON_BANCO.BDCARTAOSALCOL';

   IF (:PRCOLCON_CALC = 0) THEN
      wcam = wcam||wi||wi||wn||wn||wn;
   ELSE
      wcam = wcam||wi||', TTERCREF.bdnrodepircol'||wn||wn||wn;

   /*Terceiro nao tem dados de fgts apenas de gps*/
   IF (:PRCOLCON_FGTSGPS = 0) THEN
      wcam = wcam||wd||wv||wi||wn||wi||wn||wn;
   ELSE
      wcam = wcam||wd||wv||', COLCON_FGTSGPS.BDCATEGORIACOL '||
                   ', COLCON_FGTSGPS.BDPERCFGTSCOL, COLCON_FGTSGPS.BDOCORRENCIACOL '||
                   ', COLCON_FGTSGPS.BDPERCRATCOL, COLCON_FGTSGPS.BDPERCDESCFPASCOL';

   IF (:PRCOLCON_MVINC = 0) THEN
      wcam = wcam||wn||wn||wn||wn||wn||wn||wn||wn;
   ELSE
      wcam = wcam||', COLCON_MVINC.BDBASEINSSNCOL, COLCON_MVINC.BDVALORINSSNCOL, COLCON_MVINC.BDBASEIRRFNCOL '||
                   ', COLCON_MVINC.BDVALORIRRFNCOL'||wn||wn||
                   wn||wn;

--   if (:PRCOL_ADM = 0) then
      wcam = wcam||wi||wi||wd||wn||wi||wd||wi||wd||wv||wi||wv||wv||wv||wv||wv||wi;

--   if (:PRCOL_CALC = 0) then
      wcam = wcam||wi||wn||wn||wn||wn||wi||wn||wi||wn||wi||wi||wv||wv||wv||wv||wv||wv||wv||wv||wv;

--   if (:PRCOL_HISTF = 0) then
      wcam = wcam||wb;

--   if (:PRCON_VINC = 0) then
      wcam = wcam||wi||wv;

   IF (:prcolcon_dia = 0) THEN
      wcam = wcam||wi||wn||wi||wi||wi||wi||wi;
   ELSE
      wcam = wcam||wi||wn||wi||wi||', COLCON_VINC.BDCODCBO, COLCON_VINC.BDCODCBOTSIN'||wi;


   /* Tabela de Rescisao nao existe para terceiros*/
    wcam = wcam||wi||wd||wd||wd||wd||
                 wn||wv||wn||wv||
                 wd||wv||wv||wd||wv;

    /* Motivos de rescis?o nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||wi||
                 wv||wi||wi||wv||wv||wv||
                 wv||wi||wi||
                 wv||wv||
                 wv||
                 wv||
                 wv;


   /* Tabela de Transferencias nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wd;

    /* Motivos de transfer?ncia nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||
                 wv||wv||
                 wv||
                 wv||
                 wv;

   -- TABELAS
   wcam = wcam||' from vrh_base_tterc COLCON ';
   wcam = wcam||' join VW_VRH_BASE_TTERC_REF TTERCREF on (TTERCREF.bdcodCOL = COLCON.bdcodter) ';

   IF (:PRCOLCON_DOC <> 0) THEN
      wcam = wcam||' join vw_VRH_BASE_TTERC_DOC  COLCON_DOC on (COLCON_DOC.bdcodter = COLCON.bdcodter) ';

   IF (:PRCOLCON_VINC = 1 OR :PRCODCLA IS NOT NULL)  THEN
      BEGIN
        wcam = wcam||' join VW_VRH_BASE_TTERC_VINC COLCON_VINC '||
                         'on (COLCON_VINC.BDCODCOL = COLCON.bdcodter) ';

        -- Grupo da Classe
        wcam = wcam||' join VRH_BASE_TCLASSE CLASSE '||
                            'on (CLASSE.BDCODCLA = COLCON_VINC.BDCODCLA) ';
      END

   IF (:PRCOLCON_BANCO = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_BASE_TTERC_BANCO '||
                            'COLCON_BANCO on (COLCON_BANCO.BDCODCOL = COLCON.bdcodter) ';
      END

   IF (:PRCOLCON_FGTSGPS = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_BASE_TTERC_FGTSGPS '||
                            'COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODCOL = COLCON.bdcodter) ';
      END

   IF (:PRCOLCON_MVINC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_BASE_TTERC_MVINC '||
                            'COLCON_MVINC on (COLCON_MVINC.BDCODCOL = COLCON.BDCODTER) ';
      END

   -- WHERE
   wwhe = '';
   IF (:prCODCOL IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcol;

      END

   IF (:PRCODCLA IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcla;
      END

  /* filtra as empresas por usuario */
/*  if (wcodusu is not null and wcodusu <> 0) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';

       wwhe = wwhe||'((exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||') and '||
                        'exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TSERV.BDCODEMP)) '||
                       'or '||
                       '(not exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||'))'||
                       ') ';
     end*/

   IF ((wwhe <> '') AND (:wwhe IS NOT NULL)) THEN
      wwhe = ' where '||wwhe;
      
   wcam = wcam||wwhe;

   FOR EXECUTE STATEMENT wcam
      INTO :
           -- VRH_EMP_TCOLCON
           BDCODCOL, :BDCODMCAG, :BDCODCID, :BDCODCSEG, :BDREFCSEG,
           :BDCODCIDNASC, :BDCODUF, :BDNOMCOL, :BDLOGRCOL, :BDENDCOL,
           :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL, :BDDDDCOL,
           :BDFONECOL, :BDCELCOL, :BDEMAILCOL, :BDSEXOCOL,
           :BDDATANASCCOL, :BDDATACADCOL, :BDGRAUINSTCOL, :BDESTCIVCOL,
           :BDDATAADMCOL, :BDDATAADICCOL,

           :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDCPFCOL,
           :BDRESERVISTACOL, :BDPISCOL, :BDDATAEMIPISCOL,

           :BDCODUF_COL_DOC, :BDTITELEICOL, :BDZONAELEICOL,
           :BDSECAOELEICOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDVENCCNHCOL, :BDCATCNHCOL,

           :BDCODCID_HIST, :BDCODPAIS, :BDNATURALIZADOCOL, :BDDATACHEBRASILCOL,

           :BDCODCIDNASCCONJ, :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL,

           :BDCORCOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL,:BDPESOCOL, :BDSINAISCOL,
           :BDDEFFISICOCOL, :BDTIPOSANGUECOL,

           :BDNROCONSPROCOL, :BDSIGLACONSPROCOL, :BDCODCCMPROCOL,

           :BDCODCLA, :BDGRUPOCLA,

           :BDCODMEN, :BDCODSINTRAB,

           :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL, :BDTIPOCTACOL, :BDMODOPAGTOCOL, :BDCARTAOSALCOL,

           :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL,

           :BDDATAOPCAOFGTSCOL, :BDCTAFGTSCOL, :BDCATEGORIACOL, :BDPERCFGTSCOL,
           :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL,

           :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
           :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL,

           :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDSALINICOL, :BDDIASPRAZO1COL,
           :BDDATAFIMPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO2COL, :BDDESCCONTSINCOL, :BDVINCEMPCOL,
           :BDALVARACOL, :BDSINDICALIZADOCOL, :BDREGIMEPARCIALCOL, :BDFICHAREGCOL, :BDLIVROREGCOL,
           :BDNROFOLHAREGCOL,

           :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL,
           :BDPERCINSALUBCOL , :BDINCIDINSALUBCOL, :BDPERCPERCULCOL, :BDINCIDPERICULCOL,
           :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL,
           :BDCALCADIANTACOL, :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL,
           :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL,

           :BDOBSCOL,

           :BDCODGPS, :BDDESCINSSDOIRCOL,

           :BDCODMAS, :BDSALBASECOL,
           :BDCODPLAFUC, :BDCODTFUC, :BDCODCBO, :BDCODCBOTSIN, :BDCODQH,

           -- Rescisao
           :BDCODPRES,
           :BDDATARESCISAO,
           :BDDATAAVPREVIO,
           :BDDATAHOM,
           :BDDATAPAGRESCISAO,
           :BDSALDOFGTS,
           :BDCALCFGTSMESANT,
           :BDMAIORREMUNERACAO,
           :BDCHAVEINDENTIFICACAO,
           :BDDATAPAGGRFC,
           :BDREPOSICAOVAGA,
           :BDDISSIDIO,
           :BDDATADISSIDIO,
           :BDDESCANSOINDENIZADO,
           :BDCODMFGRESC,
           :BDCODSAQUERESC,
           :BDCODMRAISRESC,
           :BDCODMCAGRESC,
           :bddescpres,
           :BDINIPRES,
           :BDJCPRES,
           :BDAVPREPRES,
           :BDGRRFPRES,
           :BDESTPRES,
           :BDINDFER13,
           :BDTERMCONTRPRES,
           :BDMULTAPRES,
           :BDDIASAVPREPRES,
           :BDDIASPAGPRES,
           :BDCODSEFMFGRESC,
           :BDDESCMFGRESC,
           :BDDESCSAQUERESC,
           :BDDESCMRAISRESC,
           :BDDESCMCAGEDRESC,

           --Transferencia
           :BDCODEMPDESTTRAN,
           :BDCODPTRAN,
           :BDCODCOLTRANS,
           :BDDATATRANS,
           :BDCODMCAGENTTRANS,
           :BDCODMCAGSAITRANS,
           :BDCODMFGTRANS,
           :BDCODMRAISTRANS,
           :BDDESCPTRANS,
           :BDCODSEFMFGTRANS,
           :BDDESCMFGTRANS,
           :BDDESCRAISTRANS,
           :BDDESCMCAGEDENTTRANS,
           :BDDESCMCAGEDSAITRANS
           DO

    SUSPEND;

   EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRH_SP_COLCON) */
ALTER PROCEDURE VRH_SP_COLCON(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSIN VARCHAR(1000),
PRCODCLA VARCHAR(1000),
PRCODFUC VARCHAR(1000),
PRREF INTEGER,
PRULTDIA DATE,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOL_DOC SMALLINT,
PRCOL_HIST SMALLINT,
PRCOL_PARENT SMALLINT,
PRCOL_FIS SMALLINT,
PRCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOL_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOL_ADM SMALLINT,
PRCOL_CALC SMALLINT,
PRCOL_HISTF SMALLINT,
PRCON_VINC SMALLINT,
PRCOLCON_DIA SMALLINT,
PRFILTRARESC SMALLINT,
PRFILTRATRANS SMALLINT,
PRFILTRASIT SMALLINT,
PRFILTRAFERIAS SMALLINT,
PRFILTRA13SALARIO SMALLINT,
PRFILTRAFOLHANORMAL SMALLINT,
PRREFFOLHANORMAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL INTEGER,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCONTRCOL INTEGER,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB SUB_TYPE 1 SEGMENT SIZE 5000,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(18,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255))
 AS
DECLARE VARIABLE WCAM VARCHAR(20000);
DECLARE VARIABLE WWHE VARCHAR(10000);
DECLARE VARIABLE WV VARCHAR(30);
DECLARE VARIABLE WI VARCHAR(3);
DECLARE VARIABLE WD VARCHAR(30);
DECLARE VARIABLE WB VARCHAR(30);
DECLARE VARIABLE WN VARCHAR(30);
DECLARE VARIABLE WTRUE VARCHAR(5);
DECLARE VARIABLE WDATA VARCHAR(10);
DECLARE VARIABLE WCODUSU INTEGER;
BEGIN
   -- Seta a competencia atual.
   -- Algumas Views utilizam essas variaveis de contexto para filtrar e agrupar tabelas.
   wdata = CAST(prref AS VARCHAR(6));
   wdata = SUBSTRING(wdata FROM 5 FOR 2)||'-01-'||SUBSTRING(wdata FROM 1 FOR 4);
   EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wdata AS DATE), prultdia);

   /* Retorna o usuario logado */
   FOR SELECT BDCODUSU FROM sp_get_usuario
     INTO
       :wcodusu
     DO

   wtrue = '(0=0)';
   prcodemp = COALESCE(prcodemp,wtrue);
   prcodcol = COALESCE(prcodcol,wtrue);
   prcodcla = COALESCE(prcodcla,wtrue);
   prcodsin = COALESCE(prcodsin,wtrue);
   prcodfuc = COALESCE(prcodfuc,wtrue);

   wv = ', CAST(NULL AS varchar(1))';
   wi = ', 0';
   wd = ', CAST(NULL AS DATE)';
   wb = ', CAST(NULL AS BLOB)';
   wn = ', CAST(NULL AS NUMERIC(15,6))';

   wcam = 'select COLCON.BDCODEMP, COLCON.BDCODCOL ';

   -- CAMPOS
   IF (:PRCOLCON = 0) THEN
      wcam = wcam||wi||wi||wi||wi||
                   wi||wi||wv||wv||wv||
                   wi||wv||wv||wv||wi||
                   wv||wv||wv||wi||
                   wd||wd||wi||wi||
                   wd||wd||wi;
   ELSE
      wcam = wcam||', COLCON.BDCODMCAG, COLCAD.BDCODCID, COLCON.BDCODCSEG, COLCON.BDREFCSEG '||
                   ', COLCON.BDCODCIDNASC, DOCREF.BDCODUF, COLCAD.BDNOMCOL, COLCAD.BDLOGRCOL, COLCAD.BDENDCOL '||
                   ', COLCAD.BDNUMCOL, COLCAD.BDCOMPLCOL, COLCAD.BDBAICOL, COLCAD.BDCEPCOL, COLCAD.BDDDDCOL '||
                   ', COLCAD.BDFONECOL, COLCAD.BDCELCOL, COLCAD.BDEMAILCOL, COLCAD.BDSEXOCOL '||
                   ', COLCON.BDDATANASCCOL, COLCON.BDDATACADCOL, COLCAD.BDGRAUINSTCOL, COLCAD.BDESTCIVCOL '||
                   ', COLCON.BDDATAADMCOL, COLCON.BDDATAADICCOL, COLCON.BDCONTRCOL ';

   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wd||
                   wv||wv||wv||wd;
   ELSE
      wcam = wcam||', DOCREF.BDRGCOL, DOCREF.BDORGEMIRGCOL, DOCREF.BDDATAEMIRGCOL '||
                   ', COLCON_DOC.BDCPFCOL, COLCON_DOC.BDRESERVISTACOL, DOCREF.BDPISCOL, DOCREF.BDDATAEMIPISCOL';

   IF (:PRCOL_DOC = 0) THEN
      wcam = wcam||wi||wv||
                   wi||wi||wi||wi||
                   wv||wd||wv||wd||
                   wv;
   ELSE
      wcam = wcam||', DOCREF.BDCODUF, COL_DOC.BDTITELEICOL '||
                   ', COL_DOC.BDZONAELEICOL, COL_DOC.BDSECAOELEICOL, DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL '||
                   ', DOCREF.BDDSERIECTPSCOL, DOCREF.BDDATAEMICTPSCOL, DOCREF.BDCNHCOL, DOCREF.BDVENCCNHCOL '||
                   ', DOCREF.BDCATCNHCOL';

   IF (:PRCOL_HIST = 0) THEN
      wcam = wcam||wi||wi||wv||wd;
   ELSE
      wcam = wcam||', COLCON.BDCODCIDNASC, COL_HIST.BDCODPAIS, COL_HIST.BDNATURALIZADOCOL, COLCAD.BDDATACHEBRASILCOL';

   IF (:PRCOL_PARENT = 0) THEN
      wcam = wcam||wi||wv||wv||wv||wd;
   ELSE
      wcam = wcam||', COL_PARENT.BDCODCIDNASCCONJ, COL_PARENT.BDNOMPAICOL, COL_PARENT.BDNOMMAECOL, COL_PARENT.BDNOMCONJCOL, COL_PARENT.BDDATANASCCONJCOL';

   IF (:PRCOL_FIS = 0) THEN
      wcam = wcam||wi||wi||wi||wn||wn||wv||wi||wi;
   ELSE
      wcam = wcam||', CFIS.BDCORCOL, COL_FIS.BDCABELOSCOL, COL_FIS.BDOLHOSCOL, COL_FIS.BDALTURACOL, COL_FIS.BDPESOCOL '||
                   ', COL_FIS.BDSINAISCOL, COL_FIS.BDDEFFISICOCOL, COL_FIS.BDTIPOSANGUECOL';

   IF (:PRCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wv;
   ELSE
      wcam = wcam||', CON_DOC.BDNROCONSPROCOL, CON_DOC.BDSIGLACONSPROCOL, CON_DOC.BDCODCCMPROCOL';

--   wcam = wcam||', COLCON_REF.BDREFCOL';

   IF (:PRCOLCON_VINC = 0 AND :PRCODCLA IS NULL) THEN
      wcam = wcam||wi||wi;
   ELSE
      wcam = wcam||', COLCON_VINC.BDCODCLA, CLASSE.BDGRUPOCLA';

   IF (:PRCOL_VINC = 0 AND :PRCODSIN IS NULL) THEN
      wcam = wcam||wi||wi;
   ELSE
      wcam = wcam||', COL_VINC.BDCODMEN, COL_VINC.BDCODSINTRAB';

   IF (:PRCOLCON_BANCO = 0) THEN
      wcam = wcam||wi||wi||wv||wv||wi||wi||wv;
   ELSE
      wcam = wcam||', COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPCOL, COLCON_BANCO.BDDIGCTADEPCOL '||
                   ', COLCON_BANCO.BDTIPOCTACOL, COLCON_BANCO.BDMODOPAGTOCOL, COLCON_BANCO.BDCARTAOSALCOL';

   IF (:PRCOLCON_CALC = 0) THEN
      wcam = wcam||wi||wi||wn||wn||wn;
   ELSE
      wcam = wcam||', COLCON_CALC.BDFORMAPAGTOCOL, COLCON_CALC.BDNRODEPIRCOL, COLCON_CALC.BDBASEIRRFADCOL '||
                   ', COLCON_CALC.BDVALORPREVPRIVNCOL, COLCON_CALC.BDVALORPREVPRIV13COL';

   IF (:PRCOLCON_FGTSGPS = 0) THEN
      wcam = wcam||wd||wv||wi||wn||wi||wn||wn;
   ELSE
      wcam = wcam||', COLCON_FGTSGPS.BDDATAOPCAOFGTSCOL, COLCON_FGTSGPS.BDCTAFGTSCOL, COLCON_FGTSGPS.BDCATEGORIACOL '||
                   ', COLCON_FGTSGPS.BDPERCFGTSCOL, COLCON_FGTSGPS.BDOCORRENCIACOL '||
                   ', COLCON_FGTSGPS.BDPERCRATCOL, COLCON_FGTSGPS.BDPERCDESCFPASCOL';

   IF (:PRCOLCON_MVINC = 0) THEN
      wcam = wcam||wn||wn||wn||wn||wn||wn||wn||wn;
   ELSE
      wcam = wcam||', COLCON_MVINC.BDBASEINSSNCOL, COLCON_MVINC.BDVALORINSSNCOL, COLCON_MVINC.BDBASEIRRFNCOL '||
                   ', COLCON_MVINC.BDVALORIRRFNCOL, COLCON_MVINC.BDBASEINSS13COL, COLCON_MVINC.BDVALORINSS13COL '||
                   ', COLCON_MVINC.BDBASEIRRF13COL, COLCON_MVINC.BDVALORIRRF13COL';

   IF (:PRCOL_ADM = 0) THEN
      BEGIN
        wcam = wcam||wi||wi||wd||wn||wi||wd||wi||wd||wv||wi||wv||wv;

        IF (:PRCOL_CALC = 0) THEN
           wcam = wcam||wv;
        ELSE
           wcam = wcam||', COL_CALC.BDREGIMEPARCIALCOL';

        wcam = wcam||wv||wv||wi;

      END
   ELSE
      BEGIN
        wcam = wcam||', COL_ADM.BDTIPOADMCOL, COL_ADM.BDNATUOCUPCOL, COL_ADM.BDDATAINIAQUICOL, COL_ADM.BDSALINICOL '||
                     ', COL_ADM.BDDIASPRAZO1COL, COL_ADM.BDDATAFIMPRAZO1COL, COL_ADM.BDDIASPRAZO2COL, COL_ADM.BDDATAFIMPRAZO2COL '||
                     ', COL_ADM.BDDESCCONTSINCOL, ADMREF.BDVINCEMPCOL, ADMREF.BDALVARACOL, ADMREF.BDSINDICALIZADOCOL ';

        IF (:PRCOL_CALC = 0) THEN
           wcam = wcam||wv;
        ELSE
           wcam = wcam||', COL_CALC.BDREGIMEPARCIALCOL';

        wcam = wcam||', COL_ADM.BDFICHAREGCOL, COL_ADM.BDLIVROREGCOL, COL_ADM.BDNROFOLHAREGCOL';
      END

   IF (:PRCOL_CALC = 0) THEN
      wcam = wcam||wi||wn||wn||wn||wn||wi||wn||wi||wn||wi||wi||wv||wv||wv||wv||wv||wv||wv||wv||wv;
   ELSE
      wcam = wcam||', COL_CALC.BDTIPOCOL, COL_CALC.BDHORASMENSAISCOL, COL_CALC.BDHORASSEMANAISCOL, COL_CALC.BDHORASDIARIASCOL '||
                   ', COL_CALC.BDPERCINSALUBCOL, COL_CALC.BDINCIDINSALUBCOL, COL_CALC.BDPERCPERCULCOL, COL_CALC.BDINCIDPERICULCOL '||
                   ', COL_CALC.BDPERCNOTURNOCOL, COL_CALC.BDINCIDNOTURNOCOL, COL_CALC.BDNRODEPSALFAMCOL, COL_CALC.BDIGNORAFALTASFERCOL '||
                   ', COL_CALC.BDCALCADIANTACOL, COL_CALC.BDNAOARREDONDARCOL, COL_CALC.BDIMPETIQUETACOL, COL_CALC.BDCALCDSRRVCOL  '||
                   ', COL_CALC.BDCALCDSRHECOL, COL_CALC.BDCALCDSRSALCOL, COL_CALC.BDCALCVALTRANSCOL, COL_CALC.BDCALCVALREFCOL';

   IF (:PRCOL_HISTF = 0) THEN
      wcam = wcam||wb;
   ELSE
      wcam = wcam||', COL_HISTF.BDOBSCOL';

   IF (:PRCON_VINC = 0) THEN
      wcam = wcam||wi||wv;
   ELSE
      wcam = wcam||', CON_VINC.BDCODGPS, CON_VINC.BDDESCINSSDOIRCOL';

   IF (:prcolcon_dia = 0) THEN
      wcam = wcam||wi||wn||wi||wi||wi;
   ELSE
      wcam = wcam||', COLCON_DIACALC.BDCODMAS, COLCON_DIACALC.BDSALBASECOL, '||
                   'COL_DIAVINC.BDCODPLAFUC, COL_DIAVINC.BDCODTFUC, COL_DIAVINC.BDCODQH ';


   /* Tabela de Rescisao */
   IF (:prfiltraresc = 0) THEN
      BEGIN
        wcam = wcam||wi||wd||wd||wd||wd||
                     wn||wv||wn||wv||
                     wd||wv||wv||wd||wv;

        /* Motivos de rescisao */
        wcam = wcam||wi||wi||wi||wi||wv||wi||
                     wv||wi||wi||wv||wv||wv||
                     wv||wi||wi||
                     wv||wv||
                     wv||
                     wv||
                     wv;
      END
   ELSE
      BEGIN

        wcam = wcam||', RESC.BDCODPRES, RESC.BDDATARESCISAO, RESC.BDDATAAVPREVIO, RESC.BDDATAHOM, RESC.BDDATAPAGRESCISAO'||
                     ', RESC.BDSALDOFGTS, RESC.BDCALCFGTSMESANT, RESC.BDMAIORREMUNERACAO, RESC.BDCHAVEINDENTIFICACAO'||
                     ', RESC.BDDATAPAGGRFC, RESC.BDREPOSICAOVAGA, RESC.BDDISSIDIO, RESC.BDDATADISSIDIO, RESC.BDDESCANSOINDENIZADO';
        wcam = wcam||', RESC.BDCODMFG, RESC.BDCODSAQUE, RESC.BDCODMRAIS, RESC.BDCODMCAG, RESC.BDDESCPRES, RESC.BDINIPRES'||
                     ', RESC.BDJCPRES, RESC.BDAVPREPRES, RESC.BDGRRFPRES, RESC.BDESTPRES, RESC.BDINDFER13, RESC.BDTERMCONTRPRES'||
                     ', RESC.BDMULTAPRES, RESC.BDDIASAVPREPRES, RESC.BDDIASPAGPRES'||
                     ', RESC.BDCODSEFMFG, RESC.BDDESCMFG'||
                     ', RESC.BDDESCSAQUE'||
                     ', RESC.BDDESCMRAIS'||
                     ', RESC.BDDESCMCAGED ';

      END

   /* Tabela de Transferencias */
   IF (:prfiltratrans = 0) THEN
      BEGIN
        wcam = wcam||wi||wi||wi||wd;

        /* Motivos de transferencia */
        wcam = wcam||wi||wi||wi||wi||wv||
                     wv||wv||
                     wv||
                     wv||
                     wv;
      END
   ELSE
      BEGIN
        wcam = wcam||', TRANS.BDCODEMPDEST, TRANS.BDCODPTRAN, TRANS.BDCODCOLDEST, TRANS.BDDATATRF';
        wcam = wcam||', TRANS.BDCODMCAGENT, TRANS.BDCODMCAGSAI, TRANS.BDCODMFG, TRANS.BDCODMRAIS, TRANS.BDDESCPTRAN'||
                     ', TRANS.BDCODSEFMFG, TRANS.BDDESCMFG'||
                     ', TRANS.BDDESCMRAIS'||
                     ', TRANS.BDDESCMCAGED_TE'||
                     ', TRANS.BDDESCMCAGED_TS ';
      END

   -- TABELAS
   wcam = wcam||' from VRH_EMP_TCOLCON COLCON ';
   wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) ';
   wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_FIS CFIS on (CFIS.BDCODEMP = COLCON.BDCODEMP and CFIS.BDCODCOL = COLCON.BDCODCOL) ';
   wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';

   IF (:PRCOLCON_DOC = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOLCON_DOC  COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ';

   IF (:PRCOL_DOC = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOL_DOC     COL_DOC on (COL_DOC.BDCODEMP = COLCON.BDCODEMP and COL_DOC.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCOL_HIST = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOL_HIST    COL_HIST on (COL_HIST.BDCODEMP = COLCON.BDCODEMP and COL_HIST.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCOL_PARENT = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOL_PARENT  COL_PARENT on (COL_PARENT.BDCODEMP = COLCON.BDCODEMP and COL_PARENT.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCOL_FIS = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOL_FIS     COL_FIS on (COL_FIS.BDCODEMP = COLCON.BDCODEMP and COL_FIS.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCON_DOC = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCON_DOC     CON_DOC on (CON_DOC.BDCODEMP = COLCON.BDCODEMP and CON_DOC.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCOL_ADM = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VRH_EMP_TCOL_ADM '||
                           'COL_ADM on (COL_ADM.BDCODEMP = COLCON.BDCODEMP and '||
                                       'COL_ADM.BDCODCOL = COLCON.BDCODCOL) ';
        wcam = wcam||' left outer join VW_VRH_EMP_TCOL_ADMREF '||
                           'ADMREF on (ADMREF.BDCODEMP = COLCON.BDCODEMP and '||
                                       'ADMREF.BDCODCOL = COLCON.BDCODCOL) ';
      END

   --wcam = wcam||' left outer join VW_TCOLCON_REF_ATUAL COLCON_REF '||
   --                 'on (COLCON_REF.BDCODEMP = COLCON.BDCODEMP and COLCON_REF.BDCODCOL = COLCON.BDCODCOL) ';

   IF (:PRCOLCON_VINC = 1 OR :PRCODCLA IS NOT NULL)  THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC '||
                         'on (COLCON_VINC.BDCODEMP = COLCON.BDCODEMP and '||
                             'COLCON_VINC.BDCODCOL = COLCON.BDCODCOL) ';

        -- Grupo da Classe
        wcam = wcam||' left outer join VRH_BASE_TCLASSE CLASSE '||
                            'on (CLASSE.BDCODCLA = COLCON_VINC.BDCODCLA) ';
      END

   IF (:PRCOL_VINC = 1 OR :PRCODSIN IS NOT NULL) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRH_EMP_TCOL_VINC '||
                            'COL_VINC on (COL_VINC.BDCODEMP = COLCON.BDCODEMP and '||
                                         'COL_VINC.BDCODCOL = COLCON.BDCODCOL) ';

      END

   IF (:PRCOLCON_BANCO = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOLCON_BANCO '||
                            'COLCON_BANCO on (COLCON_BANCO.BDCODEMP = COLCON.BDCODEMP and '||
                                             'COLCON_BANCO.BDCODCOL = COLCON.BDCODCOL) ';
      END
   IF (:PRCOLCON_CALC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOLCON_CALC '||
                            'COLCON_CALC on (COLCON_CALC.BDCODEMP = COLCON.BDCODEMP and '||
                                            'COLCON_CALC.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCOLCON_FGTSGPS = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS '||
                            'COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODEMP = COLCON.BDCODEMP and '||
                                               'COLCON_FGTSGPS.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCOLCON_MVINC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOLCON_MVINC '||
                            'COLCON_MVINC on (COLCON_MVINC.BDCODEMP = COLCON.BDCODEMP and '||
                                             'COLCON_MVINC.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCOL_CALC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOL_CALC '||
                            'COL_CALC on (COL_CALC.BDCODEMP = COLCON.BDCODEMP and '||
                                         'COL_CALC.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCOL_HISTF = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOL_HIST '||
                            'COL_HISTF on (COL_HISTF.BDCODEMP = COLCON.BDCODEMP and '||
                                          'COL_HISTF.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCON_VINC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCON_VINC '||
                            'CON_VINC on (CON_VINC.BDCODEMP = COLCON.BDCODEMP and '||
                                         'CON_VINC.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:prcolcon_dia = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_CALCDIA '||
                            'COLCON_DIACALC on (COLCON_DIACALC.BDCODEMP = COLCON.BDCODEMP and '||
                                               'COLCON_DIACALC.BDCODCOL = COLCON.BDCODCOL) ';

        wcam = wcam||' left outer join VW_TCOLCON_VINCDIA '||
                            'COL_DIAVINC on (COL_DIAVINC.BDCODEMP = COLCON.BDCODEMP and '||
                                            'COL_DIAVINC.BDCODCOL = COLCON.BDCODCOL) ';

      END


   IF (:prfiltraresc > 0) THEN
      BEGIN
        IF (prfiltraresc > 3) THEN
           BEGIN
             wcam = wcam||' left outer join VW_RESCISAO_PREVIA '||
                                 'RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and '||
                                          'RESC.BDCODCOL = COLCON.BDCODCOL) ';
           END
        ELSE
           BEGIN
             wcam = wcam||' left outer join VW_RESCISAO '||
                                 'RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and '||
                                          'RESC.BDCODCOL = COLCON.BDCODCOL) ';
           END

      END


   IF (:prfiltratrans > 0) THEN
      BEGIN
        wcam = wcam||' left outer join vw_transf '||
                            'TRANS on (TRANS.BDCODEMPORIG = COLCON.BDCODEMP and TRANS.BDCODCOLORIG = COLCON.BDCODCOL) ';
      END


   -- WHERE
   wwhe = '';
   IF (:prCODEMP IS NOT NULL) THEN
      BEGIN
        wwhe = prcodemp;
      END

   IF (:prCODCOL IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcol;

      END

   IF (:PRCODSIN IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodsin;
      END

   IF (:PRCODCLA IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcla;
      END

   IF (:prcolcon_dia <> 0 AND :prcodfuc IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodfuc;
      END

   -- Retira admitidos posteriores
   IF (:PRCOLCON <> 0) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||' COLCON.BDDATAADMCOL <= '''||:prultdia||'''';
      END

   -- Faz filtro para retirar colaboradores transferidos
   IF (:PRFILTRATRANS = 2) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
               '((TRANS.BDDATATRF is null) or '||
                '(TRANS.BDDATATRF >= '''||wdata||''')) ';

               --'((TRANS.BDDATATRF is null) or '||
               --'(cast((substring(cast(TRANS.BDDATATRF as VARCHAR(10)) from 1 for 4)||substring(cast(TRANS.BDDATATRF as VARCHAR(10)) from 6 for 2)) as INTEGER) >= '||:PRREF||')) ';
      END

   IF (:PRFILTRATRANS = 3) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
               '((TRANS.BDDATATRF is null) or '||
                '(TRANS.BDDATATRF > '''||prultdia||''')) ';
      END

   -- Faz filtro para retirar colaboradores demitidos
   -- Elimina recisoes anteriores ao ano/mes atual
   IF (:PRFILTRARESC = 2) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
               '((RESC.BDDATARESCISAO is null) or '||
                '(RESC.BDDATARESCISAO >= '''||wdata||''')) ';

      END

   -- Elimina rescisoes a partir do mes atual, ou seja,
   -- nao inclui no resultado do select os demitidos no mes.
   IF (:PRFILTRARESC = 3) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
              '((RESC.BDDATARESCISAO is null) or '||
               '(RESC.BDDATARESCISAO > '''||prultdia||''')) ';

      END

   -- Faz filtro para retirar colaboradores demitidos   PREVIA
   -- Elimina recisoes anteriores ao ano/mes atual
   IF (:PRFILTRARESC = 4) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
               '((RESC.BDDATARESCISAO is null) or '||
                '(RESC.BDDATARESCISAO >= '''||wdata||''')) ';

      END

   -- Elimina rescisoes a partir do mes atual, ou seja,
   -- nao inclui no resultado do select os demitidos no mes.       PREVIA
   IF (:PRFILTRARESC = 5) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
              '((RESC.BDDATARESCISAO is null) or '||
               '(RESC.BDDATARESCISAO > '''||prultdia||''')) ';

      END


   IF (:PRFILTRASIT = 1) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||'not exists(select SIT.* from vrh_emp_tsitcol SIT '||
                                'where SIT.BDCODEMP = COLCON.BDCODEMP and '||
                                      'SIT.BDCODCOL = COLCON.BDCODCOL and '||
                                      'SIT.BDDATAINISIT <= '''||prultdia||''' and '||
                                      '(SIT.BDDATAFIMSIT is null or '||
                                       'SIT.BDDATAFIMSIT >= '''||wdata||'''))';
                                      --'cast((substring(cast(bddatainisit as varchar(10)) from 1 for 4) || substring(cast(bddatainisit as varchar(10)) from 6 for 2)) as Integer) <= '||:PRREF||' and '||
                                      --'(bddatafimsit is null or '||
                                      --     'cast((substring(cast(bddatafimsit as varchar(10)) from 1 for 4) || substring(cast(bddatafimsit as varchar(10)) from 6 for 2)) as Integer) >= '||:PRREF||'))';
      END

   IF (:PRFILTRAFERIAS = 1) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||'not exists(select FER.* from vrh_emp_tferias FER '||
                                'where FER.BDCODEMP = COLCON.BDCODEMP and '||
                                      'FER.BDCODCOL = COLCON.BDCODCOL and '||
                                     '((FER.BDINIPERGOZOFE is not null and FER.BDINIPERGOZOFE between '''||wdata||''' and '''||prultdia||''') or '||
                                      '(FER.BDFIMPERGOZOFE is not null and FER.BDFIMPERGOZOFE between '''||wdata||''' and '''||prultdia||''')'||
                                     ')'||
                               ') ';
                  --'(CAST((SUBSTRING(CAST(FER.BDINIPERGOZOFE as VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(FER.BDINIPERGOZOFE as VARCHAR(10)) FROM 6 FOR 2)) as INTEGER) = '||:PRREF||') or (CAST((SUBSTRING(CAST(FER.BDFIMPERGOZOFE as VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(FER.BDFIMPERGOZOFE as VARCHAR(10)) FROM 6 FOR 2)) as INTEGER) = '||:PRREF||')) or '||
                  --'(FER.BDINIABONOFE is not null and (CAST((SUBSTRING(CAST(FER.BDINIABONOFE as VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(FER.BDINIABONOFE as VARCHAR(10)) FROM 6 FOR 2)) as INTEGER) = '||:PRREF||') or (CAST((SUBSTRING(CAST(FER.BDFIMABONOFE as VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(FER.BDFIMABONOFE as VARCHAR(10)) FROM 6 FOR 2)) as INTEGER) = '||:PRREF||')))) ';
      END

   IF (:PRFILTRA13SALARIO = 1) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||'exists(select T13SAL.BDCODEMP from vrhf_emp_t13sal T13SAL '||
                                'where T13SAL.BDCODEMP = COLCON.BDCODEMP and '||
                                      'T13SAL.BDCODCOL = COLCON.BDCODCOL and '||
                                      '(substring(cast(T13SAL.BDREF13 as integer) from 1 for 4)) =  (substring(cast('||:PRREF||' as integer) from 1 for 4) '||')) ';
      END

   IF (prfiltrafolhanormal IS NOT NULL AND prfiltrafolhanormal = 1) THEN
      BEGIN
        IF (PRREFFOLHANORMAL IS NOT NULL AND PRREFFOLHANORMAL <> 0) THEN
           BEGIN
             IF (wwhe <> '') THEN
                 wwhe = wwhe||' and ';
     
             wwhe = wwhe||'exists(select TFOLHANORMAL.BDCODEMP from vrhf_emp_tfolhanormal TFOLHANORMAL '||
                                     'where TFOLHANORMAL.BDCODEMP = COLCON.BDCODEMP and '||
                                           'TFOLHANORMAL.BDCODCOL = COLCON.BDCODCOL and '||
                                           'TFOLHANORMAL.BDREFFN = ' ||:PRREFFOLHANORMAL|| ') ';
           END
      END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhe <> '') THEN
          wwhe = wwhe||' and ';

       wwhe = wwhe||'((exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||') and '||
                        'exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = COLCON.BDCODEMP)) '||
                       'or '||
                       '(not exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||'))'||
                       ') ';
     END

   IF ((wwhe <> '') AND (:wwhe IS NOT NULL)) THEN
      wwhe = ' where '||wwhe;
      
   wcam = wcam||wwhe;

   FOR EXECUTE STATEMENT wcam
      INTO :BDCODEMP,
           -- VRH_EMP_TCOLCON
           :BDCODCOL, :BDCODMCAG, :BDCODCID, :BDCODCSEG, :BDREFCSEG,
           :BDCODCIDNASC, :BDCODUF, :BDNOMCOL, :BDLOGRCOL, :BDENDCOL,
           :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL, :BDDDDCOL,
           :BDFONECOL, :BDCELCOL, :BDEMAILCOL, :BDSEXOCOL,
           :BDDATANASCCOL, :BDDATACADCOL, :BDGRAUINSTCOL, :BDESTCIVCOL,
           :BDDATAADMCOL, :BDDATAADICCOL, :BDCONTRCOL,

           :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDCPFCOL,
           :BDRESERVISTACOL, :BDPISCOL, :BDDATAEMIPISCOL,

           :BDCODUF_COL_DOC, :BDTITELEICOL, :BDZONAELEICOL,
           :BDSECAOELEICOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDVENCCNHCOL, :BDCATCNHCOL,

           :BDCODCID_HIST, :BDCODPAIS, :BDNATURALIZADOCOL, :BDDATACHEBRASILCOL,

           :BDCODCIDNASCCONJ, :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL,

           :BDCORCOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL,:BDPESOCOL, :BDSINAISCOL,
           :BDDEFFISICOCOL, :BDTIPOSANGUECOL,

           :BDNROCONSPROCOL, :BDSIGLACONSPROCOL, :BDCODCCMPROCOL,

           :BDCODCLA, :BDGRUPOCLA,

           :BDCODMEN, :BDCODSINTRAB,

           :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL, :BDTIPOCTACOL, :BDMODOPAGTOCOL, :BDCARTAOSALCOL,

           :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL,

           :BDDATAOPCAOFGTSCOL, :BDCTAFGTSCOL, :BDCATEGORIACOL, :BDPERCFGTSCOL,
           :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL,

           :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
           :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL,

           :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDSALINICOL, :BDDIASPRAZO1COL,
           :BDDATAFIMPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO2COL, :BDDESCCONTSINCOL, :BDVINCEMPCOL,
           :BDALVARACOL, :BDSINDICALIZADOCOL, :BDREGIMEPARCIALCOL, :BDFICHAREGCOL, :BDLIVROREGCOL,
           :BDNROFOLHAREGCOL,

           :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL,
           :BDPERCINSALUBCOL , :BDINCIDINSALUBCOL, :BDPERCPERCULCOL, :BDINCIDPERICULCOL,
           :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL,
           :BDCALCADIANTACOL, :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL,
           :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL,

           :BDOBSCOL,

           :BDCODGPS, :BDDESCINSSDOIRCOL,

           :BDCODMAS, :BDSALBASECOL,
           :BDCODPLAFUC, :BDCODTFUC, :BDCODQH,

           -- Rescisao
           :BDCODPRES,
           :BDDATARESCISAO,
           :BDDATAAVPREVIO,
           :BDDATAHOM,
           :BDDATAPAGRESCISAO,
           :BDSALDOFGTS,
           :BDCALCFGTSMESANT,
           :BDMAIORREMUNERACAO,
           :BDCHAVEINDENTIFICACAO,
           :BDDATAPAGGRFC,
           :BDREPOSICAOVAGA,
           :BDDISSIDIO,
           :BDDATADISSIDIO,
           :BDDESCANSOINDENIZADO,
           :BDCODMFGRESC,
           :BDCODSAQUERESC,
           :BDCODMRAISRESC,
           :BDCODMCAGRESC,
           :BDDESCPRES,
           :BDINIPRES,
           :BDJCPRES,
           :BDAVPREPRES,
           :BDGRRFPRES,
           :BDESTPRES,
           :BDINDFER13,
           :BDTERMCONTRPRES,
           :BDMULTAPRES,
           :BDDIASAVPREPRES,
           :BDDIASPAGPRES,
           :BDCODSEFMFGRESC,
           :BDDESCMFGRESC,
           :BDDESCSAQUERESC,
           :BDDESCMRAISRESC,
           :BDDESCMCAGEDRESC,

           --Transferencia
           :BDCODEMPDESTTRAN,
           :BDCODPTRAN,
           :BDCODCOLTRANS,
           :BDDATATRANS,
           :BDCODMCAGENTTRANS,
           :BDCODMCAGSAITRANS,
           :BDCODMFGTRANS,
           :BDCODMRAISTRANS,
           :BDDESCPTRANS,
           :BDCODSEFMFGTRANS,
           :BDDESCMFGTRANS,
           :BDDESCRAISTRANS,
           :BDDESCMCAGEDENTTRANS,
           :BDDESCMCAGEDSAITRANS
           DO

    SUSPEND;

   EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRH_SP_CONS_COL) */
ALTER PROCEDURE VRH_SP_CONS_COL(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
WFILTRO VARCHAR(500),
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODCLA INTEGER,
BDDATAADMCOL DATE,
BDGRUPOCLA INTEGER,
BDTIPOCOL INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(2000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(wReferencia, NULL, prultdiames);


  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON_REF.BDCODCLA, COLCON_REF.BDGRUPOCLA, COLCON_REF.BDTIPOCOL, RESC.BDDATARESCISAO, CLA.BDDESCCLA, '||
         'COLCON_DOC.BDCPFCOL, DOCREF.BDPISCOL, COLCON_DIA.BDSALBASECOL, sit.bdcodsit ' ;
  wsql = wsql || 'from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_COLABORADORES_REF_ATUAL COLCON_REF ';
  wsql = wsql || 'on (COLCON_REF.BDCODEMP = COLCON.BDCODEMP and COLCON_REF.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_TCOLCON_CALCDIA COLCON_DIA ';
  wsql = wsql || 'on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC ';
  wsql = wsql || 'on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_BASE_TCLASSE CLA ';
  wsql = wsql || 'on (CLA.BDCODCLA = COLCON_REF.BDCODCLA) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';


  wsql = wsql||'left outer join (select sit.bdcodemp,sit.bdcodcol, max(sit.bdcodsit) bdcodsit from vrh_sp_dados_situacao(';

  IF ((wempresa IS NOT NULL) OR (wempresa <> 0)) THEN
     wsql = wsql||''''||'sit.BDCODEMP = '||wempresa||''''; /* empresa sit */
  ELSE
     wsql = wsql||''''||''''; /* empresa sit */

  wsql = wsql||','||''''||''''||','; /* colaborador sit */
  wsql = wsql||''''||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)||''''||',';   /* data inicial  */
  wsql = wsql||''''||prultdiames||''''||') sit group by sit.bdcodemp,sit.bdcodcol) sit on (colcon.bdcodemp = sit.bdcodemp and colcon.bdcodcol = sit.bdcodcol) ';

  wsql = wsql || 'where ';
  wsql = wsql || '(COLCON.bdcodemp = ' || :wempresa || ' or ' || :wempresa || '= 0) ';

  IF (wfiltro IS NOT NULL) THEN
     wsql = wsql || ' and ' || wfiltro;

  wsql = wsql || 'order by COLCON.BDCODCOL';

  FOR EXECUTE STATEMENT
    wSQL
  INTO
    :bdcodemp, :BDCODCOL, :BDNOMCOL, :BDDATAADMCOL, :BDCODCLA, :BDGRUPOCLA, :BDTIPOCOL, :BDDATARESCISAO, :BDDESCCLA, :BDCPFCOL, :BDPISCOL, :BDSALBASECOL, :bdcodsit
  DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRH_SP_CONS_COL_NOVO) */
ALTER PROCEDURE VRH_SP_CONS_COL_NOVO(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
WFILTRO VARCHAR(500),
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODCLA INTEGER,
BDDATAADMCOL DATE,
BDGRUPOCLA INTEGER,
BDTIPOCOL INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER,
BDCODPRES INTEGER,
BDDESCPRES VARCHAR(110),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDSTATUSQC INTEGER,
BDSTATUS_ES INTEGER)
 AS
declare variable WSQL varchar(30000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(wReferencia, NULL, prultdiames);

  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCON.BDDATAADMCOL,'||
                 'COLCON_REF.BDCODCLA, COLCON_REF.BDGRUPOCLA, calc.BDTIPOCOL,'||
                 'RESC.BDDATARESCISAO, COLCON_REF.BDDESCCLA, COLCON_DOC.BDCPFCOL, DOCREF.BDPISCOL,'||
                 'COLCON_DIA.BDSALBASECOL, ';

wsql = wsql || '( ';
wsql = wsql || '  select max(bdcodsit) from VRH_EMP_TSITCOL SIT where ';
  IF (wempresa IS NOT NULL AND wempresa <> 0) THEN
     wsql = wsql||'BDCODEMP = '||wempresa||' and ';

wsql = wsql||'SIT.bdCODEMP= COLCON.BDCODEMP and SIT.bdCODCOL=COLCON.BDCODCOL ' ;
wsql = wsql || '  and ' ;
wsql = wsql || '  ((sit.BDDATAINISEFIP between ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)||''' AND ''' || prultdiames || ''') or ' ;
wsql = wsql || '  (sit.BDDATAFIMSIT between ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' AND ''' || prultdiames || ''') or ' ;
wsql = wsql || '  (sit.BDDATAINISEFIP < ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' and (sit.BDDATAFIMSIT is null or sit.BDDATAFIMSIT > ''' || prultdiames || '''))) ' ;
wsql = wsql || ') as bdCODSIT, RESC.BDCODPRES, PRESC.BDDESCPRES, VDIA.BDCODTFUC, FUC.BDDESCTFUC, COLCON.BDSTATUSQC, COLCON.BDSTATUS_ES ';

  wsql = wsql || 'from (select COLCON.* from VRH_EMP_TCOLCON COLCON';

  IF (wempresa IS NOT NULL AND wempresa <> 0) THEN
     wsql = wsql||' where COLCON.BDCODEMP = '||wempresa;

  wsql = wsql||') COLCON ';
  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.BDCODEMP = COLCON.BDCODEMP and vinc.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_VRHF_EMP_TCOL_CALC calc on (calc.BDCODEMP = COLCON.BDCODEMP and calc.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_TCOLCON_CALCDIA COLCON_DIA ';
  wsql = wsql || 'on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC ';
  wsql = wsql || 'on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_BASE_TCLASSE COLCON_REF on (COLCON_REF.BDCODCLA = vinc.BDCODCLA) ';
  wsql = wsql || 'left outer join VRH_BASE_TPREPRESC PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
  wsql = wsql || 'left outer join VRH_EMP_TCOL_VINCDIA VDIA on (VDIA.BDCODEMP = COLCON.BDCODEMP) and (VDIA.BDCODCOL = COLCON.BDCODCOL) and (VDIA.BDDATACOL = COLCON_DIA.BDDATACOL) ';
  wsql = wsql || 'left outer join VRH_FUNCOES_TFUC FUC on (FUC.BDCODPLAFUC = VDIA.BDCODPLAFUC) and (FUC.BDCODTFUC = VDIA.BDCODTFUC) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';

  IF ((wempresa IS NOT NULL) OR (wempresa <> 0)) THEN
  BEGIN
    wsql = wsql || 'where ';
    wsql = wsql || '(COLCON.bdcodemp = ' || :wempresa || ' or ' || :wempresa || '= 0) ';

    IF ((wfiltro IS NOT NULL) AND (wfiltro <> '')) THEN
       wsql = wsql || ' and ' || wfiltro;
  END
  ELSE
  BEGIN
    IF ((wfiltro IS NOT NULL) AND (wfiltro <> '')) THEN
       wsql = wsql || ' where ' || wfiltro;
  END

  FOR EXECUTE STATEMENT
    wSQL
  INTO
    :bdcodemp, :BDCODCOL , :BDNOMCOL  , :BDDATAADMCOL, :BDCODCLA  , :BDGRUPOCLA, :BDTIPOCOL, :BDDATARESCISAO, :BDDESCCLA, :BDCPFCOL, :BDPISCOL, :BDSALBASECOL,
    :BDCODSIT, :BDCODPRES, :BDDESCPRES, :BDCODTFUC   , :BDDESCTFUC, :BDSTATUSQC, :BDSTATUS_ES
  DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
/*
  execute procedure sp_seta_competencia(wReferencia, null, prultdiames);


  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDNOMCOL, COLCON.BDDATAADMCOL,'||
                 'COLCON_REF.BDCODCLA, COLCON_REF.BDGRUPOCLA, calc.BDTIPOCOL,'||
                 'RESC.BDDATARESCISAO, COLCON_REF.BDDESCCLA, COLCON_DOC.BDCPFCOL, COLCON_DOC.BDPISCOL,'||
                 'COLCON_DIA.BDSALBASECOL, sit.bdcodsit ';
  wsql = wsql || 'from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.BDCODEMP = COLCON.BDCODEMP and vinc.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_VRHF_EMP_TCOL_CALC calc on (calc.BDCODEMP = COLCON.BDCODEMP and calc.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_TCOLCON_CALCDIA COLCON_DIA ';
  wsql = wsql || 'on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC ';
  wsql = wsql || 'on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_BASE_TCLASSE COLCON_REF on (COLCON_REF.BDCODCLA = vinc.BDCODCLA) ';


  wsql = wsql||'left outer join (select sit.bdcodemp,sit.bdcodcol, max(sit.bdcodsit) bdcodsit from vrh_sp_dados_situacao(';

  if ((wempresa is not null) or (wempresa <> 0)) then
     wsql = wsql||''''||'sit.BDCODEMP = '||wempresa||''''; -- empresa sit
  else
     wsql = wsql||''''||''''; -- empresa sit

  wsql = wsql||','||''''||''''||','; -- colaborador sit
  wsql = wsql||''''||substring(cast(wreferencia as varchar(6)) from 5 for 2)||'-01-'||substring(cast(wreferencia as varchar(6)) from 1 for 4)||''''||',';   -- data inicial
  wsql = wsql||''''||prultdiames||''''||') sit group by sit.bdcodemp,sit.bdcodcol) sit on (colcon.bdcodemp = sit.bdcodemp and colcon.bdcodcol = sit.bdcodcol) ';

  wsql = wsql || 'where ';
  wsql = wsql || '(COLCON.bdcodemp = ' || :wempresa || ' or ' || :wempresa || '= 0) ';

  if (wfiltro is not null) then
     wsql = wsql || ' and ' || wfiltro;

  wsql = wsql || 'order by COLCON.BDCODCOL';

  for execute statement
    wSQL
  into
    :bdcodemp, :BDCODCOL, :BDNOMCOL, :BDDATAADMCOL, :BDCODCLA, :BDGRUPOCLA, :BDTIPOCOL, :BDDATARESCISAO, :BDDESCCLA, :BDCPFCOL, :BDPISCOL, :BDSALBASECOL, :bdcodsit
  do

  suspend;

  execute procedure sp_seta_competencia(null, null, null);
*/
END
^

/* Alter (VRH_SP_CONS_COLCON) */
ALTER PROCEDURE VRH_SP_CONS_COLCON(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDTIPOCOL INTEGER,
BDCODCLA INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(wreferencia, NULL, prultdiames);

  wsql = 'select ' ||
         'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON_CALC.BDTIPOCOL, COLVINC.BDCODCLA, RESC.BDDATARESCISAO, ' ||
         'CLA.BDDESCCLA, COLCON_DOC.BDCPFCOL, DOCREF.BDPISCOL, COLCON_DIA.BDSALBASECOL, ';

wsql = wsql || '( ';
wsql = wsql || '  select max(bdcodsit) from VRH_EMP_TSITCOL SIT where SIT.bdCODEMP= COLCON.BDCODEMP and SIT.bdCODCOL=COLCON.BDCODCOL ' ;
wsql = wsql || '  and ' ;
wsql = wsql || '  ((sit.BDDATAINISEFIP between ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)||''' AND ''' || prultdiames || ''') or ' ;
wsql = wsql || '  (sit.BDDATAFIMSIT between ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' AND ''' || prultdiames || ''') or ' ;
wsql = wsql || '  (sit.BDDATAINISEFIP < ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' and (sit.BDDATAFIMSIT is null or sit.BDDATAFIMSIT > ''' || prultdiames || '''))) ' ;
wsql = wsql || ') as bdCODSIT ';

wsql = wsql || 'from vrh_emp_tcolcon COLCON ' ||
         'join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VW_VRHF_EMP_TCOL_CALC COLCON_CALC on (COLCON_CALC.bdcodemp = COLCON.bdCODEMP and COLCON_CALC.bdcodcol = COLCON.bdCODCOL) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.bdcodemp = COLCON.bdcodemp and COLVINC.bdcodcol = COLCON.bdcodcol) ' ||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) ' ||
         'left outer join VW_TCOLCON_CALCDIA COLCON_DIA on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';

  wwhere = '';

  IF (wempresa IS NOT NULL AND wempresa <> 0) THEN
     wwhere = wwhere||'COLCON.BDCODEMP = '||wempresa;

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  wsql = wsql||wwhere;
  --wsql = wsql||'order by COLCON.BDCODCOL ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :BDCODCOL,
    :BDNOMCOL,
    :BDDATAADMCOL,
    :BDTIPOCOL,
    :BDCODCLA,
    :BDDATARESCISAO,
    :BDDESCCLA,
    :BDCPFCOL,
    :BDPISCOL,
    :BDSALBASECOL,
    :BDCODSIT
  DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
/*
  execute procedure sp_seta_competencia(wreferencia, null, prultdiames);

 wsql = 'select ' ||
         'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON_CALC.BDTIPOCOL, COLVINC.BDCODCLA, RESC.BDDATARESCISAO, ' ||
         'CLA.BDDESCCLA, COLCON_DOC.BDCPFCOL, COLCON_DOC.BDPISCOL, COLCON_DIA.BDSALBASECOL, sit.bdcodsit ' ||
         'from vrh_emp_tcolcon COLCON ' ||
         'join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VW_VRHF_EMP_TCOL_CALC COLCON_CALC on (COLCON_CALC.bdcodemp = COLCON.bdCODEMP and COLCON_CALC.bdcodcol = COLCON.bdCODCOL) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.bdcodemp = COLCON.bdcodemp and COLVINC.bdcodcol = COLCON.bdcodcol) ' ||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) ' ||
         'left outer join VW_TCOLCON_CALCDIA COLCON_DIA on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ';

  wsql = wsql||'left outer join (select sit.bdcodemp,sit.bdcodcol, max(sit.bdcodsit) bdcodsit from vrh_sp_dados_situacao(';

  if ((wempresa is not null) or (wempresa <> 0)) then
     wsql = wsql||''''||'sit.BDCODEMP = '||wempresa||''''; -- empresa sit
  else
     wsql = wsql||''''||''''; -- empresa sit

  wsql = wsql||','||''''||''''||','; -- colaborador sit
  wsql = wsql||''''||substring(cast(wreferencia as varchar(6)) from 5 for 2)||'-01-'||substring(cast(wreferencia as varchar(6)) from 1 for 4)||''''||',';   -- data inicial
  wsql = wsql||''''||prultdiames||''''||') sit group by sit.bdcodemp,sit.bdcodcol) sit on (colcon.bdcodemp = sit.bdcodemp and colcon.bdcodcol = sit.bdcodcol) ';

  wwhere = '';

  if (wempresa is not null and wempresa <> 0) then
     wwhere = wwhere||'COLCON.BDCODEMP = '||wempresa;

  if (wwhere <> '') then
     wwhere = 'where '||wwhere;

  wsql = wsql||wwhere;
  wsql = wsql||'order by COLCON.BDCODCOL ';

  for execute statement wsql
  into
    :bdcodemp,
    :BDCODCOL,
    :BDNOMCOL,
    :BDDATAADMCOL,
    :BDTIPOCOL,
    :BDCODCLA,
    :BDDATARESCISAO,
    :BDDESCCLA,
    :BDCPFCOL,
    :BDPISCOL,
    :BDSALBASECOL,
    :BDCODSIT
  do

  suspend;

  execute procedure sp_seta_competencia(null, null, null);
  */
END
^

/* Alter (VRH_SP_CONS_FERIAS_PER_AQUIS) */
ALTER PROCEDURE VRH_SP_CONS_FERIAS_PER_AQUIS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDGOZOFE NUMERIC(18,6),
BDQTDABONOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDNOMEMP DM_BDNOMEMP,
BDNOMCOL DM_BDNOMCOL,
BDSALDOFINALSINDFE NUMERIC(18,6),
BDCALCA13FE VARCHAR(5),
BDTIPOA13FE INTEGER,
BDPERCA13FE NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref,  NULL, NULL);

  wsql = 'select FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE, FER.BDINIPERGOZOFE, FER.BDFIMPERAQUISFE, '||
                'FER.BDFIMPERGOZOFE, FER.BDDATAPAGFE, FER.BDQTDGOZOFE, FER.BDQTDABONOFE, FER.BDSALDOINIFE, '||
                'FER.BDSALDOFIMFE, FER.BDBASEIRFE, FER.BDALIQIRFE, FER.BDVALORIRFE, FER.BDBASEINSSFE, FER.BDALIQINSSFE, '||
                'FER.BDVALORINSSFE, FER.BDDEPFE, FER.BDSALBASEFE, FER.BDSALBASEHEFE, FER.BDDATABAIXAFE, FER.BDCOLETIVASFE, '||
                'FER.BDREFPAGABOFE, FER.BDFALTASFE, EMP.BDNOMEMP, COL.BDNOMCOL, FER.BDSALDOFINALSINDFE, '||
                'FER.BDCALCA13FE, FER.BDTIPOA13FE, FER.BDPERCA13FE ';

  wsql = wsql || 'from VRH_EMP_TFERIAS FER '||
                 'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
                    'on (EMP.BDCODEMP = FER.BDCODEMP) '||
                 'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
                    'on (COL.BDCODEMP = FER.BDCODEMP and COL.BDCODCOL = FER.BDCODCOL) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     BEGIN
       wwhere = ' where '||wwhere;
       wsql = wsql||wwhere;
     END

  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE,
       :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE,
       :BDSALDOFIMFE, :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE,
       :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
       :BDREFPAGABOFE, :BDFALTASFE, :BDNOMEMP, :BDNOMCOL, :BDSALDOFINALSINDFE,
    :BDCALCA13FE, :BDTIPOA13FE, :BDPERCA13FE
  DO

  SUSPEND;

END
^

/* Alter (VRH_SP_CONS_VERBAS) */
ALTER PROCEDURE VRH_SP_CONS_VERBAS(WREFERENCIA INTEGER,
WVERBAS VARCHAR(32700),
WTAMANHOCLASSE INTEGER)
 RETURNS(BDCODVER INTEGER,
BDCLAVER VARCHAR(20),
BDAPEVER VARCHAR(20),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDORDEMVER INTEGER,
BDINATIVAVER VARCHAR(5),
BDSITVER INTEGER,
BDTIPOVER INTEGER,
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDIRVER INTEGER,
BDFGTSVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDFORMINTVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDREFVER INTEGER,
BDFORMREFAUXVER VARCHAR(5000),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDRENDISENTOIRVER VARCHAR(5),
BDSITMATVER VARCHAR(5),
BDSITDOEVER VARCHAR(5),
BDSITACITRABVER VARCHAR(5),
BDSITMILITARVER VARCHAR(5),
BDSITMATEMPVER VARCHAR(5),
BDSITACITRAB15VER VARCHAR(5),
BDSITDOETRABVER VARCHAR(5),
BDSITLICVENCVER VARCHAR(5),
BDSITDOE15VER VARCHAR(5),
BDSITSINDICALVER VARCHAR(5),
BDSITAPOINVVER VARCHAR(5),
BDSITOUTRASVER VARCHAR(5),
BDPAGAESTOUROVER DM_BOOLEAN,
BDGARANTIAMINVER DM_BOOLEAN,
BDINDRESC DM_BOOLEAN,
BDNAOCONVHORASVER DM_BOOLEAN,
BDBASEDSRHNVER DM_BOOLEAN,
BDBASEDSROUVER DM_BOOLEAN)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(wreferencia,  NULL, NULL);

  wsql = 'select VR.BDCODVER, V.BDCLAVER, V.BDAPEVER, V.BDDESCVER, V.BDDESCREDVER, V.BDORDEMVER, V.BDINATIVAVER, V.BDSITVER, V.BDTIPOVER, VR.BDTIPOCODVER, VR.BDINSSVER, VR.BDIRVER, ';
  wsql = wsql || 'VR.BDFGTSVER, VR.BDTIPOREFVER, VR.BDBASESFVER, VR.BDPISVER, VR.BDBASEHEVER, VR.BDBASEMAIORVER, VR.BDRAISVER, VR.BDBASEGPSVER, ';
  wsql = wsql || 'VR.BDMENORESVER, VR.BDPROPVER, VR.BDBASEVTVER, VR.BDREEMBGPSVER, VR.BDHEVER, VR.BDGRAVAFICHAHNVER, VR.BDCCPRINCIPALVER, ';
  wsql = wsql || 'VR.BDFORMREFVER, VR.BDFORMVALVER, VR.BDFORMINTVER, VR.BDBASEDSRHEVER, VR.BDBASEDSRRVVER, VR.BDREFVER, VR.BDFORMREFAUXVER, ';
  wsql = wsql || 'VR.BDDEDFORMREFAUXVER, VR.BDDEDFORMREFVER, ';
  wsql = wsql || 'VR.BDDEDFORMVALVER, VR.BDRENDISENTOIRVER, ';
  wsql = wsql || 'V.BDSITMATVER,V.BDSITDOEVER,V.BDSITACITRABVER,V.BDSITMILITARVER,V.BDSITMATEMPVER,V.BDSITACITRAB15VER,V.BDSITDOETRABVER,V.BDSITLICVENCVER,V.BDSITDOE15VER,';
  wsql = wsql || 'V.BDSITSINDICALVER,V.BDSITAPOINVVER,V.BDSITOUTRASVER, VR.BDPAGAESTOUROVER , VR.BDGARANTIAMINVER, VR.BDINDRESC, VR.BDNAOCONVHORASVER, VR.BDBASEDSRHNVER, VR.BDBASEDSROUVER ';

  wsql = wsql || 'from VW_VERBAS_REF_ATUAL VR, ';
  wsql = wsql || 'vrh_base_tverbas V ';

  wwhere = ' where (v.bdcodver = vr.bdcodver) ';

  IF (wverbas IS NOT NULL AND wverbas <> '') THEN
     wwhere = wwhere||' and (' || wverbas || ')';

  IF (WTAMANHOCLASSE IS NOT NULL) THEN
     wwhere = wwhere||' and (strlen(v.bdclaver) > '||WTAMANHOCLASSE||')';

  wsql = wsql||wwhere;   --||' order by V.BDCODVER';

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODVER, :BDCLAVER, :BDAPEVER, :BDDESCVER, :BDDESCREDVER, :BDORDEMVER, :BDINATIVAVER, :BDSITVER, :BDTIPOVER, :BDTIPOCODVER, :BDINSSVER,
      :BDIRVER, :BDFGTSVER, :BDTIPOREFVER, :BDBASESFVER, :BDPISVER, :BDBASEHEVER, :BDBASEMAIORVER,
      :BDRAISVER, BDBASEGPSVER, :BDMENORESVER, :BDPROPVER, :BDBASEVTVER, :BDREEMBGPSVER, :BDHEVER,
      :BDGRAVAFICHAHNVER, :BDCCPRINCIPALVER, :BDFORMREFVER, :BDFORMVALVER, :BDFORMINTVER, :BDBASEDSRHEVER,
      :BDBASEDSRRVVER, :BDREFVER, : BDFORMREFAUXVER,
      :BDDEDFORMREFAUXVER, :BDDEDFORMREFVER, :BDDEDFORMVALVER, :BDRENDISENTOIRVER,
      :BDSITMATVER, :BDSITDOEVER, :BDSITACITRABVER, :BDSITMILITARVER, :BDSITMATEMPVER, :BDSITACITRAB15VER, :BDSITDOETRABVER, :BDSITLICVENCVER,
      :BDSITDOE15VER, :BDSITSINDICALVER, :BDSITAPOINVVER, :BDSITOUTRASVER, :BDPAGAESTOUROVER , :BDGARANTIAMINVER, :BDINDRESC, :BDNAOCONVHORASVER,
      :BDBASEDSRHNVER, :BDBASEDSROUVER
    DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL,  NULL, NULL);
END
^

/* Alter (VRH_SP_CONSULTA_SITUACAO) */
ALTER PROCEDURE VRH_SP_CONSULTA_SITUACAO(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODSIT INTEGER,
BDDESCSIT VARCHAR(70),
BDDATAINISEFIP DATE,
BDDATAINISIT DATE,
BDDATAFIMSIT DATE,
BDDIASSIT INTEGER,
BDNBENEFICIOSIT VARCHAR(20),
BDDATAPERICIASIT DATE,
BDDATAPARTOSIT DATE,
BDDATAESTAB DATE,
BDCODDOE INTEGER,
BDDESCDOE VARCHAR(200),
BDTIPOACID VARCHAR(50),
BDCODMED INTEGER,
BDNOMMED VARCHAR(60),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDOBSERVACAO VARCHAR(255),
BDGRUPOSIT INTEGER)
 AS
DECLARE VARIABLE WFROM VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WCODSIND INTEGER;
DECLARE VARIABLE WSQLAUX VARCHAR(1000);
DECLARE VARIABLE WDIASETB INTEGER;
DECLARE VARIABLE WGRUPOETBSIT INTEGER;
DECLARE VARIABLE WDATAESTAB DATE;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wsql = 'select SIT.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'SIT.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'SIT.BDCODSIT, '||
                'PSIT.BDDESCSIT, '||
                'SIT.BDDATAINISEFIP, '||
                'SIT.BDDATAINISIT, '||          
                'SIT.BDDATAFIMSIT, '||
                'SIT.BDDIASSIT, '||
                'SIT.BDNBENEFICIOSIT, '||
                'SIT.BDDATAPERICIASIT, '||
                'SIT.BDDATAPARTOSIT, '||
                --'SIT.BDDATAESTAB, '||
                'SIT.BDCODDOE, '||
                'DOE.BDDESCDOE, '||
                'case when (SIT.BDTIPOACID = 0) then '''' '||
                'when (SIT.BDTIPOACID = 1) then ''1 - Atropelamento'' '||
                'when (SIT.BDTIPOACID = 2) then ''2 - Colis?o'' '||
                'when (SIT.BDTIPOACID = 3) then ''3 - Outros'' '||
                'end BDTIPOACID, '||
                'SIT.BDCODMED, '||
                'MED.BDNOMMED, '||
                'SIT.BDCODSINTRAB, '||
                'SIND.BDDESCSINTRAB, '||
                'SIT.BDOBSERVACAO, '||
                'PSIT.BDGRUPOSIT ';

  wfrom = 'from VW_TEMPRESAS_REF EMP, '||
               'VW_VRH_EMP_TCOLCON_CAD COL, '||
               'VRH_BASE_TPREPSIT PSIT, '||
               'VRH_EMP_TSITCOL SIT '||
               'left outer join VRH_BASE_TDOENCAS DOE on (SIT.BDCODDOE=DOE.BDCODDOE) '||
               'left outer join VRH_BASE_TMEDICOS MED on (SIT.BDCODMED=MED.BDCODMED) '||
               'left outer join VRH_BASE_TSINDTRAB SIND on (SIT.BDCODSINTRAB=SIND.BDCODSINTRAB) ';

  wwhere = ' where EMP.BDCODEMP = SIT.BDCODEMP and COL.BDCODEMP = SIT.BDCODEMP and COL.BDCODCOL = SIT.BDCODCOL and PSIT.BDCODSIT = SIT.BDCODSIT ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wfrom||wwhere;
  wsql = wsql||' order by SIT.BDCODEMP, SIT.BDCODCOL, '||
                         'SIT.BDDATAINISIT desc, SIT.BDCODSIT';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODSIT,
    :BDDESCSIT,
    :BDDATAINISEFIP,
    :BDDATAINISIT,
    :BDDATAFIMSIT,
    :BDDIASSIT,
    :BDNBENEFICIOSIT,
    :BDDATAPERICIASIT,
    :BDDATAPARTOSIT,
    --:BDDATAESTAB,
    :BDCODDOE,
    :BDDESCDOE,
    :BDTIPOACID,
    :BDCODMED,
    :BDNOMMED,
    :BDCODSINTRAB,
    :BDDESCSINTRAB,
    :BDOBSERVACAO,
    :BDGRUPOSIT
  DO
    BEGIN
      BDDATAESTAB = NULL;
      IF (BDDATAFIMSIT IS NOT NULL) THEN
         BEGIN
           wdataestab = BDDATAFIMSIT;
           wAnoMes = CAST((SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

           wsqlaux = 'select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||wanomes||
                     ' order by BDREFCOL DESC ';

           wcodsind = NULL;
           EXECUTE STATEMENT wsqlaux INTO :wcodsind;

           IF (wcodsind IS NOT NULL) THEN
              BEGIN
                FOR SELECT PE.BDGRUPOSITETB, PE.BDDIASETB FROM VRH_BASE_TPREPESTAB PE WHERE COALESCE(PE.BDTIPOETB,0) = 0 AND PE.BDCODSINTRAB = :wcodsind INTO :wgrupoetbsit, :wdiasetb DO
                  BEGIN
                    IF (COALESCE(wgrupoetbsit, 0) = COALESCE(BDGRUPOSIT, 0) AND COALESCE(wdiasetb, 0) > 0) THEN
                       BEGIN
                         IF (BDGRUPOSIT IN (0,4)) THEN   -- Maternidade
                            BEGIN
                              IF (BDDATAPARTOSIT IS NOT NULL) THEN
                                 wdataestab = BDDATAPARTOSIT;
                              ELSE
                                 wdataestab = BDDATAINISIT;
                            END

                         wdataestab = wdataestab + wdiasetb - 1;
                         BDDATAESTAB = wdataestab;
                       END
                  END
              END
         END

      SUSPEND;
    END
END
^

/* empty dependent procedure body */
/* Clear: VRHF_SPF_BC_PROLABORISTAS for: VRH_SP_EMPRESAS */
ALTER PROCEDURE VRHF_SPF_BC_PROLABORISTAS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SPF_BC_SEGURADOS for: VRH_SP_EMPRESAS */
ALTER PROCEDURE VRHF_SPF_BC_SEGURADOS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VRHF_SPF_BC_TERCEIROS for: VRH_SP_EMPRESAS */
ALTER PROCEDURE VRHF_SPF_BC_TERCEIROS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

/* Alter (VRH_SP_EMPRESAS) */
ALTER PROCEDURE VRH_SP_EMPRESAS(PREMP VARCHAR(10000),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCID INTEGER,
BDCODUF INTEGER,
BDCODPLAFUC INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCENTROS INTEGER,
BDPAGEMP INTEGER,
BDFECHAMESEMP INTEGER,
BDFECHAVTEMP INTEGER,
BDARREMP INTEGER,
BDTIPOARREMP INTEGER,
BDTIPOFEREMP INTEGER,
BDSOMSALFEREMP VARCHAR(5),
BDTIPOAD13EMP INTEGER,
BDSOMSALAD13EMP VARCHAR(5),
BDPERCADSALEMP NUMERIC(15,6),
BDREFHOREMP VARCHAR(5),
BDLICREMFEREMP VARCHAR(5),
BDESTOUROEMP VARCHAR(5),
BDESTOURORESEMP VARCHAR(5),
BDFALFEREMP VARCHAR(5),
BDFALHORFEREMP VARCHAR(5),
BDDEPIRRESCEMP VARCHAR(5),
BDCODGPS INTEGER,
BDCODTERC INTEGER,
BDCODFPAS INTEGER,
BDCNAERATEMP NUMERIC(15,6),
BDEMPEMP NUMERIC(15,6),
BDAUTEMP NUMERIC(15,6),
BDFUNEMP NUMERIC(15,6),
BDCODSINPAT INTEGER,
BDCAPSOCEMP NUMERIC(15,6),
BDETIQEMP VARCHAR(5),
BDTAXSEREMP NUMERIC(15,6),
BDREFCAGEDEMP INTEGER,
BDPROPADMEMP INTEGER,
BDPROPRESEMP INTEGER,
BDPROPFEREMP INTEGER,
BDPROPSITEMP INTEGER,
BDCALCMEDIASTEMP INTEGER,
BDNATESTEMP INTEGER,
BDDATABASEEMP INTEGER,
BDPATEMP VARCHAR(5),
BDNROPROPEMP INTEGER,
BDSERPROPRIOPATEMP INTEGER,
BDPATREFCONVENIOEMP INTEGER,
BDPATCESTAALIMENTOEMP INTEGER,
BDPATADMCOZINHAEMP INTEGER,
BDPATREFTRANSPEMP INTEGER,
BDPATALICONVENIOEMP INTEGER,
BDSINDICALIZEMP VARCHAR(5),
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDIDENTEMP VARCHAR(14),
BDCATSEFIPEMP INTEGER,
BDISENFILEMP NUMERIC(15,6),
BDCETRTALIZAEMP INTEGER,
BDCODIR INTEGER,
BDCODINSS INTEGER,
BDCODMEN INTEGER,
BDCALCFCNAFNEMP VARCHAR(5),
BDCALCC13NAFNEMP VARCHAR(5),
BDTIPOCONTAB INTEGER,
BDTIPOEMIGUIAS INTEGER,
BDFAP NUMERIC(15,6),
BDTAXACNAEEMP NUMERIC(15,6),
BDPERTERC NUMERIC(15,6),
BDPERCPIS NUMERIC(15,6),
BDLIMINARAVPREVEMP INTEGER,
BDSIMPLESGPS INTEGER,
BDMESDSREMP INTEGER,
BDCODPLACONVSAU INTEGER,
BDARREDONDAFN DM_BOOLEAN,
BDARREDONDAFC DM_BOOLEAN,
BDARREDONDAFE DM_BOOLEAN,
BDARREDONDAA13 DM_BOOLEAN,
BDARREDONDA13 DM_BOOLEAN,
BDARREDONDAC13 DM_BOOLEAN,
BDARREDONDAAD DM_BOOLEAN,
BDARREDONDAAU DM_BOOLEAN,
BDARREDONDAFA DM_BOOLEAN,
BDPAGEMPCONTR INTEGER,
BDDESCFALHORASDIAS DM_BOOLEAN,
BDPERCLIMIDESCPAR NUMERIC(15,6),
BDCALCC13FNNEGEMP DM_BOOLEAN)
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WTAB VARCHAR(10000);
DECLARE VARIABLE WCODUSU INTEGER;
DECLARE VARIABLE WWHE VARCHAR(10000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  /*
  for select BDCODUSU from sp_get_usuario
  into
    wcodusu
  do  */

  wsql = 'select temp.BDCODEMP, temp_ref.BDCODCID, cid.bdcoduf, temp_ref.BDCODPLAFUC, temp_ref.BDNOMEMP, temp_ref.BDCODCENTROS, ';

  wsql = wsql || 'vrhf_temp_ref.bdpagemp, vrhf_temp_ref.bdfechamesemp, vrhf_temp_ref.bdfechavtemp, '||                   --'vrhf_tcal.bdpagemp, vrhf_tcal.bdfechamesemp, vrhf_tcal.bdfechavtemp, '||
                 'vrhf_temp_ref.bdarremp, vrhf_temp_ref.bdtipoarremp, vrhf_temp_ref.bdtipoferemp, '||                    --'vrhf_tcal.bdarremp, vrhf_tcal.bdtipoarremp, vrhf_tcal.bdtipoferemp, '||
                 'vrhf_temp_ref.bdsomsalferemp, vrhf_temp_ref.bdtipoad13emp, vrhf_temp_ref.bdsomsalad13emp, '||          --'vrhf_tcal.bdsomsalferemp, vrhf_tcal.bdtipoad13emp, vrhf_tcal.bdsomsalad13emp, '||
--                 'vrhf_temp_ref.bdpercadsalemp, vrhf_temp_ref.bdiradsalemp, vrhf_temp_ref.bdrefhoremp, '||               --'vrhf_tcal.bdpercadsalemp, vrhf_tcal.bdiradsalemp, vrhf_tcal.bdrefhoremp, '||
                 'vrhf_temp_ref.bdpercadsalemp, vrhf_temp_ref.bdrefhoremp, '||
                 'vrhf_temp_ref.bdlicremferemp, vrhf_temp_ref.bdestouroemp, vrhf_temp_ref.bdestouroresemp, '||           --'vrhf_tcal.bdlicremferemp, vrhf_tcal.bdestouroemp, vrhf_tcal.bdestouroresemp, '||
                 'vrhf_temp_ref.bdfalferemp, vrhf_temp_ref.bdfalhorferemp, vrhf_temp_ref.bddepirrescemp, ';              --'vrhf_tcal.bdfalferemp, vrhf_tcal.bdfalhorferemp, vrhf_tcal.bddepirrescemp, ';

  wsql = wsql || 'vrhf_temp_ref.BDCODGPS, vrhf_temp_ref.BDCODTERC,'||                                                                            --'vrhf_tgps.BDCODGPS, vrhf_tgps.BDCODGPSFUNEMP, vrhf_tgps.BDCODTERC, '||
                 'vrhf_temp_ref.BDCODFPAS, '||                                                                           --'vrhf_tgps.BDCODFPAS, vrhf_tgps.BDCODGPSTRANEMP, vrhf_tgps.BDFUNCOMPRAEMP, '||
                 'vrhf_temp_ref.BDCNAERATEMP, '||                                                                        --'vrhf_tgps.BDFUNVENDAEMP, vrhf_tgps.BDRETNFEMP, vrhf_tgps.BDCNAERATEMP, '||
                 'vrhf_temp_ref.BDEMPEMP, vrhf_temp_ref.BDAUTEMP, vrhf_temp_ref.BDFUNEMP, ';                             --'vrhf_tgps.BDEMPEMP, vrhf_tgps.BDAUTEMP, vrhf_tgps.BDFUNEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDCODSINPAT, vrhf_temp_ref.BDCAPSOCEMP, ';                                               --'vrhf_tgrc.BDCODSINPAT, vrhf_tgrc.BDCAPSOCEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDETIQEMP, vrhf_temp_ref.BDTAXSEREMP, '||                                                --'vrhf_tpar.BDPISDARFEMP, vrhf_tpar.BDETIQEMP, vrhf_tpar.BDTAXSEREMP, vrhf_tpar.BDREFCAGEDEMP, ';
                 'vrhf_temp_ref.BDREFCAGEDEMP, ';                                                                        --'vrhf_tpar.BDREFCAGEDEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDPROPADMEMP, vrhf_temp_ref.BDPROPRESEMP, vrhf_temp_ref.BDPROPFEREMP, ' ||               --'vrhf_tpro.BDPROPADMEMP, vrhf_tpro.BDPROPRESEMP, vrhf_tpro.BDPROPFEREMP, ' ||
                 'vrhf_temp_ref.BDPROPSITEMP, vrhf_temp_ref.BDCALCMEDIASTEMP, ';                                         --'vrhf_tpro.BDPROPSITEMP, vrhf_tpro.BDCALCMEDIASTEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDNATESTEMP, vrhf_temp_ref.BDDATABASEEMP, vrhf_temp_ref.BDPATEMP, '||                    --'vrhf_trai.BDNATESTEMP, vrhf_trai.BDDATABASEEMP, vrhf_trai.BDPATEMP, '||
                 'vrhf_temp_ref.BDNROPROPEMP, vrhf_temp_ref.BDSERPROPRIOPATEMP, vrhf_temp_ref.BDPATREFCONVENIOEMP, '||   --'vrhf_trai.BDNROPROPEMP, vrhf_trai.BDSERPROPRIOPATEMP, vrhf_trai.BDPATREFCONVENIOEMP, '||
                 'vrhf_temp_ref.BDPATCESTAALIMENTOEMP, vrhf_temp_ref.BDPATADMCOZINHAEMP, '||                             --'vrhf_trai.BDPATCESTAALIMENTOEMP, vrhf_trai.BDPATADMCOZINHAEMP, '||
                 'vrhf_temp_ref.BDPATREFTRANSPEMP, vrhf_temp_ref.BDPATALICONVENIOEMP, vrhf_temp_ref.BDSINDICALIZEMP, ';  --'vrhf_trai.BDPATREFTRANSPEMP, vrhf_trai.BDPATALICONVENIOEMP, vrhf_trai.BDSINDICALIZEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDCODBAN, vrhf_temp_ref.BDCODAG, '||                       --'vrhf_tsef.BDCODBAN, vrhf_tsef.BDCODAG, vrhf_tsef.BDNAOCALC10EMP, vrhf_tsef.BDIDENTEMP, '||
                 'vrhf_temp_ref.BDIDENTEMP, vrhf_temp_ref.BDCATSEFIPEMP, vrhf_temp_ref.BDISENFILEMP, '||                 --'vrhf_tsef.BDIDENTEMP, vrhf_tsef.BDCATSEFIPEMP, vrhf_tsef.BDISENFILEMP, '||
                 'vrhf_temp_ref.BDCETRTALIZAEMP, ';                                                                      --'vrhf_tsef.BDCETRTALIZAEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDCODIR, vrhf_temp_ref.BDCODINSS, vrhf_temp_ref.BDCODMEN, ';--vrhf_temp_ref.BDCASASDECEMP,';                              --'vrhf_tvin.BDCODIR, vrhf_tvin.BDCODINSS, vrhf_tvin.BDCODMEN ';

  wsql = wsql || 'vrhf_temp_ref.BDCALCFCNAFNEMP,vrhf_temp_ref.BDCALCC13NAFNEMP,vrhf_temp_ref.BDTIPOCONTAB,vrhf_temp_ref.BDTIPOEMIGUIAS, vrhf_temp_ref.BDFAP, ';
  wsql = wsql || 'CNAE1.BDTAXACNAE BDTAXACNAEEMP, vrhf_temp_ref.BDPERTERC, COALESCE(IMPPIS.BDALIQIMPOSTO, 0.0) BDALIQIMPOSTO, vrhf_temp_ref.BDLIMINARAVPREVEMP, ';
  wsql = wsql || 'vrhf_temp_ref.BDSIMPLESGPS, vrhf_temp_ref.BDMESDSREMP, vrhf_temp_ref.BDCODPLACONVSAU, vrhf_temp_ref.Bdarredondafn, vrhf_temp_ref.Bdarredondafc,';
  wsql = wsql || 'vrhf_temp_ref.Bdarredondafe, vrhf_temp_ref.Bdarredondaa13, vrhf_temp_ref.Bdarredonda13, vrhf_temp_ref.Bdarredondac13, vrhf_temp_ref.Bdarredondaad,';
  wsql = wsql || 'vrhf_temp_ref.Bdarredondaau, vrhf_temp_ref.Bdarredondafa, vrhf_temp_ref.BDPAGEMPCONTR, vrhf_temp_ref.BDDESCFALHORASDIAS, vrhf_temp_ref.BDPERCLIMIDESCPAR, ';    --Sol. 14911 - Bruno L. R. - 23/03/2017
  wsql = wsql || 'vrhf_temp_ref.BDCALCC13FNNEGEMP ';



  wsql = wsql || 'from TEMPRESAS temp ';
  wsql = wsql || 'left outer join VW_EMPRESAS_REF_ATUAL temp_ref ';    --wsql = wsql || 'left outer join tempresas_ref temp_ref ';
  wsql = wsql ||   'on (temp_ref.BDCODEMP = temp.BDCODEMP) ';     --wsql = wsql || 'on ((temp.bdcodemp = temp_ref.bdcodemp) and (temp_ref.bdrefemp = (select max(bdrefemp) from tempresas_ref x where temp.bdcodemp = x.bdcodemp and x.bdrefemp <= '||:prref||'))) ';

  wsql = wsql || 'left outer join tcidade cid ';
  wsql = wsql || 'on (temp_ref.bdcodcid = cid.bdcodcid) ';

  wtab = 'left outer join VW_VRHF_EMPRESAS_REF_ATUAL vrhf_temp_ref ';
  wtab = wtab ||   'on (vrhf_temp_ref.BDCODEMP = temp.BDCODEMP) ';
  wtab = wtab ||'left outer join vw_tcnae_ref CNAE1 ';
  wtab = wtab ||   'on (CNAE1.BDCODCNAE = temp_ref.BDCODCNAE) ';
--  wtab = wtab ||'left outer join vrh_base_tterceiros TERC ';
--  wtab = wtab ||   'on (TERC.BDCODTERC = vrhf_temp_ref.BDCODTERC) ';
--  wtab = wtab ||'left outer join SP_TEMPRESAIMPOSTO_REF(null, '||prref||', 1) IMPPIS ';
--  wtab = wtab ||   'on (IMPPIS.BDCODEMP = TEMP.BDCODEMP and IMPPIS.bdtiporetencao = 1) ';
  wTab = wTab|| ' left outer join SP_IMPOSTO_EMPRESA(temp.bdcodemp,2,1,'||prref||',1) IMPPIS on (IMPPIS.BDCODEMP = TEMP.BDCODEMP and IMPPIS.bdtiporetencao = 1) ';

  wwhe = '';

  /* filtra as empresas por usuario
  if (wcodusu is not null and wcodusu <> 0) then
     begin
       wwhe = wwhe||'((exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||') and '||
                        'exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = temp.BDCODEMP)) '||
                       'or '||
                       '(not exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||'))'||
                       ') ';
     end   */

  IF (premp IS NOT NULL) THEN
     BEGIN
       IF (wwhe <> '') THEN
          wwhe = wwhe||' and ';

       wwhe = wwhe ||premp ;
     END

  IF (wwhe <> '') THEN
     wwhe = ' where '||wwhe;

  --wtab = wtab || ' order by temp.BDCODEMP ';

     /*temp.bdcodemp*/
   
  FOR EXECUTE STATEMENT wsql||wtab||wwhe
  INTO
    :BDCODEMP,
    :BDCODCID,
    :bdcoduf, 
    :BDCODPLAFUC,
    :BDNOMEMP,
    :BDCODCENTROS,

    :bdpagemp,
    :bdfechamesemp,
    :bdfechavtemp,
    :bdarremp,
    :bdtipoarremp,
    :bdtipoferemp,
    :bdsomsalferemp,
    :bdtipoad13emp,
    :bdsomsalad13emp,
    :bdpercadsalemp,
--    :bdiradsalemp,
    :bdrefhoremp,
    :bdlicremferemp,
    :bdestouroemp,
    :bdestouroresemp,
    :bdfalferemp,
    :bdfalhorferemp,
    :bddepirrescemp,

    :BDCODGPS,
    :BDCODTERC,
    :BDCODFPAS,
    :BDCNAERATEMP,
    :BDEMPEMP,
    :BDAUTEMP,
    :BDFUNEMP,

    :BDCODSINPAT,
    :BDCAPSOCEMP,

    :BDETIQEMP,
    :BDTAXSEREMP,
    :BDREFCAGEDEMP,

    :BDPROPADMEMP,
    :BDPROPRESEMP,
    :BDPROPFEREMP,
    :BDPROPSITEMP,
    :BDCALCMEDIASTEMP,

    :BDNATESTEMP,
    :BDDATABASEEMP,
    :BDPATEMP,
    :BDNROPROPEMP,
    :BDSERPROPRIOPATEMP,
    :BDPATREFCONVENIOEMP,
    :BDPATCESTAALIMENTOEMP,
    :BDPATADMCOZINHAEMP,
    :BDPATREFTRANSPEMP,
    :BDPATALICONVENIOEMP,
    :BDSINDICALIZEMP,

    :BDCODBAN,
    :BDCODAG,
    :BDIDENTEMP,
    :BDCATSEFIPEMP,
    :BDISENFILEMP,
    :BDCETRTALIZAEMP,

    :BDCODIR,
    :BDCODINSS,
    :BDCODMEN,
--    :BDCASASDECEMP,
    :BDCALCFCNAFNEMP,
    :BDCALCC13NAFNEMP,
    :BDTIPOCONTAB,
    :BDTIPOEMIGUIAS,
    :BDFAP,
    :BDTAXACNAEEMP,
    :BDPERTERC,
    :BDPERCPIS,
    :BDLIMINARAVPREVEMP,
    :BDSIMPLESGPS,
    :BDMESDSREMP,
    :BDCODPLACONVSAU,
    :BDARREDONDAFN,
    :BDARREDONDAFC,
    :BDARREDONDAFE,
    :BDARREDONDAA13,
    :BDARREDONDA13,
    :BDARREDONDAC13,
    :BDARREDONDAAD,
    :BDARREDONDAAU,
    :BDARREDONDAFA,
    :BDPAGEMPCONTR,
    :BDDESCFALHORASDIAS,
    :BDPERCLIMIDESCPAR,  --Sol. 14911 - Bruno L. R. - 23/03/2017
    :BDCALCC13FNNEGEMP
  DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRH_SP_GRRF) */
ALTER PROCEDURE VRH_SP_GRRF(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRDATAPAGTO DATE,
PRPRIDIA DATE,
PRULTDIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODPRES INTEGER,
BDREFRESCISAO INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDSALDOFGTS NUMERIC(15,6),
BDDATAHOM DATE,
BDDATAPAGGRFC DATE,
BDDATADISSIDIO DATE,
BDAVPREPRES INTEGER,
BDCODSEFMFG VARCHAR(5),
BDCODSAQUE INTEGER,
BDBFGTS NUMERIC(15,6),
BDBFGTSMESANT NUMERIC(15,6),
BDVALINDEN NUMERIC(15,6),
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDLOGREMP VARCHAR(15),
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDCODCNAE INTEGER,
BDCODCONT INTEGER,
BDSIMPLESGPS INTEGER,
BDCODFPAS INTEGER,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDSEXOCOL INTEGER,
BDGRAUINSTCOL INTEGER,
BDDATANASCCOL DATE,
BDCONTRCOL INTEGER,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCATEGORIACOL INTEGER,
BDOCORRENCIACOL INTEGER,
BDDATAOPCAOFGTSCOL DATE,
BDHORASSEMANAISCOL NUMERIC(15,6),
BDCODCBO VARCHAR(4),
BDTAMCNPJ INTEGER,
BDNOMREDUZEMP DM_BDNOMREDUZEMP,
BDFGTSSEMIND NUMERIC(15,6),
BDSITEMP DM_BOOLEAN)
 AS
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(20000);
declare variable WCODEMP varchar(20000);
declare variable WCODCOL varchar(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomes, prpridia, prultdia);

  IF (prcodemp IS NULL OR (prcodemp = '')) THEN
     wcodemp = 'null';
  ELSE
     wcodemp = ''''||prcodemp||'''';

  IF (prcodcol IS NULL OR (prcodcol = '')) THEN
     wcodcol = 'null';
  ELSE
     wcodcol = ''''||prcodcol||'''';


  wsql = 'select '||
/*00*/                'COLCON.BDCODEMP, '||
/*01*/                'COLCON.BDCODCOL, '||
/*02*/                'COLCON.BDCODPRES, '||

/*03*/                'COLCON.BDREFRESCISAO, '||

/*03*/                'COLCON.BDDATARESCISAO, '||
/*04*/                'COLCON.BDDATAAVPREVIO, '||
/*05*/                'COLCON.BDREPOSICAOVAGA, '||
/*06*/                'COLCON.BDSALDOFGTS, '||
/*07*/                'COLCON.BDDATAHOM, '||
/*08*/                'COLCON.BDDATAPAGGRFC, '||
/*09*/                'COLCON.BDDATADISSIDIO, '||
/*10*/                'PRES.BDAVPREPRES, '||
/*11*/                'MFGT.BDCODSEFMFG, '||
/*12*/                'SAQU.BDCODSAQUE, '||
/*13*/                'coalesce(FOLH.BDBFGTSFN, 0.0) + coalesce(FOLH.BDBFGTSFEFN, 0.0) + coalesce(FOLH.BDBFGTS13FN, 0.0) + COALESCE(SAL13.BDBASEFGTS13,0.0) + COALESCE(AD13.BDBASEFGTSA13,0.0) - coalesce(VALIND.BDVALOR, 0.0) BDBFGTS, '||
/*14*/                'coalesce(FOLA.BDBFGTSFN, 0.0) + coalesce(FOLA.BDBFGTSFEFN, 0.0) + coalesce(FOLA.BDBFGTS13FN, 0.0) + COALESCE(SAL13_ANT.BDBASEFGTS13,0.0) + COALESCE(AD13_ANT.BDBASEFGTSA13,0.0) BDBFGTSMESANT, '||
/*15*/                'coalesce(VALIND.BDVALOR, 0.0) BDVALINDEN, '||
/*16*/                'EMP.BDCNPJEMP, '||
/*17*/                'EMPR.BDNOMEMP, '||
/*18*/                'EMPR.BDLOGREMP, '||
/*19*/                'EMPR.BDENDEMP, '||
/*20*/                'EMPR.BDNUMEMP, '||
/*21*/                'EMPR.BDCOMPLEMP, '||
/*22*/                'EMPR.BDBAIEMP, '||
/*23*/                'EMPR.BDCEPEMP, '||
/*24*/                'EMPR.BDDDDEMP, '||
/*25*/                'EMPR.BDFONEEMP, '||
/*26*/   --             'EMPR.BDCNAEPREP, '||
/*27*/                'EMPR.BDCODCNAE, '||
/*28*/                'EMPR.BDCODCONTRH BDCODCONT, '||
/*29*/                'EMPG.BDSIMPLESGPS, '||
/*30*/                'EMPG.BDCODFPAS, '||
/*31*/                'CIDEMP.BDNOMCID, '||
/*32*/                'UFEMP.BDSIGLAUF, '||
/*33*/                'COLCAD.BDNOMCOL, '||
/*34*/                'COL.BDDATAADMCOL, '||
/*35*/                'COLCAD.BDSEXOCOL, '||
/*36*/                'COLCAD.BDGRAUINSTCOL, '||
/*37*/                'COL.BDDATANASCCOL, '||
/*38*/                'COL.BDCONTRCOL, '||
/*39*/                'COLDOC.BDCPFCOL, '||
/*40*/                'DOCREF.BDPISCOL, '||
/*41*/                'DOCREF.BDCTPSCOL, '||
/*42*/                'DOCREF.BDSERIECTPSCOL, '||
/*43*/                'DOCREF.BDDSERIECTPSCOL, '||
/*44*/                'COLFGTS.BDCATEGORIACOL, '||
/*45*/                'COLFGTS.BDOCORRENCIACOL, '||
/*46*/                'COLFGTS.BDDATAOPCAOFGTSCOL, '||
/*47*/                'COLCALC.BDHORASSEMANAISCOL, '||
/*48*/                'SUBSTRING((CAST(FUC.BDCODCBO AS VARCHAR(10))) from 1 for 4) BDCODCBO, '||
/*49*/                'STRLEN(TRIM(EMP.BDCNPJEMP)) BDTAMCNPJ, '||
/*50*/                'EMPR.BDNOMREDUZEMP, '||
/*51*/                'EMPR.BDSITEMP ';

  wsql = wsql||' from VRH_EMP_TRESCISAO COLCON '||
               'join tempresas EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
               'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = COLCON.BDCODPRES) '||
               'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = COLCON.BDCODEMP and COL.BDCODCOL = COLCON.BDCODCOL) '||
               'join VRH_BASE_TMOTFGTS MFGT on (MFGT.BDCODMFG = PRES.BDCODMFG) '||
               'join VRH_BASE_TSAQUE SAQU on (SAQU.BDCODSAQUE = PRES.BDCODSAQUE) ';

  IF (prdatapagto IS NOT NULL) THEN
     BEGIN
       wsql = wsql||'join VRHF_SP_TFOLHA_NORMAL('||wcodemp||','||wcodcol||', null, null,1) FOLH on (FOLH.BDCODEMP = COLCON.BDCODEMP and FOLH.BDCODCOL = COLCON.BDCODCOL and FOLH.BDREFFN = COLCON.BDREFRESCISAO)';
     END
  ELSE
     BEGIN
       wsql = wsql||'join VRHF_SP_TFOLHA_NORMAL('||wcodemp||','||wcodcol||','||pranomes||','||pranomes||',1) FOLH on (FOLH.BDCODEMP = COLCON.BDCODEMP and FOLH.BDCODCOL = COLCON.BDCODCOL and FOLH.BDREFFN = COLCON.BDREFRESCISAO)';
     END


--               'join VRHF_SP_TFOLHA_NORMAL('||wcodemp||','||wcodcol||','||pranomes||','||pranomes||',1) FOLH on (FOLH.BDCODEMP = COLCON.BDCODEMP and FOLH.BDCODCOL = COLCON.BDCODCOL and FOLH.BDREFFN = COLCON.BDREFRESCISAO)'||

  wsql = wsql||'left outer join SP_VRHF_EMP_TFOLHANORMAL_ANT(COLCON.BDDATARESCISAO,'||wcodemp||','||wcodcol||') FOLA on (FOLA.BDCODEMP = COLCON.BDCODEMP and FOLA.BDCODCOL = COLCON.BDCODCOL and COLCON.BDCALCFGTSMESANT = '||'''TRUE'''||') '||
               'left outer join SP_VRHF_FN_VALORES_INDENIZADOS('||wcodemp||', '||wcodcol||', COLCON.BDREFRESCISAO) VALIND on (VALIND.BDCODEMP = COLCON.BDCODEMP and VALIND.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_TEMPRESAS_REF EMPR on (EMPR.BDCODEMP = COLCON.BDCODEMP) '||
               'left outer join VW_VRHF_BASE_TEMPGPS EMPG on (EMPG.BDCODEMP = COLCON.BDCODEMP) '||
               'left outer join TCIDADE CIDEMP on (CIDEMP.BDCODCID = EMPR.BDCODCID) '||
               'left outer join TUF UFEMP on (UFEMP.BDCODUF = CIDEMP.BDCODUF) '||
               'left outer join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = COLCON.BDCODEMP and COLDOC.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VRH_EMP_TCOL_DOC COL2DOC on (COL2DOC.BDCODEMP = COLCON.BDCODEMP and COL2DOC.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS on (COLFGTS.BDCODEMP = COLCON.BDCODEMP and COLFGTS.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COLCON.BDCODEMP and COLCALC.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_VRH_EMP_TCOL_VINCDIA COLVDIA on (COLVDIA.BDCODEMP = COLCON.BDCODEMP and COLVDIA.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VRH_FUNCOES_TFUC FUC on (FUC.BDCODPLAFUC = COLVDIA.BDCODPLAFUC and FUC.BDCODTFUC = COLVDIA.BDCODTFUC) '||
               'left outer join VRHF_EMP_T13SAL SAL13 on (SAL13.BDCODEMP = COLCON.BDCODEMP and SAL13.BDCODCOL = COLCON.BDCODCOL and SAL13.BDREF13 = BDREFRESCISAO)'||
               'left outer join VRHF_EMP_TA13SAL AD13 on (AD13.BDCODEMP = COLCON.BDCODEMP and AD13.BDCODCOL = COLCON.BDCODCOL and AD13.BDREFA13 = BDREFRESCISAO)'||
               'left outer join VRHF_EMP_T13SAL SAL13_ANT on (SAL13_ANT.BDCODEMP = COLCON.BDCODEMP and SAL13_ANT.BDCODCOL = COLCON.BDCODCOL and SAL13_ANT.BDREF13 = FOLA.BDREFFN and COLCON.BDCALCFGTSMESANT = '||'''TRUE'''||') '||
               'left outer join VRHF_EMP_TA13SAL AD13_ANT on (AD13_ANT.BDCODEMP = COLCON.BDCODEMP and AD13_ANT.BDCODCOL = COLCON.BDCODCOL and AD13_ANT.BDREFA13 = FOLA.BDREFFN and COLCON.BDCALCFGTSMESANT = '||'''TRUE'''||') '||
               'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';

  wwhere = 'where PRES.BDGRRFPRES is not null and PRES.BDGRRFPRES > 0 ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||'and '||prcodemp||' ';
  ELSE
     wwhere = wwhere||' and UPPER(COALESCE(EMPR.BDSITEMP, ''FALSE'')) = ''FALSE'' and EMPG.BDCODFPAS <> 868 ';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||'and '||prcodcol||' ';

  IF (prdatapagto IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'and COLCON.BDDATAPAGGRFC = '''||prdatapagto||''' ';
     END
  ELSE
     BEGIN
       wwhere = wwhere||'and COLCON.BDDATARESCISAO between '''||prpridia||''' and  '''||prultdia||''' ';
     END

  wsql = wsql||wwhere||'order by EMPR.BDCODCONTRH, COLCON.BDDATAPAGGRFC, BDTAMCNPJ DESC, EMP.BDCNPJEMP, DOCREF.BDPISCOL, COL.BDDATAADMCOL, COLFGTS.BDCATEGORIACOL';

  BDFGTSSEMIND = 0;
  FOR EXECUTE STATEMENT wsql
  INTO
/*00*/    :BDCODEMP,
/*01*/    :BDCODCOL,
/*02*/    :BDCODPRES,

/*03*/    :BDREFRESCISAO,

/*03*/    :BDDATARESCISAO,
/*04*/    :BDDATAAVPREVIO,
/*05*/    :BDREPOSICAOVAGA,
/*06*/    :BDSALDOFGTS,
/*07*/    :BDDATAHOM,
/*08*/    :BDDATAPAGGRFC,
/*09*/    :BDDATADISSIDIO,
/*10*/    :BDAVPREPRES,
/*11*/    :BDCODSEFMFG,
/*12*/    :BDCODSAQUE,
/*13*/    :BDBFGTS,
/*14*/    :BDBFGTSMESANT,
/*15*/    :BDVALINDEN,
/*16*/    :BDCNPJEMP,
/*17*/    :BDNOMEMP,
/*18*/    :BDLOGREMP,
/*19*/    :BDENDEMP,
/*20*/    :BDNUMEMP,
/*21*/    :BDCOMPLEMP,
/*22*/    :BDBAIEMP,
/*23*/    :BDCEPEMP,
/*24*/    :BDDDDEMP,
/*25*/    :BDFONEEMP,
/*26*/--    :BDCNAEPREP,
/*27*/    :BDCODCNAE,
/*28*/    :BDCODCONT,
/*29*/    :BDSIMPLESGPS,
/*30*/    :BDCODFPAS,
/*31*/    :BDNOMCID,
/*32*/    :BDSIGLAUF,
/*33*/    :BDNOMCOL,
/*34*/    :BDDATAADMCOL,
/*35*/    :BDSEXOCOL,
/*36*/    :BDGRAUINSTCOL,
/*37*/    :BDDATANASCCOL,
/*38*/    :BDCONTRCOL,
/*39*/    :BDCPFCOL,
/*40*/    :BDPISCOL,
/*41*/    :BDCTPSCOL,
/*42*/    :BDSERIECTPSCOL,
/*43*/    :BDDSERIECTPSCOL,
/*44*/    :BDCATEGORIACOL,
/*45*/    :BDOCORRENCIACOL,
/*46*/    :BDDATAOPCAOFGTSCOL,
/*47*/    :BDHORASSEMANAISCOL,
/*48*/    :BDCODCBO,
/*49*/    :BDTAMCNPJ,
/*50*/    :BDNOMREDUZEMP,
/*51*/    :BDSITEMP
  DO
  SUSPEND;
END
^

/* Alter (VRH_SP_LISTAADM_RESC) */
ALTER PROCEDURE VRH_SP_LISTAADM_RESC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMESINI INTEGER,
PRANOMESFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAADM DATE,
BDDATARESCISAO DATE)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO VARCHAR(4);
DECLARE VARIABLE WPRIDIA VARCHAR(10);
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WMES VARCHAR(2);
DECLARE VARIABLE WDIA VARCHAR(2);
BEGIN
  wmes = SUBSTRING(CAST(:pranomesfim AS VARCHAR(6)) FROM 5 FOR 2) ;
  wano = CAST(SUBSTRING(CAST(:pranomesfim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:pranomesini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:pranomesini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  wpridia = wmes||'/'||'01'||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfim, NULL, wultdia);

  wsql = 'select COLCON.bdcodemp, EMPRESAS.bdnomemp,  EMPRESAS.BDCNPJEMP, COLCON.bdcodcol, COLCAD.bdnomcol , COLCON.BDDATAADMCOL';

  IF (prfiltraresc IS NOT NULL AND prfiltraresc = 1) THEN
     wsql = wsql||', rescisao.bddatarescisao ';
  ELSE
     wsql = wsql||', CAST(null as date) BDDATARESCISAO ';

  wsql = wsql||'from VRH_EMP_TCOLCON COLCON
          left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL)
          join SP_CONSULTAEMPRESAS(' || pranomesfim || ', null, null) empresas on (empresas.bdcodemp = COLCON.bdcodemp ) ';

  wsql = wsql||' join vw_vrh_emp_tcolcon_vinc colcon_vinc on (colcon_vinc.bdcodemp = colcon.bdcodemp and colcon_vinc.bdcodcol = colcon.bdcodcol';

  IF (prclasse IS NOT NULL AND prclasse <> 0) THEN
     BEGIN
       wsql = wsql||' and colcon_vinc.bdcodcla = '||prclasse;
     END

  wsql = wsql||') ';
  wsql = wsql||'join vrh_base_tclasse classe on (colcon_vinc.bdcodcla = classe.bdcodcla) ';

  IF (prfuncao IS NOT NULL AND prfuncao <> 0) THEN
     BEGIN
       wsql = wsql||' join vw_vrh_emp_tcol_vincdia col_vincdia on (col_vincdia.bdcodemp = colcon.bdcodemp and col_vincdia.bdcodcol = colcon.bdcodcol and col_vincdia.bdcodtfuc = '||prfuncao||') ';
     END

  IF (prsindicato IS NOT NULL AND prsindicato <> 0) THEN
     BEGIN
       wsql = wsql||' join VW_VRH_EMP_TCOL_VINC col_vinc on (col_vinc.bdcodemp = colcon.bdcodemp and col_vinc.bdcodcol = colcon.bdcodcol and col_vinc.bdcodsintrab = '||prsindicato||') ';
     END


  IF (prfiltraresc IS NOT NULL AND prfiltraresc = 1) THEN
     wsql = wsql||'join vrh_emp_trescisao RESCISAO on (rescisao.bdcodemp = colcon.bdcodemp and rescisao.bdcodcol = colcon.bdcodcol and
           rescisao.bddatarescisao >= '''||:wpridia||''' AND rescisao.bddatarescisao <= '''||:wultdia||''') ';


  wwhere = ' where COLCON.BDCONTRCOL <> 1';

  IF (:prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (:prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  IF (prfiltraadm = 1 ) THEN
     wwhere = wwhere||' and COLCON.bddataadmcol between '''||:wpridia||''' AND '''||:wultdia||'''';

  wwhere = wwhere||' and classe.bdgrupocla <> 5 ';
  -- oder by
  wwhere = wwhere|| ' order by colcon.bdcodemp, colcon.bdcodcol  ';

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :bdcnpjemp,
        :BDCODCOL,
        :bdnomcol,
        :bddataadm,
        :bddatarescisao
      DO

    SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRH_SP_LISTAADM_RESC_TOT_EMP) */
ALTER PROCEDURE VRH_SP_LISTAADM_RESC_TOT_EMP(PRCODEMP VARCHAR(10000),
PRANOMESANT INTEGER,
PRANOMESATU INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCAMPOC INTEGER,
BDCAMPOD INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO VARCHAR(4);
DECLARE VARIABLE WPRIDIA VARCHAR(10);
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WMES VARCHAR(2);
DECLARE VARIABLE WDIA VARCHAR(2);
BEGIN

  wmes = SUBSTRING(CAST(:pranomesatu AS VARCHAR(6)) FROM 5 FOR 2) ;
  wano = CAST(SUBSTRING(CAST(:pranomesatu AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;
  wpridia = wmes||'/'||'01'||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(pranomesatu, NULL, wultdia);

  wsql = 'select COLCON.bdcodemp, EMPRESAS.bdnomemp , count(COLCON.bdcodemp) BDCAMPO from VRH_EMP_TCOLCON COLCON
          left outer join vrh_sp_colcon(null,null,null,null,null, ' || pranomesatu || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) spcolcon  on (COLCON.BDCODEMP = spcolcon.BDCODEMP and COLCON.BDCODCOL = spcolcon.BDCODCOL)
          left outer join SP_CONSULTAEMPRESAS(' || pranomesatu || ', null, null) empresas on (empresas.bdcodemp = COLCON.bdcodemp )
          left outer join vrh_emp_trescisao RESCISAO on (rescisao.bdcodemp = colcon.bdcodemp and rescisao.bdcodcol = colcon.bdcodcol)';

  wwhere = '';

  IF (:prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and (colcon.bdcodemp = ' || prcodemp || ')';
       ELSE
          wwhere = wwhere || '(colcon.bdcodemp = ' || prcodemp || ')';
     END

  IF (prfiltraadm = 1 ) THEN
    BEGIN
      IF (wwhere <> '') THEN
          wwhere = wwhere||' and (COLCON.bddataadmcol between '''||:wpridia||''' AND '''||:wultdia||''')';
      ELSE
          wwhere = wwhere||'(COLCON.bddataadmcol between '''||:wpridia||''' AND '''||:wultdia||''')';
    END

  IF (prfiltraresc = 1 ) THEN
    BEGIN
      IF (wwhere <> '') THEN
          wwhere = wwhere||' and (rescisao.bddatarescisao between '''||:wpridia||''' AND '''||:wultdia||''')';
      ELSE
          wwhere = wwhere||'(rescisao.bddatarescisao between '''||:wpridia||''' AND '''||:wultdia||''')';
    END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'spcolcon.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'spcolcon.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'spcolcon.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END



  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  -- oder by
  wwhere = wwhere|| ' order by colcon.bdcodemp, colcon.bdcodcol  ';

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp
      DO

     bdcampoc = 0;
     bdcampod = 0;

    SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Alter (VRH_SP_REL_RECIBO_FOLCOMP) */
ALTER PROCEDURE VRH_SP_REL_RECIBO_FOLCOMP(PRCODEMP INTEGER,
PRREF INTEGER,
PRREFPAG INTEGER,
PRCODCLA VARCHAR(10000),
PRCODTPCC VARCHAR(20000) = null,
PRSITCOL SMALLINT = 1)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFFC INTEGER,
BDREFVFN_SUM NUMERIC(18,6),
BDREFVFN_MAX NUMERIC(18,6),
BDREFAUXVFN_SUM NUMERIC(18,6),
BDREFAUXVFN_MAX NUMERIC(18,6),
BDVALVFN NUMERIC(18,6),
BDDATAFN INTEGER,
BDSALBASE NUMERIC(18,6),
BDBINSS NUMERIC(18,6),
BDBFGTS NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDBIRRF NUMERIC(18,6),
BDCNPJEMP VARCHAR(18),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDORDEMVER INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDPISCOL VARCHAR(14),
BDCPFCOL VARCHAR(14),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDTIPOREFVER INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDMODOPAGTOCOL INTEGER,
BDCLAVER VARCHAR(20),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER)
 AS
declare variable WSQL varchar(20000);
BEGIN
/*
   O par?metro prsitcol filtra os colaboradores conforme o combobox de situa??o

   0 = Somente ativos
   1 = Todos
   2 = Somente admitidos no m?s
   3 = Somente demitidos no m?s (Estagi?rios)
   4 = Ativos sem os demitidos no m?s   (Estagi?rios demitidos no m?s)
   5 = Ativos sem os transferidos no m?s
   6 = Ativos sem os afastados o m?s inteiro
   7 = Afastados o m?s inteiro.

 */

  wSql = '';
  wSql = wSql||'select ';
  wSql = wSql||'  FOL.BDCODEMP, ';
  wSql = wSql||'  FOL.BDCODCOL, ';
  wSql = wSql||'  FOL.BDCODVER, ';
  wSql = wSql||'  FOL.BDREFFN, ';
  wSql = wSql||'  FOL.BDREFFC, ';
  wSql = wSql||'  FOL.BDREFVFN_SUM, ';
  wSql = wSql||'  FOL.BDREFVFN_MAX, ';
  wSql = wSql||'  FOL.BDREFAUXVFN_SUM, ';
  wSql = wSql||'  FOL.BDREFAUXVFN_MAX, ';
  wSql = wSql||'  FOL.BDVALVFN, ';
  wSql = wSql||'  FOL.BDREFFC as BDDATAFN, ';
  wSql = wSql||'  FOLB.BDSALBASE, ';
  wSql = wSql||'  FOLB.BDBINSS, ';
  wSql = wSql||'  FOLB.BDBFGTS, ';
  wSql = wSql||'  FOLB.BDFGTS, ';
  wSql = wSql||'  FOLB.BDBIRRF, ';
  wSql = wSql||'  EMP.BDCNPJEMP, ';
  wSql = wSql||'  VERB.BDDESCVER, ';
  wSql = wSql||'  VERB.BDDESCREDVER, ';
  wSql = wSql||'  VERB.BDORDEMVER, ';
  wSql = wSql||'  COLCAD.BDNOMCOL, ';
  wSql = wSql||'  COL.BDDATAADMCOL, ';
  wSql = wSql||'  DOCREF.BDPISCOL, ';
  wSql = wSql||'  COLDOC.BDCPFCOL, ';
  wSql = wSql||'  VERR.BDTIPOCODVER, ';
  wSql = wSql||'  case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  wSql = wSql||'  VERR.BDTIPOREFVER, ';
  wSql = wSql||'  COLBANCO.BDCODBAN, ';
  wSql = wSql||'  COLBANCO.BDCODAG, ';
  wSql = wSql||'  COLBANCO.BDCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDDIGCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDMODOPAGTOCOL, ';
  wSql = wSql||'  VERB.BDCLAVER, ';
  wSql = wSql||'  FOL.BDCODCENTRO, ';
  wSql = wSql||'  FOL.BDCODTPCC ';
    
  wSql = wSql||'from (select ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     wSql = wSql||'first 0 ';

  wSql = wSql||'          X.BDCODEMP, ';
  wSql = wSql||'          X.BDCODCOL, ';
  wSql = wSql||'          X.BDREFFN, ';
  wSql = wSql||'          X.BDREFFC, ';
  wSql = wSql||'          X.BDREFCOMP, ';
  wSql = wSql||'          X.BDCODVER, ';
  wSql = wSql||'          X.BDREFVFC as BDREFVFN_SUM, ';
  wSql = wSql||'          X.BDREFVFC as BDREFVFN_MAX, ';
  wSql = wSql||'          X.BDREFAUXVFC as BDREFAUXVFN_SUM, ';
  wSql = wSql||'          X.BDREFAUXVFC as BDREFAUXVFN_MAX, ';
  wSql = wSql||'          X.BDVALVFC as BDVALVFN, ';
  wSql = wSql||'          0 as BDCODCENTRO, ';
  wSql = wSql||'          0 as BDCODTPCC ';
  wSql = wSql||'      from ';
  wSql = wSql||'          VRHF_EMP_TVERBAFC X ';

  IF (prsitcol = 2) THEN
     wSql = wSql||' join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = '||prref||')';

  IF (PRCODEMP > 0) THEN
     wSql = wSql||'      where X.BDCODEMP = '||:PRCODEMP||' and X.BDREFFN = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
  ELSE
     wSql = wSql||'      where X.BDREFFN = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
            
  -- Somente ativos e todos  (nunca entram demitidos que n?o sejam estagi?rios)
  IF (prsitcol IN (0, 1, 2)) THEN
     wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                  '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||'))))';
  ELSE
  -- Somente estagi?rios demitidos no m?s
  IF (prsitcol = 3) THEN
     wSql = wSql||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                              'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                              'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                              'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                              'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                              'Y.BDREFRESCISAO = '||prref||' and cla.bdgrupocla = 5)';
  ELSE
  -- Ativos sem demitidos
  IF (prsitcol = 4) THEN
     wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFRESCISAO < '||prref||')';
  ELSE
  -- Ativos sem transferidos
  IF (prsitcol = 5) THEN
     wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                  '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||')))) ' ||
                  ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV = 1) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFRESCISAO = '||prref||')';
  ELSE
  -- Ativos sem os afastados o m?s inteiro
  IF (prsitcol = 6) THEN
     wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                  '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||')))) ' ||
                  ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
                                  'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                  '((Y.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and Z.BDCODVER is not null) ';
  ELSE
  -- Afastados o m?s inteiro
  IF (prsitcol = 7) THEN
     wSql = wSql||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
                              'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
                              'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                              '((Y.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and Z.BDCODVER is not null) ';

  wSql = wSql||'      UNION ';
            

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wSql = wSql||'      select ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          X.BDCODVER, ';
       wSql = wSql||'          sum(X.BDREFVFC) as BDREFVFN_SUM, ';
       wSql = wSql||'          max(X.BDREFVFC) as BDREFVFN_MAX, ';
       wSql = wSql||'          sum(X.BDREFAUXVFC) as BDREFAUXVFN_SUM, ';
       wSql = wSql||'          max(X.BDREFAUXVFC) as BDREFAUXVFN_MAX, ';
       wSql = wSql||'          sum(X.BDVALVFC) as BDVALVFN, ';
       wSql = wSql||'          Y.BDCODCENTRO, ';
       wSql = wSql||'          Y.BDCODTPCC ';
       wSql = wSql||'      from ';
       wSql = wSql||'          VRHF_EMP_TVERBAFCTOMADOR X ';
       wSql = wSql||'      join VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDORDEM = X.BDORDEM) ';

       IF (prsitcol = 2) THEN
          wSql = wSql||' join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = '||prref||')';

       IF (PRCODEMP > 0) THEN
          wSql = wSql||'      where X.BDCODEMP = '||:PRCODEMP||' and X.BDREFTOMADOR = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
       ELSE
          wSql = wSql||'      where X.BDREFTOMADOR = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
     
       wSql = wSql||' and '||prcodtpcc;

       -- Somente ativos e todos  (nunca entram demitidos que n?o sejam estagi?rios)
       IF (prsitcol IN (0, 1, 2)) THEN
          wSql = wSql||' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp and vd.bdcodcol = RESC.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and '||
                                       '(((RESC.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (RESC.BDREFRESCISAO <= '||prref||'))))';
       ELSE
       -- Somente estagi?rios demitidos no m?s
       IF (prsitcol = 3) THEN
          wSql = wSql||' and exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                   'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                   'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp and vd.bdcodcol = RESC.bdcodcol) '||
                                   'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                   'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and '||
                                   'RESC.BDREFRESCISAO = '||prref||' and cla.bdgrupocla = 5)';
       ELSE
       -- Ativos sem demitidos
       IF (prsitcol = 4) THEN
          wSql = wSql||' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and RESC.BDREFRESCISAO < '||prref||')';
       ELSE
       -- Ativos sem transferidos
       IF (prsitcol = 5) THEN
          wSql = wSql||' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp and vd.bdcodcol = RESC.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and '||
                                       '(((RESC.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (RESC.BDREFRESCISAO <= '||prref||')))) ' ||
                       ' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV = 1) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and RESC.BDREFRESCISAO = '||prref||')';
       ELSE
       -- Ativos sem os afastados o m?s inteiro
       IF (prsitcol = 6) THEN
          wSql = wSql||' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp and vd.bdcodcol = RESC.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and '||
                                       '(((RESC.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (RESC.BDREFRESCISAO <= '||prref||')))) ' ||
                       ' and not exists(select SIT.BDCODEMP, SIT.BDCODCOL from VRH_EMP_TSITCOL SIT '||
                                       'join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
                                       'where SIT.BDCODEMP = X.BDCODEMP and SIT.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                       '((SIT.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and SIT.BDCODVER is not null) ';
       ELSE
       -- Afastados o m?s inteiro
       IF (prsitcol = 7) THEN
          wSql = wSql||' and exists(select SIT.BDCODEMP, SIT.BDCODCOL from VRH_EMP_TSITCOL SIT '||
                                   'join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
                                   'where SIT.BDCODEMP = X.BDCODEMP and SIT.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                   '((SIT.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and SIT.BDCODVER is not null) ';

       wSql = wSql||'      group by ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          X.BDCODVER, ';
       wSql = wSql||'          Y.BDCODCENTRO, ';
       wSql = wSql||'          Y.BDCODTPCC) FOL, ';
     END
  ELSE
     BEGIN
       wSql = wSql||'      select ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          X.BDCODVER, ';
       wSql = wSql||'          SUM(X.BDREFVFC) as BDREFVFN_SUM, ';
       wSql = wSql||'          MAX(X.BDREFVFC) as BDREFVFN_MAX, ';
       wSql = wSql||'          SUM(X.BDREFAUXVFC) as BDREFAUXVFN_SUM, ';
       wSql = wSql||'          MAX(X.BDREFAUXVFC) as BDREFAUXVFN_MAX, ';
       wSql = wSql||'          SUM(X.BDVALVFC) as BDVALVFN, ';
       wSql = wSql||'          0 BDCODCENTRO, ';
       wSql = wSql||'          0 BDCODTPCC ';
       wSql = wSql||'      from ';
       wSql = wSql||'          VRHF_EMP_TVERBAFCTOMADOR X ';

       IF (prsitcol = 2) THEN
          wSql = wSql||' join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = '||prref||')';


       IF (PRCODEMP > 0) THEN
          wSql = wSql||'      where X.BDCODEMP = '||:PRCODEMP||' and X.BDREFTOMADOR = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
       ELSE
          wSql = wSql||'      where X.BDREFTOMADOR = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
     
       -- Somente ativos e todos  (nunca entram demitidos que n?o sejam estagi?rios)
       IF (prsitcol IN (0, 1, 2)) THEN
          wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                       '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||'))))';
       ELSE
       -- Somente estagi?rios demitidos no m?s
       IF (prsitcol = 3) THEN
          wSql = wSql||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                   'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                   'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                   'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                   'Y.BDREFRESCISAO = '||prref||' and cla.bdgrupocla = 5)';
       ELSE
       -- Ativos sem demitidos
       IF (prsitcol = 4) THEN
          wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFRESCISAO < '||prref||')';
       ELSE
       -- Ativos sem transferidos
       IF (prsitcol = 5) THEN
          wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                       '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||')))) ' ||
                       ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV = 1) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFRESCISAO = '||prref||')';
       ELSE
       -- Ativos sem os afastados o m?s inteiro
       IF (prsitcol = 6) THEN
          wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                       '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||')))) ' ||
                       ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
                                       'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                       '((Y.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and Z.BDCODVER is not null) ';
       ELSE
       -- Afastados o m?s inteiro
       IF (prsitcol = 7) THEN
          wSql = wSql||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
                                   'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                   '((Y.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and Z.BDCODVER is not null) ';

       wSql = wSql||'      group by ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          X.BDCODVER) FOL ';
     END

  wSql = wSQL||'INNER JOIN ';
  wSql = wSql||'     (select ';
  wSql = wSql||'          BDCODEMP, ';
  wSql = wSql||'          BDCODCOL, ';
  wSql = wSql||'          BDREFFN, ';
  wSql = wSql||'          BDREFFC, ';
  wSql = wSql||'          BDREFCOMP, ';
  wSql = wSql||'          BDBFGTSFC + BDBFGTS13FC as BDBFGTS, ';
  wSql = wSql||'          BDFGTSFC + BDFGTS13FC as BDFGTS, ';
  wSql = wSql||'          BDBINSSFC + BDBINSS13FC as BDBINSS, ';
  wSql = wSql||'          BDBIRRFFC + BDBIRRF13FC as BDBIRRF, ';
  wSql = wSql||'          BDSALBASEFC as BDSALBASE, ';
  wSql = wSql||'          BDDATAPAGFC, ';
  wSql = wSql||'          0 BDCODCENTRO, ';
  wSql = wSql||'          0 BDCODTPCC ';
  wSql = wSql||'      from ';
  wSql = wSql||'          VRHF_EMP_TFOLHACOMP ';

  IF (PRCODEMP > 0) THEN
     wSql = wSql||'      where BDCODEMP = '||:PRCODEMP||' and BDREFFN = '||:PRREF||' and CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
  ELSE
     wSql = wSql||'      where BDREFFN = '||:PRREF||' and CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
            
  wSql = wSql||'      UNION ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wSql = wSql||'      select ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          SUM(X.BDBFGTSFC + X.BDBFGTS13FC), ';
       wSql = wSql||'          SUM(X.BDFGTSFC + X.BDFGTS13FC), ';
       wSql = wSql||'          SUM(X.BDBINSSFC + X.BDBINSS13FC), ';
       wSql = wSql||'          SUM(X.BDBIRRFFC + X.BDBIRRF13FC), ';
       wSql = wSql||'          MAX(X.BDSALBASEFC), ';
       wSql = wSql||'          X.BDDATAPAGFC, ';
       wSql = wSql||'          Y.BDCODCENTRO, ';
       wSql = wSql||'          Y.BDCODTPCC ';
       wSql = wSql||'      from ';
       wSql = wSql||'          VRHF_EMP_TFOLTOMCOMP X, ';
       wSql = wSql||'          VRHF_EMP_TPREPFN Y ';
       wSql = wSql||'      where ';
     
       IF (PRCODEMP > 0) THEN
          wSql = wSql||'       X.BDCODEMP = '||:PRCODEMP||' and X.BDREFTOMADOR = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
       ELSE
          wSql = wSql||'       X.BDREFTOMADOR = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
     
       wSql = wSql||'          and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';

       wSql = wSql||' and '||prcodtpcc;

       wSql = wSql||'      group by ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          X.BDDATAPAGFC,';
       wSql = wSql||'          Y.BDCODCENTRO, ';
       wSql = wSql||'          Y.BDCODTPCC) FOLB ON (FOL.BDCODEMP = FOLB.BDCODEMP) and (FOL.BDCODCOL = FOLB.BDCODCOL) and (FOL.BDREFFN = FOLB.BDREFFN) and (FOL.BDREFFC = FOLB.BDREFFC)';
     END
  ELSE
     BEGIN
       wSql = wSql||'      select ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          SUM(X.BDBFGTSFC + X.BDBFGTS13FC), ';
       wSql = wSql||'          SUM(X.BDFGTSFC + X.BDFGTS13FC), ';
       wSql = wSql||'          SUM(X.BDBINSSFC + X.BDBINSS13FC), ';
       wSql = wSql||'          SUM(X.BDBIRRFFC + X.BDBIRRF13FC), ';
       wSql = wSql||'          MAX(X.BDSALBASEFC), ';
       wSql = wSql||'          X.BDDATAPAGFC, ';
       wSql = wSql||'          0 BDCODCENTRO, ';
       wSql = wSql||'          0 BDCODTPCC ';
       wSql = wSql||'      from ';
       wSql = wSql||'          VRHF_EMP_TFOLTOMCOMP X, ';
       wSql = wSql||'          VRHF_EMP_TPREPFN Y ';
       wSql = wSql||'      where ';
     
       IF (PRCODEMP > 0) THEN
          wSql = wSql||'       X.BDCODEMP = '||:PRCODEMP||' and X.BDREFTOMADOR = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
       ELSE
          wSql = wSql||'       X.BDREFTOMADOR = '||:PRREF||' and CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(10)) FROM 5 FOR 2)) AS INTEGER) = '||:PRREFPAG||' ';
     
       wSql = wSql||'          and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';
       wSql = wSql||'      group by ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          X.BDDATAPAGFC) FOLB ON (FOL.BDCODEMP = FOLB.BDCODEMP) and (FOL.BDCODCOL = FOLB.BDCODCOL) and (FOL.BDREFFN = FOLB.BDREFFN) and (FOL.BDREFFC = FOLB.BDREFFC)';
     END




  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     BEGIN
        wSql = wSql||' INNER JOIN VRH_EMP_TCOLCON_VINC COLCON_VIN ON  ';
        wsql = wsql||' (COLCON_VIN.BDCODEMP = FOL.BDCODEMP) and (COLCON_VIN.BDCODCOL = FOL.BDCODCOL) and (COLCON_VIN.BDREFCOL = ';
       wSql = wSql||'     (select ';
       wSql = wSql||'      coalesce ';
       wSql = wSql||'      ( ';
       wSql = wSql||'          (select max(d2.bdrefcol) from VRH_EMP_TCOLCON_VINC d2 where d2.bdcodemp = FOL.bdcodemp and d2.bdcodcol = FOL.BDCODCOL and d2.bdrefcol <= (select TRIM(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) from rdb$database)), ';
       wSql = wSql||'          (select min(d1.bdrefcol) from VRH_EMP_TCOLCON_VINC d1 where d1.bdcodemp = FOL.BDCODEMP and d1.bdcodcol = FOL.bdcodcol) ';
       wSql = wSql||'      ) as bdREF from rdb$database ';
        wSql = wSql||'     )) and ('||:prCODCLA||') ';
     END

  wSql = wSql||' inner join TEMPRESAS EMP on FOL.BDCODEMP = EMP.BDCODEMP';
  wSql = wSql||' inner join VRH_BASE_TVERBAS VERB on FOL.BDCODVER = VERB.BDCODVER';
  wSql = wSql||' inner join VRH_EMP_TCOLCON COL on (FOL.BDCODEMP = COL.BDCODEMP) and (FOL.BDCODCOL = COL.BDCODCOL)';
  wSql = wSql||' inner join VRH_EMP_TCOLCON_CAD COLCAD on (FOL.BDCODEMP = COLCAD.BDCODEMP) and (FOL.BDCODCOL = COLCAD.BDCODCOL) and (COLCAD.BDREFCOL = (select coalesce((select max(D2.BDREFCOL)
                                                                                                                                                        from VRH_EMP_TCOLCON_CAD D2
                                                                                                                                                        where D2.BDCODEMP = FOL.BDCODEMP and
                                                                                                                                                              D2.BDCODCOL = FOL.BDCODCOL and
                                                                                                                                                              D2.BDREFCOL <= (select trim(RDB$GET_CONTEXT(''USER_SESSION'', ''W_ANOMES''))
                                                                                                                                                                              from RDB$DATABASE)),
                                                                                                                                              (select min(D1.BDREFCOL)
                                                                                                                                               from VRH_EMP_TCOLCON_CAD D1
                                                                                                                                               where D1.bdcodemp = FOL.BDCODEMP and
                                                                                                                                                     D1.BDCODCOL = FOL.BDCODCOL)) as BDREF
                                                                                                                                       from RDB$DATABASE))';
  wSql = wSql||' inner join VRH_EMP_TCOLCON_DOCREF DOCREF on (FOL.BDCODEMP = DOCREF.BDCODEMP) and (FOL.BDCODCOL = DOCREF.BDCODCOL) and (DOCREF.BDREFCOL = (select coalesce((select max(D2.BDREFCOL)
                                                                                                                                                           from VRH_EMP_TCOLCON_DOCREF D2
                                                                                                                                                           where D2.BDCODEMP = FOL.BDCODEMP and
                                                                                                                                                                 D2.BDCODCOL = FOL.BDCODCOL and
                                                                                                                                                                 D2.BDREFCOL <= (select trim(RDB$GET_CONTEXT(''USER_SESSION'', ''W_ANOMES''))
                                                                                                                                                                                 from RDB$DATABASE)),
                                                                                                                                                 (select min(D1.BDREFCOL)
                                                                                                                                                  from VRH_EMP_TCOLCON_DOCREF D1
                                                                                                                                                  where D1.BDCODEMP = FOL.BDCODEMP and
                                                                                                                                                        D1.BDCODCOL = FOL.BDCODCOL)) as BDREF
                                                                                                                                          from RDB$DATABASE))';
  wSql = wSql||' inner join VRH_EMP_TCOLCON_DOC COLDOC on (FOL.BDCODEMP = COLDOC.BDCODEMP) and (FOL.BDCODCOL = COLDOC.BDCODCOL)';
  wSql = wSql||' inner join VRH_BASE_TVERBAS_REF VERR on (FOL.BDCODVER = VERR.BDCODVER) and (VERB.BDCODVER = VERR.BDCODVER) and (VERR.BDREFVER = (select coalesce((select max(D2.BDREFVER)
                                                                                                                                                  from VRH_BASE_TVERBAS_REF D2
                                                                                                                                                  where D2.BDCODVER = FOL.BDCODVER and
                                                                                                                                                        D2.BDREFVER <= (select trim(RDB$GET_CONTEXT(''USER_SESSION'', ''W_ANOMES''))
                                                                                                                                                                        from RDB$DATABASE)),
                                                                                                                                        (select min(D1.BDREFVER)
                                                                                                                                         from VRH_BASE_TVERBAS_REF D1
                                                                                                                                         where D1.BDCODVER = FOL.BDCODVER)) as BDREF
                                                                                                                                 from RDB$DATABASE))';
  wSql = wSql||' inner join VRHF_EMP_TCOLCON_BANCO COLBANCO on (FOL.BDCODEMP = COLBANCO.BDCODEMP) and (FOL.BDCODCOL = COLBANCO.BDCODCOL) and (COLBANCO.BDREFCOL = (select coalesce((select max(D2.BDREFCOL)
                                                                                                                                                                   from VRHF_EMP_TCOLCON_BANCO D2
                                                                                                                                                                   where D2.BDCODEMP = FOL.BDCODEMP and
                                                                                                                                                                         D2.BDCODCOL = FOL.BDCODCOL and
                                                                                                                                                                         D2.BDREFCOL <= (select trim(RDB$GET_CONTEXT(''USER_SESSION'', ''W_ANOMES''))
                                                                                                                                                                                         from RDB$DATABASE)),
                                                                                                                                                         (select min(D1.BDREFCOL)
                                                                                                                                                          from VRHF_EMP_TCOLCON_BANCO D1
                                                                                                                                                          where D1.BDCODEMP = FOL.BDCODEMP and
                                                                                                                                                                D1.BDCODCOL = FOL.BDCODCOL)) as BDREFCOL
                                                                                                                                                  from RDB$DATABASE))';


  FOR EXECUTE STATEMENT wSql
    INTO :BDCODEMP,
         :BDCODCOL,
         :BDCODVER,
         :BDREFFN,
         :BDREFFC,
         :BDREFVFN_SUM,
         :BDREFVFN_MAX,
         :BDREFAUXVFN_SUM,
         :BDREFAUXVFN_MAX,
         :BDVALVFN,
         :BDDATAFN,
         :BDSALBASE,
         :BDBINSS,
         :BDBFGTS,
         :BDFGTS,
         :BDBIRRF,
         :BDCNPJEMP,
         :BDDESCVER,
         :BDDESCREDVER,
         :BDORDEMVER,
         :BDNOMCOL,
         :BDDATAADMCOL,
         :BDPISCOL,
         :BDCPFCOL,
         :BDTIPOCODVER,
         :BDORDEMTIPOCODVER,
         :BDTIPOREFVER,
         :BDCODBAN,
         :BDCODAG,
         :BDCTADEPCOL,
         :BDDIGCTADEPCOL,
         :BDMODOPAGTOCOL,
         :BDCLAVER,
         :BDCODCENTRO,
         :BDCODTPCC
  DO
  BEGIN
    SUSPEND;
  END
END
^

/* Alter (VRH_SP_REL_RECIBO_FOLHA_NORMAL) */
ALTER PROCEDURE VRH_SP_REL_RECIBO_FOLHA_NORMAL(PRCODEMP INTEGER,
PRREF INTEGER,
PRCODCLA VARCHAR(10000),
PRCODTPCC VARCHAR(20000) = NULL,
PRDATAINI DATE = NULL,
PRDATAFIM DATE = NULL,
PRSITCOL SMALLINT = 1)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFVFN_SUM NUMERIC(15,6),
BDREFVFN_MAX NUMERIC(15,6),
BDREFAUXVFN_SUM NUMERIC(15,6),
BDREFAUXVFN_MAX NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDDATAFN INTEGER,
BDSALBASE NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDCNPJEMP VARCHAR(18),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDORDEMVER INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDPISCOL VARCHAR(14),
BDCPFCOL VARCHAR(14),
BDRG VARCHAR(13),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDTIPOREFVER INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDMODOPAGTOCOL INTEGER,
BDCLAVER VARCHAR(20),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WDTI VARCHAR(20);
DECLARE VARIABLE WDTF VARCHAR(20);
DECLARE VARIABLE WMES VARCHAR(2); /* Para filtrar os somente demitidos no m?s */
DECLARE VARIABLE WANO VARCHAR(4);
DECLARE VARIABLE WULTDIA VARCHAR(2);
BEGIN
/*
   O par?metro prsitcol filtra os colaboradores conforme o combobox de situa??o

   0 = Somente ativos
   1 = Todos
   2 = Somente admitidos no m?s
   3 = Somente demitidos no m?s (Estagi?rios, Prolaboristas desligados da empresa)
   4 = Ativos sem os demitidos no m?s   (Estagi?rios demitidos no m?s, Prolaboristas desligados da empresa)
   5 = Ativos sem os transferidos no m?s
   6 = Ativos sem os afastados o m?s inteiro
   7 = Afastados o m?s inteiro.

 */



  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wSql = '';
  wSql = wSql||'select ';
  wSql = wSql||'      FOL.BDCODEMP, ';
  wSql = wSql||'      FOL.BDCODCOL, ';
  wSql = wSql||'      FOL.BDCODVER, ';
  wSql = wSql||'      FOL.BDREFFN, ';
  wSql = wSql||'      FOL.BDREFVFN_SUM, ';
  wSql = wSql||'      FOL.BDREFVFN_MAX, ';
  wSql = wSql||'      FOL.BDREFAUXVFN_SUM, ';
  wSql = wSql||'      FOL.BDREFAUXVFN_MAX, ';
  wSql = wSql||'      FOL.BDVALVFN, ';
  wSql = wSql||'      FOL.BDREFFN, ';
  wSql = wSql||'      FOLB.BDSALBASE, ';
  wSql = wSql||'      FOLB.BDBINSS, ';
  wSql = wSql||'      FOLB.BDBFGTS, ';
  wSql = wSql||'      FOLB.BDFGTS, ';
  wSql = wSql||'      FOLB.BDBIRRF, ';
  wSql = wSql||'      EMP.BDCNPJEMP, ';
  wSql = wSql||'      VERB.BDDESCVER, ';
  wSql = wSql||'      VERB.BDDESCREDVER, ';
  wSql = wSql||'      VERB.BDORDEMVER, ';
  wSql = wSql||'      COLCAD.BDNOMCOL, ';
  wSql = wSql||'      COL.BDDATAADMCOL, ';
  wSql = wSql||'      DOCREF.BDPISCOL, ';
  wSql = wSql||'      COLDOC.BDCPFCOL, ';
  wSql = wSql||'      DOCREF.BDRGCOL, ';
  wSql = wSql||'      VERR.BDTIPOCODVER, ';
  wSql = wSql||'      case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  wSql = wSql||'      VERR.BDTIPOREFVER, ';
  wSql = wSql||'      COLBANCO.BDCODBAN, ';
  wSql = wSql||'      COLBANCO.BDCODAG, ';
  wSql = wSql||'      COLBANCO.BDCTADEPCOL, ';
  wSql = wSql||'      COLBANCO.BDDIGCTADEPCOL, ';
  wSql = wSql||'      COLBANCO.BDMODOPAGTOCOL, ';
  wSql = wSql||'      VERB.BDCLAVER, ';
  wSql = wSql||'      FOL.BDCODCENTRO, ';
  wSql = wSql||'      FOL.BDCODTPCC ';

  wSql = wSql||'from (select ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     wSql = wSql||'first 0 ';

  wSql = wSql||'            X.BDCODEMP, ';
  wSql = wSql||'            X.BDCODCOL, ';
  wSql = wSql||'            X.BDREFFN, ';
  wSql = wSql||'            X.BDCODVER, ';
  wSql = wSql||'            X.BDREFVFN as BDREFVFN_SUM, ';
  wSql = wSql||'            X.BDREFAUXVFN as BDREFAUXVFN_SUM, ';
  wSql = wSql||'            X.BDREFVFN as BDREFVFN_MAX, ';
  wSql = wSql||'            X.BDREFAUXVFN as BDREFAUXVFN_MAX, ';
  wSql = wSql||'            X.BDVALVFN, ';
  wSql = wSql||'            0 BDCODCENTRO, ';
  wSql = wSql||'            0 BDCODTPCC ';
  wSql = wSql||'      from ';
  wSql = wSql||'            VRHF_EMP_TVERBAFN X ';

  IF (prsitcol = 2) THEN
     wSql = wSql||' join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = '||prref||')';

  IF (PRCODEMP > 0) THEN
     wSql = wSql||'      where X.BDCODEMP = '||:PRCODEMP||' and X.BDREFFN = '||PRREF||' ';
  ELSE
     wSql = wSql||'      where X.BDREFFN = '||PRREF||' ';

  wmes = SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2);
  wano = SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4);

  SELECT CAST(ultdia AS VARCHAR(2)) FROM ultimo_dia_mes(CAST(:wmes AS SMALLINT),CAST(:wano AS INTEGER)) INTO :wultdia;
       
  IF (strlen(wmes) = 1) THEN
    wmes = '0'||wmes;
        
  IF (strlen(wultdia) = 1) THEN
    wultdia = '0'||wultdia;
        
  wdti = ''''||wmes||'/01/'||wano||'''';
  wdtf = ''''||wmes||'/'||wultdia||'/'||wano||'''';
     
  -- Somente ativos e todos  (nunca entram demitidos que n?o sejam estagi?rios)
  IF (prsitcol IN (0, 1, 2)) THEN
     BEGIN
        wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                  '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla not in (2,5)) and (Y.BDREFRESCISAO <= '||prref||'))))';

        IF (prsitcol = 1) THEN --Prolaborista tamb?m pode ter recibo de sal?rio no m?s da rescis?o
          BEGIN
            wSql = wSql|| ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                      'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1)'||
                                      'join vrh_emp_tcon_doc Colab on (Colab.bdcodemp = Y.BDCODEMP and Colab.bdcodcol = Y.BDCODCOL)'||
                                      'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol)'||
                                      'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla)'||
                                      'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                      '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 2)) or ((cla.bdgrupocla <> 2) and (Colab.bddatabaixacol <= '||wdtf||'))))';
          END
     END
  ELSE
  -- Somente estagi?rios demitidos no m?s
  IF (prsitcol = 3) THEN
    BEGIN
      wSql = wSql||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                              'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                              'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                              'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                              'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                              'Y.BDREFRESCISAO = '||prref||' and cla.bdgrupocla = 5)';
    
      wSql = wSql|| ' or exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                               'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1)'||
                               'join vrh_emp_tcon_doc Colab on (Colab.bdcodemp = Y.BDCODEMP and Colab.bdcodcol = Y.BDCODCOL)'||
                               'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol)'||
                               'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla)'||
                               'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                               '(((Y.BDREFRESCISAO = '||prref||') and (cla.bdgrupocla = 2)) and (Colab.bddatabaixacol between '||wdti||' and '||wdtf||')))';
    END                              
  ELSE
  -- Ativos sem demitidos
  IF (prsitcol = 4) THEN
     wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFRESCISAO < '||prref||')';
  ELSE
  -- Ativos sem transferidos
  IF (prsitcol = 5) THEN
     wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                  '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||')))) ' ||
                  ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV = 1) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFRESCISAO = '||prref||')';
  ELSE
  -- Ativos sem os afastados o m?s inteiro
  IF (prsitcol = 6) THEN
     wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                  'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                  '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||')))) ' ||
                  ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
                                  'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
                                  'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                  '((Y.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and Z.BDCODVER is not null) ';
  ELSE
  -- Afastados o m?s inteiro
  IF (prsitcol = 7) THEN
     wSql = wSql||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
                              'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
                              'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                              '((Y.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and Z.BDCODVER is not null) ';

  wSql = wSql||'      UNION ALL ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wSql = wSql||'      select ';
       wSql = wSql||'            X.BDCODEMP, ';
       wSql = wSql||'            X.BDCODCOL, ';
       wSql = wSql||'            X.BDREFTOMADOR, ';
       wSql = wSql||'            X.BDCODVER, ';
       wSql = wSql||'            X.BDREFVFN_SUM, ';
       wSql = wSql||'            X.BDREFAUXVFN_SUM, ';
       wSql = wSql||'            X.BDREFVFN_MAX, ';
       wSql = wSql||'            X.BDREFAUXVFN_MAX, ';
       wSql = wSql||'            X.BDVALVFT, ';
       wSql = wSql||'            X.BDCODCENTRO, ';
       wSql = wSql||'            X.BDCODTPCC ';
       wSql = wSql||'      from ';
       wSql = wSql||'            SP_VRHF_UNION_FT_MES('||prcodemp||','||prref||','''||prcodtpcc||''') X ';

       IF (prsitcol = 2) THEN
          wSql = wSql||' join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = '||prref||')';

       wSql = wSql||'      where X.BDREFTOMADOR = '||PRREF||' ';

       -- Somente ativos e todos  (nunca entram demitidos que n?o sejam estagi?rios)
       IF (prsitcol IN (0, 1, 2)) THEN
         BEGIN
           wSql = wSql||' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp and vd.bdcodcol = RESC.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and '||
                                       '(((RESC.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla not in (2,5)) and (RESC.BDREFRESCISAO <= '||prref||'))))';

           IF (prsitcol = 1) THEN --Prolaborista tamb?m pode ter recibo de sal?rio no m?s da rescis?o
             BEGIN
               wSql = wSql|| ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1)'||
                                       'join vrh_emp_tcon_doc Colab on (Colab.bdcodemp = Y.BDCODEMP and Colab.bdcodcol = Y.BDCODCOL)'||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol)'||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla)'||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                       '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 2)) or ((cla.bdgrupocla <> 2) and (Colab.bddatabaixacol <= '||wdtf||'))))';
             END
         END
       ELSE
       -- Somente estagi?rios demitidos no m?s
       IF (prsitcol = 3) THEN
         BEGIN
           wSql = wSql||' and exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                   'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                   'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp and vd.bdcodcol = RESC.bdcodcol) '||
                                   'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                   'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and '||
                                   'RESC.BDREFRESCISAO = '||prref||' and cla.bdgrupocla = 5)';

           wSql = wSql|| ' or exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                   'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1)'||
                                   'join vrh_emp_tcon_doc Colab on (Colab.bdcodemp = Y.BDCODEMP and Colab.bdcodcol = Y.BDCODCOL)'||
                                   'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol)'||
                                   'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla)'||
                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                   '((Y.BDREFRESCISAO = '||prref||') and (cla.bdgrupocla = 2)) and (Colab.bddatabaixacol between '||wdti||' and '||wdtf||'))';
         END
       ELSE
       -- Ativos sem demitidos
       IF (prsitcol = 4) THEN
          wSql = wSql||' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and RESC.BDREFRESCISAO < '||prref||')';
       ELSE
       -- Ativos sem transferidos
       IF (prsitcol = 5) THEN
          wSql = wSql||' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp and vd.bdcodcol = RESC.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and '||
                                       '(((RESC.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (RESC.BDREFRESCISAO <= '||prref||')))) ' ||
                       ' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV = 1) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and RESC.BDREFRESCISAO = '||prref||')';
       ELSE
       -- Ativos sem os afastados o m?s inteiro
       IF (prsitcol = 6) THEN
          wSql = wSql||' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL from VRH_EMP_TRESCISAO RESC '||
                                       'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES and PRES.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp and vd.bdcodcol = RESC.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where RESC.BDCODEMP = X.BDCODEMP and RESC.BDCODCOL = X.BDCODCOL and '||
                                       '(((RESC.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (RESC.BDREFRESCISAO <= '||prref||')))) ' ||
                       ' and not exists(select SIT.BDCODEMP, SIT.BDCODCOL from VRH_EMP_TSITCOL SIT '||
                                       'join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
                                       'where SIT.BDCODEMP = X.BDCODEMP and SIT.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                       '((SIT.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and SIT.BDCODVER is not null) ';
       ELSE
       -- Afastados o m?s inteiro
       IF (prsitcol = 7) THEN
          wSql = wSql||' and exists(select SIT.BDCODEMP, SIT.BDCODCOL from VRH_EMP_TSITCOL SIT '||
                                   'join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
                                   'where SIT.BDCODEMP = X.BDCODEMP and SIT.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                   '((SIT.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and SIT.BDCODVER is not null) ';
       wSql = wSql||'     ) FOL ';
     END
  ELSE
     BEGIN
       wSql = wSql||'      select ';
       wSql = wSql||'            X.BDCODEMP, ';
       wSql = wSql||'            X.BDCODCOL, ';
       wSql = wSql||'            X.BDREFTOMADOR, ';
       wSql = wSql||'            X.BDCODVER, ';
       wSql = wSql||'            X.BDREFVFN_SUM, ';
       wSql = wSql||'            X.BDREFAUXVFN_SUM, ';
       wSql = wSql||'            X.BDREFVFN_MAX, ';
       wSql = wSql||'            X.BDREFAUXVFN_MAX, ';
       wSql = wSql||'            X.BDVALVFT, ';
       wSql = wSql||'            X.BDCODCENTRO, ';
       wSql = wSql||'            X.BDCODTPCC ';
       wSql = wSql||'      from ';
       wSql = wSql||'            SP_VRHF_UNION_FT_MES('||prcodemp||','||prref||') X ';
     
       IF (prsitcol = 2) THEN
          wSql = wSql||' join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = '||prref||')';

       wSql = wSql||'      where X.BDREFTOMADOR = '||PRREF||' ';
     
       -- Somente ativos e todos  (nunca entram demitidos que n?o sejam estagi?rios)
       IF (prsitcol IN (0, 1, 2)) THEN
          BEGIN
            wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                       '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla not in (2,5)) and (Y.BDREFRESCISAO <= '||prref||'))))';

            IF (prsitcol = 1) THEN --Prolaborista tamb?m pode ter recibo de sal?rio no m?s da rescis?o
              BEGIN
                wSql = wSql|| ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                      'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1)'||
                                      'join vrh_emp_tcon_doc Colab on (Colab.bdcodemp = Y.BDCODEMP and Colab.bdcodcol = Y.BDCODCOL)'||
                                      'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol)'||
                                      'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla)'||
                                      'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                      '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 2)) or ((cla.bdgrupocla <> 2) and (Colab.bddatabaixacol <= '||wdtf||'))))';

              END
          END
       ELSE
       -- Somente estagi?rios demitidos no m?s
       IF (prsitcol = 3) THEN
          BEGIN    
            wSql = wSql||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                   'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                   'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                   'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                   'Y.BDREFRESCISAO = '||prref||' and cla.bdgrupocla = 5)';
                                   

            wSql = wSql|| ' or exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                   'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1)'||
                                   'join vrh_emp_tcon_doc Colab on (Colab.bdcodemp = Y.BDCODEMP and Colab.bdcodcol = Y.BDCODCOL)'||
                                   'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol)'||
                                   'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla)'||
                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                   '(((Y.BDREFRESCISAO = '||prref||') and (cla.bdgrupocla = 2)) and (Colab.bddatabaixacol between '||wdti||' and '||wdtf||')))';
          END
       ELSE
       -- Ativos sem demitidos
       IF (prsitcol = 4) THEN
          wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFRESCISAO < '||prref||')';
       ELSE
       -- Ativos sem transferidos
       IF (prsitcol = 5) THEN
          wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                       '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||')))) ' ||
                       ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV = 1) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFRESCISAO = '||prref||')';
       ELSE
       -- Ativos sem os afastados o m?s inteiro
       IF (prsitcol = 6) THEN
          wSql = wSql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y '||
                                       'join vrh_base_tprepresc Z on (Z.BDCODPRES = Y.BDCODPRES and Z.BDTIPOMOV <> 1) '||
                                       'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = Y.bdcodemp and vd.bdcodcol = Y.bdcodcol) '||
                                       'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                                       '(((Y.BDREFRESCISAO < '||prref||') and (cla.bdgrupocla = 5)) or ((cla.bdgrupocla <> 5) and (Y.BDREFRESCISAO <= '||prref||')))) ' ||
                       ' and not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
                                       'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
                                       'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                       '((Y.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and Z.BDCODVER is not null) ';
       ELSE
       -- Afastados o m?s inteiro
       IF (prsitcol = 7) THEN
          wSql = wSql||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
                                   'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and CAST((SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prref||' and '||
                                   '((Y.BDDATAFIMSIT is null) or (CAST((SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(Y.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prref||')) and Z.BDCODVER is not null) ';

       wSql = wSql||'     ) FOL ';
     END

  wSql = wSql||'join (select ';
  wSql = wSql||'            BDCODEMP, ';
  wSql = wSql||'            BDCODCOL, ';
  wSql = wSql||'            BDREFFN, ';
  wSql = wSql||'            coalesce(BDBFGTSFN,0) + coalesce(BDBFGTSFEFN,0) as BDBFGTS, ';
  wSql = wSql||'            coalesce(BDFGTSFN,0) + coalesce(BDFGTSFEFN,0) as BDFGTS, ';
  wSql = wSql||'            coalesce(BDBINSSFN,0)+coalesce(BDBINSSFEFOLFN,0) as BDBINSS, ';
  wSql = wSql||'            BDBIRRFFN as BDBIRRF, ';
  wSql = wSql||'            BDSALBASEFN as BDSALBASE, ';
  wSql = wSql||'            0 BDCODCENTRO, ';
  wSql = wSql||'            0 BDCODTPCC ';
  wSql = wSql||'      from ';
  wSql = wSql||'            VRHF_EMP_TFOLHANORMAL ';

  IF (PRCODEMP > 0) THEN
     wSql = wSql||'      where BDCODEMP = '||:PRCODEMP||' and BDREFFN = '||PRREF||' ';
  ELSE
     wSql = wSql||'      where BDREFFN = '||PRREF||' ';

  wSql = wSql||'      UNION All ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wSql = wSql||'      select ';
       wSql = wSql||'            X.BDCODEMP, ';
       wSql = wSql||'            X.BDCODCOL, ';
       wSql = wSql||'            X.BDREFTOMADOR BDREFFN, ';
       wSql = wSql||'            sum(X.BDBFGTSFT) + sum(x.BDBFGTSFEFT), ';
       wSql = wSql||'            sum(X.BDFGTSFT) + sum(x.BDFGTSFEFT), ';
       wSql = wSql||'            sum(X.BDBINSSFT) + sum(x.BDBINSSFEFOLFT), ';
       wSql = wSql||'            sum(X.BDBIRRFFT), ';
       wSql = wSql||'            max(X.BDSALBASEFT), ';
       wSql = wSql||'            Y.BDCODCENTRO, ';
       wSql = wSql||'            Y.BDCODTPCC ';
       wSql = wSql||'      from ';
       wSql = wSql||'            VRHF_EMP_TFOLHATOMADOR X, ';
       wSql = wSql||'            VRHF_EMP_TPREPFN Y ';
     
       IF (PRCODEMP > 0) THEN
          wSql = wSql||'      where X.BDCODEMP = '||:PRCODEMP||' and X.BDREFTOMADOR = '||PRREF||' and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';
       ELSE
          wSql = wSql||'      where X.BDREFTOMADOR = '||PRREF||' and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';

       wsql = wsql||' and '||prcodtpcc;

       wsql = wsql||' group by X.BDCODEMP,X.BDCODCOL,X.BDREFTOMADOR,Y.BDCODCENTRO,Y.BDCODTPCC ';

       wSql = wSql||') FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDREFFN = FOL.BDREFFN) ';
     END
  ELSE
     BEGIN
       wSql = wSql||'      select ';
       wSql = wSql||'            X.BDCODEMP, ';
       wSql = wSql||'            X.BDCODCOL, ';
       wSql = wSql||'            X.BDREFTOMADOR BDREFFN, ';
       wSql = wSql||'            SUM(X.BDBFGTSFT)+sum(x.BDBFGTSFEFT), ';
       wSql = wSql||'            SUM(X.BDFGTSFT)+sum(x.BDFGTSFEFT), ';
       wSql = wSql||'            SUM(X.BDBINSSFT)+sum(x.BDBINSSFEFOLFT), ';
       wSql = wSql||'            SUM(X.BDBIRRFFT), ';
       wSql = wSql||'            MAX(X.BDSALBASEFT), ';
       wSql = wSql||'            0 BDCODCENTRO, ';
       wSql = wSql||'            0 BDCODTPCC ';
       wSql = wSql||'      from ';
       wSql = wSql||'            VRHF_EMP_TFOLHATOMADOR X, ';
       wSql = wSql||'            VRHF_EMP_TPREPFN Y ';
     
       IF (PRCODEMP > 0) THEN
          wSql = wSql||'      where X.BDCODEMP = '||:PRCODEMP||' and X.BDREFTOMADOR = '||PRREF||' and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';
       ELSE
          wSql = wSql||'      where X.BDREFTOMADOR = '||PRREF||' and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';
     
       wSql = wSql||'      group by ';
       wSql = wSql||'            X.BDCODEMP, ';
       wSql = wSql||'            X.BDCODCOL, ';
       wSql = wSql||'            X.BDREFTOMADOR) FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDREFFN = FOL.BDREFFN) ';
     END

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     BEGIN
       prcodcla = REPLACE(UPPER(:prcodcla), 'BDCODCLA', 'COLCON_VIN.BDCODCLA');
       wSql = wSql||' join VW_VRH_EMP_TCOLCON_VINC COLCON_VIN on (COLCON_VIN.BDCODEMP = FOL.BDCODEMP and COLCON_VIN.BDCODCOL = FOL.BDCODCOL and '||prcodcla||') ';
     END

  wSql = wSql||' left outer join TEMPRESAS EMP on (EMP.BDCODEMP = FOL.BDCODEMP) ';
  wSql = wSql||' left outer join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||' left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||' left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||' left outer join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = FOL.BDCODEMP and COLDOC.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||' left outer join VW_VRH_BASE_TVERBAS_REF VERR on (VERR.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||' left outer join VW_VRHF_EMP_TCOLCON_BANCO COLBANCO on (COLBANCO.BDCODEMP = FOL.BDCODEMP and COLBANCO.BDCODCOL = FOL.BDCODCOL) ';

  -- Elimina situa??o
  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       wdti = ''''||CAST(prdataini AS VARCHAR(10))||'''';
       wdtf = ''''||CAST(prdatafim AS VARCHAR(10))||'''';

       wSql = wSql||' where not exists (select SIT.BDCODEMP,SIT.BDCODCOL from VRH_SP_DADOS_SITUACAO('''||'SIT.BDCODEMP = '||prcodemp||''',null,'''||prdataini||''', '''||prdatafim||''') SIT where '||
              'SIT.BDCODEMP = FOL.BDCODEMP and SIT.BDCODCOL = FOL.BDCODCOL and SIT.BDRELSIT = 1 and '||
              '(SIT.BDDATAINISIT <= '||wdti||' and ((SIT.BDDATAFIMSIT is null) or (SIT.BDDATAFIMSIT >= '||wdtf||')))) ';
   END


  FOR EXECUTE STATEMENT wSql
    INTO :BDCODEMP,
         :BDCODCOL,
         :BDCODVER,
         :BDREFFN,
         :BDREFVFN_SUM,
         :BDREFVFN_MAX,
         :BDREFAUXVFN_MAX,
         :BDREFAUXVFN_SUM,
         :BDVALVFN,
         :BDDATAFN,
         :BDSALBASE,
         :BDBINSS,
         :BDBFGTS,
         :BDFGTS,
         :BDBIRRF,
         :BDCNPJEMP,
         :BDDESCVER,
         :BDDESCREDVER,
         :BDORDEMVER,
         :BDNOMCOL,
         :BDDATAADMCOL,
         :BDPISCOL,
         :BDCPFCOL,
         :BDRG,
         :BDTIPOCODVER,
         :BDORDEMTIPOCODVER,
         :BDTIPOREFVER,
         :BDCODBAN,
         :BDCODAG,
         :BDCTADEPCOL,
         :BDDIGCTADEPCOL,
         :BDMODOPAGTOCOL,
         :BDCLAVER,
         :BDCODCENTRO,
         :BDCODTPCC
  DO
  BEGIN
    SUSPEND;
  END
END
^

/* Alter (VRH_SP_RELATORIO_CAT2) */
ALTER PROCEDURE VRH_SP_RELATORIO_CAT2(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRCHAVE INTEGER,
PRULTIMODIA DATE,
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCHAVE INTEGER,
BDCODCID INTEGER,
BDDATAACIDENTE DATE,
BDDATAEMISSAO DATE,
BDDATAULTIMODIA DATE,
BDDATAOBITO DATE,
BDEMITENTE INTEGER,
BDNRCAT VARCHAR(25),
BDTIPOAFAST INTEGER,
BDREGPOLICIAL VARCHAR(5),
BDAFASTAMENTO VARCHAR(5),
BDHORAACIDENTE TIME,
BDTIPOCAT INTEGER,
BDLOCALACIDENTE INTEGER,
BDESPLOCALACIDENTE VARCHAR(40),
BDOBJETOCAUSADORACID VARCHAR(10000),
BDDESCACIDENTE BLOB SUB_TYPE 1 SEGMENT SIZE 210,
BDPARTESATINGIDAS VARCHAR(10000),
BDAREAACIDENTE INTEGER,
BDHOUVEOBITO VARCHAR(5),
BDREMUNMENSAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDBAIEMP DM_BDBAIRRO,
BDCODCNAE INTEGER,
BDNUMEMP INTEGER,
BDENDEMP DM_BDENDERECO,
BDLOGREMP VARCHAR(15),
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDCNPJEMP VARCHAR(18),
BDNOMCOL DM_BDNOMCOL,
BDNOMMAECOL VARCHAR(70),
BDDATANASCCOL DATE,
BDSEXOCOL INTEGER,
BDESTCIVCOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDRGCOL VARCHAR(13),
BDDATAEMIRGCOL DATE,
BDORGEMIRGCOL VARCHAR(8),
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL INTEGER,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDFILIACAOPREV INTEGER,
BDAPOSENTADO INTEGER,
BDNOMCIDACID VARCHAR(40),
BDUFACID VARCHAR(2),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDNOMECIDCOL VARCHAR(40),
BDUFCOL VARCHAR(2),
BDUFCTPS VARCHAR(2),
BDDESCCBO VARCHAR(100),
BDCODCBO INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDUFRG VARCHAR(2),
BDDDDCELCOL INTEGER,
BDCELCOL DM_BDTELEFONE,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDDTAPOSENT DATE)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WSQLA VARCHAR(5000);
DECLARE VARIABLE WDESC VARCHAR(1000);
DECLARE VARIABLE WVALUE NUMERIC(18,6);
BEGIN

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, prultimodia);

    wSql = 'select ';
    wSql = wSql || 'CAT.BDCODEMP, ';
    wSql = wSql || 'CAT.BDCODCOL, ';
    wSql = wSql || 'CAT.BDCHAVE, ';
    wSql = wSql || 'CAT.BDCODCID, ';
    wSql = wSql || 'CAT.BDDATAACIDENTE, ';
    wSql = wSql || 'CAT.BDDATAEMISSAO, ';
    wSql = wSql || 'CAT.BDDATAULTIMODIA, ';
    wSql = wSql || 'CAT.BDDATAOBITO, ';
    wSql = wSql || 'case when (CAT.BDEMITENTE = 5) then 3 else CAT.BDEMITENTE end BDEMITENTE, ';
    wSql = wSql || 'CAT.BDNRCAT, ';
    wSql = wSql || 'CAT.BDTIPOAFAST, ';
    wSql = wSql || 'CAT.BDREGPOLICIAL, ';
    wSql = wSql || 'CAT.BDAFASTAMENTO, ';
    wSql = wSql || 'CAT.BDHORAACIDENTE, ';
    wSql = wSql || 'CAT.BDTIPOCAT, ';
    wSql = wSql || 'CAT.BDLOCALACIDENTE, ';
    wSql = wSql || 'CAT.BDESPLOCALACIDENTE, ';
    wSql = wSql || 'CAT.BDOBJETOCAUSADORACID, ';
    wSql = wSql || 'CAT.BDDESCACIDENTE, ';
    wSql = wSql || 'CAT.BDPARTESATINGIDAS, ';
    wSql = wSql || 'coalesce(CAT.BDAREAACIDENTE,0)+1, ';
    wSql = wSql || 'CAT.BDHOUVEOBITO, ';
    wSql = wSql || 'CAT.BDREMUNMENSAL, ';
    wSql = wSql || 'EMPR.bdnomemp, ';
    wSql = wSql || 'EMPR.bdbaiemp, ';
    wSql = wSql || 'EMPR.bdcodcnae, ';
    wSql = wSql || 'EMPR.bdnumemp, ';
    wSql = wSql || 'EMPR.bdendemp, ';
    wSql = wSql || 'EMPR.bdlogremp, ';
    wSql = wSql || 'EMPR.bdcepemp, ';
    wSql = wSql || 'EMPR.bddddemp, ';
    wSql = wSql || 'EMPR.bdfoneemp, ';
    wSql = wSql || 'EMP.bdcnpjemp, ';
    wSql = wSql || 'COL.BDNOMCOL, ';
    wSql = wSql || 'COL.BDNOMMAECOL, ';
    wSql = wSql || 'COL.BDDATANASCCOL, ';
    wSql = wSql || 'COL.BDSEXOCOL, ';
    wSql = wSql || 'COL.BDESTCIVCOL, ';
    wSql = wSql || 'COL.BDCTPSCOL, ';
    wSql = wSql || 'COL.BDSERIECTPSCOL, ';
    wSql = wSql || 'COL.BDDSERIECTPSCOL, ';
    wSql = wSql || 'COL.BDDATAEMICTPSCOL, ';
    wSql = wSql || 'COL.BDRGCOL, ';
    wSql = wSql || 'COL.BDDATAEMIRGCOL, ';
    wSql = wSql || 'COL.BDORGEMIRGCOL, ';
    wSql = wSql || 'COL.BDPISCOL, ';
    wSql = wSql || 'COL.BDLOGRCOL, ';
    wSql = wSql || 'COL.BDENDCOL, ';
    wSql = wSql || 'COL.BDNUMCOL, ';
    wSql = wSql || 'COL.BDBAICOL, ';
    wSql = wSql || 'COL.BDCEPCOL, ';
    wSql = wSql || 'COL.BDDDDCOL, ';
    wSql = wSql || 'COL.BDFONECOL, ';
    wSql = wSql || 'COLR.BDGRUPOCLA bdfiliacaoPrev, ';
    wSql = wSql || 'COLR.BDGRUPOCLA bdAposentado, ';
    wSql = wSql || 'CID_CAT.bdnomcid bdnomcidacid, ';
    wSql = wSql || 'UF_CAT.BDSIGLAUF bdUFacid, ';
    wSql = wSql || 'CID_EMP.bdnomcid, ';
    wSql = wSql || 'UF_EMP.bdsiglauf, ';
    wSql = wSql || 'CID_COL.bdnomcid BDNOMECIDCOL, ';
    wSql = wSql || 'uf_col.bdsiglauf BDUFCOL, ';
    wSql = wSql || 'UF_CTPS.BDSIGLAUF bdUFCTPS, ';
    wSql = wSql || 'case when ((CBO_TSIN.BDDESCCBOTSIN is null) or (CBO_TSIN.BDDESCCBOTSIN = '''||''||''')) then CBO.BDDESCCBO else CBO_TSIN.BDDESCCBOTSIN end BDDESCCBO, ';
    wSql = wSql || 'CBO.bdcodcbo, ';
    wSql = wSql || 'COL_CALCDIA.bdsalbasecol, ';
    wSql = wSql || 'UF_RG.BDSIGLAUF, ';
    wSql = wSql || 'COL.BDDDDCELCOL, ';
    wSql = wSql || 'COL.BDCELCOL, ';
    wSql = wSql || 'COLR.BDTIPOCOL, ';
    wSql = wSql || 'COLR.BDHORASMENSAISCOL, ';
    wSql = wSql || 'COL.BDDTAPOSENT ';
    wSql = wSql || 'from (select * from VRH_EMP_TCAT ';

    IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
       BEGIN
         wSql = wSql||' where '||prcodemp;

         IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
           wSql = wSql||' and '||prcodcol;

         IF (COALESCE(prchave, 0) <> 0) THEN
           wSql = wSql||' and BDCHAVE = '||prchave;
         ELSE
           wSql = wSql||' and BDREFCAT = '||prref;
       END
    ELSE
       IF (COALESCE(prchave, 0) <> 0) THEN 
         wSql = wSql||' where BDREFCAT = '||prchave;

    wSql = wSql||') CAT ';

    wSql = wSql||'join VW_COLABORADORES COL on (COL.BDCODEMP = CAT.BDCODEMP and COL.BDCODCOL = CAT.BDCODCOL) ';
    wSql = wSql||'join VW_COLABORADORES_REF_ATUAL COLR on (COLR.BDCODEMP = CAT.BDCODEMP and COLR.BDCODCOL = CAT.BDCODCOL) ';
    wSql = wSql||'join VW_EMPRESAS_REF_ATUAL EMPR on (EMPR.BDCODEMP = CAT.BDCODEMP) ';
    wSql = wSql||'join TEMPRESAS EMP on (EMP.BDCODEMP = CAT.BDCODEMP) ';
    wSql = wSql||'left outer join (select * from VW_TCOLCON_VINCDIA ';

    IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
       BEGIN
         wSql = wSql||' where '||prcodemp;

         IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
            wSql = wSql||' and '||prcodcol;
       END

    wSql = wSql||') COL_DIAVINC on (COL_DIAVINC.BDCODEMP = cat.BDCODEMP and COL_DIAVINC.BDCODCOL = cat.BDCODCOL) ';
    wSql = wSql || 'left outer join vw_tcolcon_calcdia COL_CALCDIA on (COL_CALCDIA.bdcodemp = CAT.bdcodemp and COL_CALCDIA.BDCODCOL = cat.BDCODCOL) ';
    wSql = wSql || 'left outer join TCIDADE CID_CAT on (CID_CAT.bdcodcid = CAT.BDCODCID) ';
    wSql = wSql || 'left outer join TUF UF_CAT on (UF_CAT.bdcoduf = CID_CAT.bdcoduf) ';
    wSql = wSql || 'left outer join TCIDADE CID_EMP on (CID_EMP.bdcodcid = EMPR.BDCODCID) ';
    wSql = wSql || 'left outer join TUF UF_EMP on (UF_EMP.bdcoduf = CID_EMP.bdcoduf) ';
    wSql = wSql || 'left outer join TCIDADE CID_COL on (CID_COL.bdcodcid = COL.BDCODCID) ';
    wSql = wSql || 'left outer join TUF UF_COL on (UF_COL.bdcoduf = CID_COL.bdcoduf) ';
    wSql = wSql || 'left outer join TUF UF_CTPS on (UF_CTPS.bdcoduf = COL.bdcoduf) ';
    wSql = wSql || 'left outer join TUF UF_RG on (UF_RG.bdcoduf = COL.bdcodufrg) ';

    wSql = wSql || 'left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = COL_DIAVINC.bdcodplafuc and tfuc.bdcodtfuc = COL_DIAVINC.bdcodtfuc) ';
    wSql = wSql || 'left outer join vrh_base_tcbo CBO on (CBO.bdcodcbo = tfuc.bdcodcbo) ';
    wSql = wSql || 'left outer join vrh_base_cbo_tsin CBO_TSIN on (CBO_TSIN.bdcodcbo = tfuc.bdcodcbo and CBO_TSIN.bdcodcbotsin = tfuc.bdcodcbotsin) ';
    wSql = wSql || 'order by CAT.BDCODEMP,CAT.BDCODCOL,CAT.BDCHAVE ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCHAVE,
    :BDCODCID,
    :BDDATAACIDENTE,
    :BDDATAEMISSAO,
    :BDDATAULTIMODIA,
    :BDDATAOBITO,
    :BDEMITENTE,
    :BDNRCAT,
    :BDTIPOAFAST,
    :BDREGPOLICIAL,
    :BDAFASTAMENTO,
    :BDHORAACIDENTE,
    :BDTIPOCAT,
    :BDLOCALACIDENTE,
    :BDESPLOCALACIDENTE,
    :BDOBJETOCAUSADORACID,
    :BDDESCACIDENTE,
    :BDPARTESATINGIDAS,
    :BDAREAACIDENTE,
    :BDHOUVEOBITO,
    :BDREMUNMENSAL,
    :BDNOMEMP,
    :BDBAIEMP,
    :BDCODCNAE,
    :BDNUMEMP,
    :BDENDEMP,
    :BDLOGREMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDCNPJEMP,
    :BDNOMCOL,
    :BDNOMMAECOL,
    :BDDATANASCCOL,
    :BDSEXOCOL,
    :BDESTCIVCOL,
    :BDCTPSCOL,
    :BDSERIECTPSCOL,
    :BDDSERIECTPSCOL,
    :BDDATAEMICTPSCOL,
    :BDRGCOL,
    :BDDATAEMIRGCOL,
    :BDORGEMIRGCOL,
    :BDPISCOL,
    :BDLOGRCOL,
    :BDENDCOL,
    :BDNUMCOL,
    :BDBAICOL,
    :BDCEPCOL,
    :BDDDDCOL,
    :BDFONECOL,
    :BDFILIACAOPREV,
    :BDAPOSENTADO,
    :BDNOMCIDACID,
    :BDUFACID,
    :BDNOMCID,
    :BDSIGLAUF,
    :BDNOMECIDCOL,
    :BDUFCOL,
    :BDUFCTPS,
    :BDDESCCBO,
    :BDCODCBO,
    :BDSALBASECOL,
    :BDUFRG,
    :BDDDDCELCOL,
    :BDCELCOL,
    :BDTIPOCOL,
    :BDHORASMENSAISCOL,
    :BDDTAPOSENT
  DO
    BEGIN
      IF ((bdpartesatingidas) IS NULL OR (bdpartesatingidas = '')) THEN
         BEGIN
           bdpartesatingidas = '';

           wsqla = 'select Y.BDDESCPCORPO from TCAT_PCORPOATINGIDA Y join VRH_EMP_TCAT_PATINGIDAS X on (X.BDCODPCORPO = Y.BDCODPCORPO and X.BDCODEMP = '||bdcodemp||
                   ' and X.BDCODCOL = '||bdcodcol||' and X.BDCHAVE = '||bdchave||') ';

           FOR EXECUTE STATEMENT wsqla INTO :wdesc DO
             BEGIN
               IF (bdpartesatingidas <> '') THEN
                  bdpartesatingidas = bdpartesatingidas||', ';

               bdpartesatingidas = bdpartesatingidas||TRIM(wdesc);
             END
         END

      IF ((bdobjetocausadoracid) IS NULL OR (bdobjetocausadoracid = '')) THEN
         BEGIN
           bdobjetocausadoracid = '';

           wsqla = 'select Y.BDDESCAGCAUSA from TCAT_AGENTECAUSADOR Y join VRH_EMP_TCAT_AGCAUSADOR X on (X.BDCODAGCAUSA = Y.BDCODAGCAUSA and X.BDCODEMP = '||bdcodemp||
                   ' and X.BDCODCOL = '||bdcodcol||' and X.BDCHAVE = '||bdchave||') ';

           FOR EXECUTE STATEMENT wsqla INTO :wdesc DO
             BEGIN
               IF (bdobjetocausadoracid <> '') THEN
                  bdobjetocausadoracid = bdobjetocausadoracid||', ';

               bdobjetocausadoracid = bdobjetocausadoracid||TRIM(wdesc);
             END
         END

      IF (bdtipocol = 2) THEN 
         BEGIN
           bdsalbasecol = bdsalbasecol * bdhorasmensaiscol;
         END

      IF (bdtipocol = 4) THEN
         BEGIN
           SELECT COALESCE(SUM(X.BDSALSHE),0)
           FROM VRH_EMP_TCOL_SHE X
           JOIN (
              SELECT BDCODEMP, BDCODCOL, BDCODSHE, MAX(BDDATASHE) BDDATASHE
              FROM VRH_EMP_TCOL_SHE
              WHERE BDCODEMP = :bdcodemp AND BDCODCOL = :bdcodcol AND BDDATASHE <= :prultimodia
              GROUP BY BDCODEMP, BDCODCOL, BDCODSHE
           ) Y ON (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDCODSHE = X.BDCODSHE AND Y.BDDATASHE = X.BDDATASHE)
           INTO :wvalue;

           bdsalbasecol = CAST((wvalue * bdhorasmensaiscol) AS NUMERIC(15,6));
           -- DSR
           bdsalbasecol = CAST((bdsalbasecol + (bdsalbasecol / 6)) AS NUMERIC(15,6));
         END

      IF ((bdaposentado = 4) OR (bddtaposent IS NOT NULL)) THEN
        bdaposentado = 1;
      ELSE
        bdaposentado = 0;

      SUSPEND;
    END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);

END
^

/* Alter (VRH_SP_SERV_TERC) */
ALTER PROCEDURE VRH_SP_SERV_TERC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRSERV VARCHAR(1000),
PRCODCLA VARCHAR(1000),
PRREF INTEGER,
PRINICIO DATE,
PRFIM DATE,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOLCON_DIA SMALLINT)
 RETURNS(BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDHORASERV TIME,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL VARCHAR(10),
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODCBO INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255),
BDCONTRCOL INTEGER,
BDPERTRANSPINSSTER NUMERIC(15,6),
BDPERTRANSPIRTER NUMERIC(15,6),
BDACORDOINSSTERC DM_BOOLEAN,
BDPERCIRTERC NUMERIC(18,6),
BDPIRTERC DM_BOOLEAN)
 AS
DECLARE VARIABLE WCAM VARCHAR(20000);
DECLARE VARIABLE WWHE VARCHAR(10000);
DECLARE VARIABLE WV VARCHAR(30);
DECLARE VARIABLE WI VARCHAR(3);
DECLARE VARIABLE WD VARCHAR(30);
DECLARE VARIABLE WB VARCHAR(30);
DECLARE VARIABLE WN VARCHAR(30);
DECLARE VARIABLE WTRUE VARCHAR(5);
DECLARE VARIABLE WDATA VARCHAR(10);
DECLARE VARIABLE WCODUSU INTEGER;
DECLARE VARIABLE WTABELA VARCHAR(300);
DECLARE VARIABLE WAPELIDO VARCHAR(300);
DECLARE VARIABLE WJOINREF VARCHAR(3200);
BEGIN
   -- Seta a competencia atual.
   -- Algumas Views utilizam essas variaveis de contexto para filtrar e agrupar tabelas.
   wdata = CAST(prref AS VARCHAR(6));
   wdata = SUBSTRING(wdata FROM 5 FOR 2)||'-01-'||SUBSTRING(wdata FROM 1 FOR 4);
   EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wdata AS DATE), prfim);

   /* Retorna o usuario logado */
   FOR SELECT BDCODUSU FROM sp_get_usuario
     INTO
       :wcodusu
     DO

   wtrue = '(0=0)';
   prcodemp = COALESCE(prcodemp,wtrue);
   prcodcol = COALESCE(prcodcol,wtrue);
   prcodcla = COALESCE(prcodcla,wtrue);

   wv = ', CAST(NULL AS varchar(1))';
   wi = ', 0';
   wd = ', CAST(NULL AS DATE)';
   wb = ', CAST(NULL AS BLOB)';
   wn = ', CAST(NULL AS NUMERIC(15,6))';

   wcam = 'select TSERV.BDCODSERV, TSERV.BDDATASERV, TSERV.BDDATAPAGSERV, TSERV.BDHORASERV, TSERV.BDCODEMP, TSERV.BDCODTER ';

   -- CAMPOS
   IF (:PRCOLCON = 0) THEN
      wcam = wcam||wi||wi||wi||wi||
                   wi||wi||wv||wv||wv||
                   wv||wv||wv||wv||wi||
                   wv||wv||wv||wi||
                   wd||wd||wi||wi||
                   wd||wd;
   ELSE
      wcam = wcam||wi||', COLCON.BDCODCID'||wi||wi||
                   ', COLCON.BDCODCIDNASCTER'||wi||', COLCON.BDNOMTER, COLCON.BDLOGRTER, COLCON.BDENDTER '||
                   ', COLCON.BDNUMTER, COLCON.BDCOMPLTER, COLCON.BDBAITER, COLCON.BDCEPTER, COLCON.BDDDDTER '||
                   ', COLCON.BDFONETER, COLCON.BDCELTER, COLCON.BDEMAILTER, COLCON.BDSEXOTER '||
                   ', COLCON.BDDATANASCTER, COLCON.BDDATACADTER, TTERCREF.BDGRAUINSTTER, TTERCREF.BDESTCIVTER '||
                   wd||wd;

   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wd||
                   wv||wv||wv||wd;
   ELSE
      wcam = wcam||', COLCON_DOC.bdrgter, COLCON_DOC.BDORGEMIRGTER, COLCON_DOC.BDDATAEMIRGTER '||
                   ', COLCON_DOC.BDCPFTER, COLCON_DOC.BDRESERVISTATER, COLCON_DOC.BDPISTER'||wd;

   /*Dados nao existentes no terceiro
   if (:PRCOL_DOC = 0) then*/
      wcam = wcam||wi||wv||
                   wi||wi||wi||wi||
                   wv||wd||wv||wd||
                   wv;

/* Dados nao existentes para o terceiro
   if (:PRCOL_HIST = 0) then*/
      wcam = wcam||wi||wi||wv||wd;

--   if (:PRCOL_PARENT = 0) then
      wcam = wcam||wi||wv||wv||wv||wd;

--   if (:PRCOL_FIS = 0) then
      wcam = wcam||wi||wi||wi||wn||wn||wv||wi||wi;

--   if (:PRCON_DOC = 0) then
   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wv;
   ELSE
      wcam = wcam||', COLCON_DOC.BDNROCONSPROTER, COLCON_DOC.BDSIGLACONSPROTER, COLCON_DOC.BDCODCCMPROTER';

   IF (:PRCOLCON_VINC = 0 AND :PRCODCLA IS NULL) THEN
      wcam = wcam||wi||wi;
   ELSE
      wcam = wcam||', coalesce(COLCON_VINC.BDCODCLA, COLCON_VINC2.BDCODCLA, 0), coalesce(CLASSE.BDGRUPOCLA, CLASSE2.BDGRUPOCLA, 0)';

   /*SINDICATO terceiro nao possui*/
   wcam = wcam||wi||wi;

   IF (:PRCOLCON_BANCO = 0) THEN
      wcam = wcam||wi||wi||wv||wv||wi||wi||wv;
   ELSE
      wcam = wcam||', COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPTER, COLCON_BANCO.BDDIGCTADEPTER '||
                   ', COLCON_BANCO.BDTIPOCTATER, COLCON_BANCO.BDMODOPAGTOTER, COLCON_BANCO.BDCARTAOSALTER';

   IF (:PRCOLCON_CALC = 0) THEN
      wcam = wcam||wi||wi||wn||wn||wn;
   ELSE
      wcam = wcam||wi||', TTERCREF.BDNRODEPIRTER'||wn||wn||wn;

   /*Terceiro nao tem dados de fgts apenas de gps*/
   IF (:PRCOLCON_FGTSGPS = 0) THEN
      wcam = wcam||wd||wv||wi||wn||wi||wn||wn;
   ELSE
      wcam = wcam||wd||wv||', COLCON_FGTSGPS.BDCATEGORIATER '||wn||
                   ', COLCON_FGTSGPS.BDOCORRENCIATER '||
                   ', COLCON_FGTSGPS.BDPERCRATTER'||wn;

   IF (:PRCOLCON_MVINC = 0) THEN
      wcam = wcam||wn||wn||wn||wn||wn||wn||wn||wn;
   ELSE
      wcam = wcam||', COLCON_MVINC.BDBASEINSSNTER, COLCON_MVINC.BDVALORINSSNTER, COLCON_MVINC.BDBASEIRRFNTER '||
                   ', COLCON_MVINC.BDVALORIRRFNTER'||wn||wn||
                   wn||wn;

--   if (:PRCOL_ADM = 0) then
      wcam = wcam||wi||wi||wd||wn||wi||wd||wi||wd||wv||wi||wv||wv||wv||wv||wv||wi;

--   if (:PRCOL_CALC = 0) then
      wcam = wcam||wi||wn||wn||wn||wn||wi||wn||wi||wn||wi||wi||wv||wv||wv||wv||wv||wv||wv||wv||wv;

--   if (:PRCOL_HISTF = 0) then
      wcam = wcam||wb;

--   if (:PRCON_VINC = 0) then
      wcam = wcam||wi||wv;

   IF (:prcolcon_dia = 0) THEN
      wcam = wcam||wi||wn||wi||wv||wn||wv||wi;
   ELSE
      wcam = wcam||wi||', TSERV.bdvalorserv, COLCON_VINC.BDCODCBO, COLCON_VINC.BDACORDOINSSTERC, COLCON_VINC.BDPERCIRTERC, COLCON_VINC.BDPIRTERC'||wi; --Sol. 14603 - Marcelo B. M. - 26/08/2016


   /* Tabela de Rescisao nao existe para terceiros*/
    wcam = wcam||wi||wd||wd||wd||wd||
                 wn||wv||wn||wv||
                 wd||wv||wv||wd||wv;

    /* Motivos de rescisao nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||wi||
                 wv||wi||wi||wv||wv||wv||
                 wv||wi||wi||
                 wv||wv||
                 wv||
                 wv||
                 wv;


   /* Tabela de Transferencias nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wd;

    /* Motivos de transferencia nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||
                 wv||wv||
                 wv||
                 wv||
                 wv;

   wcam = wcam||', 2';

   /*Terceiro nao tem dados de fgts apenas de gps*/
   IF (:PRCOLCON_FGTSGPS = 0) THEN
      wcam = wcam||wn||wn;
   ELSE
      wcam = wcam||', COLCON_FGTSGPS.BDPERTRANSPINSSTER , COLCON_FGTSGPS.BDPERTRANSPIRTER ';

   -- TABELAS
   wtabela = 'vrh_base_tterc_ref';
   WAPELIDO = 'TTERCREF.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

   wcam = wcam||' from vrh_base_tservterc TSERV ';
   wcam = wcam||' left outer join vrh_base_tterc COLCON on (COLCON.bdcodter = TSERV.bdcodter) ';
   wcam = wcam||' left outer join VRH_BASE_TTERC_REF TTERCREF on (TTERCREF.bdcodter = TSERV.bdcodter'||wjoinref||') ';

   IF (:PRCOLCON_DOC <> 0) THEN
      wcam = wcam||' left outer join vw_VRH_BASE_TTERC_DOC COLCON_DOC on (COLCON_DOC.bdcodter = COLCON.bdcodter) ';

   IF (:PRCOLCON_VINC = 1 OR :PRCODCLA IS NOT NULL)  THEN
      BEGIN
        wtabela = 'VRH_BASE_TTERC_VINC';
        WAPELIDO = 'COLCON_VINC.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRH_BASE_TTERC_VINC COLCON_VINC '||
                         'on (COLCON_VINC.BDCODTER = COLCON.bdcodter'||wjoinref||') ';

        -- Grupo da Classe
        wcam = wcam||' left outer join VRH_BASE_TCLASSE CLASSE '||
                            'on (CLASSE.BDCODCLA = COLCON_VINC.BDCODCLA) ';


        wtabela = 'VRH_BASE_TTERC_VINC';
        WAPELIDO = 'COLCON_VINC2.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MIN(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc > (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRH_BASE_TTERC_VINC COLCON_VINC2 '||
                         'on (COLCON_VINC2.BDCODTER = COLCON.bdcodter'||wjoinref||') ';

        -- Grupo da Classe
        wcam = wcam||' left outer join VRH_BASE_TCLASSE CLASSE2 '||
                            'on (CLASSE2.BDCODCLA = COLCON_VINC2.BDCODCLA) ';
      END

   IF (:PRCOLCON_BANCO = 1) THEN
      BEGIN
        wtabela = 'VRHF_BASE_TTERC_BANCO';
        WAPELIDO = 'COLCON_BANCO.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRHF_BASE_TTERC_BANCO '||
                            'COLCON_BANCO on (COLCON_BANCO.BDCODter = COLCON.bdcodter'||wjoinref||') ';
      END

   IF (:PRCOLCON_FGTSGPS = 1) THEN
      BEGIN
        wtabela = 'VRHF_BASE_TTERC_FGTSGPS';
        WAPELIDO = 'COLCON_FGTSGPS.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRHF_BASE_TTERC_FGTSGPS '||
                            'COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODter = COLCON.bdcodter'||wjoinref||') ';
      END

   IF (:PRCOLCON_MVINC = 1) THEN
      BEGIN
        wtabela = 'VRHF_BASE_TTERC_MVINC';
        WAPELIDO = 'COLCON_MVINC.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRHF_BASE_TTERC_MVINC '||
                            'COLCON_MVINC on (COLCON_MVINC.BDCODTER = COLCON.BDCODTER'||wjoinref||') ';
      END

   -- WHERE
   wwhe = '';
   IF (:prCODEMP IS NOT NULL) THEN
      BEGIN
        wwhe = prcodemp;
      END

   IF ((:prserv IS NOT NULL) AND (prserv <> '')) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||prserv;
      END
   ELSE
      BEGIN
        IF ((:prfim IS NOT NULL) AND (:prinicio IS NOT NULL)) THEN
           BEGIN
              IF (wwhe <> '') THEN
                 wwhe = wwhe||' and ';
    
              wwhe = wwhe||'tserv.bddataserv >= '''||prinicio||'''';
              wwhe = wwhe||' and ';
              wwhe = wwhe||'tserv.bddataserv <= '''||prfim||'''';
           END
      END

   IF (:prCODCOL IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcol;

      END

   IF (:PRCODCLA IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcla;
      END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhe <> '') THEN
          wwhe = wwhe||' and ';

       wwhe = wwhe||'((exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||') and '||
                        'exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TSERV.BDCODEMP)) '||
                       'or '||
                       '(not exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||'))'||
                       ') ';
     END

   IF ((wwhe <> '') AND (:wwhe IS NOT NULL)) THEN
      wwhe = ' where '||wwhe;
      
   wcam = wcam||wwhe;

   wcam = wcam||' order by TSERV.BDCODEMP, TSERV.BDCODTER, TSERV.BDDATASERV, TSERV.BDHORASERV';

   FOR EXECUTE STATEMENT wcam
      INTO :BDCODSERV, BDDATASERV, BDDATAPAGSERV, BDHORASERV,
            BDCODEMP,
           -- VRH_EMP_TCOLCON
           :BDCODCOL, :BDCODMCAG, :BDCODCID, :BDCODCSEG, :BDREFCSEG,
           :BDCODCIDNASC, :BDCODUF, :BDNOMCOL, :BDLOGRCOL, :BDENDCOL,
           :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL, :BDDDDCOL,
           :BDFONECOL, :BDCELCOL, :BDEMAILCOL, :BDSEXOCOL,
           :BDDATANASCCOL, :BDDATACADCOL, :BDGRAUINSTCOL, :BDESTCIVCOL,
           :BDDATAADMCOL, :BDDATAADICCOL,

           :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDCPFCOL,
           :BDRESERVISTACOL, :BDPISCOL, :BDDATAEMIPISCOL,

           :BDCODUF_COL_DOC, :BDTITELEICOL, :BDZONAELEICOL,
           :BDSECAOELEICOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDVENCCNHCOL, :BDCATCNHCOL,

           :BDCODCID_HIST, :BDCODPAIS, :BDNATURALIZADOCOL, :BDDATACHEBRASILCOL,

           :BDCODCIDNASCCONJ, :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL,

           :BDCORCOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL,:BDPESOCOL, :BDSINAISCOL,
           :BDDEFFISICOCOL, :BDTIPOSANGUECOL,

           :BDNROCONSPROCOL, :BDSIGLACONSPROCOL, :BDCODCCMPROCOL,

           :BDCODCLA, :BDGRUPOCLA,

           :BDCODMEN, :BDCODSINTRAB,

           :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL, :BDTIPOCTACOL, :BDMODOPAGTOCOL, :BDCARTAOSALCOL,

           :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL,

           :BDDATAOPCAOFGTSCOL, :BDCTAFGTSCOL, :BDCATEGORIACOL, :BDPERCFGTSCOL,
           :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL,

           :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
           :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL,

           :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDSALINICOL, :BDDIASPRAZO1COL,
           :BDDATAFIMPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO2COL, :BDDESCCONTSINCOL, :BDVINCEMPCOL,
           :BDALVARACOL, :BDSINDICALIZADOCOL, :BDREGIMEPARCIALCOL, :BDFICHAREGCOL, :BDLIVROREGCOL,
           :BDNROFOLHAREGCOL,

           :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL,
           :BDPERCINSALUBCOL , :BDINCIDINSALUBCOL, :BDPERCPERCULCOL, :BDINCIDPERICULCOL,
           :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL,
           :BDCALCADIANTACOL, :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL,
           :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL,

           :BDOBSCOL,

           :BDCODGPS, :BDDESCINSSDOIRCOL,

           :BDCODMAS, :BDSALBASECOL,
           :BDCODCBO, :BDACORDOINSSTERC, :BDPERCIRTERC, :BDPIRTERC, :BDCODQH,  --Sol. 14603 - Marcelo B. M. - 26/08/2016

           -- Rescisao
           :BDCODPRES,
           :BDDATARESCISAO,
           :BDDATAAVPREVIO,
           :BDDATAHOM,
           :BDDATAPAGRESCISAO,
           :BDSALDOFGTS,
           :BDCALCFGTSMESANT,
           :BDMAIORREMUNERACAO,
           :BDCHAVEINDENTIFICACAO,
           :BDDATAPAGGRFC,
           :BDREPOSICAOVAGA,
           :BDDISSIDIO,
           :BDDATADISSIDIO,
           :BDDESCANSOINDENIZADO,
           :BDCODMFGRESC,
           :BDCODSAQUERESC,
           :BDCODMRAISRESC,
           :BDCODMCAGRESC,
           :BDDESCPRES,
           :BDINIPRES,
           :BDJCPRES,
           :BDAVPREPRES,
           :BDGRRFPRES,
           :BDESTPRES,
           :BDINDFER13,
           :BDTERMCONTRPRES,
           :BDMULTAPRES,
           :BDDIASAVPREPRES,
           :BDDIASPAGPRES,
           :BDCODSEFMFGRESC,
           :BDDESCMFGRESC,
           :BDDESCSAQUERESC,
           :BDDESCMRAISRESC,
           :BDDESCMCAGEDRESC,

           --Transferencia
           :BDCODEMPDESTTRAN,
           :BDCODPTRAN,
           :BDCODCOLTRANS,
           :BDDATATRANS,
           :BDCODMCAGENTTRANS,
           :BDCODMCAGSAITRANS,
           :BDCODMFGTRANS,
           :BDCODMRAISTRANS,
           :BDDESCPTRANS,
           :BDCODSEFMFGTRANS,
           :BDDESCMFGTRANS,
           :BDDESCRAISTRANS,
           :BDDESCMCAGEDENTTRANS,
           :BDDESCMCAGEDSAITRANS,
           :BDCONTRCOL,
           :BDPERTRANSPINSSTER,
           :BDPERTRANSPIRTER
           DO

    SUSPEND;

   EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRH_SP_SERV_TERC_MANUAL) */
ALTER PROCEDURE VRH_SP_SERV_TERC_MANUAL(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRSERV INTEGER,
PRDATA DATE,
PRREF INTEGER,
PRDATAPAG DATE,
PRHORA VARCHAR(10),
PRVALOR NUMERIC(15,2))
 RETURNS(BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDHORASERV TIME,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL DM_LOGRADOURO,
BDENDCOL DM_BDENDERECO,
BDNUMCOL VARCHAR(10),
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODCBO INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255),
BDCONTRCOL INTEGER,
BDPERTRANSPINSSTER NUMERIC(15,6),
BDPERTRANSPIRTER NUMERIC(15,6))
 AS
DECLARE VARIABLE WCAM VARCHAR(20000);
DECLARE VARIABLE WWHE VARCHAR(10000);
DECLARE VARIABLE WV VARCHAR(30);
DECLARE VARIABLE WI VARCHAR(3);
DECLARE VARIABLE WD VARCHAR(30);
DECLARE VARIABLE WB VARCHAR(30);
DECLARE VARIABLE WN VARCHAR(30);
DECLARE VARIABLE WDATA VARCHAR(10);
DECLARE VARIABLE WTABELA VARCHAR(300);
DECLARE VARIABLE WAPELIDO VARCHAR(300);
DECLARE VARIABLE WJOINREF VARCHAR(3200);
BEGIN
   -- Seta a competencia atual.
   -- Algumas Views utilizam essas variaveis de contexto para filtrar e agrupar tabelas.
   wdata = CAST(prref AS VARCHAR(6));
   wdata = SUBSTRING(wdata FROM 5 FOR 2)||'-01-'||SUBSTRING(wdata FROM 1 FOR 4);
   EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wdata AS DATE), PRDATA);

   wv = ', CAST(NULL AS varchar(1))';
   wi = ', 0';
   wd = ', CAST(NULL AS DATE)';
   wb = ', CAST(NULL AS BLOB)';
   wn = ', CAST(NULL AS NUMERIC(15,6))';

   IF (PRHORA IS NULL) THEN
      PRHORA = 'null';

   wcam = 'select first 1 ' ||prserv||' BDCODSERV, cast('||''''||PRDATA||''''||' as date) BDDATASERV, '||''''||PRDATAPAG||''''||' BDDATAPAGSERV, '||
                              ''''||prhora||''''||' BDHORASERV, '||
                              prcodemp||' BDCODEMP, '||prcodcol||'BDCODTER ';

   -- CAMPOS
   wcam = wcam||wi||', COLCON.BDCODCID'||wi||wi||
                   ', COLCON.BDCODCIDNASCTER'||wi||', COLCON.BDNOMTER, COLCON.BDLOGRTER, COLCON.BDENDTER '||
                   ', COLCON.BDNUMTER, COLCON.BDCOMPLTER, COLCON.BDBAITER, COLCON.BDCEPTER, COLCON.BDDDDTER '||
                   ', COLCON.BDFONETER, COLCON.BDCELTER, COLCON.BDEMAILTER, COLCON.BDSEXOTER '||
                   ', COLCON.BDDATANASCTER, COLCON.BDDATACADTER, TTERCREF.BDGRAUINSTTER, TTERCREF.BDESTCIVTER '||
                   wd||wd;

   wcam = wcam||', COLCON_DOC.bdrgter, COLCON_DOC.BDORGEMIRGTER, COLCON_DOC.BDDATAEMIRGTER '||
                   ', COLCON_DOC.BDCPFTER, COLCON_DOC.BDRESERVISTATER, COLCON_DOC.BDPISTER'||wd;

   wcam = wcam||wi||wv||
                   wi||wi||wi||wi||
                   wv||wd||wv||wd||
                   wv;

   wcam = wcam||wi||wi||wv||wd;
   wcam = wcam||wi||wv||wv||wv||wd;
   wcam = wcam||wi||wi||wi||wn||wn||wv||wi||wi;
   wcam = wcam||', COLCON_DOC.BDNROCONSPROTER, COLCON_DOC.BDSIGLACONSPROTER, COLCON_DOC.BDCODCCMPROTER';
   wcam = wcam||', COLCON_VINC.BDCODCLA, CLASSE.BDGRUPOCLA';

   /*SINDICATO terceiro nao possui*/
   wcam = wcam||wi||wi;

   wcam = wcam||', COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPTER, COLCON_BANCO.BDDIGCTADEPTER '||
                   ', COLCON_BANCO.BDTIPOCTATER, COLCON_BANCO.BDMODOPAGTOTER, COLCON_BANCO.BDCARTAOSALTER';

   wcam = wcam||wi||', TTERCREF.BDNRODEPIRTER'||wn||wn||wn;

   /*Terceiro nao tem dados de fgts apenas de gps*/
   wcam = wcam||wd||wv||', COLCON_FGTSGPS.BDCATEGORIATER '||wn||
                   ', COLCON_FGTSGPS.BDOCORRENCIATER '||
                   ', COLCON_FGTSGPS.BDPERCRATTER'||wn;

      wcam = wcam||', COLCON_MVINC.BDBASEINSSNTER, COLCON_MVINC.BDVALORINSSNTER, COLCON_MVINC.BDBASEIRRFNTER '||
                   ', COLCON_MVINC.BDVALORIRRFNTER'||wn||wn||
                   wn||wn;

      wcam = wcam||wi||wi||wd||wn||wi||wd||wi||wd||wv||wi||wv||wv||wv||wv||wv||wi;

      wcam = wcam||wi||wn||wn||wn||wn||wi||wn||wi||wn||wi||wi||wv||wv||wv||wv||wv||wv||wv||wv||wv;

      wcam = wcam||wb;

      wcam = wcam||wi||wv;

      wcam = wcam||wi||', '||prvalor||' bdvalorserv'||', COLCON_VINC.BDCODCBO'||wi;


   /* Tabela de Rescisao nao existe para terceiros*/
    wcam = wcam||wi||wd||wd||wd||wd||
                 wn||wv||wn||wv||
                 wd||wv||wv||wd||wv;

    /* Motivos de rescisao nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||wi||
                 wv||wi||wi||wv||wv||wv||
                 wv||wi||wi||
                 wv||wv||
                 wv||
                 wv||
                 wv;


   /* Tabela de Transferencias nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wd;

    /* Motivos de transferencia nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||
                 wv||wv||
                 wv||
                 wv||
                 wv;

   wcam = wcam||', 2';

   /*Terceiro nao tem dados de fgts apenas de gps*/
      wcam = wcam||', COLCON_FGTSGPS.BDPERTRANSPINSSTER , COLCON_FGTSGPS.BDPERTRANSPIRTER ';

   -- TABELAS
   wtabela = 'vrh_base_tterc_ref';
   WAPELIDO = 'TTERCREF.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' from vrh_base_tterc COLCON ';
--   wcam = wcam||' left outer join vrh_base_tterc COLCON on (COLCON.bdcodter = TSERV.bdcodter) ';
   wcam = wcam||' left outer join VRH_BASE_TTERC_REF TTERCREF on (TTERCREF.bdcodter = COLCON.bdcodter'||wjoinref||') ';

   wcam = wcam||' left outer join vw_VRH_BASE_TTERC_DOC COLCON_DOC on (COLCON_DOC.bdcodter = COLCON.bdcodter) ';

   wtabela = 'VRH_BASE_TTERC_VINC';
   WAPELIDO = 'COLCON_VINC.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
               ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' left outer join VRH_BASE_TTERC_VINC COLCON_VINC '||
                    'on (COLCON_VINC.BDCODTER = COLCON.bdcodter'||wjoinref||') ';

   -- Grupo da Classe
   wcam = wcam||' left outer join VRH_BASE_TCLASSE CLASSE '||
                       'on (CLASSE.BDCODCLA = COLCON_VINC.BDCODCLA) ';

   wtabela = 'VRHF_BASE_TTERC_BANCO';
   WAPELIDO = 'COLCON_BANCO.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
               ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' left outer join VRHF_BASE_TTERC_BANCO '||
                       'COLCON_BANCO on (COLCON_BANCO.BDCODter = COLCON.bdcodter'||wjoinref||') ';

   wtabela = 'VRHF_BASE_TTERC_FGTSGPS';
   WAPELIDO = 'COLCON_FGTSGPS.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
               ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' left outer join VRHF_BASE_TTERC_FGTSGPS '||
                       'COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODter = COLCON.bdcodter'||wjoinref||') ';

   wtabela = 'VRHF_BASE_TTERC_MVINC';
   WAPELIDO = 'COLCON_MVINC.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
               ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' left outer join VRHF_BASE_TTERC_MVINC '||
                       'COLCON_MVINC on (COLCON_MVINC.BDCODTER = COLCON.BDCODTER'||wjoinref||') ';

   IF (:prCODCOL IS NOT NULL) THEN
      BEGIN
        wwhe = ' COLCON.BDCODTER = '||prcodcol;

      END

   IF ((wwhe <> '') AND (:wwhe IS NOT NULL)) THEN
      wwhe = ' where '||wwhe;
      
   wcam = wcam||wwhe;

   FOR EXECUTE STATEMENT wcam
      INTO :BDCODSERV, BDDATASERV, BDDATAPAGSERV, BDHORASERV,
            BDCODEMP,
           -- VRH_EMP_TCOLCON
           :BDCODCOL, :BDCODMCAG, :BDCODCID, :BDCODCSEG, :BDREFCSEG,
           :BDCODCIDNASC, :BDCODUF, :BDNOMCOL, :BDLOGRCOL, :BDENDCOL,
           :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL, :BDDDDCOL,
           :BDFONECOL, :BDCELCOL, :BDEMAILCOL, :BDSEXOCOL,
           :BDDATANASCCOL, :BDDATACADCOL, :BDGRAUINSTCOL, :BDESTCIVCOL,
           :BDDATAADMCOL, :BDDATAADICCOL,

           :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDCPFCOL,
           :BDRESERVISTACOL, :BDPISCOL, :BDDATAEMIPISCOL,

           :BDCODUF_COL_DOC, :BDTITELEICOL, :BDZONAELEICOL,
           :BDSECAOELEICOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDVENCCNHCOL, :BDCATCNHCOL,

           :BDCODCID_HIST, :BDCODPAIS, :BDNATURALIZADOCOL, :BDDATACHEBRASILCOL,

           :BDCODCIDNASCCONJ, :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL,

           :BDCORCOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL,:BDPESOCOL, :BDSINAISCOL,
           :BDDEFFISICOCOL, :BDTIPOSANGUECOL,

           :BDNROCONSPROCOL, :BDSIGLACONSPROCOL, :BDCODCCMPROCOL,

           :BDCODCLA, :BDGRUPOCLA,

           :BDCODMEN, :BDCODSINTRAB,

           :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL, :BDTIPOCTACOL, :BDMODOPAGTOCOL, :BDCARTAOSALCOL,

           :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL,

           :BDDATAOPCAOFGTSCOL, :BDCTAFGTSCOL, :BDCATEGORIACOL, :BDPERCFGTSCOL,
           :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL,

           :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
           :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL,

           :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDSALINICOL, :BDDIASPRAZO1COL,
           :BDDATAFIMPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO2COL, :BDDESCCONTSINCOL, :BDVINCEMPCOL,
           :BDALVARACOL, :BDSINDICALIZADOCOL, :BDREGIMEPARCIALCOL, :BDFICHAREGCOL, :BDLIVROREGCOL,
           :BDNROFOLHAREGCOL,

           :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL,
           :BDPERCINSALUBCOL , :BDINCIDINSALUBCOL, :BDPERCPERCULCOL, :BDINCIDPERICULCOL,
           :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL,
           :BDCALCADIANTACOL, :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL,
           :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL,

           :BDOBSCOL,

           :BDCODGPS, :BDDESCINSSDOIRCOL,

           :BDCODMAS, :BDSALBASECOL,
           :BDCODCBO, :BDCODQH,

           -- Rescisao
           :BDCODPRES,
           :BDDATARESCISAO,
           :BDDATAAVPREVIO,
           :BDDATAHOM,
           :BDDATAPAGRESCISAO,
           :BDSALDOFGTS,
           :BDCALCFGTSMESANT,
           :BDMAIORREMUNERACAO,
           :BDCHAVEINDENTIFICACAO,
           :BDDATAPAGGRFC,
           :BDREPOSICAOVAGA,
           :BDDISSIDIO,
           :BDDATADISSIDIO,
           :BDDESCANSOINDENIZADO,
           :BDCODMFGRESC,
           :BDCODSAQUERESC,
           :BDCODMRAISRESC,
           :BDCODMCAGRESC,
           :BDDESCPRES,
           :BDINIPRES,
           :BDJCPRES,
           :BDAVPREPRES,
           :BDGRRFPRES,
           :BDESTPRES,
           :BDINDFER13,
           :BDTERMCONTRPRES,
           :BDMULTAPRES,
           :BDDIASAVPREPRES,
           :BDDIASPAGPRES,
           :BDCODSEFMFGRESC,
           :BDDESCMFGRESC,
           :BDDESCSAQUERESC,
           :BDDESCMRAISRESC,
           :BDDESCMCAGEDRESC,

           --Transferencia
           :BDCODEMPDESTTRAN,
           :BDCODPTRAN,
           :BDCODCOLTRANS,
           :BDDATATRANS,
           :BDCODMCAGENTTRANS,
           :BDCODMCAGSAITRANS,
           :BDCODMFGTRANS,
           :BDCODMRAISTRANS,
           :BDDESCPTRANS,
           :BDCODSEFMFGTRANS,
           :BDDESCMFGTRANS,
           :BDDESCRAISTRANS,
           :BDDESCMCAGEDENTTRANS,
           :BDDESCMCAGEDSAITRANS,
           :BDCONTRCOL,
           :BDPERTRANSPINSSTER,
           :BDPERTRANSPIRTER
           DO

    SUSPEND;

   EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_ARREDONDAMENTOS) */
ALTER PROCEDURE VRHF_SP_ARREDONDAMENTOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFARRE INTEGER,
BDVALARRE NUMERIC(15,6))
 AS
DECLARE VARIABLE WREF VARCHAR(50);
DECLARE VARIABLE WTABLE VARCHAR(255);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(25000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FOL.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, '||
                'COL.BDNOMCOL, ';

  /* Tipos de calculo:
     -----------------
     0 - Todos; (nAo pode ser todos)
     1 - Folha normal;
     2 - Adiantamento salarial;
     3 - Adiantamento de 13o. salario;
     4 - 13o. salario;
     5 - Complemento de 13o. salario;
     6 - Ferias;
     7 - PLR;
     8 - Folha complementar;
     9 - Rescisao. (folha normal)
  */

  IF (prtipocalculo = 2) THEN
     BEGIN
       wsql = wsql||'cast((substring((cast(FOL.BDDATAAD as VARCHAR(10))) from 1 for 4)||substring((cast(FOL.BDDATAAD as VARCHAR(10))) from 6 for 2)) as INTEGER) BDREF, '||
                    'FOL.BDVALVAD ';
       wTable = 'VRHF_EMP_TVERBAAD';
       wref = 'FOL.BDDATAAD';
     END
  ELSE
  IF (prtipocalculo = 3) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFA13, '||
                    'FOL.BDVALVA13 ';
       wTable = 'VRHF_EMP_TVERBAA13';
       wref = 'FOL.BDREFA13';
     END
  ELSE
  IF (prtipocalculo = 4) THEN
     BEGIN
       wsql = wsql||'FOL.BDREF13, '||
                    'FOL.BDVALV13 ';
       wTable = 'VRHF_EMP_TVERBA13';
       wref = 'FOL.BDREF13';
     END
  ELSE
  IF (prtipocalculo = 5) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFC13, '||
                    'FOL.BDVALVC13 ';
       wTable = 'VRHF_EMP_TVERBAC13';
       wref = 'FOL.BDREFC13';
     END
  ELSE
  IF (prtipocalculo = 6) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFFE, '||
                    'FOL.BDVALVRFE ';
       wTable = 'VRHF_EMP_TVERBAFE';
       wref = 'FOL.BDREFFE';
     END
  ELSE
  IF (prtipocalculo = 8) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFCOMP, '||
                    'FOL.BDVALVFC ';
       wTable = 'VRHF_EMP_TVERBAFC';
       wref = 'FOL.BDREFCOMP';
     END
  ELSE
     BEGIN
       wsql = wsql||'FOL.BDREFFN, '||
                    'FOL.BDVALVFN ';
       wTable = 'VWRH_UNION_FN_FT_MES';
       wref = 'FOL.BDREFFN';
     END

  wsql = wsql||
         'from '||wtable||' FOL '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
         'on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) '||
         'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
         'on (EMP.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join VW_VRHF_EMPRESAS_REF_ATUAL ARRED '||
         'on (ARRED.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join vrh_base_tverbas VERBAS '||
         'on (VERBAS.BDCODVER = FOL.BDCODVER) ';

  wwhere = 'where ((ARRED.bdtipoarremp < 2 and VERBAS.BDCLAVER like '''||'9.001.0%'||''') or '||
                  '(ARRED.bdtipoarremp >= 2 and VERBAS.BDCLAVER like '''||'9.001.1%'||''')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wwhere||' order by FOL.BDCODEMP, FOL.BDCODCOL, '||wref||' DESC ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFARRE,
    :BDVALARRE
  DO

  SUSPEND;
END
^

/* Alter (VRHF_SP_CALC_AUTONOMO) */
ALTER PROCEDURE VRHF_SP_CALC_AUTONOMO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRSERVICO INTEGER,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = NULL,
PRCODTPCC VARCHAR(10000) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(5000),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBINSSCALC NUMERIC(15,6),
BDBIRCALC NUMERIC(15,6),
BDDATAPGTO DATE)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
/*01*/  wsql = wsql||'FN.BDCODEMP, '||
/*02*/               'FN.BDCODTER, '||
/*03*/               'FN.BDCODVER, '||
/*04*/               'FN.BDCODSERV, '||
/*05*/               'FN.BDREFERENCIA, '||
/*06*/               'FN.BDREFAUXILIAR, '||
/*07*/               'FN.BDVALOR, '||
/*08*/               'FN.BDIGNFORREF, '||
/*09*/               'FN.BDIGNFORVAL, '||
/*10*/               'RVA.BDTIPOCODVER, '||
/*10*/               'RVA.BDORDEMTIPOCODVER, '||
/*11*/               'RVA.BDINSSVER, '||
/*12*/               'RVA.BDFGTSVER, '||
/*13*/               'RVA.BDIRVER, '||
/*14*/               'RVA.BDTIPOREFVER, '||
/*15*/               'RVA.BDBASESFVER, '||
/*16*/               'RVA.BDPISVER, '||
/*17*/               'RVA.BDBASEHEVER, '||
/*18*/               'RVA.BDBASEMAIORVER, '||
/*19*/               'RVA.BDRAISVER, '||
/*20*/               'RVA.BDBASEGPSVER, '||
/*21*/               'RVA.BDMENORESVER, '||
/*22*/               'RVA.BDPROPVER, '||
/*23*/               'RVA.BDBASEVTVER, '||
/*24*/               'RVA.BDREEMBGPSVER, '||
/*25*/               'RVA.BDHEVER, '||
/*26*/               'RVA.BDGRAVAFICHAHNVER, '||
/*27*/               'RVA.BDCCPRINCIPALVER, '||
/*28*/               'RVA.BDFORMREFAUXVER, '||
/*29*/               'RVA.BDFORMREFVER, '||
/*30*/               'RVA.BDFORMVALVER, '||
/*31*/               'RVA.BDBASEDSRHEVER, '||
/*32*/               'RVA.BDBASEDSRRVVER, '||
/*33*/               'RVA.BDDEDFORMREFAUXVER, '||
/*34*/               'RVA.BDDEDFORMREFVER, '||
/*35*/               'RVA.BDDEDFORMVALVER, '||
/*36*/               'VER.BDDESCVER, '||
/*37*/               'VER.BDDESCREDVER, '||
/*38*/               'VER.BDCLAVER, '||
/*39*/               'VER.BDORDEMVER, '||
/*40*/               'EMPREF.BDREFHOREMP, '||
/*41*/               'SERV.BDDATABAIXA,'||/*'FOLN.BDDATABAIXAFN, '|| /*CRIAR CAMPO TABELA*/
/*42*/               '0.0, '|| /*FOLN.BDBFGTSFN*/
/*43*/               '0.0, '|| /*FOLN.BDFGTSFN*/
/*44*/               '0.0, '|| /*FOLN.BDFGTSCSFN*/
/*45*/               '0.0, '|| /*FOLN.BDBFGTS13FN*/
/*46*/               '0.0, '|| /*FOLN.BDFGTS13FN*/
/*47*/               '0.0, '|| /*FOLN.BDFGTS13CSFN*/
/*48*/               '0.0, '|| /*FOLN.BDMAIORREMFN*/
/*49*/               'FOLN.BDBASEINSS, '||
/*50*/               'FOLN.BDFAIXAINSS, '||
/*51*/               'FOLN.BDVALORINSS, '||
/*52*/               'FOLN.BDBASEIR, '||
/*53*/               'FOLN.BDFAIXAIR, '||
/*54*/               'FOLN.BDVALORIR, '||
/*55*/               '0.0, '|| /*FOLN.BDBINSS13FN*/
/*56*/               '0.0, '|| /*FOLN.BDALIQINSS13FN*/
/*57*/               '0.0, '|| /*FOLN.BDINSS13FN*/
/*58*/               '0.0, '|| /*FOLN.BDBIRRF13FN*/
/*59*/               '0.0, '|| /*FOLN.BDALIQIRRF13FN*/
/*60*/               '0.0, '|| /*FOLN.BDIRRF13FN*/
/*61*/               '0.0, '|| /*FOLN.BDBSALFAMFN*/
/*62*/               '0.0, '|| /*FOLN.BDSALFAMFN*/
/*63*/               '0.0, '|| /*FOLN.BDBRAISFN*/
/*64*/               'SERV.BDVALORSERV, '||
/*65*/               'FOLN.BDVALORDEP, '||
/*66*/               'VER.BDAPEVER,'||
/*67*/               '0.0, '|| /*FOLN.BDBINSSFEFOLFN*/
/*68*/               '0.0, '|| /*FOLN.BDINSSFEFOLFN*/
/*69*/               '0.0, '|| /*FOLN.BDALIQINSSFEFOLFN*/
/*70*/               'FOLN.BDCREDITOSERV, '||
/*71*/               'FOLN.BDDEBITOSERV, '||
                     'FOLN.BDBASEIRCALC, '||
                     'FOLN.BDBINSSCALC, '||
                     'SERV.BDDATAPAGSERV ';

  wsql = wsql||'from VRHF_BASE_ITEMS_CALCTERC FN '|| /*OK*/
               ' join VW_VERBAS_REF_ATUAL RVA '|| /*OK*/
                 'on (RVA.BDCODVER = FN.BDCODVER) '||
               ' join VRH_BASE_TSERVTERC SERV '||
                 'on (SERV.BDCODEMP = FN.BDCODEMP and SERV.BDCODTER = FN.BDCODTER and SERV.BDCODSERV = FN.BDCODSERV) '||
               ' join VRH_BASE_TVERBAS VER '|| /*OK*/
                 'on (VER.BDCODVER = FN.BDCODVER) '||
               ' join VW_VRHF_BASE_TEMPCALC EMPREF '|| /*OK*/
                 'on (EMPREF.BDCODEMP = FN.BDCODEMP) '||
               ' join VRHF_BASE_CALC_TERC FOLN '|| /*OK*/
                 'on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODTER = FN.BDCODTER and FOLN.BDCODSERV = FN.BDCODSERV) ';

  IF (prpuxafiliais = 1) THEN
     BEGIN
       wsql = wsql||' join tempresas emp on (fn.bdcodemp = emp.bdcodemp) ';

       prcodemp = UPPER(prcodemp);

       IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'FN.BDCODEMP','EMP.BDCODMATRIZ') INTO wwhere;
            prcodemp = '('||prcodemp||' or (('||wwhere||') and (emp.bdcodemp in ('||prfiliais||'))))';
          END
       ELSE
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'FN.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
          END
     END

  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wwhere||PRCODEMP;

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||PRCODCOL;
     END

  IF (prservico IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'FN.BDCODSERV = '||prservico;
     END

  IF (prreferencia IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(select bdaaaamm from aaaamm(SERV.bddataserv) ) = '||prreferencia;
     END

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       wwhere = wwhere||prcodtpcc;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||' order by RVA.BDTIPOCODVER, FN.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
/*01*/    :BDCODEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDCODVER,
/*04*/    :BDREFFN, /* :bdcodserv, */
/*05*/    :BDREFV,
/*06*/    :BDREFAUXV,
/*07*/    :BDVALV,
/*08*/    :BDIGNREFV,
/*09*/    :BDIGNVALV,
/*10*/    :BDTIPOCODVER,
          :BDORDEMTIPOCODVER,
/*11*/    :BDINSSVER,
/*12*/    :BDFGTSVER,
/*13*/    :BDIRVER,
/*14*/    :BDTIPOREFVER,
/*15*/    :BDBASESFVER,
/*16*/    :BDPISVER,
/*17*/    :BDBASEHEVER,
/*18*/    :BDBASEMAIORVER,
/*19*/    :BDRAISVER,
/*20*/    :BDBASEGPSVER,
/*21*/    :BDMENORESVER,
/*22*/    :BDPROPVER,
/*23*/    :BDBASEVTVER,
/*24*/    :BDREEMBGPSVER,
/*25*/    :BDHEVER,
/*26*/    :BDGRAVAFICHAHNVER,
/*27*/    :BDCCPRINCIPALVER,
/*28*/    :BDFORMREFAUXVER,
/*29*/    :BDFORMREFVER,
/*30*/    :BDFORMVALVER,
/*31*/    :BDBASEDSRHEVER,
/*32*/    :BDBASEDSRRVVER,
/*33*/    :BDDEDFORMREFAUXVER,
/*34*/    :BDDEDFORMREFVER,
/*35*/    :BDDEDFORMVALVER,
/*36*/    :BDDESCVER,
/*37*/    :BDDESCREDVER,
/*38*/    :BDCLAVER,
/*39*/    :BDORDEMVER,
/*40*/    :BDREFHOREMP,
/*41*/    :BDDATABAIXA,
/*42*/    :BDBFGTS,
/*43*/    :BDFGTS,
/*44*/    :BDFGTSCS,
/*45*/    :BDBFGTS13,
/*46*/    :BDFGTS13,
/*47*/    :BDFGTS13CS,
/*48*/    :BDMAIORREM,
/*49*/    :BDBINSS,
/*50*/    :BDALIQINSS,
/*51*/    :BDINSS,
/*52*/    :BDBIRRF,
/*53*/    :BDALIQIRRF,
/*54*/    :BDIRRF,
/*55*/    :BDBINSS13,
/*56*/    :BDALIQINSS13,
/*57*/    :BDINSS13,
/*58*/    :BDBIRRF13,
/*59*/    :BDALIQIRRF13,
/*60*/    :BDIRRF13,
/*61*/    :BDBSALFAM,
/*62*/    :BDSALFAM,
/*63*/    :BDBRAIS,
/*64*/    :BDSALBASE,
/*65*/    :BDDEP,
/*66*/    :BDDETALHE,
/*67*/    :BDBINSSFEFOL,
/*68*/    :BDINSSFEFOL,
/*69*/    :BDALIQINSSFEFOL,
/*70*/    :bdcredito,
/*71*/    :bddebito,
          :bdbircalc,
          :bdbinsscalc,
          :bddatapgto
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_CALC_FOLHANORMAL) */
ALTER PROCEDURE VRHF_SP_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = null,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(800),
BDFORMREFVER VARCHAR(800),
BDFORMVALVER VARCHAR(800),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFEFOL NUMERIC(15,6),
BDFGTSFEFOL NUMERIC(15,6),
BDDATAPGTO DATE,
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDCODCONTTI INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WPARAUX varchar(32700);
declare variable WORDEM varchar(300);
BEGIN

  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE IF (prrefini IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'COLCON.BDCODEMP, '||
               'COLCON.BDCODCOL, '||
               'COLCON.BDCODVER, '||
               'COLCON.BDREFFN, '||
               'COLCON.BDREFVFN, '||
               'COLCON.BDREFAUXVFN, '||
               'COLCON.BDVALVFN, '||
                'case when (RVA.BDTIPOCODVER in (0, 2)) then COLCON.BDVALVFN '||
                     'else 0 end BDPROVENTO, '||
                'case when (RVA.BDTIPOCODVER in (0, 2)) then 0 '||
                     'else COLCON.BDVALVFN end BDDESCONTO, '||
               'COLCON.BDIGNREFVFN, '||
               'COLCON.BDIGNVALVFN, '||
               'RVA.BDTIPOCODVER, '||
               'RVA.BDORDEMTIPOCODVER, '||
               'RVA.BDINSSVER, '||
               'RVA.BDFGTSVER, '||
               'RVA.BDIRVER, '||
               'RVA.BDTIPOREFVER, '||
               'RVA.BDBASESFVER, '||
               'RVA.BDPISVER, '||
               'RVA.BDBASEHEVER, '||
               'RVA.BDBASEMAIORVER, '||
               'RVA.BDRAISVER, '||
               'RVA.BDBASEGPSVER, '||
               'RVA.BDMENORESVER, '||
               'RVA.BDPROPVER, '||
               'RVA.BDBASEVTVER, '||
               'RVA.BDREEMBGPSVER, '||
               'RVA.BDHEVER, '||
               'RVA.BDGRAVAFICHAHNVER, '||
               'RVA.BDCCPRINCIPALVER, '||
               'RVA.BDFORMREFAUXVER, '||
               'RVA.BDFORMREFVER, '||
               'RVA.BDFORMVALVER, '||
               'RVA.BDBASEDSRHEVER, '||
               'RVA.BDBASEDSRRVVER, '||
               'RVA.BDDEDFORMREFAUXVER, '||
               'RVA.BDDEDFORMREFVER, '||
               'RVA.BDDEDFORMVALVER, '||
               'RVA.BDDESCVER, '||
               'RVA.BDDESCREDVER, '||
               'RVA.BDCLAVER, '||
               'RVA.BDORDEMVER, '||
               'EMPREF.BDREFHOREMP, '||
               'FOLN.BDDATABAIXAFN, '||
               'FOLN.BDBFGTSFN, '||
               'FOLN.BDFGTSFN, '||
               'FOLN.BDFGTSCSFN, '||
               'FOLN.BDBFGTS13FN, '||
               'FOLN.BDFGTS13FN, '||
               'FOLN.BDFGTS13CSFN, '||
               'FOLN.BDMAIORREMFN, '||
               'FOLN.BDBINSSFN, '||
               'FOLN.BDALIQINSSFN, '||
               'FOLN.BDINSSFN, '||
               'FOLN.BDBIRRFFN, '||
               'FOLN.BDALIQIRRFFN, '||
               'FOLN.BDIRRFFN, '||
               'FOLN.BDBINSS13FN, '||
               'FOLN.BDALIQINSS13FN, '||
               'FOLN.BDINSS13FN, '||
               'FOLN.BDBIRRF13FN, '||
               'FOLN.BDALIQIRRF13FN, '||
               'FOLN.BDIRRF13FN, '||
               'FOLN.BDBSALFAMFN, '||
               'FOLN.BDSALFAMFN, '||
               'FOLN.BDBRAISFN, '||
               'FOLN.BDSALBASEFN, '||
               'FOLN.BDDEPFN, '||
               '''Compet?ncia: '''||'||substring(COLCON.BDREFFN from 5 for 2)||'||'''/'''||'||substring(COLCON.BDREFFN from 1 for 4) BDDETALHE, '||
               'FOLN.BDBINSSFEFOLFN, '||
               'FOLN.BDINSSFEFOLFN, '||
               'FOLN.BDALIQINSSFEFOLFN, '||
               'FOLN.BDCREDITOFN, '||
               'FOLN.BDDEBITOFN, '||
               'FOLN.BDBFGTSFEFN, '||
               'FOLN.BDFGTSFEFN, '||
               'COLCON.BDCODCENTRO, '||
               'COLCON.BDCODTPCC, '||
               'FOLN.BDDATAPGTO, '||
               'FOLN.BDBINSSAPFN, '||
               'FOLN.BDINSSAPFN, '||
               'FOLN.BDBINSS13APFN, '||
               'FOLN.BDINSS13APFN, '||
               'COLCON.BDCODCONTTI ';

  wparaux = '';
  IF (prcodemp IS NOT NULL) THEN
     wparaux = wparaux||''''||PRCODEMP||''''||',';
  ELSE
     wparaux = wparaux||'null'||',';

  IF (prcodcol IS NOT NULL) THEN
     wparaux = wparaux||''''||prcodcol||''''||',';
  ELSE
     wparaux = wparaux||'null'||',';

  IF (prrefini IS NOT NULL) THEN
     wparaux = wparaux||prrefini||',';
  ELSE
     wparaux = wparaux||'null'||',';

  IF (prreffim IS NOT NULL) THEN
     wparaux = wparaux||prreffim||',';
  ELSE
     wparaux = wparaux||'null'||',';

  -- wparaux = wparaux||'null'||',';

  wparaux = wparaux||pragrupatomador ;

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     wparaux = wparaux||', '''||prcodtpcc||'''';
  ELSE
     wparaux = wparaux||', null';

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  wparaux = wparaux||' ,'||prpuxafiliais;

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     wparaux = wparaux||', '''||prfiliais||'''';
  ELSE
     wparaux = wparaux||', null';

  wordem = '';

  IF (pragrupatomador = 0) THEN
     wordem = ' ((FOLN.BDORDEM = COLCON.BDORDEM) or (foln.bdordem is null and colcon.bdordem is null))';
  ELSE
  IF (pragrupatomador = 2) THEN
     wordem = ' ((FOLN.BDCODTPCC = COLCON.BDCODTPCC) or ((FOLN.BDCODTPCC is null) and (COLCON.BDCODTPCC is null)))';
  ELSE IF ((pragrupatomador = 3) OR (pragrupatomador = 4))  THEN
     wordem = ' ((FOLN.BDCODTPCC = COLCON.BDCODTPCC) or ((FOLN.BDCODTPCC is null) and (COLCON.BDCODTPCC is null)))';


  wsql = wsql||'from VRHF_SP_TVERBAFN('||wparaux||') COLCON '||
               'join SP_VRH_VERBAS('||:prrefini||') RVA on (RVA.BDCODVER = COLCON.BDCODVER) '||
               ' join VRHF_SP_TFOLHA_NORMAL('||wparaux||') FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
               ' left outer join VW_VRHF_BASE_TEMPCALC EMPREF on (EMPREF.BDCODEMP = COLCON.BDCODEMP) ';

  wwhere = '';
  IF (wordem <> '') THEN
    wwhere = wwhere||wordem;


  /*wsql = wsql||'from VRHF_SP_TVERBAFN('||wparaux||') COLCON '||
               ' join VW_VERBAS_REF_ATUAL RVA '||
                 'on (RVA.BDCODVER = COLCON.BDCODVER) '||
               ' join VRH_BASE_TVERBAS VER '||
                 'on (VER.BDCODVER = COLCON.BDCODVER) '||
               ' join VW_VRHF_EMPRESAS_REF_ATUAL EMPREF '||
                 'on (EMPREF.BDCODEMP = COLCON.BDCODEMP) '||
               ' join VRHF_SP_TFOLHA_NORMAL('||wparaux||') FOLN '||
                 'on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN ' ||wordem|| ') ';*/

  IF ((prcodemp IS NOT NULL) AND (prpuxafiliais = 0)) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      wwhere = wwhere||PRCODEMP;
    END

  IF (prcodcol IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      wwhere = wwhere||PRCODCOL;
    END

--  if (prcodtpcc is not null) then
--     wwhere = wwhere||' and '||prcodtpcc;

  -- verficar se precisa aqui tambem ja que tem la em cima na  RHF_SP_TVERBAFN

/*
  if (prrefini is not null) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'COLCON.BDREFFN = '||prrefini;
     end
*/


  IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      wwhere = wwhere||'COLCON.BDREFFN >= '||prrefini||' and '||'COLCON.BDREFFN <= '||prreffim;
    END
  ELSE
     BEGIN
       IF (prrefini IS NOT NULL) THEN
         BEGIN
           IF (wwhere <> '') THEN
             wwhere = wwhere||' and ';
           wwhere = wwhere||'COLCON.BDREFFN = '||prrefini;
         END
       ELSE
          BEGIN
            IF (prreffim IS NOT NULL) THEN
              BEGIN
                IF (wwhere <> '') THEN
                  wwhere = wwhere||' and ';
                wwhere = wwhere||'COLCON.BDREFFN = '||prreffim;
              END
          END
     END

  IF (wwhere <> '') THEN
    wwhere  = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||' order by RVA.BDTIPOCODVER, COLCON.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDMENORESVER,
    :BDPROPVER,
    :BDBASEVTVER,
    :BDREEMBGPSVER,
    :BDHEVER,
    :BDGRAVAFICHAHNVER,
    :BDCCPRINCIPALVER,
    :BDFORMREFAUXVER,
    :BDFORMREFVER,
    :BDFORMVALVER,
    :BDBASEDSRHEVER,
    :BDBASEDSRRVVER,
    :BDDEDFORMREFAUXVER,
    :BDDEDFORMREFVER,
    :BDDEDFORMVALVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :bdcredito,
    :bddebito,
    :bdbfgtsfefol,
    :bdfgtsfefol,
    :bdcodcentro,
    :bdcodtpcc,
    :bddatapgto,
    :bdbinssapfn,
    :bdinssapfn,
    :bdbinss13apfn,
    :bdinss13apfn,
    :bdcodcontti
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_CALC_GPS) */
ALTER PROCEDURE VRHF_SP_CALC_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
DECLARE VARIABLE WSQLEMP VARCHAR(32000);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WTIPOEMISSAO INTEGER;
DECLARE VARIABLE WTIPOEMISSAOANT INTEGER;
DECLARE VARIABLE WWHEREEMP VARCHAR(10000);
DECLARE VARIABLE WSQLCALC VARCHAR(32000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32000);
DECLARE VARIABLE WMATRIZ INTEGER;
BEGIN
  /* prtipogps
     0 = normal
     1 = folha complementar
     2 = 13 sal
     3 = comp. 13 sal
     4 = pr?via de rescis?o
  */
  /* prtipoemissao
     0 = por cc
     1 = agrupado
  */
  /* prapenasgps
     0 = apenas gps
     1 = historicos compensacoes/nf/gps
  */
  /* PRPUXAFILIAIS
     0 = Nao
     1 = Sim
  */
  /*
    BDTIPOREG
    0 = GPS
    1 = nf
    2 = gps comp
    3 = compensacao
    4 = historico comp
    5 = historico nf
    6 = historico gps
    7 = registro acumulados
    8 = contabilizacao
  */
  /* Procedure Text */


--  pranomes = 201005;
  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

--  wsqlemp = 'select colcon.bdcodemp,coalesce(colcon.BDTIPOEMIGUIAS,1) xtipoguia,temp.bdcodmatriz from VW_VRHF_EMPRESAS_REF_ATUAL colcon ';
--  wsqlemp = wsqlemp||' join tempresas temp on (colcon.bdcodemp = temp.bdcodemp)';
  wsqlemp = 'select colcon.bdcodemp,coalesce(colcon.BDTIPOEMIGUIAS,1) xtipoguia,temp.bdcodmatriz from tempresas temp ';
  wsqlemp = wsqlemp||' left outer join VW_VRHF_BASE_TEMPPAR colcon on (colcon.bdcodemp = temp.bdcodemp)';
  IF (prcodemp IS NOT NULL) THEN
     wsqlemp = wsqlemp||' where '||prcodemp;

  wsqlemp = wsqlemp||' order by xtipoguia, colcon.bdcodemp';

  wwhereemp = '';
  wtipoemissaoant = -1;
  wmatriz = NULL;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  FOR EXECUTE STATEMENT wsqlemp
  INTO
    : wempatu,
    : wtipoemissao,
    : wmatriz
  DO
    BEGIN
      IF ((prpuxafiliais <> 1) OR (wmatriz IS NULL)) THEN
         BEGIN
              IF ((wtipoemissao IS NULL) OR (wtipoemissao < 0) ) THEN
                 wtipoemissao = 0;
              IF ((wtipoemissao = wtipoemissaoant) OR (wtipoemissaoant = -1)) THEN
                 BEGIN
                   wtipoemissaoant = wtipoemissao;
                   IF (CHAR_LENGTH(wwhereemp)>0) THEN
                      wwhereemp = wwhereemp||',';
                   wwhereemp = wwhereemp||CAST(wempatu AS VARCHAR(10));
                 END
              ELSE
                 BEGIN
                   wsqlcalc = 'select '||
                        'bdtiporeg, '||
                        'bdcodemp , '||
                        'bdcodcol,'||
                        'bdcodter,'||
                        'bdreffn , '||
                        'bdrefpag , '||
                        'bdcodcentro, '||
                        'bdcodtpcc , '||
                        'bdtotseg , '||
                        'bdtotbase , '||
                        'bdsegfun , '||
                        'bdbasefun , '||
                        'bdpercfun , '||
                        'bdvalfunemp , '||
                        'bdsegpro , '||
                        'bdbasepro , '||
                        'bdpercpro , '||
                        'bdvalproemp , '||
                        'bdsegaut , '||
                        'bdbaseaut , '||
                        'bdpercaut , '||
                        'bdvalautemp , '||
                        'bdsalfam , '||
                        'bdsalmaternidade , '||
                        'bdbaseratapo , '||
                        'bdvalorratapo , '||
                        'bdbasefpas , '||
                        'bdpercfpas , '||
                        'bdvalorfpas , '||
                        'bdpercrat , '||
                        'bdvalorrat , '||
                        'bdvalorbruto , '||
                        'bdvalorliquido , '||
                        'bdnfcoop , '||
                        'bdchave , '||
                        'bdvalcompensado , '||
                        'bdvalacompensar , '||
                        'bdvaloracumulado , '||
                        'bdvaloracumuladousado , '||
                        'bdvaloracuterceiros , '||
                        'bdvaloracuterceirosusado , '||
                        'bdcodempant , '||
                        'BDCHAVEDARFANT , '||
                        'bdcodimpant , '||
                        'bdcodperiodoant , '||
                        'bdordemant , '||
                        'bdreferenciaant , '||
                        'bdquotaant , '||
                        'bddescacumdet , '||
                        'bddescacum , '||
                        'bdvalorcampo6 , '||
                        'bdvalnotas , '||
                        'bddescnotas , '||
                        'bdtotdesccomp , '||
                        'bdtotvaloracumulado , '||
                        'bdtotvaloracumuladoterc , '||
                        'bdinicomp , '||
                        'bdfimcomp , '||
                        'bdtotcompensacao , '||
                        'bddescsalfam , '||
                        'bddescdedgps , '||
                        'bdvaloutentidade, '||
                        'bdsimplesgps, '||
                        'bdcodenqfed, '||
                        'bddescenqfed, '||
                        'BDVALFUNEMPFN, '||
                        'BDVALFUNEMPFC, '||
                        'BDVALFUNEMPFERFN, '||
                        'BDVALFUNEMPFERFC, '||
                        'BDVALFUNEMP13FN, '||
                        'BDVALFUNEMP13FC, '||
                        'BDVALFUNEMP13, '||
                        'BDVALFUNEMPC13, '||
                        'BDVALPROEMPFN, '||
                        'BDVALPROEMPFC, '||
                        'BDVALPROEMPFERFN, '||
                        'BDVALPROEMPFERFC, '||
                        'BDVALPROEMP13FN, '||
                        'BDVALPROEMP13FC, '||
                        'BDVALPROEMP13, '||
                        'BDVALPROEMPC13, '||
                        'BDVALAUTEMPFN, '||
                        'BDVALAUTEMPFC, '||
                        'BDVALAUTEMPFERFN, '||
                        'BDVALAUTEMPFERFC, '||
                        'BDVALAUTEMP13FN, '||
                        'BDVALAUTEMP13FC, '||
                        'BDVALAUTEMP13, '||
                        'BDVALAUTEMPC13, '||
                        'BDVALFPASEMPFN, '||
                        'BDVALFPASEMPFC, '||
                        'BDVALFPASEMPFERFN, '||
                        'BDVALFPASEMPFERFC, '||
                        'BDVALFPASEMP13FN, '||
                        'BDVALFPASEMP13FC, '||
                        'BDVALFPASEMP13, '||
                        'BDVALFPASEMPC13, '||
                        'BDVALRATEMPFN, '||
                        'BDVALRATEMPFC, '||
                        'BDVALRATEMPFERFN, '||
                        'BDVALRATEMPFERFC, '||
                        'BDVALRATEMP13FN, '||
                        'BDVALRATEMP13FC, '||
                        'BDVALRATEMP13, '||
                        'BDVALRATEMPC13, '||
                        'BDVALRATAPOEMPFN, '||
                        'BDVALRATAPOEMPFC, '||
                        'BDVALRATAPOEMPFERFN, '||
                        'BDVALRATAPOEMPFERFC, '||
                        'BDVALRATAPOEMP13FN, '||
                        'BDVALRATAPOEMP13FC, '||
                        'BDVALRATAPOEMP13, '||
                        'BDVALRATAPOEMPC13, '||
                        'BDCHAVEDARF '||
                        'from vrhf_sp_gps(';
        
                   IF (prcodimp IS NULL) THEN
                      wparsqlcalc = 'null,';
                   ELSE
                      wparsqlcalc = prcodimp||',';
        
                   --prcodemp varchar(32000),
                   IF (prpuxafiliais = 1) THEN
                      WPARSQLCALC = wparsqlcalc||''''||'(colcon.bdcodemp in ('||wwhereemp||') or temp.bdcodmatriz in ('||wwhereemp||'))'||'''';
                   ELSE
                      WPARSQLCALC = wparsqlcalc||''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';
        
                   --prcodcol varchar(32000),
                   wparsqlcalc = wparsqlcalc||',';
                   IF (prcodcol IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                       wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
        
                   --prcodaut varchar(32000),
                   wparsqlcalc = wparsqlcalc||',';
                   IF (prcodaut IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                       wparsqlcalc = wparsqlcalc||''''||prcodaut||'''';
        
                   wparsqlcalc = wparsqlcalc||',';

                   --prtipocol integer,
                   IF (prtipocol IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||prtipocol;

                   wparsqlcalc = wparsqlcalc||',';

                   --pranomes integer,
                   IF (pranomes IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||pranomes;
        
                   wparsqlcalc = wparsqlcalc||',';
        
                   --pranomespag integer,
                   IF (pranomespag IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||pranomespag;
        
                   wparsqlcalc = wparsqlcalc||',';
        
                   --prtipoemissao integer,
                   /* na tabela
                      0 = centro custo
                      1 = agrupada
                   */
                   wparsqlcalc = wparsqlcalc||CAST(wtipoemissaoant AS VARCHAR(10));
                   wparsqlcalc = wparsqlcalc||',';
        
                   --prapenasgps integer,
                   IF (prapenasgps IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||prapenasgps;
                   wparsqlcalc = wparsqlcalc||',';
        
                   --prtipogps integer)
                   IF (prtipogps IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||prtipogps;
                   wparsqlcalc = wparsqlcalc||',';
        
                   -- puxa filiais
                   IF (prpuxafiliais IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||prpuxafiliais;
        
        
                   wsqlcalc = wsqlcalc||wparsqlcalc||')';
        
                   FOR EXECUTE STATEMENT wsqlcalc
                   INTO
                     :bdtiporeg,
                     :bdcodemp,
                     :bdcodcol, 
                     :bdcodter,
                     :bdreffn,
                     :bdrefpag,
                     :bdcodcentro,
                     :bdcodtpcc,
                     :bdtotseg,
                     :bdtotbase,
                     :bdsegfun,
                     :bdbasefun,
                     :bdpercfun,
                     :bdvalfunemp,
                     :bdsegpro,
                     :bdbasepro,
                     :bdpercpro,
                     :bdvalproemp,
                     :bdsegaut,
                     :bdbaseaut,
                     :bdpercaut,
                     :bdvalautemp,
                     :bdsalfam,
                     :bdsalmaternidade,
                     :bdbaseratapo,
                     :bdvalorratapo,
                     :bdbasefpas,
                     :bdpercfpas,
                     :bdvalorfpas,
                     :bdpercrat,
                     :bdvalorrat,
                     :bdvalorbruto,
                     :bdvalorliquido,
                     :bdnfcoop,
                     :bdchave,
                     :bdvalcompensado,
                     :bdvalacompensar,
                     :bdvaloracumulado,
                     :bdvaloracumuladousado ,
                     :bdvaloracumuterceiro,
                     :bdvaloracuterceirosusado ,
                     :bdcodempant ,
                     :BDCHAVEDARFANT,
                     :bdcodimpant ,
                     :bdcodperiodoant,
                     :bdordemant ,
                     :bdreferenciaant ,
                     :bdquotaant,
                     :bddescacumdet,
                     :bddescacu,
                     :bdvalorcampo6,
                     :BDVALORNOTAS,
                     :bddescnotas,
                     :bdtotdesccomp,
                     :bdtotvaloracumulado,
                     :bdtotvaloracumuladoTerc,
                     :bdinicomp,
                     :bdfimcomp,
                     :bdtotcompensacao,
                     :bddescsalfam,
                     :bddescdedgps,
                     :BDVALOUTENTIDADES,
                     :bdsimplesgps,
                     :bdcodenqfed,
                     :bddescenqfed,
                     :BDVALFUNEMPFN,
                     :BDVALFUNEMPFC,
                     :BDVALFUNEMPFERFN,
                     :BDVALFUNEMPFERFC,
                     :BDVALFUNEMP13FN,
                     :BDVALFUNEMP13FC,
                     :BDVALFUNEMP13,
                     :BDVALFUNEMPC13,
                     :BDVALPROEMPFN,
                     :BDVALPROEMPFC,
                     :BDVALPROEMPFERFN,
                     :BDVALPROEMPFERFC,
                     :BDVALPROEMP13FN,
                     :BDVALPROEMP13FC,
                     :BDVALPROEMP13,
                     :BDVALPROEMPC13,
                     :BDVALAUTEMPFN,
                     :BDVALAUTEMPFC,
                     :BDVALAUTEMPFERFN,
                     :BDVALAUTEMPFERFC,
                     :BDVALAUTEMP13FN,
                     :BDVALAUTEMP13FC,
                     :BDVALAUTEMP13,
                     :BDVALAUTEMPC13,
                     :BDVALFPASEMPFN,
                     :BDVALFPASEMPFC,
                     :BDVALFPASEMPFERFN,
                     :BDVALFPASEMPFERFC,
                     :BDVALFPASEMP13FN,
                     :BDVALFPASEMP13FC,
                     :BDVALFPASEMP13,
                     :BDVALFPASEMPC13,
                     :BDVALRATEMPFN,
                     :BDVALRATEMPFC,
                     :BDVALRATEMPFERFN,
                     :BDVALRATEMPFERFC,
                     :BDVALRATEMP13FN,
                     :BDVALRATEMP13FC,
                     :BDVALRATEMP13,
                     :BDVALRATEMPC13,
                     :BDVALRATAPOEMPFN,
                     :BDVALRATAPOEMPFC,
                     :BDVALRATAPOEMPFERFN,
                     :BDVALRATAPOEMPFERFC,
                     :BDVALRATAPOEMP13FN,
                     :BDVALRATAPOEMP13FC,
                     :BDVALRATAPOEMP13,
                     :BDVALRATAPOEMPC13,
                     :BDCHAVEDARF
                   DO
                     SUSPEND;
        
                   /*proximo sql*/
                   wtipoemissaoant = wtipoemissao;
                   wwhereemp = CAST(wempatu AS VARCHAR(10));
                 END
         END
    END

   wsqlcalc = 'select '||
                'bdtiporeg, '||
                'bdcodemp , '||
                'bdcodcol,'||
                'bdcodter,'||
                'bdreffn , '||
                'bdrefpag , '||
                'bdcodcentro, '||
                'bdcodtpcc , '||
                'bdtotseg , '||
                'bdtotbase , '||
                'bdsegfun , '||
                'bdbasefun , '||
                'bdpercfun , '||
                'bdvalfunemp , '||
                'bdsegpro , '||
                'bdbasepro , '||
                'bdpercpro , '||
                'bdvalproemp , '||
                'bdsegaut , '||
                'bdbaseaut , '||
                'bdpercaut , '||
                'bdvalautemp , '||
                'bdsalfam , '||
                'bdsalmaternidade , '||
                'bdbaseratapo , '||
                'bdvalorratapo , '||
                'bdbasefpas , '||
                'bdpercfpas , '||
                'bdvalorfpas , '||
                'bdpercrat , '||
                'bdvalorrat , '||
                'bdvalorbruto , '||
                'bdvalorliquido , '||
                'bdnfcoop , '||
                'bdchave , '||
                'bdvalcompensado , '||
                'bdvalacompensar , '||
                'bdvaloracumulado , '||
                'bdvaloracumuladousado , '||
                'bdvaloracuterceiros , '||
                'bdvaloracuterceirosusado , '||
                'bdcodempant , '||
                'BDCHAVEDARFANT , '||
                'bdcodimpant , '||
                'bdcodperiodoant , '||
                'bdordemant , '||
                'bdreferenciaant , '||
                'bdquotaant , '||
                'bddescacumdet , '||
                'bddescacum , '||
                'bdvalorcampo6 , '||
                'bdvalnotas , '||
                'bddescnotas , '||
                'bdtotdesccomp , '||
                'bdtotvaloracumulado , '||
                'bdtotvaloracumuladoterc , '||
                'bdinicomp , '||
                'bdfimcomp , '||
                'bdtotcompensacao , '||
                'bddescsalfam , '||
                'bddescdedgps , '||
                'bdvaloutentidade, '||
                'bdsimplesgps, '||
                'bdcodenqfed, '||
                'bddescenqfed, '||
                'BDVALFUNEMPFN, '||
                'BDVALFUNEMPFC, '||
                'BDVALFUNEMPFERFN, '||
                'BDVALFUNEMPFERFC, '||
                'BDVALFUNEMP13FN, '||
                'BDVALFUNEMP13FC, '||
                'BDVALFUNEMP13, '||
                'BDVALFUNEMPC13, '||
                'BDVALPROEMPFN, '||
                'BDVALPROEMPFC, '||
                'BDVALPROEMPFERFN, '||
                'BDVALPROEMPFERFC, '||
                'BDVALPROEMP13FN, '||
                'BDVALPROEMP13FC, '||
                'BDVALPROEMP13, '||
                'BDVALPROEMPC13, '||
                'BDVALAUTEMPFN, '||
                'BDVALAUTEMPFC, '||
                'BDVALAUTEMPFERFN, '||
                'BDVALAUTEMPFERFC, '||
                'BDVALAUTEMP13FN, '||
                'BDVALAUTEMP13FC, '||
                'BDVALAUTEMP13, '||
                'BDVALAUTEMPC13, '||
                'BDVALFPASEMPFN, '||
                'BDVALFPASEMPFC, '||
                'BDVALFPASEMPFERFN, '||
                'BDVALFPASEMPFERFC, '||
                'BDVALFPASEMP13FN, '||
                'BDVALFPASEMP13FC, '||
                'BDVALFPASEMP13, '||
                'BDVALFPASEMPC13, '||
                'BDVALRATEMPFN, '||
                'BDVALRATEMPFC, '||
                'BDVALRATEMPFERFN, '||
                'BDVALRATEMPFERFC, '||
                'BDVALRATEMP13FN, '||
                'BDVALRATEMP13FC, '||
                'BDVALRATEMP13, '||
                'BDVALRATEMPC13, '||
                'BDVALRATAPOEMPFN, '||
                'BDVALRATAPOEMPFC, '||
                'BDVALRATAPOEMPFERFN, '||
                'BDVALRATAPOEMPFERFC, '||
                'BDVALRATAPOEMP13FN, '||
                'BDVALRATAPOEMP13FC, '||
                'BDVALRATAPOEMP13, '||
                'BDVALRATAPOEMPC13, '||
                'BDCHAVEDARF '||
                ' from vrhf_sp_gps(';

   IF (prcodimp IS NULL) THEN
      wparsqlcalc = 'null,';
   ELSE
      wparsqlcalc = prcodimp||',';

   --prcodemp varchar(32000),
    IF (prpuxafiliais = 1) THEN
       WPARSQLCALC = wparsqlcalc||''''||'(colcon.bdcodemp in ('||wwhereemp||') or temp.bdcodmatriz in ('||wwhereemp||'))'||'''';
    ELSE
       WPARSQLCALC = wparsqlcalc||''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';

   --prcodcol varchar(32000),
   wparsqlcalc = wparsqlcalc||',';
   IF (prcodcol IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
       wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';

   --prcodaut varchar(32000),
   wparsqlcalc = wparsqlcalc||',';
   IF (prcodaut IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
       wparsqlcalc = wparsqlcalc||''''||prcodaut||'''';

   wparsqlcalc = wparsqlcalc||',';

   --prtipocol integer,
   IF (prtipocol IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||prtipocol;

   wparsqlcalc = wparsqlcalc||',';

   --pranomes integer,
   IF (pranomes IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||pranomes;

   wparsqlcalc = wparsqlcalc||',';

   --pranomespag integer,
   IF (pranomespag IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||pranomespag;

   wparsqlcalc = wparsqlcalc||',';

   --prtipoemissao integer,
   wparsqlcalc = wparsqlcalc||CAST(wtipoemissaoant AS VARCHAR(10));
   wparsqlcalc = wparsqlcalc||',';

   --prapenasgps integer,
   IF (prapenasgps IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||prapenasgps;
   wparsqlcalc = wparsqlcalc||',';

   --prtipogps integer)
   IF (prtipogps IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||prtipogps;
   wparsqlcalc = wparsqlcalc||',';

   -- puxa filiais
   IF (prpuxafiliais IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||prpuxafiliais;

   wsqlcalc = wsqlcalc||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsqlcalc
   INTO
     :bdtiporeg,
     :bdcodemp,
     :bdcodcol,
     :bdcodter,
     :bdreffn,
     :bdrefpag,
     :bdcodcentro,
     :bdcodtpcc,
     :bdtotseg,
     :bdtotbase,
     :bdsegfun,
     :bdbasefun,
     :bdpercfun,
     :bdvalfunemp,
     :bdsegpro,
     :bdbasepro,
     :bdpercpro,
     :bdvalproemp,
     :bdsegaut,
     :bdbaseaut,
     :bdpercaut,
     :bdvalautemp,
     :bdsalfam,
     :bdsalmaternidade,
     :bdbaseratapo,
     :bdvalorratapo,
     :bdbasefpas,
     :bdpercfpas,
     :bdvalorfpas,
     :bdpercrat,
     :bdvalorrat,
     :bdvalorbruto,
     :bdvalorliquido,
     :bdnfcoop,
     :bdchave,
     :bdvalcompensado,
     :bdvalacompensar,
     :bdvaloracumulado,
     :bdvaloracumuladousado ,
     :bdvaloracumuterceiro,
     :bdvaloracuterceirosusado ,
     :bdcodempant ,
     :BDCHAVEDARFANT,
     :bdcodimpant ,
     :bdcodperiodoant,
     :bdordemant ,
     :bdreferenciaant ,
     :bdquotaant,
     :bddescacumdet,
     :bddescacu,
     :bdvalorcampo6,
     :BDVALORNOTAS,
     :bddescnotas,
     :bdtotdesccomp,
     :bdtotvaloracumulado,
     :bdtotvaloracumuladoTerc,
     :bdinicomp,
     :bdfimcomp,
     :bdtotcompensacao,
     :bddescsalfam,
     :bddescdedgps,
     :BDVALOUTENTIDADES,
     :bdsimplesgps,
     :bdcodenqfed,
     :bddescenqfed,
     :BDVALFUNEMPFN,
     :BDVALFUNEMPFC,
     :BDVALFUNEMPFERFN,
     :BDVALFUNEMPFERFC,
     :BDVALFUNEMP13FN,
     :BDVALFUNEMP13FC,
     :BDVALFUNEMP13,
     :BDVALFUNEMPC13,
     :BDVALPROEMPFN,
     :BDVALPROEMPFC,
     :BDVALPROEMPFERFN,
     :BDVALPROEMPFERFC,
     :BDVALPROEMP13FN,
     :BDVALPROEMP13FC,
     :BDVALPROEMP13,
     :BDVALPROEMPC13,
     :BDVALAUTEMPFN,
     :BDVALAUTEMPFC,
     :BDVALAUTEMPFERFN,
     :BDVALAUTEMPFERFC,
     :BDVALAUTEMP13FN,
     :BDVALAUTEMP13FC,
     :BDVALAUTEMP13,
     :BDVALAUTEMPC13,
     :BDVALFPASEMPFN,
     :BDVALFPASEMPFC,
     :BDVALFPASEMPFERFN,
     :BDVALFPASEMPFERFC,
     :BDVALFPASEMP13FN,
     :BDVALFPASEMP13FC,
     :BDVALFPASEMP13,
     :BDVALFPASEMPC13,
     :BDVALRATEMPFN,
     :BDVALRATEMPFC,
     :BDVALRATEMPFERFN,
     :BDVALRATEMPFERFC,
     :BDVALRATEMP13FN,
     :BDVALRATEMP13FC,
     :BDVALRATEMP13,
     :BDVALRATEMPC13,
     :BDVALRATAPOEMPFN,
     :BDVALRATAPOEMPFC,
     :BDVALRATAPOEMPFERFN,
     :BDVALRATAPOEMPFERFC,
     :BDVALRATAPOEMP13FN,
     :BDVALRATAPOEMP13FC,
     :BDVALRATAPOEMP13,
     :BDVALRATAPOEMPC13,
     :BDCHAVEDARF
   DO
     SUSPEND;
END
^

/* Alter (VRHF_SP_CONS_CALC_AUTONOMOS) */
ALTER PROCEDURE VRHF_SP_CONS_CALC_AUTONOMOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lancada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,  NULL, NULL);

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODTER, '||
                'COL.BDNOMTER, '||
                'GRUPOVERBAS.BDCODSERV, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERB.BDDESCVER, '||
                'VERB.BDDESCREDVER, '||
                'GRUPOVERBAS.BDREFERENCIA, '||
                'GRUPOVERBAS.BDREFAUXILIAR, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALOR '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALOR '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNFORREF, '||
                'GRUPOVERBAS.BDIGNFORVAL, '||
                'VERB.BDCLAVER, '||
                'VERB.BDORDEMVER, '||
                'Y.BDREFINSSSERV, '||
                'EMPCALC.BDREFHOREMP, '||
                '0.0 BDBFGTSFN, '||
                '0.0 BDFGTSFN, '||
                '0.0 BDFGTSCSFN, '||
                '0.0 BDBFGTS13FN, '||
                '0.0 BDFGTS13FN, '||
                '0.0 BDFGTS13CSFN, '||
                '0.0 BDMAIORREMFN, '||
                'Y.BDBASEINSS, '||
                'Y.BDFAIXAINSS, '||
                'Y.BDVALORINSS, '||
                'Y.BDBASEIR, '||
                'Y.BDFAIXAIR, '||
                'Y.BDVALORIR, '||
                '0.0 BDBINSS13FN, '||
                '0.0 BDALIQINSS13FN, '||
                '0.0 BDINSS13FN, '||
                '0.0 BDBIRRF13FN, '||
                '0.0 BDALIQIRRF13FN, '||
                '0.0 BDIRRF13FN, '||
                '0.0 BDBSALFAMFN, '||
                '0.0 BDSALFAMFN, '||
                '0.0 BDBRAISFN, '||
                '0.0 BDSALBASEFN, '||
                '0.0 BDDEPFN, '||
                '0.0 BDBFGTSFEFN, '||
                '0.0 BDFGTSFEFN, '||
                'Y.BDCREDITOSERV, '||
                'Y.BDDEBITOSERV '||
         'from VRHF_BASE_ITEMS_CALCTERC GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VRH_BASE_TTERC COL, '||
         'VRH_BASE_TVERBAS VERB, '||
         'VW_VERBAS_REF_ATUAL VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_BASE_CALC_TERC Y ';

  wwhere = 'where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODTER = GRUPOVERBAS.BDCODTER and '||
           'VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and '||
           'Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODTER = GRUPOVERBAS.BDCODTER and Y.BDCODSERV = GRUPOVERBAS.BDCODSERV';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and Y.BDREFINSSSERV = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODSERV,
    :BDCODVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdbfgtsfe,
    :BDFGTSFE,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;
END
^

/* Alter (VRHF_SP_CONS_CALC_FOLHAINT) */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHAINT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODCONTTI INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
declare variable WWHERE varchar(32700);
declare variable WSQL varchar(32700);
declare variable WSUM numeric(15,6);
declare variable WMAX numeric(15,6);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lancada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,  NULL, NULL);

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODCONTTI, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERB.BDDESCVER, '||
                'VERB.BDDESCREDVER, '||
                'GRUPOVERBAS.BDREFVFN, '||
                'GRUPOVERBAS.BDREFAUXVFN, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVFN '||
                     'when (VERREF.BDTIPOCODVER = 2) then GRUPOVERBAS.BDVALVFN '||
                     'else 0.00 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER = 1) then GRUPOVERBAS.BDVALVFN '||
                     'when (VERREF.BDTIPOCODVER = 3) then GRUPOVERBAS.BDVALVFN '||
                     'else 0.00 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFVFN, '||
                'GRUPOVERBAS.BDIGNVALVFN, '||
                'VERB.BDCLAVER, '||
                'VERB.BDORDEMVER, '||
                'GRUPOVERBAS.BDREFFN, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDBFGTSFN, '||
                'Y.BDFGTSFN, '||
                'Y.BDFGTSCSFN, '||
                'Y.BDBFGTS13FN, '||
                'Y.BDFGTS13FN, '||
                'Y.BDFGTS13CSFN, '||
                'Y.BDMAIORREMFN, '||
                'Y.BDBINSSFN, '||
                'Y.BDALIQINSSFN, '||
                'Y.BDINSSFN, '||
                'Y.BDBIRRFFN, '||
                'Y.BDALIQIRRFFN, '||
                'Y.BDIRRFFN, '||
                'Y.BDBINSS13FN, '||
                'Y.BDALIQINSS13FN, '||
                'Y.BDINSS13FN, '||
                'Y.BDBIRRF13FN, '||
                'Y.BDALIQIRRF13FN, '||
                'Y.BDIRRF13FN, '||
                'Y.BDBSALFAMFN, '||
                'Y.BDSALFAMFN, '||
                'Y.BDBRAISFN, '||
                'Y.BDSALBASEFN, '||
                'Y.BDDEPFN, '||
                'Y.BDBFGTSFEFN, '||
                'Y.BDFGTSFEFN, '||
                'Y.BDCREDITOFN, '||
                'Y.BDDEBITOFN '||
         'from VRHF_EMP_TVERBAINT GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL, '||
         'VRH_BASE_TVERBAS VERB, '||
         'VW_VERBAS_REF_ATUAL VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_EMP_TFOLHAINT Y ';

  wwhere = 'where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and '||
           'VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and '||
           'Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREFFN = GRUPOVERBAS.BDREFFN and Y.BDCODCONTTI = GRUPOVERBAS.BDCODCONTTI ';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and GRUPOVERBAS.BDREFFN = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODCONTTI,
    :BDCODVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdbfgtsfe,
    :BDFGTSFE,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;

  wwhere = '';

  -- folha por tomador
/*00*/  wsql = 'select GRUPOVERBAS.BDCODEMP,'||
/*01*/                'EMP.BDNOMEMP,'||
/*02*/                'GRUPOVERBAS.BDCODCOL,'||
/*03*/                'COL.BDNOMCOL,'||
/*04*/                'GRUPOVERBAS.BDCODCONTTI,'||
/*04*/                'GRUPOVERBAS.BDCODVER,'||
/*05*/                'VERB.BDDESCVER,'||
/*06*/                'VERB.BDDESCREDVER,'||
/*07*/                'sum(GRUPOVERBAS.bdrefvft),'|| -- aki
/*08*/                'max(GRUPOVERBAS.bdrefvft),'|| -- aki
/*09*/                'sum(GRUPOVERBAS.bdrefauxvft),'||
/*10*/                'sum(case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.bdvalvft'||
                      '     when (VERREF.BDTIPOCODVER <> 0) then 0 end) BDPROVENTO,'||
/*11*/                'sum(case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.bdvalvft'||
                      '     when (VERREF.BDTIPOCODVER <= 0) then 0 end) BDDESCONTO,'||
/*12*/                'max(VERREF.BDTIPOCODVER),'||
/*13*/                'max(VERREF.BDINSSVER),'||
/*14*/                'max(VERREF.BDFGTSVER),'||
/*15*/                'max(VERREF.BDIRVER),'||
/*16*/                'max(VERREF.BDTIPOREFVER),'||
/*17*/                'max(VERREF.BDBASESFVER),'||
/*18*/                'VERREF.BDPISVER,'||
/*19*/                'VERREF.BDBASEHEVER,'||
/*20*/                'VERREF.BDBASEMAIORVER,'||
/*21*/                'VERREF.BDRAISVER,'||
/*22*/                'VERREF.BDBASEGPSVER,'||
/*23*/                'GRUPOVERBAS.bdignrefvft,'||
/*24*/                'GRUPOVERBAS.bdignvalvft,'||
/*25*/                'VERB.BDCLAVER,'||
/*26*/                'max(VERB.BDORDEMVER),'||
/*27*/                'GRUPOVERBAS.bdreftomador,'||
/*28*/                'EMPCALC.BDREFHOREMP,'||
/*29*/                'sum(Y.bdbfgtsft),'||
/*30*/                'sum(Y.bdfgtsft),'||
/*31*/                'sum(Y.bdfgtscsft),'||
/*32*/                'sum(Y.bdbfgts13ft),'||
/*33*/                'sum(Y.bdfgts13ft),'||
/*34*/                'sum(Y.bdfgts13csft),'||
/*35*/                'sum(Y.bdmaiorremft),'||
/*36*/                'sum(Y.bdbinssft),'||
/*37*/                'sum(Y.bdaliqinssft),'||
/*38*/                'sum(Y.bdinssft),'||
/*39*/                'sum(Y.bdbirrfft),'||
/*40*/                'sum(Y.bdaliqirrfft),'||
/*41*/                'sum(Y.bdirrfft),'||
/*42*/                'sum(Y.bdbinss13ft),'||
/*43*/                'sum(Y.bdaliqinss13ft),'||
/*44*/                'sum(Y.bdinss13ft),'||
/*45*/                'sum(Y.bdbirrf13ft),'||
/*46*/                'sum(Y.bdaliqirrf13ft),'||
/*47*/                'sum(Y.bdirrf13ft),'||
/*48*/                'sum(Y.bdbsalfamft),'||
/*49*/                'sum(Y.bdsalfamft),'||
/*50*/                'sum(Y.bdbraisft),'||
/*51*/                'sum(Y.bdsalbaseft),'||
/*52*/                'sum(Y.bddepft), '||
/*53*/                'sum(Y.BDBFGTSFEFT), '||
/*54*/                'sum(Y.BDFGTSFEFT), '||
/*55*/                'sum(Y.BDCREDITOFT), '||
/*56*/                'sum(Y.BDDEBITOFT) '||
         ' from vrhf_emp_tverbatomint GRUPOVERBAS,'||
         ' VW_TEMPRESAS_REF EMP,'||
         ' VW_VRH_EMP_TCOLCON_CAD COL,'||
         ' VRH_BASE_TVERBAS VERB,'||
         ' VW_VERBAS_REF_ATUAL VERREF,'||
         ' VW_VRHF_BASE_TEMPCALC EMPCALC,'||
         ' vrhf_emp_tfolhatomint Y'||
' where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and'||
' VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and'||
' Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.bdreftomador = GRUPOVERBAS.bdreftomador and Y.bdordem = GRUPOVERBAS.bdordem and Y.BDCODCONTTI = GRUPOVERBAS.BDCODCONTTI ';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and GRUPOVERBAS.bdreftomador = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  wsql = wsql||' group by GRUPOVERBAS.BDCODEMP,'||
                'EMP.BDNOMEMP,'||
                'GRUPOVERBAS.BDCODCOL,'||
                'COL.BDNOMCOL,'||
                'GRUPOVERBAS.BDCODCONTTI,'||
                'GRUPOVERBAS.BDCODVER,'||
                'GRUPOVERBAS.bdreftomador,'||
                'VERB.BDDESCVER,'||
                'VERB.BDDESCREDVER,'||
                'GRUPOVERBAS.bdignrefvft,'||
                'GRUPOVERBAS.bdignvalvft,'||
                'VERREF.BDPISVER,'||
                'VERREF.BDBASEHEVER,'||
                'VERREF.BDBASEMAIORVER,'||
                'VERREF.BDRAISVER,'||
                'VERREF.BDBASEGPSVER,'||
                'VERB.BDCLAVER,'||
                'EMPCALC.BDREFHOREMP';

  FOR EXECUTE STATEMENT wsql
  INTO
/*00*/    :BDCODEMP,
/*01*/    :BDNOMEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDNOMCOL,
          :BDCODCONTTI,
/*04*/    :BDCODVER,
/*05*/    :BDDESCVER,
/*06*/    :BDDESCREDVER,
/*07*/    :wsum,
/*08*/    :wmax,
/*09*/    :BDREFAUXV,
/*10*/    :BDPROVENTO,
/*11*/    :BDDESCONTO,
/*12*/    :BDTIPOCODVER,
/*13*/    :BDINSSVER,
/*14*/    :BDFGTSVER,
/*15*/    :BDIRVER,
/*16*/    :BDTIPOREFVER,
/*17*/    :BDBASESFVER,
/*18*/    :BDPISVER,
/*19*/    :BDBASEHEVER,
/*20*/    :BDBASEMAIORVER,
/*21*/    :BDRAISVER,
/*22*/    :BDBASEGPSVER,
/*23*/    :BDIGNREFV,
/*24*/    :BDIGNVALV,
/*25*/    :BDCLAVER,
/*26*/    :BDORDEMVER,
/*27*/    :BDREF,
/*28*/    :BDREFHOREMP,
/*29*/    :BDBFGTS,
/*30*/    :BDFGTS,
/*31*/    :BDFGTSCS,
/*32*/    :BDBFGTS13,
/*33*/    :BDFGTS13,
/*34*/    :BDFGTS13CS,
/*35*/    :BDMAIORREM,
/*36*/    :BDBINSS,
/*37*/    :BDALIQINSS,
/*38*/    :BDINSS,
/*39*/    :BDBIRRF,
/*40*/    :BDALIQIRRF,
/*41*/    :BDIRRF,
/*42*/    :BDBINSS13,
/*43*/    :BDALIQINSS13,
/*44*/    :BDINSS13,
/*45*/    :BDBIRRF13,
/*46*/    :BDALIQIRRF13,
/*47*/    :BDIRRF13,
/*48*/    :BDBSALFAM,
/*49*/    :BDSALFAM,
/*50*/    :BDBRAIS,
/*51*/    :BDSALBASE,
/*52*/    :BDDEP,
/*53*/    :bdbfgtsfe,
/*54*/    :BDFGTSFE,
/*55*/    :bdcredito,
/*56*/    :bddebito
  DO
    BEGIN
      IF (BDTIPOREFVER = 4) THEN
         BDREFV = wmax;
      ELSE
         BDREFV = wsum;
      SUSPEND;
    END

END
^

/* Alter (VRHF_SP_CONS_CALC_FOLHANORMAL) */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSUM NUMERIC(15,6);
DECLARE VARIABLE WMAX NUMERIC(15,6);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lancada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,  NULL, NULL);

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERB.BDDESCVER, '||
                'VERB.BDDESCREDVER, '||
                'GRUPOVERBAS.BDREFVFN, '||
                'GRUPOVERBAS.BDREFAUXVFN, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVFN '||
                     'when (VERREF.BDTIPOCODVER = 2) then GRUPOVERBAS.BDVALVFN '||
                     'else 0.00 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER = 1) then GRUPOVERBAS.BDVALVFN '||
                     'when (VERREF.BDTIPOCODVER = 3) then GRUPOVERBAS.BDVALVFN '||
                     'else 0.00 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFVFN, '||
                'GRUPOVERBAS.BDIGNVALVFN, '||
                'VERB.BDCLAVER, '||
                'VERB.BDORDEMVER, '||
                'GRUPOVERBAS.BDREFFN, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDBFGTSFN, '||
                'Y.BDFGTSFN, '||
                'Y.BDFGTSCSFN, '||
                'Y.BDBFGTS13FN, '||
                'Y.BDFGTS13FN, '||
                'Y.BDFGTS13CSFN, '||
                'Y.BDMAIORREMFN, '||
                'Y.BDBINSSFN, '||
                'Y.BDALIQINSSFN, '||
                'Y.BDINSSFN, '||
                'Y.BDBIRRFFN, '||
                'Y.BDALIQIRRFFN, '||
                'Y.BDIRRFFN, '||
                'Y.BDBINSS13FN, '||
                'Y.BDALIQINSS13FN, '||
                'Y.BDINSS13FN, '||
                'Y.BDBIRRF13FN, '||
                'Y.BDALIQIRRF13FN, '||
                'Y.BDIRRF13FN, '||
                'Y.BDBSALFAMFN, '||
                'Y.BDSALFAMFN, '||
                'Y.BDBRAISFN, '||
                'Y.BDSALBASEFN, '||
                'Y.BDDEPFN, '||
                'Y.BDBFGTSFEFN, '||
                'Y.BDFGTSFEFN, '||
                'Y.BDCREDITOFN, '||
                'Y.BDDEBITOFN '||
         'from VRHF_EMP_TVERBAFN GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL, '||
         'VRH_BASE_TVERBAS VERB, '||
         'VW_VERBAS_REF_ATUAL VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_EMP_TFOLHANORMAL Y ';

  wwhere = 'where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and '||
           'VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and '||
           'Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREFFN = GRUPOVERBAS.BDREFFN';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and GRUPOVERBAS.BDREFFN = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdbfgtsfe,
    :BDFGTSFE,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;

  wwhere = '';

  -- folha por tomador
/*00*/  wsql = 'select GRUPOVERBAS.BDCODEMP,'||
/*01*/                'EMP.BDNOMEMP,'||
/*02*/                'GRUPOVERBAS.BDCODCOL,'||
/*03*/                'COL.BDNOMCOL,'||
/*04*/                'GRUPOVERBAS.BDCODVER,'||
/*05*/                'VERB.BDDESCVER,'||
/*06*/                'VERB.BDDESCREDVER,'||
/*07*/                'sum(GRUPOVERBAS.bdrefvft),'|| -- aki
/*08*/                'max(GRUPOVERBAS.bdrefvft),'|| -- aki
/*09*/                'sum(GRUPOVERBAS.bdrefauxvft),'||
/*10*/                'sum(case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.bdvalvft'||
                      '     when (VERREF.BDTIPOCODVER <> 0) then 0 end) BDPROVENTO,'||
/*11*/                'sum(case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.bdvalvft'||
                      '     when (VERREF.BDTIPOCODVER <= 0) then 0 end) BDDESCONTO,'||
/*12*/                'max(VERREF.BDTIPOCODVER),'||
/*13*/                'max(VERREF.BDINSSVER),'||
/*14*/                'max(VERREF.BDFGTSVER),'||
/*15*/                'max(VERREF.BDIRVER),'||
/*16*/                'max(VERREF.BDTIPOREFVER),'||
/*17*/                'max(VERREF.BDBASESFVER),'||
/*18*/                'VERREF.BDPISVER,'||
/*19*/                'VERREF.BDBASEHEVER,'||
/*20*/                'VERREF.BDBASEMAIORVER,'||
/*21*/                'VERREF.BDRAISVER,'||
/*22*/                'VERREF.BDBASEGPSVER,'||
/*23*/                'GRUPOVERBAS.bdignrefvft,'||
/*24*/                'GRUPOVERBAS.bdignvalvft,'||
/*25*/                'VERB.BDCLAVER,'||
/*26*/                'max(VERB.BDORDEMVER),'||
/*27*/                'GRUPOVERBAS.bdreftomador,'||
/*28*/                'EMPCALC.BDREFHOREMP,'||
/*29*/                'sum(Y.bdbfgtsft),'||
/*30*/                'sum(Y.bdfgtsft),'||
/*31*/                'sum(Y.bdfgtscsft),'||
/*32*/                'sum(Y.bdbfgts13ft),'||
/*33*/                'sum(Y.bdfgts13ft),'||
/*34*/                'sum(Y.bdfgts13csft),'||
/*35*/                'sum(Y.bdmaiorremft),'||
/*36*/                'sum(Y.bdbinssft),'||
/*37*/                'sum(Y.bdaliqinssft),'||
/*38*/                'sum(Y.bdinssft),'||
/*39*/                'sum(Y.bdbirrfft),'||
/*40*/                'sum(Y.bdaliqirrfft),'||
/*41*/                'sum(Y.bdirrfft),'||
/*42*/                'sum(Y.bdbinss13ft),'||
/*43*/                'sum(Y.bdaliqinss13ft),'||
/*44*/                'sum(Y.bdinss13ft),'||
/*45*/                'sum(Y.bdbirrf13ft),'||
/*46*/                'sum(Y.bdaliqirrf13ft),'||
/*47*/                'sum(Y.bdirrf13ft),'||
/*48*/                'sum(Y.bdbsalfamft),'||
/*49*/                'sum(Y.bdsalfamft),'||
/*50*/                'sum(Y.bdbraisft),'||
/*51*/                'sum(Y.bdsalbaseft),'||
/*52*/                'sum(Y.bddepft), '||
/*53*/                'sum(Y.BDBFGTSFEFT), '||
/*54*/                'sum(Y.BDFGTSFEFT), '||
/*55*/                'sum(Y.BDCREDITOFT), '||
/*56*/                'sum(Y.BDDEBITOFT) '||
         ' from vrhf_emp_tverbatomador GRUPOVERBAS,'||
         ' VW_TEMPRESAS_REF EMP,'||
         ' VW_VRH_EMP_TCOLCON_CAD COL,'||
         ' VRH_BASE_TVERBAS VERB,'||
         ' VW_VERBAS_REF_ATUAL VERREF,'||
         ' VW_VRHF_BASE_TEMPCALC EMPCALC,'||
         ' vrhf_emp_tfolhatomador Y'||
' where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and'||
' VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and'||
' Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.bdreftomador = GRUPOVERBAS.bdreftomador and Y.bdordem = GRUPOVERBAS.bdordem';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and GRUPOVERBAS.bdreftomador = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  wsql = wsql||' group by GRUPOVERBAS.BDCODEMP,'||
                'EMP.BDNOMEMP,'||
                'GRUPOVERBAS.BDCODCOL,'||
                'COL.BDNOMCOL,'||
                'GRUPOVERBAS.BDCODVER,'||
                'GRUPOVERBAS.bdreftomador,'||
                'VERB.BDDESCVER,'||
                'VERB.BDDESCREDVER,'||
                'GRUPOVERBAS.bdignrefvft,'||
                'GRUPOVERBAS.bdignvalvft,'||
                'VERREF.BDPISVER,'||
                'VERREF.BDBASEHEVER,'||
                'VERREF.BDBASEMAIORVER,'||
                'VERREF.BDRAISVER,'||
                'VERREF.BDBASEGPSVER,'||
                'VERB.BDCLAVER,'||
                'EMPCALC.BDREFHOREMP';

  FOR EXECUTE STATEMENT wsql
  INTO
/*00*/    :BDCODEMP,
/*01*/    :BDNOMEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDNOMCOL,
/*04*/    :BDCODVER,
/*05*/    :BDDESCVER,
/*06*/    :BDDESCREDVER,
/*07*/    :wsum,
/*08*/    :wmax,
/*09*/    :BDREFAUXV,
/*10*/    :BDPROVENTO,
/*11*/    :BDDESCONTO,
/*12*/    :BDTIPOCODVER,
/*13*/    :BDINSSVER,
/*14*/    :BDFGTSVER,
/*15*/    :BDIRVER,
/*16*/    :BDTIPOREFVER,
/*17*/    :BDBASESFVER,
/*18*/    :BDPISVER,
/*19*/    :BDBASEHEVER,
/*20*/    :BDBASEMAIORVER,
/*21*/    :BDRAISVER,
/*22*/    :BDBASEGPSVER,
/*23*/    :BDIGNREFV,
/*24*/    :BDIGNVALV,
/*25*/    :BDCLAVER,
/*26*/    :BDORDEMVER,
/*27*/    :BDREF,
/*28*/    :BDREFHOREMP,
/*29*/    :BDBFGTS,
/*30*/    :BDFGTS,
/*31*/    :BDFGTSCS,
/*32*/    :BDBFGTS13,
/*33*/    :BDFGTS13,
/*34*/    :BDFGTS13CS,
/*35*/    :BDMAIORREM,
/*36*/    :BDBINSS,
/*37*/    :BDALIQINSS,
/*38*/    :BDINSS,
/*39*/    :BDBIRRF,
/*40*/    :BDALIQIRRF,
/*41*/    :BDIRRF,
/*42*/    :BDBINSS13,
/*43*/    :BDALIQINSS13,
/*44*/    :BDINSS13,
/*45*/    :BDBIRRF13,
/*46*/    :BDALIQIRRF13,
/*47*/    :BDIRRF13,
/*48*/    :BDBSALFAM,
/*49*/    :BDSALFAM,
/*50*/    :BDBRAIS,
/*51*/    :BDSALBASE,
/*52*/    :BDDEP,
/*53*/    :bdbfgtsfe,
/*54*/    :BDFGTSFE,
/*55*/    :bdcredito,
/*56*/    :bddebito
  DO
    BEGIN
      IF (BDTIPOREFVER = 4) THEN
         BDREFV = wmax;
      ELSE
         BDREFV = wsum;
      SUSPEND;
    END

END
^

/* Alter (VRHF_SP_CONS_CALC_FOLHANORMALPR) */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMALPR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6),
BDDATARESCISAOPREV DATE)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lanCada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  wsql = 'select '||
           'GRUPOVERBAS.BDCODEMP, EMP.BDNOMEMP, GRUPOVERBAS.BDCODCOL, COL.BDNOMCOL, GRUPOVERBAS.BDCODVER, VERREF.BDDESCVER, VERREF.BDDESCREDVER, GRUPOVERBAS.BDREFVFN_SUM as BDREFVFNPR,'||
           'GRUPOVERBAS.BDREFAUXVFN_SUM as BDREFAUXVFNPR, case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVFN when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO,'||
           'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALVFN when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
           'VERREF.BDORDEMTIPOCODVER,'||
           'VERREF.BDINSSVER, VERREF.BDFGTSVER,'||
           'VERREF.BDIRVER, VERREF.BDTIPOREFVER, VERREF.BDBASESFVER, VERREF.BDPISVER, VERREF.BDBASEHEVER, VERREF.BDBASEMAIORVER, VERREF.BDRAISVER, VERREF.BDBASEGPSVER,'||
           'GRUPOVERBAS.BDIGNREFVFN as BDIGNREFVFNPR, GRUPOVERBAS.BDIGNVALVFN as BDIGNVALVFNPR, VERREF.BDCLAVER, VERREF.BDORDEMVER, VERREF.BDTIPOCODVER, '||
           'RESC.BDREFRESCISAOPREV BDREFFNPR,'||
           'EMPCALC.BDREFHOREMP, Y.BDBFGTS BDBFGTSFNPR, Y.BDFGTS BDFGTSFNPR, Y.BDFGTSCS BDFGTSCSFNPR, Y.BDBFGTS13 BDBFGTS13FNPR, Y.bdfgts13 BDFGTS13FNPR, Y.bdfgts13cs BDFGTS13CSFNPR,'||
           'Y.bdmaiorrem BDMAIORREMFNPR, Y.bdbinss BDBINSSFNPR, Y.bdaliqinss BDALIQINSSFNPR, Y.bdinss BDINSSFNPR,'||
           'Y.bdbirrf BDBIRRFFNPR, Y.bdaliqirrf BDALIQIRRFFNPR, Y.bdirrf BDIRRFFNPR, Y.bdinss13 BDBINSS13FNPR, Y.bdaliqinss13 BDALIQINSS13FNPR, Y.bdinss13 BDINSS13FNPR,'||
           'Y.bdbirrf13 BDBIRRF13FNPR, Y.bdaliqirrf13 BDALIQIRRF13FNPR, Y.bdirrf13 BDIRRF13FNPR, Y.bdbsalfam BDBSALFAMFNPR,'||
           'Y.bdsalfam BDSALFAMFNPR, Y.bdbrais BDBRAISFNPR, Y.bdsalbase BDSALBASEFNPR, Y.bddep BDDEPFNPR, Y.bdbfgtsfefol BDBFGTSFEFN, Y.bdfgtsfefol BDFGTSFEFN, RESC.BDDATARESCISAOPREV '||
         'from '||
           '(select * '||
            'from vrh_emp_trescisao_previa  ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wsql = wsql||
         ') RESC '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL on (COL.BDCODEMP = RESC.BDCODEMP and COL.BDCODCOL = RESC.BDCODCOL) '||
         'join vwrh_union_fnpr_ftpr_mes GRUPOVERBAS on (GRUPOVERBAS.BDCODEMP = RESC.BDCODEMP and GRUPOVERBAS.BDCODCOL = RESC.BDCODCOL) '||
         'join VWRH_UNION_FNPR_FTPR_MES_BASES Y on (Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL) '||
         'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = RESC.BDCODEMP) '||
         'join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = GRUPOVERBAS.BDCODVER) '||
         'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = RESC.BDCODEMP) ';


  /* Select principal */
  wsql = 'select BDCODEMP, '||
                'BDNOMEMP, '||
                'BDCODCOL, '||
                'BDNOMCOL, '||
                'BDCODVER, '||
                'BDDESCVER, '||
                'BDDESCREDVER, '||
                'BDREFVFNPR, '||
                'BDREFAUXVFNPR, '||
                'BDPROVENTO, '||
                'BDDESCONTO, '||
                'BDTIPOCODVER, '||
                'BDORDEMTIPOCODVER, '||
                'BDINSSVER, '||
                'BDFGTSVER, '||
                'BDIRVER, '||
                'BDTIPOREFVER, '||
                'BDBASESFVER, '||
                'BDPISVER, '||
                'BDBASEHEVER, '||
                'BDBASEMAIORVER, '||
                'BDRAISVER, '||
                'BDBASEGPSVER, '||
                'BDIGNREFVFNPR, '||
                'BDIGNVALVFNPR, '||
                'BDCLAVER, '||
                'BDORDEMVER, '||
                'BDREFFNPR, '||
                'BDREFHOREMP, '||
                'BDBFGTSFNPR, '||
                'BDFGTSFNPR, '||
                'BDFGTSCSFNPR, '||
                'BDBFGTS13FNPR, '||
                'BDFGTS13FNPR, '||
                'BDFGTS13CSFNPR, '||
                'BDMAIORREMFNPR, '||
                'BDBINSSFNPR, '||
                'BDALIQINSSFNPR, '||
                'BDINSSFNPR, '||
                'BDBIRRFFNPR, '||
                'BDALIQIRRFFNPR, '||
                'BDIRRFFNPR, '||
                'BDBINSS13FNPR, '||
                'BDALIQINSS13FNPR, '||
                'BDINSS13FNPR, '||
                'BDBIRRF13FNPR, '||
                'BDALIQIRRF13FNPR, '||
                'BDIRRF13FNPR, '||
                'BDBSALFAMFNPR, '||
                'BDSALFAMFNPR, '||
                'BDBRAISFNPR, '||
                'BDSALBASEFNPR, '||
                'BDDEPFNPR, '||
                'BDBFGTSFEFN, '||
                'BDFGTSFEFN, '||
                'BDDATARESCISAOPREV '||
         'from ('||
         wsql||
         ') ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' where ';
       wwhere = wwhere || ' ' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' where ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || :PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  EXECUTE PROCEDURE sp_seta_competencia(:pranomes);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdbfgtsfe, 
    :bdfgtsfe,
    :bddatarescisaoprev
  DO
  SUSPEND;
END
^

/* Alter (VRHF_SP_CONS_IR_TERCEIROS) */
ALTER PROCEDURE VRHF_SP_CONS_IR_TERCEIROS(PRCODEMP VARCHAR(10000),
PRCODTER VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODTER INTEGER,
BDNOMTER VARCHAR(100),
BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDREF VARCHAR(6),
BDBASEIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDVALORDEP NUMERIC(15,6),
BDBASEINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,6),
BDCPFTER VARCHAR(14),
BDCODRECOF VARCHAR(4),
BDBASEIRTOT NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WBDCATEGORIATER INTEGER;
DECLARE VARIABLE WBDPERTRANSPIRTER NUMERIC(15,2);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(:prreffim, NULL, NULL);

--  wsql = 'select SERVICO.bdcodemp, empresas.bdnomemp , SERVICO.bdcodter, tterc.bdnometer, SERVICO.BDCODSERV, SERVICO.bddataserv , SERVICO.BDDATAPAGSERV, SERVICO.bdbaseir, ' ||
  wsql = 'select SERVICO.bdcodemp, empresas.bdnomemp , SERVICO.bdcodter, SERVICO.BDCODSERV, SERVICO.bddataserv , SERVICO.BDDATAPAGSERV, SERVICO.bdbaseir, ' ||
               'SERVICO.bdvalorir, SERVICO.bdvalordep , SERVICO.bdbaseinss , SERVICO.bdvalorinss, tterc_doc.bdcpfter, codrec.bdcodrecof, SERVICO.BDBASEIRTOT, TERC_FGTS.bdcategoriater, TERC_FGTS.bdpertranspirter '||
         'from (';

  wsql = wsql||
         'select '||
           'calc_terc.bdcodemp, calc_terc.bdcodter, calc_terc.BDCODSERV, Serv.bddataserv , Serv.BDDATAPAGSERV, calc_terc.bdbaseir , calc_terc.bdvalorir, '||
           'calc_terc.bdvalordep , calc_terc.bdbaseinss , calc_terc.bdvalorinss, calc_terc.BDBASEIRTOT '||
         'from VRH_BASE_TSERVTERC SERV '||
         'join VRHF_BASE_CALC_TERC calc_terc on (SERV.BDCODEMP = calc_terc.BDCODEMP and SERV.BDCODTER = calc_terc.BDCODTER and SERV.BDCODSERV = calc_terc.BDCODSERV) ';

  wwhere = '';
  IF (:prrefini IS NOT NULL) THEN
     wwhere = wwhere||' Serv.BDREFPAGSERV >= '||prrefini||' ';

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'Serv.BDREFPAGSERV <= '||prreffim||' ';
    END

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODEMP;
     END

  IF (:prcodter IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:prcodter;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||' union all ';

  wsql = wsql||
         'select '||
           'calc_terc.bdcodemp, calc_terc.bdcodter, calc_terc.bdcodserv, SERV.bddataserv, SERV.bddatapagserv, '||
           'calc_terc.bdbaseir - calc_terc.bdvalordep - calc_terc.bdvalorinss, calc_terc.bdvalorir, calc_terc.bdvalordep, calc_terc.bdbaseinss, calc_terc.bdvalorinss, calc_terc.BDBASEIRTOT '||
          'from VRH_BASE_TSERVTERC SERV '||
          'join vrhf_emp_tfichairrf_terc calc_terc on (SERV.BDCODEMP = calc_terc.BDCODEMP and SERV.BDCODTER = calc_terc.BDCODTER and SERV.BDCODSERV = calc_terc.BDCODSERV) ';

  wsql = wsql||wwhere;
  wsql = wsql||') SERVICO ';

  wsql = wsql||
--         'join VRH_BASE_TTERC TTERC on (TTERC.bdcodter = SERVICO.BDCODTER) '||

/*         'join (select X.* from tterceiro_ref X '||
           'join '||
             '( '||
               'select serv.BDCODTER, MAX(serv.BDREFEMP) BDREFEMP from tterceiro_ref serv where serv.BDREFEMP <= '||
                      'COALESCE ( '||
                      '(SELECT MAX(rf2.bdrefemp) FROM TTERCEIRO_REF rf2 WHERE rf2.BDREFEMP <= (SELECT TRIM(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) FROM rdb$database) AND rf2.bdcodter = SERV.BDCODTER), '||
                      '(SELECT MIN(rf2.bdrefemp) FROM TTERCEIRO_REF rf2 WHERE rf2.bdcodter = SERV.BDCODTER) '||
                      ') ';

  if (prcodter is not null and prcodter <> '') then
     wsql = wsql||' and '||prcodter||' ';

  wsql = wsql||
               'group by serv.BDCODTER '||
             ') Y on (Y.BDCODTER = X.BDCODTER and Y.BDREFEMP = X.BDREFEMP) '||
         ') TTERC on (TTERC.BDCODTER = SERVICO.BDCODTER) '|| */
         'left outer join VW_VRH_BASE_TTERC_DOC TTERC_DOC on (TTERC_DOC.bdcodter = SERVICO.BDCODTER) '||
         'left outer join VW_VRH_BASE_TTERC_VINC TTERC_VINC on (TTERC_VINC.bdcodcol = SERVICO.BDCODTER) '||
         'left outer join VRH_BASE_TCLASSE CLASSE on (CLASSE.BDCODCLA = TTERC_VINC.BDCODCLA) '||
         'left outer join TCODREC CODREC on (CODREC.BDCODREC = CLASSE.BDCODREC) '||
         'left outer join vw_tempresas_ref empresas on (empresas.bdcodemp = SERVICO.bdcodemp ) '||
         'left outer join (select tfgts.bdcodter, tfgts.bdcategoriater, tfgts.bdpertranspirter from VRHF_BASE_TTERC_FGTSGPS tfgts '||
         ' join VW_VRHF_TTERC_FGTSGPS_REFATU TREF on (TREF.bdcodter = TFGTS.BDCODTER and TREF.bdrefter = TFGTS.bdrefterc)) TERC_FGTS on (TERC_FGTS.BDCODTER = SERVICO.bdcodter) '||
         ' where strlen(TTERC_DOC.bdcpfter) = 14' ||
         'order by SERVICO.bdcodemp, SERVICO.bdcodter, SERVICO.BDDATAPAGSERV ';


  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcodter,
--    :bdnomter,
    :bdcodserv,
    :bddataserv,
    :bddatapagserv,
    :bdbaseir,
    :bdvalorir,
    :bdvalordep,
    :bdbaseinss,
    :bdvalorinss,
    :bdcpfter,
    :bdcodrecof,
    :bdbaseirtot,
    :wbdcategoriater,
    :wbdpertranspirter
  DO
  BEGIN
    IF (wbdcategoriater IN (15,16,18,23,25)) THEN
      BEGIN
        bdbaseir = bdbaseirtot * (wbdpertranspirter/100);
        bdbaseirtot = bdbaseirtot - bdbaseir;
      END
    ELSE
      BEGIN
        bdbaseir = bdbaseir + bdvalordep + bdvalorinss;
      END

    bdref = SUBSTRING(CAST(BDDATAPAGSERV AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(BDDATAPAGSERV AS VARCHAR(10)) FROM 6 FOR 2);

    wwhere = 'select first 1 BDNOMETER from TTERCEIRO_REF where BDCODTER = '||BDCODTER||' and BDREFEMP <= '||prreffim||' order by BDREFEMP DESC';
    EXECUTE STATEMENT wwhere INTO :BDNOMTER;

    SUSPEND;
  END
END
^

/* empty dependent procedure body */
/* Clear: SP_CRIA_DADOSCALC_BAIXA for: VRHF_SP_DADOS_BAIXA_CALCULO */
ALTER PROCEDURE SP_CRIA_DADOSCALC_BAIXA AS
 BEGIN EXIT; END
^

/* Alter (VRHF_SP_DADOS_BAIXA_CALCULO) */
ALTER PROCEDURE VRHF_SP_DADOS_BAIXA_CALCULO(PRCODEMP INTEGER,
PRCODTER INTEGER,
PRCODSERV INTEGER,
PRCODCOL INTEGER,
PRTIPOCALC INTEGER,
PRREFERENCIA INTEGER,
PRDATA DATE,
PRREFCOMP INTEGER,
PRINIPERAQUI DATE,
PRCODFER INTEGER,
PRLIQUIDO NUMERIC(18,6),
PRINIGOZO DATE,
PRREFABONO INTEGER)
 AS
DECLARE VARIABLE WEXISTE INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
BEGIN
/*  wexiste = 0;

  prliquido = cast(prliquido as numeric(18,2));

  /* Procedure Text */
/*  if (prtipocalc = 1) then -- Servico
     begin
       /* busca a data do servico */
/*       select x.bddataserv from vrh_base_tservterc x where x.bdcodter = :prcodter and x.bdcodemp = :prcodemp and x.bdcodserv = :prcodserv into prdata;

       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodter = : prcodter and
               x.bdcodserv = :prcodserv and
               x.bdtipocalc = 1
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end
  else
  if (prtipocalc = 7) then /* folha normal tomador */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
          where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and x.bdreferencia = :prreferencia and
                x.bdtipocalc = 7
         into wexiste,wchave;
     end
  else
  if (prtipocalc = 9) then /* folha complementar tomador */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and x.bddata = :prdata and
               x.bdtipocalc = 9
         into wexiste,wchave;
     end
  else
  if (prtipocalc in (2,3,6)) then /* folha normal / 13? / Adiantamento 13? */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and
               x.bdtipocalc = :prtipocalc
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end
  else
  if (prtipocalc in (5,8)) then /* folha complementar / complemento 13? */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and x.bdrefcomp = :prrefcomp and
               x.bdtipocalc = :prtipocalc
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end
  else
  if (prtipocalc = 4) then /* adiantamento salarial */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and x.bddata = :prdata and
               x.bdtipocalc = 4
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end
  else
  if (prtipocalc = 10) then /* f?rias */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and x.bdiniperaqui = :priniperaqui and
               x.bdcodfer = :prcodfer and
               x.bdtipocalc = 10
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end


--  if (prliquido <> 0) then
     begin
       if (wexiste = 0) then
          begin
            insert into vrhf_emp_tdadoscalc_baixa(BDCHAVE,BDCODTER,BDCODEMP,BDCODSERV,BDCODCOL,BDTIPOCALC,BDREFERENCIA,BDDATA,
                                                  BDREFCOMP,BDINIPERAQUI,BDCODFER,BDLIQUIDO,BDINIGOZO,BDREFABONO) values(
                                                  null,:prcodter,:prcodemp,:prcodserv,:prcodcol,:prtipocalc,:prreferencia,:prdata,
                                                  :prrefcomp,:priniperaqui,:prcodfer,coalesce(:prliquido,0),:prinigozo,:prrefabono);
          end
       else
          begin
            update vrhf_emp_tdadoscalc_baixa x set x.bdliquido = x.bdliquido + coalesce(:prliquido,0)
                   where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
          end
     end*/
END
^

/* Alter (VRHF_SP_DADOS_CALC_GPS) */
ALTER PROCEDURE VRHF_SP_DADOS_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENAGPS INTEGER)
 RETURNS(BDTIPO INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSCODEMP INTEGER;
DECLARE VARIABLE WEXISTE INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WSALVATIPO INTEGER;
DECLARE VARIABLE WTIPOANT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCODTOMADOR INTEGER;
DECLARE VARIABLE WCODTOMADORANT INTEGER;
DECLARE VARIABLE WEMPRESAANT INTEGER;
DECLARE VARIABLE WBDTOTSEG NUMERIC(15,6);
DECLARE VARIABLE WBDTOTBASE NUMERIC(15,6);
DECLARE VARIABLE WSUMTOTSEG NUMERIC(15,6);
DECLARE VARIABLE WSUMTOTBASE NUMERIC(15,6);
DECLARE VARIABLE WBDSEGFUN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN NUMERIC(15,6);
DECLARE VARIABLE WBDPERCFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCFUN NUMERIC(15,6);
DECLARE VARIABLE WBDSEGPRO NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO NUMERIC(15,6);
DECLARE VARIABLE WBDPERCPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCPRO NUMERIC(15,6);
DECLARE VARIABLE WBDSEGAUT NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT NUMERIC(15,6);
DECLARE VARIABLE WBDPERCAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCAUT NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO NUMERIC(15,6);
DECLARE VARIABLE WBDVALORRATAPO NUMERIC(15,6);
DECLARE VARIABLE WSUMBASERATAPO NUMERIC(15,6);
DECLARE VARIABLE WSUMVALORRATAPO NUMERIC(15,6);
DECLARE VARIABLE WBDSALFAM NUMERIC(15,6);
DECLARE VARIABLE WBDSALMATERNIDADE NUMERIC(15,6);
DECLARE VARIABLE WSUMSALFAM NUMERIC(15,6);
DECLARE VARIABLE WSUMSALMATERNIDADE NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS NUMERIC(15,6);
DECLARE VARIABLE WBDPERCFPAS NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEFPAS NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCFPAS NUMERIC(15,6);
DECLARE VARIABLE WBDPERCRAT NUMERIC(15,6);
DECLARE VARIABLE WBDVALOUTENTIDADE NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCRAT NUMERIC(15,6);
DECLARE VARIABLE WSUMVALOUTENTIDADE NUMERIC(15,6);
DECLARE VARIABLE WBDSIMPLESGPS INTEGER;
DECLARE VARIABLE WBDCODENQFED INTEGER;
DECLARE VARIABLE WBDDESCENQFED VARCHAR(10);
DECLARE VARIABLE WSUMSIMPLESGPS INTEGER;
DECLARE VARIABLE WSUMCODENQFED INTEGER;
DECLARE VARIABLE WSUMDESCENQFED VARCHAR(10);
DECLARE VARIABLE WGERAGUIA INTEGER;
DECLARE VARIABLE WEMISSAO INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCODTOMADORAUX INTEGER;
DECLARE VARIABLE WBDBASEFUNFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOC13 NUMERIC(15,6);
BEGIN
  /* prtipogps
     0 = normal
     1 = folha complementar
     2 = 13 sal
     3 = comp. 13 sal
     4 = pr?via de rescis?o
  */
  /* prtipoemissao
     0 = por cc
     1 = agrupado
     3 = por tomador (utilizado na SEFIP)
  */
  /* prapenasgps
     0 = apenas gps
     1 = historicos compensacoes/nf/gps
  */
  /* PRPUXAFILIAIS
     0 = Nao
     1 = Sim
  */
  /*
    BDTIPOREG
    0 = GPS
    1 = nf
    2 = gps comp
    3 = compensacao
    4 = historico comp
    5 = historico nf
    6 = historico gps
    7 = registro acumulados
    8 = contabilizacao
  */

  IF (prtipogps IS NULL) THEN
     prtipogps = 0;

  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     BEGIN
       prcodemp = ''''||prcodemp||'''';
     END

  IF (prcodcol IS NULL) THEN
     prcodcol = 'null';
  ELSE
     prcodcol = ''''||prcodcol||'''';

  IF (prcodaut IS NULL) THEN
     prcodaut = 'null';
  ELSE
     prcodaut = ''''||prcodaut||'''';

  IF (prtipocol IS NULL) THEN
     prtipocol = 0;

  IF (pranomes IS NULL) THEN
     pranomes = 0;

  wemissao = prtipoemissao;
  prtipoemissao = 0;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  IF (prapenagps IS NULL) THEN
     prapenagps = 1;

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  wsql = 'SELECT bdcodemp, bdtipo, bdreffn, bdrefpag, bdcodcentro, bdcodtpcc, bdtotSeg, bdtotBase, bdSEGFUN, bdBaseFun, bdPercFun, bdSegPro, bdBasePro, bdPercPro, bdSegAut, bdBaseAut,'||
         'bdPercAut, bdbaseratapo, bdvalorratapo, bdsalfam, bdsalmaternidade, bdbasefpas, bdpercfpas, bdpercrat, BDVALOUTENTIDADE, bddescenqfed, bdsimplesgps,'||
         'bdcodenqfed, bdcodtomador, bdcodcol, bdcodter, ';

  wsql =   wsql||'BDBASEFUNFN,    BDBASEFUNFC,    BDBASEFUNFERFN,    BDBASEFUNFERFC,    BDBASEFUN13RFN,    BDBASEFUN13RFC,    BDBASEFUN13,    BDBASEFUNC13,'||
                 'BDBASEPROFN,    BDBASEPROFC,    BDBASEPROFERFN,    BDBASEPROFERFC,    BDBASEPRO13RFN,    BDBASEPRO13RFC,    BDBASEPRO13,    BDBASEPROC13,'||
                 'BDBASEAUTFN,    BDBASEAUTFC,    BDBASEAUTFERFN,    BDBASEAUTFERFC,    BDBASEAUT13RFN,    BDBASEAUT13RFC,    BDBASEAUT13,    BDBASEAUTC13,'||
                 'BDBASEFPASFN,   BDBASEFPASFC,   BDBASEFPASFERFN,   BDBASEFPASFERFC,   BDBASEFPAS13RFN,   BDBASEFPAS13RFC,   BDBASEFPAS13,   BDBASEFPASC13,'||
                 'BDBASERATAPOFN, BDBASERATAPOFC, BDBASERATAPOFERFN, BDBASERATAPOFERFC, BDBASERATAPO13RFN, BDBASERATAPO13RFC, BDBASERATAPO13, BDBASERATAPOC13';

  wsql = wsql||' FROM VRHF_SP_DADOS_IND_CALC_GPS('||prcodemp||','||prcodcol||','||prcodaut||','||prtipocol||','||pranomes||','||pranomespag||',0,'||prtipogps||','||prpuxafiliais||','||prapenagps||')';

  IF (prapenagps = 0) THEN
     wsql = wsql||' where bdtipo <> 2';

  wcodtomadorant = -1;
  wsumtotSeg = 0;
  wsumtotBase = 0;
  wSUMSEGFUN = 0;
  wSUMBaseFun = 0;
  wSUMPercFun = 0;
  wSumSegPro = 0;
  wSumBasePro = 0;
  wSumPercPro = 0;
  wSumSegAut = 0;
  wSumBaseAut = 0;
  wSumPercAut = 0;
  wSumbaseratapo = 0;
  wSumvalorratapo = 0;
  wSumsalfam = 0;
  wSumsalmaternidade = 0;
  wSumbasefpas = 0;
  wSumpercfpas = 0;
  wSumpercrat = 0;
  wSumVALOUTENTIDADE = 0;
  wSumdescenqfed = NULL;
  wSumsimplesgps = NULL;
  wSumcodenqfed = NULL;

  wsumBDBASEFUNFN = 0;
  wsumBDBASEFUNFC = 0;
  wsumBDBASEFUNFERFN = 0;
  wsumBDBASEFUNFERFC = 0;
  wsumBDBASEFUN13RFN = 0;
  wsumBDBASEFUN13RFC = 0;
  wsumBDBASEFUN13 = 0;
  wsumBDBASEFUNC13 = 0;
  wsumBDBASEPROFN = 0;
  wsumBDBASEPROFC = 0;
  wsumBDBASEPROFERFN = 0;
  wsumBDBASEPROFERFC = 0;
  wsumBDBASEPRO13RFN = 0;
  wsumBDBASEPRO13RFC = 0;
  wsumBDBASEPRO13 = 0;
  wsumBDBASEPROC13 = 0;
  wsumBDBASEAUTFN = 0;
  wsumBDBASEAUTFC = 0;
  wsumBDBASEAUTFERFN = 0;
  wsumBDBASEAUTFERFC = 0;
  wsumBDBASEAUT13RFN = 0;
  wsumBDBASEAUT13RFC = 0;
  wsumBDBASEAUT13 = 0;
  wsumBDBASEAUTC13 = 0;
  wsumBDBASEFPASFN = 0;
  wsumBDBASEFPASFC = 0;
  wsumBDBASEFPASFERFN = 0;
  wsumBDBASEFPASFERFC = 0;
  wsumBDBASEFPAS13RFN = 0;
  wsumBDBASEFPAS13RFC = 0;
  wsumBDBASEFPAS13 = 0;
  wsumBDBASEFPASC13 = 0;
  wsumBDBASERATAPOFN = 0;
  wsumBDBASERATAPOFC = 0;
  wsumBDBASERATAPOFERFN = 0;
  wsumBDBASERATAPOFERFC = 0;
  wsumBDBASERATAPO13RFN = 0;
  wsumBDBASERATAPO13RFC = 0;
  wsumBDBASERATAPO13 = 0;
  wsumBDBASERATAPOC13 = 0;

  bdtipo = 0;
  WEXISTE = 0;
  FOR EXECUTE STATEMENT wsql INTO
      : bdcodemp, --bdcodemp,
      : bdtipo, -- bdtipo,
      : bdreffn, -- bdreffn,
      : bdrefpag, --bdrefpag,
      : bdcodcentro,
      : bdcodtpcc, -- bdcodtpcc,

      /*totais*/
      : wbdtotSeg, -- bdtotSeg,
      : wbdtotBase, -- bdtotBase,

      /*colaboradores*/
      : wbdSEGFUN, -- bdSEGFUN,
      : wbdBaseFun, -- bdBaseFun,
      : wbdPercFun, -- bdPercFun,

       /*prolaboristas*/
      : wbdSegPro, -- bdSegPro,
      : wbdBasePro, -- bdBasePro,
      : wbdPercPro, -- bdPercPro,

      /*autonomos*/
      : wbdSegAut, --bdSegAut,
      : wbdBaseAut, -- bdBaseAut
      : wbdPercAut, -- bdPercAut,

      /* rat aposentadoria*/
      : wbdbaseratapo, -- bdbaseratapo,
      : wbdvalorratapo, -- bdvalorratapo,

      : wbdsalfam, -- bdsalfam,
      : wbdsalmaternidade, -- bdsalmaternidade,

      /* base fpas*/
      : wbdbasefpas, -- bdbasefpas,
      : wbdpercfpas, -- bdpercfpas,

      /* rat */
      : wbdpercrat, -- bdpercrat,
      : wBDVALOUTENTIDADE, -- BDVALOUTENTIDADE,

      : wbddescenqfed, --bddescenqfed,
      : wbdsimplesgps, -- bdsimplesgps,
      : wbdcodenqfed, -- bdcodenqfed,
      : bdcodtomador, -- bdcodtomador

      : wcodcol, -- bdcodcol
      : wcodter, -- bdcodter

      : wBDBASEFUNFN,
      : wBDBASEFUNFC,
      : wBDBASEFUNFERFN,
      : wBDBASEFUNFERFC,
      : wBDBASEFUN13RFN,
      : wBDBASEFUN13RFC,
      : wBDBASEFUN13,
      : wBDBASEFUNC13,
      : wBDBASEPROFN,
      : wBDBASEPROFC,
      : wBDBASEPROFERFN,
      : wBDBASEPROFERFC,
      : wBDBASEPRO13RFN,
      : wBDBASEPRO13RFC,
      : wBDBASEPRO13,
      : wBDBASEPROC13,
      : wBDBASEAUTFN,
      : wBDBASEAUTFC,
      : wBDBASEAUTFERFN,
      : wBDBASEAUTFERFC,
      : wBDBASEAUT13RFN,
      : wBDBASEAUT13RFC,
      : wBDBASEAUT13,
      : wBDBASEAUTC13,
      : wBDBASEFPASFN,
      : wBDBASEFPASFC,
      : wBDBASEFPASFERFN,
      : wBDBASEFPASFERFC,
      : wBDBASEFPAS13RFN,
      : wBDBASEFPAS13RFC,
      : wBDBASEFPAS13,
      : wBDBASEFPASC13,
      : wBDBASERATAPOFN,
      : wBDBASERATAPOFC,
      : wBDBASERATAPOFERFN,
      : wBDBASERATAPOFERFC,
      : wBDBASERATAPO13RFN,
      : wBDBASERATAPO13RFC,
      : wBDBASERATAPO13,
      : wBDBASERATAPOC13
      DO
  BEGIN
    WEXISTE = 1;
    wsalvatipo = bdtipo;
    bdcodter = NULL;
    bdcodcol = NULL;
    IF ((wsalvatipo <> 2) OR (wtipoant <> 2)) THEN
       BEGIN
         wcodtomador = bdcodtomador;
         IF (wcodtomador IS NULL) THEN
            wcodtomador = 0;
     
         wgeraguia = 0;
         IF ((wemissao IS NULL) OR (wemissao = 1)) THEN
            BEGIN
              IF ((wempresaant <> bdcodemp) AND (wcodtomadorant <> -1)) THEN
                 wgeraguia = 1;
            END
         ELSE
            BEGIN
              IF (((wempresaant <> bdcodemp) OR (wcodtomadorant <> wcodtomador)) AND (wcodtomadorant <> -1)) THEN
                 wgeraguia = 1;
            END
     
         IF (wgeraguia = 1) THEN
            BEGIN
              bdtipo = 1;
              wscodemp = bdcodemp;
              bdcodemp = wempresaant;
              wcodtomadoraux = wcodtomador;
              wcodtomador = bdcodtpcc;
              IF (wcodtomadorant = 0) THEN
                 bdcodtpcc = NULL;
              ELSE
                 bdcodtpcc = wcodtomadorant;

              IF (wcodtomadorant = 0) THEN
                 bdcodtomador = NULL;
              ELSE
                 bdcodtomador = wcodtomadorant;
     
              bdtotSeg = wsumtotSeg;
              bdtotBase = wsumtotBase;
              bdSEGFUN = wSUMSEGFUN;
              bdBaseFun = wSUMBaseFun;
              bdPercFun = wSUMPercFun;
              bdSegPro = wSumSegPro;
              bdBasePro = wSumBasePro;
              bdPercPro = wSumPercPro;
              bdSegAut = wSumSegAut;
              bdBaseAut = wSumBaseAut;
              bdPercAut = wSumPercAut;
              bdbaseratapo = wSumbaseratapo;
              bdvalorratapo = wSumvalorratapo;
              bdsalfam = wSumsalfam;
              bdsalmaternidade = wSumsalmaternidade;
              bdbasefpas = wSumbasefpas;
              bdpercfpas = wSumpercfpas;
              bdpercrat = wSumpercrat;
              BDVALOUTENTIDADE = wSumVALOUTENTIDADE;
              bddescenqfed = wSumdescenqfed;
              bdsimplesgps = wSumsimplesgps;
              bdcodenqfed = wSumcodenqfed;
              bdcodcol = NULL;

              BDBASEFUNFN = wsumBDBASEFUNFN;
              BDBASEFUNFC = wsumBDBASEFUNFC;
              BDBASEFUNFERFN = wsumBDBASEFUNFERFN;
              BDBASEFUNFERFC = wsumBDBASEFUNFERFC;
              BDBASEFUN13RFN = wsumBDBASEFUN13RFN;
              BDBASEFUN13RFC = wsumBDBASEFUN13RFC;
              BDBASEFUN13 = wsumBDBASEFUN13;
              BDBASEFUNC13 = wsumBDBASEFUNC13;
              BDBASEPROFN = wsumBDBASEPROFN;
              BDBASEPROFC = wsumBDBASEPROFC;
              BDBASEPROFERFN = wsumBDBASEPROFERFN;
              BDBASEPROFERFC = wsumBDBASEPROFERFC;
              BDBASEPRO13RFN = wsumBDBASEPRO13RFN;
              BDBASEPRO13RFC = wsumBDBASEPRO13RFC;
              BDBASEPRO13 = wsumBDBASEPRO13;
              BDBASEPROC13 = wsumBDBASEPROC13;
              BDBASEAUTFN = wsumBDBASEAUTFN;
              BDBASEAUTFC = wsumBDBASEAUTFC;
              BDBASEAUTFERFN = wsumBDBASEAUTFERFN;
              BDBASEAUTFERFC = wsumBDBASEAUTFERFC;
              BDBASEAUT13RFN = wsumBDBASEAUT13RFN;
              BDBASEAUT13RFC = wsumBDBASEAUT13RFC;
              BDBASEAUT13 = wsumBDBASEAUT13;
              BDBASEAUTC13 = wsumBDBASEAUTC13;
              BDBASEFPASFN = wsumBDBASEFPASFN;
              BDBASEFPASFC = wsumBDBASEFPASFC;
              BDBASEFPASFERFN = wsumBDBASEFPASFERFN;
              BDBASEFPASFERFC = wsumBDBASEFPASFERFC;
              BDBASEFPAS13RFN = wsumBDBASEFPAS13RFN;
              BDBASEFPAS13RFC = wsumBDBASEFPAS13RFC;
              BDBASEFPAS13 = wsumBDBASEFPAS13;
              BDBASEFPASC13 = wsumBDBASEFPASC13;
              BDBASERATAPOFN = wsumBDBASERATAPOFN;
              BDBASERATAPOFC = wsumBDBASERATAPOFC;
              BDBASERATAPOFERFN = wsumBDBASERATAPOFERFN;
              BDBASERATAPOFERFC = wsumBDBASERATAPOFERFC;
              BDBASERATAPO13RFN = wsumBDBASERATAPO13RFN;
              BDBASERATAPO13RFC = wsumBDBASERATAPO13RFC;
              BDBASERATAPO13 = wsumBDBASERATAPO13;
              BDBASERATAPOC13 = wsumBDBASERATAPOC13;

              SUSPEND;

              bdcodemp = wscodemp;

              bdcodtpcc = wcodtomador;
              wsumtotbase = 0;
              wsumtotseg = 0;
              wSUMSEGFUN = 0;
              wSUMBaseFun = 0;
              wSUMPercFun = 0;
              wSumSegPro = 0;
              wSumBasePro = 0;
              wSumPercPro = 0;
              wSumSegAut = 0;
              wSumBaseAut = 0;
              wSumPercAut = 0;
              wSumbaseratapo = 0;
              wSumvalorratapo = 0;
              wSumsalfam = 0;
              wSumsalmaternidade = 0;
              wSumbasefpas = 0;
              wSumpercfpas = 0;
              wSumpercrat = 0;
              wSumVALOUTENTIDADE = 0;
              wSumdescenqfed = NULL;
              wSumsimplesgps = NULL;
              wSumcodenqfed = NULL;

              wsumBDBASEFUNFN = 0;
              wsumBDBASEFUNFC = 0;
              wsumBDBASEFUNFERFN = 0;
              wsumBDBASEFUNFERFC = 0;
              wsumBDBASEFUN13RFN = 0;
              wsumBDBASEFUN13RFC = 0;
              wsumBDBASEFUN13 = 0;
              wsumBDBASEFUNC13 = 0;
              wsumBDBASEPROFN = 0;
              wsumBDBASEPROFC = 0;
              wsumBDBASEPROFERFN = 0;
              wsumBDBASEPROFERFC = 0;
              wsumBDBASEPRO13RFN = 0;
              wsumBDBASEPRO13RFC = 0;
              wsumBDBASEPRO13 = 0;
              wsumBDBASEPROC13 = 0;
              wsumBDBASEAUTFN = 0;
              wsumBDBASEAUTFC = 0;
              wsumBDBASEAUTFERFN = 0;
              wsumBDBASEAUTFERFC = 0;
              wsumBDBASEAUT13RFN = 0;
              wsumBDBASEAUT13RFC = 0;
              wsumBDBASEAUT13 = 0;
              wsumBDBASEAUTC13 = 0;
              wsumBDBASEFPASFN = 0;
              wsumBDBASEFPASFC = 0;
              wsumBDBASEFPASFERFN = 0;
              wsumBDBASEFPASFERFC = 0;
              wsumBDBASEFPAS13RFN = 0;
              wsumBDBASEFPAS13RFC = 0;
              wsumBDBASEFPAS13 = 0;
              wsumBDBASEFPASC13 = 0;
              wsumBDBASERATAPOFN = 0;
              wsumBDBASERATAPOFC = 0;
              wsumBDBASERATAPOFERFN = 0;
              wsumBDBASERATAPOFERFC = 0;
              wsumBDBASERATAPO13RFN = 0;
              wsumBDBASERATAPO13RFC = 0;
              wsumBDBASERATAPO13 = 0;
              wsumBDBASERATAPOC13 = 0;
            END
     
         IF (wsalvatipo <> 2) THEN
            BEGIN
              wsumtotbase = wsumtotbase + wbdtotBase;
              wsumtotseg = wsumtotseg + wbdtotseg;
              wSUMSEGFUN = wSUMSEGFUN + wbdSEGFUN;
              wSUMBaseFun = wSUMBaseFun + wbdBaseFun;
              wSUMPercFun = wbdPercFun;
              wSumSegPro = wSumSegPro + wbdSegPro;
              wSumBasePro = wSumBasePro + wbdBasePro;
              wSumPercPro = wbdPercPro;
              wSumSegAut = wSumSegAut + wbdSegAut;
              wSumBaseAut = wSumBaseAut + wbdBaseAut;
              wSumPercAut = wbdPercAut;
              wSumbaseratapo = wSumbaseratapo + wbdbaseratapo;
              wSumvalorratapo = wSumvalorratapo + wbdvalorratapo;
              wSumsalfam = wSumsalfam + wbdsalfam;
              wSumsalmaternidade = wSumsalmaternidade + wbdsalmaternidade;
              wSumbasefpas = wSumbasefpas + wbdbasefpas;
              wSumpercfpas = wbdpercfpas;
              wSumpercrat = wbdpercrat;
              wsumvaloutentidade = wsumvaloutentidade + wbdvaloutentidade;
              wsumdescenqfed = wbddescenqfed;
              wsumsimplesgps = wbdsimplesgps;
              wsumcodenqfed = wbdcodenqfed;
          
              wSumBDBASEFUNFN = wSumBDBASEFUNFN + wBDBASEFUNFN;
              wSumBDBASEFUNFC = wSumBDBASEFUNFC + wBDBASEFUNFC;
              wSumBDBASEFUNFERFN = wSumBDBASEFUNFERFN + wBDBASEFUNFERFN;
              wSumBDBASEFUNFERFC = wSumBDBASEFUNFERFC + wBDBASEFUNFERFC;
              wSumBDBASEFUN13RFN = wSumBDBASEFUN13RFN + wBDBASEFUN13RFN;
              wSumBDBASEFUN13RFC = wSumBDBASEFUN13RFC + wBDBASEFUN13RFC;
              wSumBDBASEFUN13 = wSumBDBASEFUN13 + wBDBASEFUN13;
              wSumBDBASEFUNC13 = wSumBDBASEFUNC13 + wBDBASEFUNC13;
              wSumBDBASEPROFN = wSumBDBASEPROFN + wBDBASEPROFN;
              wSumBDBASEPROFC = wSumBDBASEPROFC + wBDBASEPROFC;
              wSumBDBASEPROFERFN = wSumBDBASEPROFERFN + wBDBASEPROFERFN;
              wSumBDBASEPROFERFC = wSumBDBASEPROFERFC + wBDBASEPROFERFC;
              wSumBDBASEPRO13RFN = wSumBDBASEPRO13RFN + wBDBASEPRO13RFN;
              wSumBDBASEPRO13RFC = wSumBDBASEPRO13RFC + wBDBASEPRO13RFC;
              wSumBDBASEPRO13 = wSumBDBASEPRO13 + wBDBASEPRO13;
              wSumBDBASEPROC13 = wSumBDBASEPROC13 + wBDBASEPROC13;
              wSumBDBASEAUTFN = wSumBDBASEAUTFN + wBDBASEAUTFN;
              wSumBDBASEAUTFC = wSumBDBASEAUTFC + wBDBASEAUTFC;
              wSumBDBASEAUTFERFN = wSumBDBASEAUTFERFN + wBDBASEAUTFERFN;
              wSumBDBASEAUTFERFC = wSumBDBASEAUTFERFC + wBDBASEAUTFERFC;
              wSumBDBASEAUT13RFN = wSumBDBASEAUT13RFN + wBDBASEAUT13RFN;
              wSumBDBASEAUT13RFC = wSumBDBASEAUT13RFC + wBDBASEAUT13RFC;
              wSumBDBASEAUT13 = wSumBDBASEAUT13 + wBDBASEAUT13;
              wSumBDBASEAUTC13 = wSumBDBASEAUTC13 + wBDBASEAUTC13;
              wSumBDBASEFPASFN = wSumBDBASEFPASFN + wBDBASEFPASFN;
              wSumBDBASEFPASFC = wSumBDBASEFPASFC + wBDBASEFPASFC;
              wSumBDBASEFPASFERFN = wSumBDBASEFPASFERFN + wBDBASEFPASFERFN;
              wSumBDBASEFPASFERFC = wSumBDBASEFPASFERFC + wBDBASEFPASFERFC;
              wSumBDBASEFPAS13RFN = wSumBDBASEFPAS13RFN + wBDBASEFPAS13RFN;
              wSumBDBASEFPAS13RFC = wSumBDBASEFPAS13RFC + wBDBASEFPAS13RFC;
              wSumBDBASEFPAS13 = wSumBDBASEFPAS13 + wBDBASEFPAS13;
              wSumBDBASEFPASC13 = wSumBDBASEFPASC13 + wBDBASEFPASC13;
              wSumBDBASERATAPOFN = wSumBDBASERATAPOFN + wBDBASERATAPOFN;
              wSumBDBASERATAPOFC = wSumBDBASERATAPOFC + wBDBASERATAPOFC;
              wSumBDBASERATAPOFERFN = wSumBDBASERATAPOFERFN + wBDBASERATAPOFERFN;
              wSumBDBASERATAPOFERFC = wSumBDBASERATAPOFERFC + wBDBASERATAPOFERFC;
              wSumBDBASERATAPO13RFN = wSumBDBASERATAPO13RFN + wBDBASERATAPO13RFN;
              wSumBDBASERATAPO13RFC = wSumBDBASERATAPO13RFC + wBDBASERATAPO13RFC;
              wSumBDBASERATAPO13 = wSumBDBASERATAPO13 + wBDBASERATAPO13;
              wSumBDBASERATAPOC13 = wSumBDBASERATAPOC13 + wBDBASERATAPOC13;

              bdtotSeg = wbdtotSeg;
              bdtotBase = wbdtotBase;
              bdSEGFUN = wbdSEGFUN;
              bdBaseFun = wbdBaseFun;
              bdPercFun = wbdPercFun;
              bdSegPro = wbdSegPro;
              bdBasePro = wbdBasePro;
              bdPercPro = wbdPercPro;
              bdSegAut = wbdSegAut;
              bdBaseAut = wbdBaseAut;
              bdPercAut = wbdPercAut;
              bdbaseratapo = wbdbaseratapo;
              bdvalorratapo = wbdvalorratapo;
              bdsalfam = wbdsalfam;
              bdsalmaternidade = wbdsalmaternidade;
              bdbasefpas = wbdbasefpas;
              bdpercfpas = wbdpercfpas;
              bdpercrat = wbdpercrat;
              bdvaloutentidade = wbdvaloutentidade;
              bddescenqfed = wbddescenqfed;
              bdsimplesgps = wbdsimplesgps;
              bdcodenqfed = wbdcodenqfed;
          
              BDBASEFUNFN = wBDBASEFUNFN;
              BDBASEFUNFC = wBDBASEFUNFC;
              BDBASEFUNFERFN = wBDBASEFUNFERFN;
              BDBASEFUNFERFC = wBDBASEFUNFERFC;
              BDBASEFUN13RFN = wBDBASEFUN13RFN;
              BDBASEFUN13RFC = wBDBASEFUN13RFC;
              BDBASEFUN13 = wBDBASEFUN13;
              BDBASEFUNC13 = wBDBASEFUNC13;
              BDBASEPROFN = wBDBASEPROFN;
              BDBASEPROFC = wBDBASEPROFC;
              BDBASEPROFERFN = wBDBASEPROFERFN;
              BDBASEPROFERFC = wBDBASEPROFERFC;
              BDBASEPRO13RFN = wBDBASEPRO13RFN;
              BDBASEPRO13RFC = wBDBASEPRO13RFC;
              BDBASEPRO13 = wBDBASEPRO13;
              BDBASEPROC13 = wBDBASEPROC13;
              BDBASEAUTFN = wBDBASEAUTFN;
              BDBASEAUTFC = wBDBASEAUTFC;
              BDBASEAUTFERFN = wBDBASEAUTFERFN;
              BDBASEAUTFERFC = wBDBASEAUTFERFC;
              BDBASEAUT13RFN = wBDBASEAUT13RFN;
              BDBASEAUT13RFC = wBDBASEAUT13RFC;
              BDBASEAUT13 = wBDBASEAUT13;
              BDBASEAUTC13 = wBDBASEAUTC13;
              BDBASEFPASFN = wBDBASEFPASFN;
              BDBASEFPASFC = wBDBASEFPASFC;
              BDBASEFPASFERFN = wBDBASEFPASFERFN;
              BDBASEFPASFERFC = wBDBASEFPASFERFC;
              BDBASEFPAS13RFN = wBDBASEFPAS13RFN;
              BDBASEFPAS13RFC = wBDBASEFPAS13RFC;
              BDBASEFPAS13 = wBDBASEFPAS13;
              BDBASEFPASC13 = wBDBASEFPASC13;
              BDBASERATAPOFN = wBDBASERATAPOFN;
              BDBASERATAPOFC = wBDBASERATAPOFC;
              BDBASERATAPOFERFN = wBDBASERATAPOFERFN;
              BDBASERATAPOFERFC = wBDBASERATAPOFERFC;
              BDBASERATAPO13RFN = wBDBASERATAPO13RFN;
              BDBASERATAPO13RFC = wBDBASERATAPO13RFC;
              BDBASERATAPO13 = wBDBASERATAPO13;
              BDBASERATAPOC13 = wBDBASERATAPOC13;

              IF ((wcodtomador = 0) OR ((wemissao IS NULL) OR (wemissao = 1))) THEN
                bdcodtomador = NULL;
              ELSE
                bdcodtomador = wcodtomador;
              bdtipo = 0;
              bdcodcol = NULL;
          
              IF (prapenagps = 1) THEN
                SUSPEND;
            END
       END

     IF (wsalvatipo = 2) THEN
       BEGIN
         bdtipo = 2;
         wcodtomador = wcodtomadoraux;
         bdtotSeg = wbdtotSeg;
         bdtotBase = wbdtotBase;
         bdSEGFUN = wbdSEGFUN;
         bdBaseFun = wbdBaseFun;
         bdPercFun = wbdPercFun;
         bdSegPro = wbdSegPro;
         bdBasePro = wbdBasePro;
         bdPercPro = wbdPercPro;
         bdSegAut = wbdSegAut;
         bdBaseAut = wbdBaseAut;
         bdPercAut = wbdPercAut;
         bdbaseratapo = wbdbaseratapo;
         bdvalorratapo = wbdvalorratapo;
         bdsalfam = wbdsalfam;
         bdsalmaternidade = wbdsalmaternidade;
         bdbasefpas = wbdbasefpas;
         bdpercfpas = wbdpercfpas;
         bdpercrat = wbdpercrat;
         bdvaloutentidade = wbdvaloutentidade;
         bddescenqfed = wbddescenqfed;
         bdsimplesgps = wbdsimplesgps;
         bdcodenqfed = wbdcodenqfed;
     
         IF ((wcodtomador = 0) OR ((wemissao IS NULL) OR (wemissao = 1))) THEN
           bdcodtomador = NULL;
         ELSE
           bdcodtomador = wcodtomador;

         bdcodcol = wcodcol;
         bdcodter = wcodter;

         BDBASEFUNFN = wBDBASEFUNFN;
         BDBASEFUNFC = wBDBASEFUNFC;
         BDBASEFUNFERFN = wBDBASEFUNFERFN;
         BDBASEFUNFERFC = wBDBASEFUNFERFC;
         BDBASEFUN13RFN = wBDBASEFUN13RFN;
         BDBASEFUN13RFC = wBDBASEFUN13RFC;
         BDBASEFUN13 = wBDBASEFUN13;
         BDBASEFUNC13 = wBDBASEFUNC13;
         BDBASEPROFN = wBDBASEPROFN;
         BDBASEPROFC = wBDBASEPROFC;
         BDBASEPROFERFN = wBDBASEPROFERFN;
         BDBASEPROFERFC = wBDBASEPROFERFC;
         BDBASEPRO13RFN = wBDBASEPRO13RFN;
         BDBASEPRO13RFC = wBDBASEPRO13RFC;
         BDBASEPRO13 = wBDBASEPRO13;
         BDBASEPROC13 = wBDBASEPROC13;
         BDBASEAUTFN = wBDBASEAUTFN;
         BDBASEAUTFC = wBDBASEAUTFC;
         BDBASEAUTFERFN = wBDBASEAUTFERFN;
         BDBASEAUTFERFC = wBDBASEAUTFERFC;
         BDBASEAUT13RFN = wBDBASEAUT13RFN;
         BDBASEAUT13RFC = wBDBASEAUT13RFC;
         BDBASEAUT13 = wBDBASEAUT13;
         BDBASEAUTC13 = wBDBASEAUTC13;
         BDBASEFPASFN = wBDBASEFPASFN;
         BDBASEFPASFC = wBDBASEFPASFC;
         BDBASEFPASFERFN = wBDBASEFPASFERFN;
         BDBASEFPASFERFC = wBDBASEFPASFERFC;
         BDBASEFPAS13RFN = wBDBASEFPAS13RFN;
         BDBASEFPAS13RFC = wBDBASEFPAS13RFC;
         BDBASEFPAS13 = wBDBASEFPAS13;
         BDBASEFPASC13 = wBDBASEFPASC13;
         BDBASERATAPOFN = wBDBASERATAPOFN;
         BDBASERATAPOFC = wBDBASERATAPOFC;
         BDBASERATAPOFERFN = wBDBASERATAPOFERFN;
         BDBASERATAPOFERFC = wBDBASERATAPOFERFC;
         BDBASERATAPO13RFN = wBDBASERATAPO13RFN;
         BDBASERATAPO13RFC = wBDBASERATAPO13RFC;
         BDBASERATAPO13 = wBDBASERATAPO13;
         BDBASERATAPOC13 = wBDBASERATAPOC13;

         SUSPEND;
       END

     wcodtomadorant = wcodtomador;
     wempresaant = bdcodemp;
     wtipoant = bdtipo;
   END
     
   bdtipo = 1;
   IF (wcodtomador = 0) THEN
      bdcodtpcc = NULL;
   ELSE
      bdcodtpcc = wcodtomador;
 
   IF ((wcodtomador = 0) OR ((wemissao IS NULL) OR (wemissao = 1))) THEN
     bdcodtomador = NULL;
   ELSE
     bdcodtomador = wcodtomador;
 
   bdtotSeg = wsumtotSeg;
   bdtotBase = wsumtotBase;
   bdSEGFUN = wSUMSEGFUN;
   bdBaseFun = wSUMBaseFun;
   bdPercFun = wSUMPercFun;
   bdSegPro = wSumSegPro;
   bdBasePro = wSumBasePro;
   bdPercPro = wSumPercPro;
   bdSegAut = wSumSegAut;
   bdBaseAut = wSumBaseAut;
   bdPercAut = wSumPercAut;
   bdbaseratapo = wSumbaseratapo;
   bdvalorratapo = wSumvalorratapo;
   bdsalfam = wSumsalfam;
   bdsalmaternidade = wSumsalmaternidade;
   bdbasefpas = wSumbasefpas;
   bdpercfpas = wSumpercfpas;
   bdpercrat = wSumpercrat;
   bdvaloutentidade = wsumvaloutentidade;
   bddescenqfed = wSumdescenqfed;
   bdsimplesgps = wSumsimplesgps;
   bdcodenqfed = wSumcodenqfed;

   BDBASEFUNFN = wsumBDBASEFUNFN;
   BDBASEFUNFC = wsumBDBASEFUNFC;
   BDBASEFUNFERFN = wsumBDBASEFUNFERFN;
   BDBASEFUNFERFC = wsumBDBASEFUNFERFC;
   BDBASEFUN13RFN = wsumBDBASEFUN13RFN;
   BDBASEFUN13RFC = wsumBDBASEFUN13RFC;
   BDBASEFUN13 = wsumBDBASEFUN13;
   BDBASEFUNC13 = wsumBDBASEFUNC13;
   BDBASEPROFN = wsumBDBASEPROFN;
   BDBASEPROFC = wsumBDBASEPROFC;
   BDBASEPROFERFN = wsumBDBASEPROFERFN;
   BDBASEPROFERFC = wsumBDBASEPROFERFC;
   BDBASEPRO13RFN = wsumBDBASEPRO13RFN;
   BDBASEPRO13RFC = wsumBDBASEPRO13RFC;
   BDBASEPRO13 = wsumBDBASEPRO13;
   BDBASEPROC13 = wsumBDBASEPROC13;
   BDBASEAUTFN = wsumBDBASEAUTFN;
   BDBASEAUTFC = wsumBDBASEAUTFC;
   BDBASEAUTFERFN = wsumBDBASEAUTFERFN;
   BDBASEAUTFERFC = wsumBDBASEAUTFERFC;
   BDBASEAUT13RFN = wsumBDBASEAUT13RFN;
   BDBASEAUT13RFC = wsumBDBASEAUT13RFC;
   BDBASEAUT13 = wsumBDBASEAUT13;
   BDBASEAUTC13 = wsumBDBASEAUTC13;
   BDBASEFPASFN = wsumBDBASEFPASFN;
   BDBASEFPASFC = wsumBDBASEFPASFC;
   BDBASEFPASFERFN = wsumBDBASEFPASFERFN;
   BDBASEFPASFERFC = wsumBDBASEFPASFERFC;
   BDBASEFPAS13RFN = wsumBDBASEFPAS13RFN;
   BDBASEFPAS13RFC = wsumBDBASEFPAS13RFC;
   BDBASEFPAS13 = wsumBDBASEFPAS13;
   BDBASEFPASC13 = wsumBDBASEFPASC13;
   BDBASERATAPOFN = wsumBDBASERATAPOFN;
   BDBASERATAPOFC = wsumBDBASERATAPOFC;
   BDBASERATAPOFERFN = wsumBDBASERATAPOFERFN;
   BDBASERATAPOFERFC = wsumBDBASERATAPOFERFC;
   BDBASERATAPO13RFN = wsumBDBASERATAPO13RFN;
   BDBASERATAPO13RFC = wsumBDBASERATAPO13RFC;
   BDBASERATAPO13 = wsumBDBASERATAPO13;
   BDBASERATAPOC13 = wsumBDBASERATAPOC13;

   IF (WEXISTE = 1) THEN
     SUSPEND;
END
^

/* Alter (VRHF_SP_DADOS_IND_CALC_GPS) */
ALTER PROCEDURE VRHF_SP_DADOS_IND_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENASGPS INTEGER)
 RETURNS(BDCODCENTRO INTEGER,
BDTIPO INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSCODEMP INTEGER;
DECLARE VARIABLE WEXISTE INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCASEAUT VARCHAR(300);
DECLARE VARIABLE WCASEPRO VARCHAR(300);
DECLARE VARIABLE WCASEFUN VARCHAR(300);
DECLARE VARIABLE WTIPOFUN VARCHAR(4);
DECLARE VARIABLE WCAMPOEMP VARCHAR(1000);
DECLARE VARIABLE WAUXCAMPO VARCHAR(10);
DECLARE VARIABLE WAUXWHEREEMP VARCHAR(32000);
DECLARE VARIABLE WAUXWHEREFUN VARCHAR(32000);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WAUX NUMERIC(15,6);
DECLARE VARIABLE WSQLFROM VARCHAR(32000);
DECLARE VARIABLE WTPCC INTEGER;
DECLARE VARIABLE WTPCCANT INTEGER;
DECLARE VARIABLE WCODTOMADOR INTEGER;
DECLARE VARIABLE WCODTOMADORANT INTEGER;
DECLARE VARIABLE WEMPRESAANT INTEGER;
DECLARE VARIABLE WBDTOTSEG NUMERIC(15,6);
DECLARE VARIABLE WBDTOTBASE NUMERIC(15,6);
DECLARE VARIABLE WSUMTOTSEG NUMERIC(15,6);
DECLARE VARIABLE WSUMTOTBASE NUMERIC(15,6);
DECLARE VARIABLE WBDSEGFUN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN NUMERIC(15,6);
DECLARE VARIABLE WBDPERCFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCFUN NUMERIC(15,6);
DECLARE VARIABLE WBDSEGPRO NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO NUMERIC(15,6);
DECLARE VARIABLE WBDPERCPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCPRO NUMERIC(15,6);
DECLARE VARIABLE WBDSEGAUT NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT NUMERIC(15,6);
DECLARE VARIABLE WBDPERCAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCAUT NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO NUMERIC(15,6);
DECLARE VARIABLE WBDVALORRATAPO NUMERIC(15,6);
DECLARE VARIABLE WSUMBASERATAPO NUMERIC(15,6);
DECLARE VARIABLE WSUMVALORRATAPO NUMERIC(15,6);
DECLARE VARIABLE WBDSALFAM NUMERIC(15,6);
DECLARE VARIABLE WBDSALMATERNIDADE NUMERIC(15,6);
DECLARE VARIABLE WSUMSALFAM NUMERIC(15,6);
DECLARE VARIABLE WSUMSALMATERNIDADE NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS NUMERIC(15,6);
DECLARE VARIABLE WBDPERCFPAS NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEFPAS NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCFPAS NUMERIC(15,6);
DECLARE VARIABLE WBDPERCRAT NUMERIC(15,6);
DECLARE VARIABLE WBDVALOUTENTIDADE NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCRAT NUMERIC(15,6);
DECLARE VARIABLE WSUMVALOUTENTIDADE NUMERIC(15,6);
DECLARE VARIABLE WBDSIMPLESGPS INTEGER;
DECLARE VARIABLE WBDCODENQFED INTEGER;
DECLARE VARIABLE WBDDESCENQFED VARCHAR(10);
DECLARE VARIABLE WSUMSIMPLESGPS INTEGER;
DECLARE VARIABLE WSUMCODENQFED INTEGER;
DECLARE VARIABLE WSUMDESCENQFED VARCHAR(10);
DECLARE VARIABLE WGERAGUIA INTEGER;
DECLARE VARIABLE WEMISSAO INTEGER;
DECLARE VARIABLE WBDBASEFUNFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOC13 NUMERIC(15,6);
BEGIN
  /* Procedure Text */
  /* prtipogps
     0 = normal
     1 = folha complementar
     2 = 13 sal
     3 = comp. 13 sal
     4 = pr?via de rescis?o
  */
  /* prtipoemissao
     0 = por cc
     1 = agrupado
     3 = por tomador (utilizado na SEFIP)
  */
  /* prapenasgps
     0 = apenas gps
     1 = historicos compensacoes/nf/gps
  */
  /* PRPUXAFILIAIS
     0 = Nao
     1 = Sim
  */

  /*
  bdtipo
    0 = contabilizacao
    1 = para calculo da gps
    2 = individual
  */

  IF (prtipogps IS NULL) THEN
     prtipogps = 0;

  wauxwhereemp = prcodemp;
  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     BEGIN
       wauxwhereemp =  'calc.'||SUBSTRING(prcodemp FROM 8);
       prcodemp = ''''||prcodemp||'''';
     END

  wauxwherefun = prcodcol;
--  wauxwhereaut = prcodaut;

  wtipofun = prtipocol;
  IF (prtipocol IS NULL) THEN
     wtipofun = '0';

  IF (prcodcol IS NULL) THEN
     prcodcol = 'null';
  ELSE
     prcodcol = ''''||prcodcol||'''';

  IF (pranomes IS NULL) THEN
     pranomes = 0;

  wemissao = prtipoemissao;
  prtipoemissao = 0;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  IF (prpuxafiliais = 0) THEN
     wcampoemp = 'calc.bdcodemp xbdcodemp';
  ELSE
     wcampoemp = 'case when temp.bdcodmatriz is not null then temp.bdcodmatriz else temp.bdcodemp end xbdcodemp';

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  wauxcampo = '13';
  IF (prtipogps = 2) THEN
     wauxcampo = '13';
  ELSE IF (prtipogps = 3) THEN
     wauxcampo = 'C13';

  IF (prtipogps IN (0,4)) THEN
     wcasefun = 'calc.bdgrupocla in (1,4,5,7,8)';
  ELSE
     wcasefun = 'f.bdgrupocla in (1,4,5,7,8)';

  IF (prtipogps IN (0,4)) THEN
     WCASEPRO = 'calc.bdgrupocla in (2)';
  ELSE
     WCASEPRO = 'f.bdgrupocla in (2)';

  IF (prtipogps IN (0,4)) THEN
     WCASEAUT = 'calc.bdgrupocla in (3,6)';
  ELSE
     WCASEAUT = 'f.bdgrupocla in (3,6)';

  /* Procedure Text */
  IF (prtipogps IN (0,4)) THEN
     wsql = 'select '||wcampoemp||',calc.bdreffn, calc.bdreffn, calc.bdcodcentro, calc.bdcodtpcc, ';
--  ELSE IF (prtipogps = 4) THEN
--     wsql = 'select '||wcampoemp||','||pranomes||' bdreffn, calc.bdreffn, calc.bdcodcentro, calc.bdcodtpcc, ';
  ELSE IF (prtipogps = 1) THEN
     wsql = 'select '||wcampoemp||',calc.bdreffn, calc.BDREFCOMP, calc.bdcodcentro, calc.bdcodtpcc,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = 'select '||wcampoemp||', calc.bdref13,'||
            ' calc.bdref13 refpag, cast(null as integer), cast(null as integer),';

       /*totais*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' coalesce(calc.bdinssfn,0)+coalesce(calc.bdinssfefolfn,0)+coalesce(calc.bdinss13fn,0)  totSeg,'||
       ' coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0)  totBase,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||'  coalesce(calc.bdinssfc,0)+coalesce(calc.bdinssfefolfc,0)+coalesce(calc.bdinss13fc,0)  totSeg,'||
       ' coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0)  totBase,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||'  coalesce(calc.bdvalorinss'||wauxcampo||',0)  totSeg,'||
       '  coalesce(calc.bdbaseinss'||wauxcampo||',0)  totBase,';

       /*colaboradores*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdinssfn,0)+coalesce(calc.bdinssfefolfn,0)+coalesce(calc.bdinss13fn,0))'||
       ' else 0 end SEGFUN,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdinssfc,0)+coalesce(calc.bdinssfefolfc,0)+coalesce(calc.bdinss13fc,0))'||
       ' else 0 end SEGFUN,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdvalorinss'||wauxcampo||',0))'||
       ' else 0 end SEGFUN,';

  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))'||
       ' else 0 end BaseFun,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))'||
       ' else 0 end BaseFun,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||'   case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdbaseinss'||wauxcampo||',0))'||
       ' else 0 end BaseFun,';

  wsql = wsql||' coalesce(emp.bdfunemp,0) PercFun,';

       /*prolaboristas*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||WCASEPRO||') then'||
       ' coalesce(calc.bdinssfn,0)+coalesce(calc.bdinssfefolfn,0)+coalesce(calc.bdinss13fn,0)'||
       ' else 0 end SegPro,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||'   case when ('||WCASEPRO||') then'||
       ' coalesce(calc.bdinssfc,0)+coalesce(calc.bdinssfefolfc,0)+coalesce(calc.bdinss13fc,0)'||
       ' else 0 end SegPro,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||'   case when ('||WCASEPRO||') then'||
       ' coalesce(calc.bdvalorinss'||wauxcampo||',0)'||
       ' else 0 end SegPro,';

  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||WCASEPRO||') then'||
       ' (coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))'||
       ' else 0 end BasePro,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||WCASEPRO||') then'||
       ' (coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))'||
       ' else 0 end BasePro,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||'   case when ('||WCASEPRO||') then'||
       ' (coalesce(calc.bdbaseinss'||wauxcampo||',0))'||
       ' else 0 end BasePro,';

  wsql = wsql||' coalesce(emp.bdempemp,0) PercPro,';

       /*autonomos*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdinssfn,0)+coalesce(calc.bdinssfefolfn,0)+coalesce(calc.bdinss13fn,0))'||
       ' else 0 end SegAut,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdinssfc,0)+coalesce(calc.bdinssfefolfc,0)+coalesce(calc.bdinss13fc,0))'||
       ' else 0 end SegAut,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdvalorinss'||wauxcampo||',0))'||
       ' else 0 end SegAut,';

  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))'||
       ' else 0 end BaseAut,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||'   case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))'||
       ' else 0 end BaseAut,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdbaseinss'||wauxcampo||',0))'||
       ' else 0 end BaseAut,';

  wsql = wsql||' coalesce(emp.bdautemp,0) PercAut,';

       /* rat aposentadoria*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
       ' (coalesce(calc.bdbratapofn,0)+coalesce(calc.bdbratapofefn,0)+coalesce(calc.bdbratapo13fn,0))'||
       ' else 0 end bratapo,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
       ' (coalesce(calc.bdbratapofc,0)+coalesce(calc.bdbratapofefc,0)+coalesce(calc.bdbratapo13fc,0))'||
       ' else 0 end bratapo,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
       ' (coalesce(calc.bdbratapo'||wauxcampo||',0))'||
       ' else 0 end bratapo,';

  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' (select bdvalor from truncar((coalesce(calc.bdbratapofn,0)+coalesce(calc.bdbratapofefn,0)+coalesce(calc.bdbratapo13fn,0))*(coalesce(colgps.bdpercratcol,0)/100),2)) vratapo,';
  ELSE IF (prtipogps = 1) THEN
    wsql = wsql||' (select bdvalor from truncar((coalesce(calc.bdbratapofc,0)+coalesce(calc.bdbratapofefc,0)+coalesce(calc.bdbratapo13fc,0))*(coalesce(colgps.bdpercratcol,0)/100),2)) vratapo,';
  ELSE IF (prtipogps IN (2,3)) THEN
    wsql = wsql||' (select bdvalor from truncar(coalesce(calc.bdbratapo'||wauxcampo||',0)*(coalesce(colgps.bdpercratcol,0)/100),2)) vratapo,';

       /* salario familia*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' coalesce(calc.bdsalfamfn,0) salfam,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' coalesce(calc.bdsalfamfc,0) salfam,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' coalesce(calc.bdsalfam'||wauxcampo||',0) salfam,';

       /* salario maternidade */
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' coalesce(calc.bdsalmatempfn,0) salMaternidade,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' coalesce(calc.bdsalmatempfc,0) salMaternidade,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' coalesce(calc.bdsalmatemp'||wauxcampo||',0) salMaternidade,';

       /* base para fpas e rat com ded.fpas*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
       ' (select bdvalor from truncar((coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
       ' else'||
       ' (coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))'||
       ' end'||
       ' else 0 end BASFPAS,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
       ' (select bdvalor from truncar((coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
       ' else'||
       ' (coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))'||
       ' end'||
       ' else 0 end BASFPAS,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
       ' (select bdvalor from truncar((coalesce(calc.bdbaseinss'||wauxcampo||',0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
       ' else'||
       ' (coalesce(calc.bdbaseinss'||wauxcampo||',0))'||
       ' end'||
       ' else 0 end BASFPAS,';

  wsql = wsql||' coalesce(emp.bdperterc,0) PercFPAS,';

  wsql = wsql||' (select bdvalor from truncar(coalesce(ratemp.bdtaxacnae,0)*(coalesce(emp.bdfap,0)),4)) PercRat, ';

  IF (prtipogps IN (0,4)) THEN
      wsql = wsql||' calc.BDVALOUTENTIDADE valOutentidade, ';
  ELSE
      wsql = wsql||' cast(null as numeric(15,6)) valOutentidade, ';

   wsql = wsql||' DESCFED.BDDESCENQFED,'||
                ' emp.bdsimplesgps,'||
                ' DESCFED.BDCODENQFED,';


   IF (prtipogps IN (0,1,4)) THEN
      wsql = wsql||' toma.bdcodtpcc bdcodtomador,';
   ELSE
      wsql = wsql||' 0 bdcodtomador,';

   IF (prtipogps IN (0,4)) THEN
      wsql = wsql||' calc.bdcodcol, calc.bdcodter, ';
   ELSE
      wsql = wsql||' calc.bdcodcol, cast(null as integer) bdcodter, ';

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

   /* BASE FUN SEPARADO TIPO CALCULO*/
  IF (prtipogps IN (0,4)) THEN  /* Folha normal */
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinssfn,0))'||
         ' else 0 end BaseFunFN,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinssfefolfn,0))'||
         ' else 0 end BaseFunFER,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinss13fn,0))'||
         ' else 0 end BaseFun13RFN,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEFUNFN,';
       wsql = wsql||' 0 BASEFUNFER,';
       wsql = wsql||' 0 BASEFUNF13RFN,';
     END

  IF (prtipogps = 1) THEN /* folha complementar */
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinssfc,0))'||
         ' else 0 end BaseFunFC,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinssfefolfc,0))'||
         ' else 0 end BaseFunFERFC,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinss13fc,0))'||
         ' else 0 end BaseFun13RFC,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEFUNFC,';
       wsql = wsql||' 0 BASEFUNFERFC,';
       wsql = wsql||' 0 BaseFun13RFC,';
     END

  IF (prtipogps = 2) THEN /* 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcasefun||') then'||
                    ' (coalesce(calc.bdbaseinss13,0))'||
                    ' else 0 end BASEFUN13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEFUN13,';
     END

  IF (prtipogps = 3) THEN /* complemento 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcasefun||') then'||
                    ' (coalesce(calc.bdbaseinssc13,0))'||
                    ' else 0 end BASEFUNC13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEFUNC13';
     END
  wsql = wsql||',';

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

   /* BASE PRO SEPARADO TIPO CALCULO*/
  IF (prtipogps IN (0,4)) THEN  /* Folha normal */
     BEGIN
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinssfn,0))'||
         ' else 0 end BasePROFN,';
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinssfefolfn,0))'||
         ' else 0 end BasePROFER,';
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinss13fn,0))'||
         ' else 0 end BasePRO13RFN,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEPROFN,';
       wsql = wsql||' 0 BASEPROFER,';
       wsql = wsql||' 0 BASEPROF13RFN,';
     END

  IF (prtipogps = 1) THEN /* folha complementar */
     BEGIN
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinssfc,0))'||
         ' else 0 end BasePROFC,';
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinssfefolfc,0))'||
         ' else 0 end BasePROFERFC,';
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinss13fc,0))'||
         ' else 0 end BasePRO13RFC,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEPROFC,';
       wsql = wsql||' 0 BASEPROFERFC,';
       wsql = wsql||' 0 BasePRO13RFC,';
     END

  IF (prtipogps = 2) THEN /* 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcasepro||') then'||
                    ' (coalesce(calc.bdbaseinss13,0))'||
                    ' else 0 end BASEPRO13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEPRO13,';
     END

  IF (prtipogps = 3) THEN /* complemento 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcasepro||') then'||
                    ' (coalesce(calc.bdbaseinssc13,0))'||
                    ' else 0 end BASEPROC13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEPROC13';
     END
  wsql = wsql||',';

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
   /* BASE AUT SEPARADO TIPO CALCULO*/
  IF (prtipogps IN (0,4)) THEN  /* Folha normal */
     BEGIN
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinssfn,0))'||
         ' else 0 end BaseAUTFN,';
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinssfefolfn,0))'||
         ' else 0 end BaseAUTFER,';
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinss13fn,0))'||
         ' else 0 end BaseAUT13RFN,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEAUTFN,';
       wsql = wsql||' 0 BASEAUTFER,';
       wsql = wsql||' 0 BASEAUTF13RFN,';
     END

  IF (prtipogps = 1) THEN /* folha complementar */
     BEGIN
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinssfc,0))'||
         ' else 0 end BaseAUTFC,';
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinssfefolfc,0))'||
         ' else 0 end BaseAUTFERFC,';
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinss13fc,0))'||
         ' else 0 end BaseAUT13RFC,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEAUTFC,';
       wsql = wsql||' 0 BASEAUTFERFC,';
       wsql = wsql||' 0 BaseAUT13RFC,';
     END

  IF (prtipogps = 2) THEN /* 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcaseaut||') then'||
                    ' (coalesce(calc.bdbaseinss13,0))'||
                    ' else 0 end BASEAUT13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEAUT13,';
     END

  IF (prtipogps = 3) THEN /* complemento 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcaseaut||') then'||
                    ' (coalesce(calc.bdbaseinssc13,0))'||
                    ' else 0 end BASEAUTC13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEAUTC13';
     END
  wsql = wsql||',';
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--  BASE FPAS POR TIPO DE CALCULO
  IF (prtipogps IN (0,4)) THEN
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinssfn,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinssfn,0))'||
         ' end'||
         ' else 0 end BASFPASFN,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinssfefolfn,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinssfefolfn,0))'||
         ' end'||
         ' else 0 end BASFPASFERFN,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinss13fn,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinss13fn,0))'||
         ' end'||
         ' else 0 end BASFPAS13RFN,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASFPASFN,';
       wsql = wsql||' 0 BASFPASFERFN,';
       wsql = wsql||' 0 BASFPAS13RFN,';
     END

  IF (prtipogps = 1) THEN
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinssfc,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinssfc,0))'||
         ' end'||
         ' else 0 end BASFPASFC,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinssfefolfc,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinssfefolfc,0))'||
         ' end'||
         ' else 0 end BASFPASFERFC,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinss13fc,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinss13fc,0))'||
         ' end'||
         ' else 0 end BASFPAS13RFC,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASFPASFC,';
       wsql = wsql||' 0 BASFPASFERFC,';
       wsql = wsql||' 0 BASFPAS13RFC,';
     END

  IF (prtipogps = 2) THEN
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbaseinss13,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbaseinss13,0))'||
         ' end'||
         ' else 0 end BASFPAS13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASFPAS13,';
     END

  IF (prtipogps = 3) THEN
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbaseinssC13,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbaseinssC13,0))'||
         ' end'||
         ' else 0 end BASFPASC13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASFPASC13';
     END
  wsql = wsql||',';

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- base rat aposentadoria por tipo de calculo
  IF (prtipogps IN (0,4)) THEN
     BEGIN
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapofn,0))'||
         ' else 0 end bratapofn,';
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapofefn,0))'||
         ' else 0 end bratapofefn,';
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapo13fn,0))'||
         ' else 0 end bratapo13fn,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 bratapofn,';
       wsql = wsql||' 0 bratapofefn,';
       wsql = wsql||' 0 bratapo13fn,';
     END

  IF (prtipogps = 1) THEN
     BEGIN
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapofc,0))'||
         ' else 0 end bratapofc,';
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapofefc,0))'||
         ' else 0 end bratapofefc,';
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapo13fc,0))'||
         ' else 0 end bratapo13fc,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 bratapofc,';
       wsql = wsql||' 0 bratapofefc,';
       wsql = wsql||' 0 bratapo13fc,';
     END

  IF (prtipogps = 2) THEN
     BEGIN
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapo13,0))'||
         ' else 0 end bratapo13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 bratapo13,';
     END

  IF (prtipogps = 3) THEN
     BEGIN
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapoc13,0))'||
         ' else 0 end bratapoc13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 bratapoc13';
     END

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
  IF (prcodaut IS NULL) THEN
     prcodaut = 'null';
  ELSE
     prcodaut = ''''||prcodaut||'''';


       /*tabelas*/
  IF (prtipogps = 0) THEN
     wsqlfrom = '  from vrhf_sp_calc_fn_aut('||prcodemp||','||prcodcol||','||pranomes||',null,'||prtipoemissao||','||wtipofun||','||prcodaut||') calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
--       ' left outer join VW_VRHF_BASE_TEMPGPS emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
--       ' left outer join vrh_base_tterceiros empfpas on (empfpas.bdcodterc = emp.bdcodterc)'||
--       ' left outer join vw_tempresas_ref empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(calc.bdcodtpcc,calc.bdcodcentro) toma on (toma.bdcodcencus = calc.bdcodtpcc and toma.bdcodcentro = calc.bdcodcentro)';
  ELSE IF (prtipogps = 4) THEN
     wsqlfrom = '  from vrhf_sp_calc_fn_aut_prev('||prcodemp||','||prcodcol||','||pranomes||',null,'||prtipoemissao||','||wtipofun||','||prcodaut||') calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(calc.bdcodtpcc,calc.bdcodcentro) toma on (toma.bdcodcencus = calc.bdcodtpcc and toma.bdcodcentro = calc.bdcodcentro)';
  ELSE IF (prtipogps = 1) THEN
     wsqlfrom = ' from vrhf_sp_tfolhacomp('||prcodemp||','||prcodcol||','||pranomes||',null,'||pranomespag||',null,'||prtipoemissao||') calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
--       ' left outer join VW_VRHF_BASE_TEMPGPS emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
--       ' left outer join vrh_base_tterceiros empfpas on (empfpas.bdcodterc = emp.bdcodterc)'||
--       ' left outer join vw_tempresas_ref empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' join vw_colaboradores_ref_atual f on (calc.bdcodemp = f.bdcodemp and calc.bdcodcol = f.bdcodcol)'||
       ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(calc.bdcodtpcc,calc.bdcodcentro) toma on (toma.bdcodcencus = calc.bdcodtpcc and toma.bdcodcentro = calc.bdcodcentro)';
  ELSE IF (prtipogps = 2) THEN
     wsqlfrom = ' from vrhf_emp_t13sal calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
--       ' left outer join VW_VRHF_BASE_TEMPGPS emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
--       ' left outer join vrh_base_tterceiros empfpas on (empfpas.bdcodterc = emp.bdcodterc)'||
--       ' left outer join vw_tempresas_ref empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' join vw_colaboradores_ref_atual f on (calc.bdcodemp = f.bdcodemp and calc.bdcodcol = f.bdcodcol)';
  ELSE IF (prtipogps = 3) THEN
     wsqlfrom = ' from vrhf_emp_tc13sal calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
--       ' left outer join VW_VRHF_BASE_TEMPGPS emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
--       ' left outer join vrh_base_tterceiros empfpas on (empfpas.bdcodterc = emp.bdcodterc)'||
--       ' left outer join vw_tempresas_ref empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' join vw_colaboradores_ref_atual f on (calc.bdcodemp = f.bdcodemp and calc.bdcodcol = f.bdcodcol)';

  wsqlfrom = wsqlfrom||' join tempresas temp on (calc.bdcodemp = temp.bdcodemp)';
  wsqlfrom = wsqlfrom||' left outer join vw_tenqfed TENQ on (TENQ.bdcodemp = temp.bdcodemp)';
  wsqlfrom = wsqlfrom||' left outer join TCADENQFED DESCFED on (TENQ.BDCODENQFED = DESCFED.BDCODENQFED)';

  /* monta where quando necessario */
    waux = 0;
    IF (wauxwhereemp IS NOT NULL) THEN
      BEGIN
        wsqlfrom = wsqlfrom||'  where ';
        waux = 1;
        wsqlfrom = wsqlfrom||wauxwhereemp;
      END
    
  IF (prtipogps NOT IN (0,4)) THEN
     BEGIN
       IF (wauxwherefun IS NOT NULL) THEN
         BEGIN
           IF (waux = 0) THEN
              wsqlfrom = wsqlfrom||'  where ';
           ELSE
              wsqlfrom = wsqlfrom||' and ';
       
           waux = 1;
           wsqlfrom = wsqlfrom||wauxwherefun;
         END
     END

  IF (prtipogps IN (3)) THEN
     BEGIN
       IF (waux = 0) THEN
          wsqlfrom = wsqlfrom||'  where ';
       ELSE
          wsqlfrom = wsqlfrom||' and ';
       waux = CAST(SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'01' AS INTEGER);
       wsqlfrom = wsqlfrom||' calc.bdref13 >= '||waux;
       waux = CAST(SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'12' AS INTEGER);
       wsqlfrom = wsqlfrom||' and calc.bdref13 <= '||waux;
     END
  ELSE IF (prtipogps IN (2)) THEN
     BEGIN
       IF (waux = 0) THEN
          wsqlfrom = wsqlfrom||'  where ';
       ELSE
          wsqlfrom = wsqlfrom||' and ';
       wsqlfrom = wsqlfrom||' calc.bdref13 = '||pranomes;
     END

       /* group by */
  IF (prtipogps IN (0,4)) THEN
     wsqlfrom = wsqlfrom||'  order by xbdcodemp, calc.bdreffn, toma.bdcodtpcc, calc.bdcodtpcc, DESCFED.BDDESCENQFED';
  ELSE IF (prtipogps = 1) THEN
     wsqlfrom = wsqlfrom||'  order by xbdcodemp, calc.bdreffn, calc.BDREFCOMP, toma.bdcodtpcc, calc.bdcodtpcc, DESCFED.BDDESCENQFED';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsqlfrom = wsqlfrom||'  order by xbdcodemp, cast(substring(cast(calc.bdref13 as varchar(6)) from 1 for 4)||'||''''||'13'||''''||' as integer), DESCFED.BDDESCENQFED';

  wcodtomadorant = -1;
  wsumtotSeg = 0;
  wsumtotBase = 0;
  wSUMSEGFUN = 0;
  wSUMBaseFun = 0;
  wSUMPercFun = 0;
  wSumSegPro = 0;
  wSumBasePro = 0;
  wSumPercPro = 0;
  wSumSegAut = 0;
  wSumBaseAut = 0;
  wSumPercAut = 0;
  wSumbaseratapo = 0;
  wSumvalorratapo = 0;
  wSumsalfam = 0;
  wSumsalmaternidade = 0;
  wSumbasefpas = 0;
  wSumpercfpas = 0;
  wSumpercrat = 0;
  wSumVALOUTENTIDADE = 0;
  wSumdescenqfed = NULL;
  wSumsimplesgps = NULL;
  wSumcodenqfed = NULL;

  wSumbdBASEFUNFN = 0;
  wSumbdbasefunferfn  = 0;
  wSumbdBASEFUN13RFN  = 0;
  wSumbdBASEFUNFC  = 0;
  wSumbdBASEFUNFERFC = 0;
  wSumbdBaseFun13RFC = 0;
  wSumbdBASEFUN13 = 0;
  wSumbdBASEFUNC13 = 0;

  wSumbdBASEPROFN = 0;
  wSumbdbasePROferfn  = 0;
  wSumbdBASEPRO13RFN  = 0;
  wSumbdBASEPROFC  = 0;
  wSumbdBASEPROFERFC = 0;
  wSumbdBasePRO13RFC = 0;
  wSumbdBASEPRO13 = 0;
  wSumbdBASEPROC13 = 0;

  wSumbdBASEAUTFN = 0;
  wSumbdbaseAUTferfn  = 0;
  wSumbdBASEAUT13RFN  = 0;
  wSumbdBASEAUTFC  = 0;
  wSumbdBASEAUTFERFC = 0;
  wSumbdBaseAUT13RFC = 0;
  wSumbdBASEAUT13 = 0;
  wSumbdBASEAUTC13 = 0;

  wSumbdBASEFPASFN = 0;
  wSumbdbaseFPASferfn  = 0;
  wSumbdBASEFPAS13RFN  = 0;
  wSumbdBASEFPASFC  = 0;
  wSumbdBASEFPASFERFC = 0;
  wSumbdBaseFPAS13RFC = 0;
  wSumbdBASEFPAS13 = 0;
  wSumbdBASEFPASC13 = 0;

  wSumbdBASERATAPOFN = 0;
  wSumbdbaseRATAPOferfn  = 0;
  wSumbdBASERATAPO13RFN  = 0;
  wSumbdBASERATAPOFC  = 0;
  wSumbdBASERATAPOFERFC = 0;
  wSumbdBaseRATAPO13RFC = 0;
  wSumbdBASERATAPO13 = 0;
  wSumbdBASERATAPOC13 = 0;

  wtpccant = -1;
  WEXISTE = 0;
  FOR EXECUTE STATEMENT wsql||wsqlfrom INTO
      : bdcodemp,
      : bdreffn,
      : bdrefpag,
      : bdcodcentro,
      : wtpcc,

      /*totais*/
      : wbdtotSeg,
      : wbdtotBase,

      /*colaboradores*/
      : wbdSEGFUN,
      : wbdBaseFun,
      : wbdPercFun,

       /*prolaboristas*/
      : wbdSegPro,
      : wbdBasePro,
      : wbdPercPro,

      /*autonomos*/
      : wbdSegAut,
      : wbdBaseAut,
      : wbdPercAut,

      /* rat aposentadoria*/
      : wbdbaseratapo,
      : wbdvalorratapo,

      : wbdsalfam,
      : wbdsalmaternidade,

      /* base fpas*/
      : wbdbasefpas,
      : wbdpercfpas,

      /* rat */
      : wbdpercrat,
      : wBDVALOUTENTIDADE,

      : wbddescenqfed,
      : wbdsimplesgps,
      : wbdcodenqfed,
      : wcodtomador,

      : wcodcol,
      : wcodter,

      : wbdBASEFUNFN,
      : wbdbasefunferfn,
      : wbdBASEFUN13RFN,
      : wbdBASEFUNFC,
      : wbdBASEFUNFERFC,
      : wbdBaseFun13RFC,
      : wbdBASEFUN13,
      : wbdBASEFUNC13,

      : wbdBASEPROFN,
      : wbdbasePROferfn,
      : wbdBASEPRO13RFN,
      : wbdBASEPROFC,
      : wbdBASEPROFERFC,
      : wbdBasePRO13RFC,
      : wbdBASEPRO13,
      : wbdBASEPROC13,

      : wbdBASEAUTFN,
      : wbdbaseAUTferfn,
      : wbdBASEAUT13RFN,
      : wbdBASEAUTFC,
      : wbdBASEAUTFERFC,
      : wbdBaseAUT13RFC,
      : wbdBASEAUT13,
      : wbdBASEAUTC13,

      : wbdBASEFPASFN,
      : wbdbaseFPASferfn,
      : wbdBASEFPAS13RFN,
      : wbdBASEFPASFC,
      : wbdBASEFPASFERFC,
      : wbdBaseFPAS13RFC,
      : wbdBASEFPAS13,
      : wbdBASEFPASC13,

      : wbdBASERATAPOFN,
      : wbdbaseRATAPOferfn,
      : wbdBASERATAPO13RFN,
      : wbdBASERATAPOFC,
      : wbdBASERATAPOFERFC,
      : wbdBaseRATAPO13RFC,
      : wbdBASERATAPO13,
      : wbdBASERATAPOC13
      DO
  BEGIN
    WEXISTE = 1;
    bdcodter = NULL;
    bdcodcol = NULL;
    IF (wtpcc IS NULL) THEN
       wtpcc = 0;

    IF (wcodtomador IS NULL) THEN
       wcodtomador = 0;

    wgeraguia = 0;
    IF ((wemissao IS NULL) OR (wemissao = 1)) THEN
       BEGIN
         IF ((wempresaant <> bdcodemp) AND (wcodtomadorant <> -1)) THEN
            wgeraguia = 1;
       END
    ELSE
       BEGIN
         IF (((wempresaant <> bdcodemp) OR (wcodtomadorant <> wcodtomador) OR (wtpccant <> wtpcc)) AND (wcodtomadorant <> -1)) THEN
            wgeraguia = 1;
       END

    IF (wgeraguia = 1) THEN
       BEGIN
         bdtipo = 0;
         bdcodcol = NULL;
--         wcodtomador = bdcodtomador;
         IF (wcodtomadorant = 0) THEN
            bdcodtomador = NULL;
         ELSE
            bdcodtomador = wcodtomadorant;

         IF (wtpccant = 0) THEN
            bdcodtpcc = NULL;
         ELSE
            bdcodtpcc = wtpccant;

         WSCODEMP = bdcodemp;
         bdcodemp = wempresaant;

         bdtotSeg = wsumtotSeg;
         bdtotBase = wsumtotBase;
         bdSEGFUN = wSUMSEGFUN;
         bdBaseFun = wSUMBaseFun;
         bdPercFun = wSUMPercFun;
         bdSegPro = wSumSegPro;
         bdBasePro = wSumBasePro;
         bdPercPro = wSumPercPro;
         bdSegAut = wSumSegAut;
         bdBaseAut = wSumBaseAut;
         bdPercAut = wSumPercAut;
         bdbaseratapo = wSumbaseratapo;
         bdvalorratapo = wSumvalorratapo;
         bdsalfam = wSumsalfam;
         bdsalmaternidade = wSumsalmaternidade;
         bdbasefpas = wSumbasefpas;
         bdpercfpas = wSumpercfpas;
         bdpercrat = wSumpercrat;
         BDVALOUTENTIDADE = wSumVALOUTENTIDADE;
         bddescenqfed = wSumdescenqfed;
         bdsimplesgps = wSumsimplesgps;
         bdcodenqfed = wSumcodenqfed;

         bdBASEFUNFN = wSumbdBASEFUNFN;
         bdbasefunferfn = wSumbdbasefunferfn;
         bdBASEFUN13RFN = wSumbdBASEFUN13RFN;
         bdBASEFUNFC = wSumbdBASEFUNFC;
         bdBASEFUNFERFC = wSumbdBASEFUNFERFC;
         bdBaseFun13RFC = wSumbdBaseFun13RFC;
         bdBASEFUN13 = wSumbdBASEFUN13;
         bdBASEFUNC13 = wSumbdBASEFUNC13;

         bdBASEPROFN    = wSumbdBASEPROFN;
         bdbasePROferfn = wSumbdbasePROferfn;
         bdBASEPRO13RFN = wSumbdBASEPRO13RFN;
         bdBASEPROFC    = wSumbdBASEPROFC;
         bdBASEPROFERFC = wSumbdBASEPROFERFC;
         bdBasePRO13RFC = wSumbdBasePRO13RFC;
         bdBASEPRO13    = wSumbdBASEPRO13;
         bdBASEPROC13   = wSumbdBASEPROC13;

         bdBASEAUTFN    = wSumbdBASEAUTFN;
         bdbaseAUTferfn = wSumbdbaseAUTferfn;
         bdBASEAUT13RFN = wSumbdBASEAUT13RFN;
         bdBASEAUTFC    = wSumbdBASEAUTFC;
         bdBASEAUTFERFC = wSumbdBASEAUTFERFC;
         bdBaseAUT13RFC = wSumbdBaseAUT13RFC;
         bdBASEAUT13    = wSumbdBASEAUT13;
         bdBASEAUTC13   = wSumbdBASEAUTC13;

         bdBASEFPASFN    = wSumbdBASEFPASFN;
         bdbaseFPASferfn = wSumbdbaseFPASferfn;
         bdBASEFPAS13RFN = wSumbdBASEFPAS13RFN;
         bdBASEFPASFC    = wSumbdBASEFPASFC;
         bdBASEFPASFERFC = wSumbdBASEFPASFERFC;
         bdBaseFPAS13RFC = wSumbdBaseFPAS13RFC;
         bdBASEFPAS13    = wSumbdBASEFPAS13;
         bdBASEFPASC13   = wSumbdBASEFPASC13;

         bdBASERATAPOFN    = wSumbdBASERATAPOFN;
         bdbaseRATAPOferfn = wSumbdbaseRATAPOferfn;
         bdBASERATAPO13RFN = wSumbdBASERATAPO13RFN;
         bdBASERATAPOFC    = wSumbdBASERATAPOFC;
         bdBASERATAPOFERFC = wSumbdBASERATAPOFERFC;
         bdBaseRATAPO13RFC = wSumbdBaseRATAPO13RFC;
         bdBASERATAPO13    = wSumbdBASERATAPO13;
         bdBASERATAPOC13   = wSumbdBASERATAPOC13;

         SUSPEND;

         bdcodemp = WSCODEMP;

         wsumtotbase = 0;
         wsumtotseg = 0;
         wSUMSEGFUN = 0;
         wSUMBaseFun = 0;
         wSUMPercFun = 0;
         wSumSegPro = 0;
         wSumBasePro = 0;
         wSumPercPro = 0;
         wSumSegAut = 0;
         wSumBaseAut = 0;
         wSumPercAut = 0;
         wSumbaseratapo = 0;
         wSumvalorratapo = 0;
         wSumsalfam = 0;
         wSumsalmaternidade = 0;
         wSumbasefpas = 0;
         wSumpercfpas = 0;
         wSumpercrat = 0;
         wSumVALOUTENTIDADE = 0;
         wSumdescenqfed = NULL;
         wSumsimplesgps = NULL;
         wSumcodenqfed = NULL;

         wSumbdBASEFUNFN = 0;
         wSumbdbasefunferfn  = 0;
         wSumbdBASEFUN13RFN  = 0;
         wSumbdBASEFUNFC  = 0;
         wSumbdBASEFUNFERFC = 0;
         wSumbdBaseFun13RFC = 0;
         wSumbdBASEFUN13 = 0;
         wSumbdBASEFUNC13 = 0;

         wSumbdBASEPROFN = 0;
         wSumbdbasePROferfn  = 0;
         wSumbdBASEPRO13RFN  = 0;
         wSumbdBASEPROFC  = 0;
         wSumbdBASEPROFERFC = 0;
         wSumbdBasePRO13RFC = 0;
         wSumbdBASEPRO13 = 0;
         wSumbdBASEPROC13 = 0;

         wSumbdBASEAUTFN = 0;
         wSumbdbaseAUTferfn  = 0;
         wSumbdBASEAUT13RFN  = 0;
         wSumbdBASEAUTFC  = 0;
         wSumbdBASEAUTFERFC = 0;
         wSumbdBaseAUT13RFC = 0;
         wSumbdBASEAUT13 = 0;
         wSumbdBASEAUTC13 = 0;

         wSumbdBASEFPASFN = 0;
         wSumbdbaseFPASferfn  = 0;
         wSumbdBASEFPAS13RFN  = 0;
         wSumbdBASEFPASFC  = 0;
         wSumbdBASEFPASFERFC = 0;
         wSumbdBaseFPAS13RFC = 0;
         wSumbdBASEFPAS13 = 0;
         wSumbdBASEFPASC13 = 0;

         wSumbdBASERATAPOFN = 0;
         wSumbdbaseRATAPOferfn  = 0;
         wSumbdBASERATAPO13RFN  = 0;
         wSumbdBASERATAPOFC  = 0;
         wSumbdBASERATAPOFERFC = 0;
         wSumbdBaseRATAPO13RFC = 0;
         wSumbdBASERATAPO13 = 0;
         wSumbdBASERATAPOC13 = 0;
       END

    wsumtotbase = wsumtotbase + wbdtotBase;
    wsumtotseg = wsumtotseg + wbdtotseg;
    wSUMSEGFUN = wSUMSEGFUN + wbdSEGFUN;
    wSUMBaseFun = wSUMBaseFun + wbdBaseFun;
    wSUMPercFun = wbdPercFun;
    wSumSegPro = wSumSegPro + wbdSegPro;
    wSumBasePro = wSumBasePro + wbdBasePro;
    wSumPercPro = wbdPercPro;
    wSumSegAut = wSumSegAut + wbdSegAut;
    wSumBaseAut = wSumBaseAut + wbdBaseAut;
    wSumPercAut = wbdPercAut;
    wSumbaseratapo = wSumbaseratapo + wbdbaseratapo;
    wSumvalorratapo = wSumvalorratapo + wbdvalorratapo;
    wSumsalfam = wSumsalfam + wbdsalfam;
    wSumsalmaternidade = wSumsalmaternidade + wbdsalmaternidade;
    wSumbasefpas = wSumbasefpas + wbdbasefpas;
    wSumpercfpas = wbdpercfpas;
    wSumpercrat = wbdpercrat;
    wsumvaloutentidade = wsumvaloutentidade + wbdvaloutentidade;
    wsumdescenqfed = wbddescenqfed;
    wsumsimplesgps = wbdsimplesgps;
    wsumcodenqfed = wbdcodenqfed;

    wSumbdBASEFUNFN = wSumbdBASEFUNFN + wbdBASEFUNFN;
    wSumbdbasefunferfn  = wSumbdbasefunferfn  + wbdbasefunferfn;
    wSumbdBASEFUN13RFN  = wSumbdBASEFUN13RFN  + wbdBASEFUN13RFN;
    wSumbdBASEFUNFC  = wSumbdBASEFUNFC  + wbdBASEFUNFC;
    wSumbdBASEFUNFERFC = wSumbdBASEFUNFERFC + wbdBASEFUNFERFC;
    wSumbdBaseFun13RFC = wSumbdBaseFun13RFC + wbdBaseFun13RFC;
    wSumbdBASEFUN13 = wSumbdBASEFUN13 + wbdBASEFUN13;
    wSumbdBASEFUNC13 = wSumbdBASEFUNC13 + wbdBASEFUNC13;

    wSumbdBASEPROFN     = wSumbdBASEPROFN     + wbdBASEPROFN;
    wSumbdbasePROferfn  = wSumbdbasePROferfn  + wbdbasePROferfn;
    wSumbdBASEPRO13RFN  = wSumbdBASEPRO13RFN  + wbdBASEPRO13RFN;
    wSumbdBASEPROFC     = wSumbdBASEPROFC     + wbdBASEPROFC;
    wSumbdBASEPROFERFC  = wSumbdBASEPROFERFC  + wbdBASEPROFERFC;
    wSumbdBasePRO13RFC  = wSumbdBasePRO13RFC  + wbdBasePRO13RFC;
    wSumbdBASEPRO13     = wSumbdBASEPRO13     + wbdBASEPRO13;
    wSumbdBASEPROC13    = wSumbdBASEPROC13    + wbdBASEPROC13;

    wSumbdBASEAUTFN     = wSumbdBASEAUTFN     + wbdBASEAUTFN;
    wSumbdbaseAUTferfn  = wSumbdbaseAUTferfn  + wbdbaseAUTferfn;
    wSumbdBASEAUT13RFN  = wSumbdBASEAUT13RFN  + wbdBASEAUT13RFN;
    wSumbdBASEAUTFC     = wSumbdBASEAUTFC     + wbdBASEAUTFC;
    wSumbdBASEAUTFERFC  = wSumbdBASEAUTFERFC  + wbdBASEAUTFERFC;
    wSumbdBaseAUT13RFC  = wSumbdBaseAUT13RFC  + wbdBaseAUT13RFC;
    wSumbdBASEAUT13     = wSumbdBASEAUT13     + wbdBASEAUT13;
    wSumbdBASEAUTC13    = wSumbdBASEAUTC13    + wbdBASEAUTC13;

    wSumbdBASEFPASFN     = wSumbdBASEFPASFN     + wbdBASEFPASFN;
    wSumbdbaseFPASferfn  = wSumbdbaseFPASferfn  + wbdbaseFPASferfn;
    wSumbdBASEFPAS13RFN  = wSumbdBASEFPAS13RFN  + wbdBASEFPAS13RFN;
    wSumbdBASEFPASFC     = wSumbdBASEFPASFC     + wbdBASEFPASFC;
    wSumbdBASEFPASFERFC  = wSumbdBASEFPASFERFC  + wbdBASEFPASFERFC;
    wSumbdBaseFPAS13RFC  = wSumbdBaseFPAS13RFC  + wbdBaseFPAS13RFC;
    wSumbdBASEFPAS13     = wSumbdBASEFPAS13     + wbdBASEFPAS13;
    wSumbdBASEFPASC13    = wSumbdBASEFPASC13    + wbdBASEFPASC13;

    wSumbdBASERATAPOFN     = wSumbdBASERATAPOFN     + wbdBASERATAPOFN;
    wSumbdbaseRATAPOferfn  = wSumbdbaseRATAPOferfn  + wbdbaseRATAPOferfn;
    wSumbdBASERATAPO13RFN  = wSumbdBASERATAPO13RFN  + wbdBASERATAPO13RFN;
    wSumbdBASERATAPOFC     = wSumbdBASERATAPOFC     + wbdBASERATAPOFC;
    wSumbdBASERATAPOFERFC  = wSumbdBASERATAPOFERFC  + wbdBASERATAPOFERFC;
    wSumbdBaseRATAPO13RFC  = wSumbdBaseRATAPO13RFC  + wbdBaseRATAPO13RFC;
    wSumbdBASERATAPO13     = wSumbdBASERATAPO13     + wbdBASERATAPO13;
    wSumbdBASERATAPOC13    = wSumbdBASERATAPOC13    + wbdBASERATAPOC13;

    bdtotSeg = wbdtotSeg;
    bdtotBase = wbdtotBase;
    bdSEGFUN = wbdSEGFUN;
    bdBaseFun = wbdBaseFun;
    bdPercFun = wbdPercFun;
    bdSegPro = wbdSegPro;
    bdBasePro = wbdBasePro;
    bdPercPro = wbdPercPro;
    bdSegAut = wbdSegAut;
    bdBaseAut = wbdBaseAut;
    bdPercAut = wbdPercAut;
    bdbaseratapo = wbdbaseratapo;
    bdvalorratapo = wbdvalorratapo;
    bdsalfam = wbdsalfam;
    bdsalmaternidade = wbdsalmaternidade;
    bdbasefpas = wbdbasefpas;
    bdpercfpas = wbdpercfpas;
    bdpercrat = wbdpercrat;
    bdvaloutentidade = wbdvaloutentidade;
    bddescenqfed = wbddescenqfed;
    bdsimplesgps = wbdsimplesgps;
    bdcodenqfed = wbdcodenqfed;

    bdBASEFUNFN = wbdBASEFUNFN;
    bdbasefunferfn  = wbdbasefunferfn;
    bdBASEFUN13RFN  = wbdBASEFUN13RFN;
    bdBASEFUNFC  = wbdBASEFUNFC;
    bdBASEFUNFERFC = wbdBASEFUNFERFC;
    bdBaseFun13RFC = wbdBaseFun13RFC;
    bdBASEFUN13 = wbdBASEFUN13;
    bdBASEFUNC13 = wbdBASEFUNC13;

    bdBASEPROFN     = wbdBASEPROFN;
    bdbasePROferfn  = wbdbasePROferfn;
    bdBASEPRO13RFN  = wbdBASEPRO13RFN;
    bdBASEPROFC     = wbdBASEPROFC;
    bdBASEPROFERFC  = wbdBASEPROFERFC;
    bdBasePRO13RFC  = wbdBasePRO13RFC;
    bdBASEPRO13     = wbdBASEPRO13;
    bdBASEPROC13    = wbdBASEPROC13;

    bdBASEAUTFN     = wbdBASEAUTFN;
    bdbaseAUTferfn  = wbdbaseAUTferfn;
    bdBASEAUT13RFN  = wbdBASEAUT13RFN;
    bdBASEAUTFC     = wbdBASEAUTFC;
    bdBASEAUTFERFC  = wbdBASEAUTFERFC;
    bdBaseAUT13RFC  = wbdBaseAUT13RFC;
    bdBASEAUT13     = wbdBASEAUT13;
    bdBASEAUTC13    = wbdBASEAUTC13;

    bdBASEFPASFN     = wbdBASEFPASFN;
    bdbaseFPASferfn  = wbdbaseFPASferfn;
    bdBASEFPAS13RFN  = wbdBASEFPAS13RFN;
    bdBASEFPASFC     = wbdBASEFPASFC;
    bdBASEFPASFERFC  = wbdBASEFPASFERFC;
    bdBaseFPAS13RFC  = wbdBaseFPAS13RFC;
    bdBASEFPAS13     = wbdBASEFPAS13;
    bdBASEFPASC13    = wbdBASEFPASC13;

    bdBASERATAPOFN     = wbdBASERATAPOFN;
    bdbaseRATAPOferfn  = wbdbaseRATAPOferfn;
    bdBASERATAPO13RFN  = wbdBASERATAPO13RFN;
    bdBASERATAPOFC     = wbdBASERATAPOFC;
    bdBASERATAPOFERFC  = wbdBASERATAPOFERFC;
    bdBaseRATAPO13RFC  = wbdBaseRATAPO13RFC;
    bdBASERATAPO13     = wbdBASERATAPO13;
    bdBASERATAPOC13    = wbdBASERATAPOC13;

    IF ((wcodtomador = 0) OR ((wemissao IS NULL) OR (wemissao = 1))) THEN
      bdcodtomador = NULL;
    ELSE
      bdcodtomador = wcodtomador;

    IF (wtpcc = 0) THEN
      bdcodtpcc = NULL;
    ELSE
      bdcodtpcc = wtpcc;
    bdtipo = 2;
    bdcodcol = wcodcol;
    bdcodter = wcodter;

    IF (prapenasgps = 1) THEN
      SUSPEND;

    wcodtomadorant = wcodtomador;
    wtpccant = wtpcc;
    wempresaant = bdcodemp;
  END

  bdtipo = 0;
  IF (wcodtomadorant = 0) THEN
     bdcodtomador = NULL;
  ELSE
     bdcodtomador = wcodtomadorant;

  IF (wtpccant = 0) THEN
     bdcodtpcc = NULL;
  ELSE
     bdcodtpcc = wtpccant;

  bdtotSeg = wsumtotSeg;
  bdtotBase = wsumtotBase;
  bdSEGFUN = wSUMSEGFUN;
  bdBaseFun = wSUMBaseFun;
  bdPercFun = wSUMPercFun;
  bdSegPro = wSumSegPro;
  bdBasePro = wSumBasePro;
  bdPercPro = wSumPercPro;
  bdSegAut = wSumSegAut;
  bdBaseAut = wSumBaseAut;
  bdPercAut = wSumPercAut;
  bdbaseratapo = wSumbaseratapo;
  bdvalorratapo = wSumvalorratapo;
  bdsalfam = wSumsalfam;
  bdsalmaternidade = wSumsalmaternidade;
  bdbasefpas = wSumbasefpas;
  bdpercfpas = wSumpercfpas;
  bdpercrat = wSumpercrat;
  bdvaloutentidade = wsumvaloutentidade;
  bddescenqfed = wSumdescenqfed;
  bdsimplesgps = wSumsimplesgps;
  bdcodenqfed = wSumcodenqfed;
  bdcodcol = NULL;

  bdBASEFUNFN = wSumbdBASEFUNFN;
  bdbasefunferfn = wSumbdbasefunferfn;
  bdBASEFUN13RFN = wSumbdBASEFUN13RFN;
  bdBASEFUNFC = wSumbdBASEFUNFC;
  bdBASEFUNFERFC = wSumbdBASEFUNFERFC;
  bdBaseFun13RFC = wSumbdBaseFun13RFC;
  bdBASEFUN13 = wSumbdBASEFUN13;
  bdBASEFUNC13 = wSumbdBASEFUNC13;

  bdBASEPROFN    = wSumbdBASEPROFN;
  bdbasePROferfn = wSumbdbasePROferfn;
  bdBASEPRO13RFN = wSumbdBASEPRO13RFN;
  bdBASEPROFC    = wSumbdBASEPROFC;
  bdBASEPROFERFC = wSumbdBASEPROFERFC;
  bdBasePRO13RFC = wSumbdBasePRO13RFC;
  bdBASEPRO13    = wSumbdBASEPRO13;
  bdBASEPROC13   = wSumbdBASEPROC13;

  bdBASEAUTFN    = wSumbdBASEAUTFN;
  bdbaseAUTferfn = wSumbdbaseAUTferfn;
  bdBASEAUT13RFN = wSumbdBASEAUT13RFN;
  bdBASEAUTFC    = wSumbdBASEAUTFC;
  bdBASEAUTFERFC = wSumbdBASEAUTFERFC;
  bdBaseAUT13RFC = wSumbdBaseAUT13RFC;
  bdBASEAUT13    = wSumbdBASEAUT13;
  bdBASEAUTC13   = wSumbdBASEAUTC13;

  bdBASEFPASFN    = wSumbdBASEFPASFN;
  bdbaseFPASferfn = wSumbdbaseFPASferfn;
  bdBASEFPAS13RFN = wSumbdBASEFPAS13RFN;
  bdBASEFPASFC    = wSumbdBASEFPASFC;
  bdBASEFPASFERFC = wSumbdBASEFPASFERFC;
  bdBaseFPAS13RFC = wSumbdBaseFPAS13RFC;
  bdBASEFPAS13    = wSumbdBASEFPAS13;
  bdBASEFPASC13   = wSumbdBASEFPASC13;

  bdBASERATAPOFN    = wSumbdBASERATAPOFN;
  bdbaseRATAPOferfn = wSumbdbaseRATAPOferfn;
  bdBASERATAPO13RFN = wSumbdBASERATAPO13RFN;
  bdBASERATAPOFC    = wSumbdBASERATAPOFC;
  bdBASERATAPOFERFC = wSumbdBASERATAPOFERFC;
  bdBaseRATAPO13RFC = wSumbdBaseRATAPO13RFC;
  bdBASERATAPO13    = wSumbdBASERATAPO13;
  bdBASERATAPOC13   = wSumbdBASERATAPOC13;
  IF (WEXISTE = 1) THEN
    SUSPEND;
END
^

/* Alter (VRHF_SP_ESTOUROS) */
ALTER PROCEDURE VRHF_SP_ESTOUROS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFEST INTEGER,
BDVALEST NUMERIC(15,6),
BDTIPO INTEGER)
 AS
DECLARE VARIABLE WREF VARCHAR(50);
DECLARE VARIABLE WTABLE VARCHAR(255);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(25000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FOL.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, '||
                'COL.BDNOMCOL, ';

  /* Tipos de calculo:
     -----------------
     0 - Todos; (nao pode ser todos)
     1 - Folha normal;
     2 - Adiantamento salarial;
     3 - Adiantamento de 13o. salario;
     4 - 13o. salario;
     5 - Complemento de 13o. salario;
     6 - Ferias;
     7 - PLR;
     8 - Folha complementar;
     9 - Rescisao. (folha normal)
  */

  IF (prtipocalculo = 2) THEN
     BEGIN
       wsql = wsql||'cast((substring((cast(FOL.BDDATAAD as VARCHAR(10))) from 1 for 4)||substring((cast(FOL.BDDATAAD as VARCHAR(10))) from 6 for 2)) as INTEGER) BDREF, '||
                    'FOL.BDVALVAD, 2';
       wTable = 'VRHF_EMP_TVERBAAD';
       wref = 'FOL.BDDATAAD';
     END
  ELSE
  IF (prtipocalculo = 3) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFA13, '||
                    'FOL.BDVALVA13, 3 ';
       wTable = 'VRHF_EMP_TVERBAA13';
       wref = 'FOL.BDREFA13';
     END
  ELSE
  IF (prtipocalculo = 4) THEN
     BEGIN
       wsql = wsql||'FOL.BDREF13, '||
                    'FOL.BDVALV13, 4 ';
       wTable = 'VRHF_EMP_TVERBA13';
       wref = 'FOL.BDREF13';
     END
  ELSE
  IF (prtipocalculo = 5) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFC13, '||
                    'FOL.BDVALVC13, 5 ';
       wTable = 'VRHF_EMP_TVERBAC13';
       wref = 'FOL.BDREFC13';
     END
  ELSE
  IF (prtipocalculo = 6) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFFE, '||
                    'FOL.BDVALVRFE, 6 ';
       wTable = 'VRHF_EMP_TVERBAFE';
       wref = 'FOL.BDREFFE';
     END
  ELSE
  IF (prtipocalculo = 8) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFCOMP, '||
                    'FOL.BDVALVFC, 8 ';
       wTable = 'VRHF_EMP_TVERBAFC';
       wref = 'FOL.BDREFCOMP';
     END
  ELSE
     BEGIN
       wsql = wsql||'FOL.BDREFFN, '||
                    'FOL.BDVALVFN, '||
                    'FOL.BDTIPO ';
       wTable = 'VWRH_UNION_MES_VERBAS';
       wref = 'FOL.BDREFFN';
     END

  wsql = wsql||
         'from '||wtable||' FOL '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
         'on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) '||
         'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
         'on (EMP.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join vrh_base_tverbas VERBAS '||
         'on (VERBAS.BDCODVER = FOL.BDCODVER) ';

  wwhere = 'where VERBAS.BDCLAVER like '''||'9.002.0.0%'||'''';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wwhere||' order by FOL.BDCODEMP, FOL.BDCODCOL, '||wref||' DESC ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFEST,
    :BDVALEST,
    :BDTIPO
  DO

  SUSPEND;
END
^

/* Alter (VRHF_SP_EXTRATO_FGTS) */
ALTER PROCEDURE VRHF_SP_EXTRATO_FGTS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRREFFIM INTEGER,
PRCC VARCHAR(10000) = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA INTEGER,
BDMOVIMENTACAO VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDACUMULADO NUMERIC(15,6),
BDVALORJAM NUMERIC(15,6),
BDVALORDEPOSITO NUMERIC(15,6))
 AS
declare variable WSQL varchar(32000);
declare variable WSQL2 varchar(1024);
declare variable WDATA varchar(8);
declare variable WVALORJAM numeric(15,6);
declare variable WINDICEJAM numeric(15,6);
declare variable WSOMAFGTS numeric(15,6);
declare variable WSALDOFGTS numeric(15,6);
BEGIN
  /* Procedure Text */
  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     prcodemp = ''''||prcodemp||'''';

  IF (prcodcol IS NULL) THEN
     prcodcol = 'null';
  ELSE
     prcodcol = ''''||prcodcol||'''';

  if (prcc is null) then
     prcc = 'null';
  else
     prcc = ''''||prcc||'''';

  wsql2 = NULL;

  IF (prreffim IS NULL) THEN
     BEGIN
       wsql = 'select rdb$get_context('||''''||'USER_SESSION'||''''||', '||''''||'W_ANOMES'||''''||') from rdb$database';
       EXECUTE STATEMENT wsql INTO wsql2;
     END

  IF (wsql2 IS NOT NULL) THEN
     prreffim = CAST(wsql2 AS INTEGER);


  IF (prreffim IS NULL) THEN
     prreffim = '999999';

  wsql = ' select x.bdcodemp,x.bdcodcol,x.bdref,x.bdvalorjam,x.bdindicejam,x.bdsomafgts,x.bdsaldofgts from VRHF_SP_FICHAFGTS2('||prcodemp||','||prcodcol||','||prreffim||','||prcc||') x';
 -- wsql = wsql||' where coalesce(x.bdsomafgts,0) <> 0';

  FOR EXECUTE STATEMENT wsql INTO
    bdcodemp,
    bdcodcol,
    wdata,
    wvalorjam,
    windicejam,
    wsomafgts,
    wsaldofgts DO
  BEGIN
    bddata = CAST(wdata AS VARCHAR(6))||'00';
    bdmovimentacao = 'Dep?sito '||SUBSTRING(bddata FROM 5 FOR 2)||'/'||SUBSTRING(bddata FROM 1 FOR 4);
    IF (SUBSTRING(bddata FROM 5 FOR 2) = '12') THEN
       bddata = (CAST(SUBSTRING(bddata FROM 1 FOR 4) AS INTEGER)+1)||'0100';
    ELSE
       BEGIN
         IF ((SUBSTRING(bddata FROM 5 FOR 2) < '09')) THEN
            bddata = SUBSTRING(bddata FROM 1 FOR 4)||'0'||(CAST(SUBSTRING(bddata FROM 5 FOR 2) AS INTEGER)+1)||'00';
         ELSE
            bddata = SUBSTRING(bddata FROM 1 FOR 4)||(CAST(SUBSTRING(bddata FROM 5 FOR 2) AS INTEGER)+1)||'00';
       END
    bdvalor = wsomafgts;
    bdvalordeposito = bdvalor;
    bdvalorjam = 0;
    bdacumulado = wsaldofgts;-- - coalesce(wvalorjam,0);
    SUSPEND;

    IF ((wvalorjam IS NOT NULL) AND (wvalorjam > 0)) THEN
       BEGIN
         wsql2 = CAST(windicejam AS VARCHAR(1024));
         SELECT bdresult FROM STRTRAN(:wsql2,'.',',') INTO wsql2;

         bddata = CAST(wdata AS VARCHAR(6))||'10';
/*         if (substring(bddata from 5 for 2) = '12') then
            bddata = substring(bddata from 1 for 4)||'0110';
         else
            begin
              if ((substring(bddata from 5 for 2) < '09')) then
                 bddata = substring(bddata from 1 for 4)||'0'||(cast(substring(bddata from 5 for 2) as integer)+1)||'10';
              else
                 bddata = substring(bddata from 1 for 4)||(cast(substring(bddata from 5 for 2) as integer)+1)||'10';
            end*/
         bdmovimentacao = 'Cr?dito de JAM '||wsql2;
         bdvalor = wvalorjam;
         bdvalordeposito = 0;
         bdvalorjam = bdvalor;
         bdacumulado = wsaldofgts - wsomafgts;
         SUSPEND;
       END
  END
END
^

/* Alter (VRHF_SP_FICHA_REG_COLABORADOR) */
ALTER PROCEDURE VRHF_SP_FICHA_REG_COLABORADOR(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRMODELO INTEGER,
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE,
PROBS INTEGER,
PRSITCOL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDCIDADEEMP VARCHAR(40),
BDUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDFONEEMP DM_BDTELEFONE,
BDDDDEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDNOMCOLORDEM DM_BDNOMCOL,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCOL DATE,
BDCORCOL INTEGER,
BDSEXOCOL INTEGER,
BDPAISCOL VARCHAR(40),
BDNACIONALIDADE VARCHAR(30),
BDDATACHEBRASILCOL DATE,
BDCIDADENASCCOL VARCHAR(40),
BDUFNASCCOL VARCHAR(2),
BDTIPOSANGUECOL INTEGER,
BDCPFCOL VARCHAR(14),
BDRGCOL VARCHAR(13),
BDDATAEMIREGCOL DATE,
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDCNHCOL VARCHAR(11),
BDCATCNHCOL VARCHAR(2),
BDVENCNHCOL DATE,
BDCTPSCOL DM_BDCTPS,
BDSERIECOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDRESERVISTACOL VARCHAR(20),
BDTITELEICOL VARCHAR(20),
BDGRAUINSTCOL INTEGER,
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDESTCIVCOL INTEGER,
BDLOGRCOL DM_LOGRADOURO,
BDENDCOL DM_BDENDERECO,
BDNUMCOL INTEGER,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCIDADECOL VARCHAR(40),
BDUFCOL VARCHAR(2),
BDCEPCOL VARCHAR(9),
BDFONECOL DM_BDTELEFONE,
BDDDDCOL INTEGER,
BDEMAILCOL DM_BDEMAIL,
BDCELCOL DM_BDTELEFONE,
BDDATAADMCOL DATE,
BDDATACADCOL DATE,
BDSALINICOL NUMERIC(15,2),
BDFORMAPAGTOCOL INTEGER,
BDPERCINSALUBCOL NUMERIC(15,6),
BDPERCPERCULCOL NUMERIC(15,2),
BDCATEGORIACOL INTEGER,
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDDEFCOL DM_BOOLEAN,
BDDEFFISICOCOL INTEGER,
BDREAB DM_BOOLEAN,
BDTIPOCOL INTEGER,
BDCTAFGTSCOL VARCHAR(20),
BDDATAOPCAOFGTSCOL DATE,
BDCTADEPCOL VARCHAR(20),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDCODCBO INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDDATAPAGGRFC DATE,
BDCODPRES INTEGER,
BDDESCPRES VARCHAR(110),
BDFOTOCOL BLOB,
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDUFCTPS VARCHAR(2),
BDDESCCATEGORIA VARCHAR(300),
BDNOMBAN VARCHAR(60),
BDCODBAN INTEGER,
BDNOMAG VARCHAR(40),
BDCODAG INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDOBSCOL BLOB SUB_TYPE 1 SEGMENT SIZE 5000,
BDDDDCELCOL INTEGER,
BDSIGLAUFRG VARCHAR(2),
BDDIANASC VARCHAR(2),
BDMESNASC VARCHAR(2),
BDANONASC VARCHAR(10),
BDCONTRCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC DM_BDNOMEMP,
BDNOMCIDTPCC VARCHAR(40),
BDUFTPCC VARCHAR(2))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(15000);
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WDTINI VARCHAR(10);
DECLARE VARIABLE WSQL2 VARCHAR(5000);
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WNOMTPCC DM_BDNOMEMP;
DECLARE VARIABLE WNOMCIDTPCC VARCHAR(40);
DECLARE VARIABLE WUFTPCC VARCHAR(2);
DECLARE VARIABLE WORDEMTPCC INTEGER;
DECLARE VARIABLE WREFADM INTEGER;
BEGIN
  IF (prreferencia IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, PRULTIMODIA);

  wSql = 'select ';
  wSql = wSql || 'temp.bdcodemp, ';
  wSql = wSql || 'temp.bdnomemp, ';
  wSql = wSql || 'temp2.bdcnpjemp, ';
  wSql = wSql || 'temp.bdendemp, ';
  wSql = wSql || 'temp.bdnumemp, ';
  wSql = wSql || 'temp.bdcomplemp, ';
  wSql = wSql || 'temp.bdbaiemp, ';
  wSql = wSql || 'tcidemp.bdnomcid, ';
  wSql = wSql || 'tufemp.bdsiglauf, ';
  wSql = wSql || 'temp.bdcepemp, ';
  wSql = wSql || 'temp.bdfoneemp, ';
  wSql = wSql || 'temp.bddddemp, ';
  wSql = wSql || 'vw_col.bdcodcol, ';
  wSql = wSql || 'vw_col.bdnomcol, ';
  wSql = wSql || 'UPPER(vw_col.bdnomcol) as BDNOMCOLORDEM, ';
  wSql = wSql || 'vw_col.bdnompaicol, ';
  wSql = wSql || 'vw_col.bdnommaecol, ';
  wSql = wSql || 'vw_col.bdnomconjcol, ';
  wSql = wSql || 'vw_col.bddatanasccol, ';
  wSql = wSql || 'vw_col.bdcorcol, ';
  wSql = wSql || 'vw_col.bdsexocol, ';
  wSql = wSql || 'vw_col.bddatachebrasilcol, ';
  wSql = wSql || 'tpaiscol.bddescpais, ';
  wSql = wSql || 'tpaiscol.bdnacionalidade, ';
  wSql = wSql || 'tcidnasccol.bdnomcid, ';
  wSql = wSql || 'tufnasccol.bdsiglauf, ';
  wSql = wSql || 'vw_col.bdTipoSanguecol, ';
  wSql = wSql || 'vw_col.bdcpfcol, ';
  wSql = wSql || 'vw_col.bdrgcol, ';
  wSql = wSql || 'vw_col.bddataemirgcol, ';
  wSql = wSql || 'vw_col.bdorgemirgcol, ';
  wSql = wSql || 'vw_col.bdcnhcol, ';
  wSql = wSql || 'vw_col.bdcatcnhcol, ';
  wSql = wSql || 'vw_col.bdvenccnhcol, ';
  wSql = wSql || 'vw_col.bdctpscol, ';
  wSql = wSql || 'vw_col.bdseriectpscol, ';
  wSql = wSql || 'vw_col.bddseriectpscol, ';
  wSql = wSql || 'vw_col.bdreservistacol, ';
  wSql = wSql || 'vw_col.bdtiteleicol, ';
  wSql = wSql || 'vw_col_ref_atual.bdgrauinstcol, ';
  wSql = wSql || 'vw_col.bdzonaeleicol, ';
  wSql = wSql || 'vw_col.bdsecaoeleicol, ';
  wSql = wSql || 'vw_col.bdpiscol, ';
  wSql = wSql || 'vw_col.bddataemipiscol, ';
  wSql = wSql || 'vw_col_ref_atual.bdestcivcol, ';
  wSql = wSql || 'vw_col.bdlogrcol, ';
  wSql = wSql || 'vw_col.bdendcol, ';
  wSql = wSql || 'vw_col.bdnumcol, ';
  wSql = wSql || 'vw_col.bdcomplcol, ';
  wSql = wSql || 'vw_col.bdbaicol, ';
  wSql = wSql || 'tcidcol.bdnomcid, ';
  wSql = wSql || 'tufcol.bdsiglauf, ';
  wSql = wSql || 'vw_col.bdcepcol, ';
  wSql = wSql || 'vw_col.bdfonecol, ';
  wSql = wSql || 'vw_col.bddddcol, ';
  wSql = wSql || 'vw_col.bdemailcol, ';
  wSql = wSql || 'vw_col.bdcelcol, ';
  wSql = wSql || 'vw_col.bddataadmcol, ';
  wSql = wSql || 'vw_col.bddatacadcol, ';
  wSql = wSql || 'vw_col.bdsalinicol, ';
  wSql = wSql || 'vw_col_ref_atual.bdformapagtocol, ';
  wSql = wSql || 'vw_col_ref_atual.bdpercinsalubcol, ';
  wSql = wSql || 'vw_col_ref_atual.bdpercperculcol, ';
  wSql = wSql || 'vw_col_ref_atual.bdcategoriacol, ';
  wSql = wSql || 'tsintrab.bdCodsintrab, ';
  wSql = wSql || 'tsintrab.bdDescSintrab, ';
  wSql = wSql || 'vw_col.bddefcol, ';
  wSql = wSql || 'case ';
  wSql = wSql ||    'when (vw_col.BDDEFCOL = '||'''FALSE'''||') then 0 ';
  wSql = wSql ||    'else case ';
  wSql = wSql ||             'when (vw_col.BDDEFFIS = '||'''TRUE'''||') and (vw_col.BDDEFVIS = '||'''TRUE'''||' or vw_col.BDDEFAUD = '||'''TRUE'''||' or vw_col.BDDEFMEN = '||'''TRUE'''||' or vw_col.BDREAB = '||'''TRUE'''||') or ';
  wSql = wSql ||                  '(vw_col.BDDEFVIS = '||'''TRUE'''||') and (vw_col.BDDEFFIS = '||'''TRUE'''||' or vw_col.BDDEFAUD = '||'''TRUE'''||' or vw_col.BDDEFMEN = '||'''TRUE'''||' or vw_col.BDREAB = '||'''TRUE'''||') or ';
  wSql = wSql ||                  '(vw_col.BDDEFAUD = '||'''TRUE'''||') and (vw_col.BDDEFFIS = '||'''TRUE'''||' or vw_col.BDDEFVIS = '||'''TRUE'''||' or vw_col.BDDEFMEN = '||'''TRUE'''||' or vw_col.BDREAB = '||'''TRUE'''||') or ';
  wSql = wSql ||                  '(vw_col.BDDEFMEN = '||'''TRUE'''||' or  vw_col.BDDEFINT = '||'''TRUE'''||') and (vw_col.BDDEFFIS = '||'''TRUE'''||' or vw_col.BDDEFAUD = '||'''TRUE'''||' or vw_col.BDDEFVIS = '||'''TRUE'''||' or vw_col.BDREAB = '||'''TRUE'''||') or ';
  wSql = wSql ||                  '(vw_col.BDREAB   = '||'''TRUE'''||') and (vw_col.BDDEFFIS = '||'''TRUE'''||' or vw_col.BDDEFAUD = '||'''TRUE'''||' or vw_col.BDDEFMEN = '||'''TRUE'''||' or vw_col.BDDEFVIS = '||'''TRUE'''||') then 6 ';
  wSql = wSql ||             'else case ';
  wSql = wSql ||                    'when (vw_col.BDDEFFIS = '||'''TRUE'''||') then 1 ';
  wSql = wSql ||                    'else case ';
  wSql = wSql ||                           'when (vw_col.BDDEFAUD = '||'''TRUE'''||') then 2 ';
  wSql = wSql ||                           'else case ';
  wSql = wSql ||                                  'when (vw_col.BDDEFVIS = '||'''TRUE'''||') then 3 ';
  wSql = wSql ||                                  'else case ';
  wSql = wSql ||                                           'when (vw_col.BDDEFMEN = '||'''TRUE'''||' or vw_col.BDDEFINT = '||'''TRUE'''||') then 4 ';
  wSql = wSql ||                                         'else case ';
  wSql = wSql ||                                                'when (vw_col.BDREAB = '||'''TRUE'''||') then 5 ';
  wSql = wSql ||                                              'end ';
  wSql = wSql ||                                       'end ';
  wSql = wSql ||                                'end ';
  wSql = wSql ||                         'end ';
  wSql = wSql ||                  'end ';
  wSql = wSql ||           'end ';
  wSql = wSql ||    'end BDDEFFISICOCOL, ';
  wSql = wSql || 'vw_col_ref_atual.bdtipocol, ';
  wSql = wSql || 'vw_col_ref_atual.bdctafgtscol, ';
  wSql = wSql || 'vw_col_ref_atual.bddataopcaofgtscol, ';
  wSql = wSql || 'vw_col_ref_atual.bdctadepcol, ';
  wsql = wSql || 'COL_DIAVINC.bdCODTFUC, ';
  wSql = wSql || 'tfuc.bddesctfuc, ';
  wsql = wSql || 'tfuc.bdcodcbo,  ';
  wSql = wsql || 'vw_rescisao.bdDATARESCISAO, ';
  wSql = wSql || 'vw_rescisao.bdDATAAVPREVIO, ';
  wsql = wSql || 'vw_rescisao.bdSALDOFGTS, ';
  wSql = wSql || 'vw_rescisao.bdMAIORREMUNERACAO, ';
  wSql = wSql || 'vw_rescisao.bdDATAPAGGRFC, ';
  wSql = wSql || 'vw_rescisao.bdCODPRES, ';
  wSql = wSql || 'vw_rescisao.bdDESCPRES, ';
  wsql = wSql || 'TCOLCON_IMG.BDFOTOCOL_IMG, ';
  wSql = wSql || 'vw_col.bdFICHAREGCOL, ';
  wSql = wSql || 'vw_col.bdLIVROREGCOL, ';
  wSql = wSql || 'vw_col.bdNROFOLHAREGCOL, ';
  wSql = wSql || 'tufctps.bdSIGLAUF, ';
  wSql = wSql || 'tcateg.bdDESCCATEGORIA, ';
  wSql = wSql || 'tban.bdNOMBAN, ';
  wSql = wSql || 'tban.BDCODBAN, ';
  wSql = wSql || 'tbanag.bdNOMAG, ';
  wSql = wsql || 'tbanag.BDCODAG, ';
  wSql = wSql || 'vw_col.bdNATURALIZADOCOL, ';
  wSql = wSql || 'vw_col.bdCABELOSCOL, ';
  wSql = wSql || 'vw_col.bdOLHOSCOL, ';
  wSql = wSql || 'vw_col.bdALTURACOL, ';
  wSql = wSql || 'vw_col.bdPESOCOL, ';
  wSql = wSql || 'vw_col.bdSINAISCOL, ';
  wSql = wSql || 'vw_col.BDCONTRCOL, ';

  IF (probs IS NOT NULL AND probs = 1) THEN
     wSql = wSql || 'vw_col_ref_atual.bdobscol, ';
  ELSE
     wSql = wSql || 'CAST(null as BLOB) bdobscol, ';

  wSql = wSql || 'vw_col.bdDDDCELCOL, ';
  wSql = wSql || 'uf_rg.BDSIGLAUF ';

  wsql = wSql || 'from VW_COLABORADORES_REF_ADM vw_col_ref_atual ';

  wsql = wSql || 'join TEMPRESAS temp2 on (temp2.bdCodemp =  vw_col_ref_atual.bdcodemp) ';
  wsql = wSql || 'left outer join VW_TEMPRESAS_REF temp on (temp.bdCodemp =  vw_col_ref_atual.bdcodemp) ';
  wSql = wSql || 'left outer join tcidade tcidemp on (tcidemp.bdcodcid = temp.bdcodcid) ';
  wSql = wSql || 'left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
  wSql = wSql || 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = vw_col_ref_atual.bdcodemp and vw_col.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  wSql = wSql || 'left outer join tcidade tcidnasccol on (tcidnasccol.bdcodcid = vw_col.bdcodcidnasc) ';
  wSql = wSql || 'left outer join tuf tufnasccol on (tufnasccol.bdcoduf = tcidnasccol.bdcoduf) ';
  wSql = wSql || 'left outer join tcidade tcidcol on (tcidcol.bdcodcid = vw_col.bdcodcid) ';
  wSql = wSql || 'left outer join tuf tufcol on (tufcol.bdcoduf = tcidcol.bdcoduf) ';
  wSql = wSql || 'left outer join tpais tpaiscol on (tpaiscol.bdcodpais = vw_col.bdcodpais) ';
  wsql = wSql || 'left outer join vrh_base_tsindtrab TSINTRAB on (TSINTRAB.bdcodsintrab =  vw_col_ref_atual.bdcodsintrab) ';
  wsql = wsql || 'left outer join VW_TCOLCON_VINCDIA_ADM COL_DIAVINC on (COL_DIAVINC.BDCODEMP = vw_col_ref_atual.BDCODEMP and COL_DIAVINC.BDCODCOL = vw_col_ref_atual.BDCODCOL) ';
  wSql = wSql || 'left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = COL_DIAVINC.bdcodplafuc and tfuc.bdcodtfuc = COL_DIAVINC.bdcodtfuc) ';
  wSql = wSql || 'left outer join VW_RESCISAO on (vw_rescisao.bdCODEMP = temp.bdcodemp and vw_rescisao.bdCODCOL = vw_col_ref_atual.bdCODCOL) ';
  wSql = wSql || 'left outer join VRH_EMP_TCOLCON_IMG TCOLCON_IMG on (TCOLCON_IMG.bdcodemp = vw_col_ref_atual.bdCODEMP and TCOLCON_IMG.bdcodcol = vw_col_ref_atual.bdCODCOL) ';
  wSql = wSql || 'left outer join tuf tufctps on (tufctps.bdcoduf = vw_col.bdcoduf_col_doc) ';
  wSql = wSql || 'left outer join vrh_base_tcategoria tcateg on (vw_col_ref_atual.bdcategoriacol = tcateg.bdcodcategoria) ';
  wSql = wSql || 'left outer join vw_vrhf_base_tempsefip tempsefip on (vw_col_ref_atual.bdcodemp = tempsefip.bdcodemp) ';
  wSql = wSql || 'left outer join tbancos tban on (tban.bdcodban = tempsefip.bdcodban) ';
  wSql = wSql || 'left outer join tbancos_ag tbanag on (tbanag.bdcodban = tempsefip.bdcodban and tbanag.bdcodag = tempsefip.bdcodag) ';
  wSql = wSql || 'left outer join tuf uf_rg on (uf_rg.bdcoduf = vw_col.bdcodufrg) ';

  wdtini = CAST(prultimodia AS VARCHAR(10));
  wdtini = SUBSTRING(wdtini FROM 1 FOR 8)||'01';

  IF (prsitcol IS NOT NULL AND prsitcol = 0) THEN  -- somente ativos
     wsql = wsql || 'join sp_somente_ativos('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 2) THEN  -- somente demitidos
     wsql = wsql || 'join sp_somente_demitidos('''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 3) THEN  -- admitidos no m?s
     wsql = wsql || 'join sp_somente_admitidos_mes('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 4) THEN  -- demitidos no m?s
     wsql = wsql || 'join sp_somente_demitidos_mes('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 5) THEN  -- ativos sem demitidos no m?s
     wsql = wsql || 'join sp_ativos_sem_demitidos_mes('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 6) THEN  -- ativos sem demitidos no m?s, com transferidos
     wsql = wsql || 'join sp_ati_sem_dem_com_transf('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 7) THEN  -- ativos sem afastados o m?s inteiro
     wsql = wsql || 'join sp_ati_sem_afast_mes_int('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 8) THEN  -- afastados o m?s inteiro
     wsql = wsql || 'join sp_afastados_mes_inteiro('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';


  wwhere = '';

  IF (prempresa <> '') THEN
     wwhere = wwhere||prempresa||' ';
  /*Wesley Kowalsi - 18/05/2018 - Solicita??o: 23914 -  Corrigindo erro com o filtro do colaborador*/
  IF ((prcolaborador <> '') and (prcolaborador <> '''''')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'tfuc.bdCODTFUC = '||prfuncao||' ';
     END

  IF (prSindicato > 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'vw_col_ref_atual.bdCODSINTRAB = '||prsindicato||' ';
     END

  IF (prclasse > 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'vw_col_ref_atual.bdCODCLA = '||prClasse||' ';
     END


  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;


  worderby = '';
  IF (prordemimp IS NOT NULL) THEN
     BEGIN
        worderby = 'order by ';
        
        IF (prordemimp = 0) THEN
           worderby = wOrderBy||'vw_col_ref_atual.bdcodemp, vw_col_ref_atual.bdcodcol ';
        ELSE
           IF (prordemimp = 1) THEN
              worderby = wOrderBy||'vw_col_ref_atual.bdcodemp, BDNOMCOLORDEM, vw_col_ref_atual.bdcodcol ';
     END

  wsql = wsql||wwhere||worderby;

  FOR EXECUTE STATEMENT wsql
      INTO
           :bdcodemp,
           :bdnomemp,
           :bdcnpjemp,
           :bdendemp,
           :bdnumemp,
           :bdcomplemp,
           :bdbaiemp,
           :bdcidadeemp,
           :bdufemp,
           :bdcepemp,
           :bdfoneemp,
           :bddddemp,
           :bdcodcol,
           :bdnomcol,
           :bdnomcolordem,
           :bdnompaicol,
           :bdnommaecol,
           :bdnomconjcol,
           :bddatanasccol,
           :bdcorcol,
           :bdsexocol, 
           :bddatachebrasilcol,
           :bdpaiscol,
           :bdnacionalidade,
           :bdcidadenasccol,
           :bdufnasccol,
           :bdtiposanguecol,
           :bdcpfcol,
           :bdrgcol,
           :bddataemiregcol,
           :bdorgemirgcol,
           :bdcnhcol,
           :bdcatcnhcol,
           :bdvencnhcol,
           :bdctpscol,
           :bdseriecol,
           :bddseriectpscol,
           :bdreservistacol,
           :bdtiteleicol,
           :bdgrauinstcol,
           :bdzonaeleicol,
           :bdsecaoeleicol,
           :bdpiscol,
           :bddataemipiscol,
           :bdestcivcol,
           :bdlogrcol,
           :bdendcol,
           :bdnumcol,
           :bdcomplcol,
           :bdbaicol,
           :bdcidadecol,
           :bdufcol,
           :bdcepcol,
           :bdfonecol,
           :bddddcol,
           :bdemailcol,
           :bdcelcol,
           :bddataadmcol,
           :bddatacadcol,
           :bdsalinicol,
           :bdformapagtocol,
           :bdpercinsalubcol,
           :bdpercperculcol,
           :bdcategoriacol,
           :bdcodsintrab,
           :bddescsintrab,
           :bddefcol,
           :bddeffisicocol,
           :bdtipocol,
           :bdctafgtscol,
           :bddataopcaofgtscol,
           :bdctadepcol,
           :bdcodtfuc,
           :bddesctfuc,
           :bdcodcbo,
           :bddatarescisao,
           :bddataavprevio,
           :bdsaldofgts,
           :bdmaiorremuneracao,
           :bddatapaggrfc,
           :bdcodpres,
           :bddescpres,
           :bdfotocol,
           :bdficharegcol,
           :bdlivroregcol,
           :bdnrofolharegcol,
           :bdufctps,
           :bddesccategoria,
           :bdnomban,
           :bdcodban,
           :bdnomag,
           :bdcodag,
           :bdnaturalizadocol,
           :bdcabeloscol,
           :bdolhoscol,
           :bdalturacol,
           :bdpesocol,
           :bdsinaiscol,
           :bdcontrcol,
           :bdobscol,
           :bddddcelcol,
           :bdsiglaufrg
         DO
       BEGIN

         IF (bddatanasccol IS NOT NULL) THEN
            BEGIN
              bddianasc = SUBSTRING(CAST(bddatanasccol AS VARCHAR(10)) FROM 9 FOR 2);
              bdmesnasc = SUBSTRING(CAST(bddatanasccol AS VARCHAR(10)) FROM 6 FOR 2);
              bdanonasc = SUBSTRING(CAST(bddatanasccol AS VARCHAR(10)) FROM 1 FOR 4);
            END

         wcodcentro = NULL;
         wcodtpcc = NULL;
         wnomtpcc = NULL;
         wnomcidtpcc = NULL;
         wuftpcc = NULL;
         wordemtpcc = NULL;
         
        /*Wesley Kowalski - 18/05/2018 - Solicita??o: 23914 - 
          Alterado o sql para pegar o ?ltimo centro de custo lan?ado no colaborador, antes n?o estava trazendo corretamente o ?ltimo centro de custo.*/    
          wsql2 = ' select first 1'||
                   ' BDCODCENTRO,'||
                 ' BDCODTPCC,'||
                 ' BDORDEM'||
                 ' from (select'||
                 '       BDCODCENTRO,'||
                 '       BDCODTPCC,'||
                 '       BDORDEM'||
                 '       from VRHF_EMP_TPREPFN'||
                 '       where'||
                 '       BDCODEMP = '||bdcodemp||'and'||
                 '       BDCODCOL = '||bdcodcol||
                 '       order by BDCODCOL ASC, BDORDEM DESC) as X'||
                 ' ORDER BY BDORDEM DESC';

         EXECUTE STATEMENT wsql2 INTO :wcodcentro, :wcodtpcc, :wordemtpcc;

         /* verifica se o lan?amento ? para a empresa */
         IF ((wcodtpcc IS NULL) AND (wordemtpcc IS NOT NULL)) THEN
            BEGIN
              wsql2 = 'select EMP.BDNOMEMP, CID.BDNOMCID, UF.BDSIGLAUF '||
                      'from VW_TEMPRESAS_REF EMP '||
                      'left outer join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID) '||
                      'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) '||
                      'where EMP.BDCODEMP = '||bdcodemp;
    
              EXECUTE STATEMENT wsql2 INTO :wnomtpcc, :wnomcidtpcc, :wuftpcc;
            END
         ELSE
         IF (wcodtpcc IS NOT NULL AND wcodcentro IS NOT NULL) THEN
            BEGIN
              wsql2 = 'select COALESCE(CID.BDNOMCID, CID2.BDNOMCID) BDNOMCID, '||
                      'case when ((CID.BDNOMCID = '''||''||''') or (CID.BDNOMCID is null)) then UF2.BDSIGLAUF else UF.BDSIGLAUF end BDSIGLAUF, '||
                      'case when ((CT.BDNOMETOM = '''||''||''') or (CT.BDNOMETOM is null)) then CUS.BDNOMCTA else CT.BDNOMETOM end BDNOMTPCC '||
                      'from CENTROS_TPCC CUS '||
                      'left outer join VRH_BASE_TCUSTOM CT on (CT.BDCODCENTRO = CUS.BDCODCENTRO and CT.BDCODTPCC = CUS.BDCODTPCC) '||
                      'left outer join VRH_CUSTOS_TCUSTOS CC on (CC.BDCODCENTRO = CUS.BDCODCENTRO and CC.BDCODTPCC = CUS.BDCODTPCC) '||
                      'left outer join TCIDADE CID on (CID.BDCODCID = CC.BDCODCID) '||
                      'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) '||
                      'left outer join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = '||bdcodemp||')'||
                      'left outer join TCIDADE CID2 on (EMP.BDCODCID = CID2.BDCODCID) '||
                      'left outer join TUF UF2 on (CID2.BDCODUF = UF2.BDCODUF) '||
                      'where CUS.BDCODCENTRO = '||wcodcentro||' and CUS.BDCODTPCC = '||wcodtpcc;

              EXECUTE STATEMENT wsql2 INTO :wnomcidtpcc, :wuftpcc, :wnomtpcc;
            END

         bdcodcentro = wcodcentro;
         bdcodtpcc = wcodtpcc;
         bdnomtpcc = wnomtpcc;
         bdnomcidtpcc = wnomcidtpcc;
         bduftpcc = wuftpcc;
         SUSPEND;
       END
END
^

/* Alter (VRHF_SP_FICHAFGTS2) */
ALTER PROCEDURE VRHF_SP_FICHAFGTS2(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFFIM INTEGER,
PRCC VARCHAR(15000) = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODIND INTEGER,
BDBFGTS NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDBFGTSFC NUMERIC(18,6),
BDFGTSFC NUMERIC(18,6),
BDBASEFGTSA13 NUMERIC(18,6),
BDFGTSA13 NUMERIC(18,6),
BDBASEFGTS13 NUMERIC(18,6),
BDFGTS13 NUMERIC(18,6),
BDBASEFGTSC13 NUMERIC(18,6),
BDFGTSC13 NUMERIC(18,6),
BDINDICEJAM NUMERIC(18,6),
BDSALDOANTFGTS NUMERIC(18,6),
BDVALORJAM NUMERIC(18,6),
BDSALDOFGTS NUMERIC(18,6),
BDSOMAFGTS NUMERIC(18,6),
BDPERCINDCOMP NUMERIC(18,6),
BDVALORINDCOMP NUMERIC(18,6),
BDTIPO INTEGER)
 AS
declare variable WSQLAUX varchar(3000);
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WANO integer;
declare variable WMES integer;
declare variable WDATA date;
declare variable WTOTALFGTS numeric(15,6);
declare variable WCONTAJAM integer;
declare variable WVALORMES1 numeric(15,6);
declare variable WVALORMES2 numeric(15,6);
declare variable WINDJAMANT numeric(15,6);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODIND integer;
BEGIN
  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       prreffim = wano||LPAD(wmes, 2, '0');
     END

  EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  IF ((PRCODEMP IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       prcodemp = UPPER(prcodemp);
       IF (POSITION('TAB.BDCODEMP',prcodemp) > 0) THEN
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'TAB.BDCODEMP','EMP.BDCODEMP') INTO prcodemp;
          END
     END

  wsql = 'select TEMP.BDCODEMP, '||
                'TEMP.BDCODCOL, '||
                'TEMP.BDREF, '||
                'SUM(TEMP.BDBFGTSFN), '||
                'SUM(TEMP.BDFGTSFN), '||
                'SUM(TEMP.BDBFGTSFC), '||
                'SUM(TEMP.BDFGTSFC), '||
                'SUM(TEMP.BDBASEFGTSA13), '||
                'SUM(TEMP.BDFGTSA13), '||
                'SUM(TEMP.BDBASEFGTS13), '||
                'SUM(TEMP.BDFGTS13), '||
                'SUM(TEMP.BDBASEFGTSC13), '||
                'SUM(TEMP.BDFGTSC13), '||
                'case when COALESCE(TEMP.BDTIPO,0) = 9 then 9 else 0 end BDTIPO ';    --15882 - Bruno L. R. - 27/10/2016

  if (COALESCE(prCC, '') <> '') then
     wsql = wsql||'from VW_UNION_FGTS_CC TEMP ';
  else
     wsql = wsql||'from VW_UNION_FGTS TEMP ';

  wsql = wsql||'join SP_CONSULTAEMPRESAS('||prreffim||',';

  IF ((UPPER(prcodemp) IS NULL) OR (prcodemp = '')) THEN
    wsql = wsql||'null,';
  ELSE
    wsql = wsql||''''||prcodemp||''', ';

  wsql = wsql||'0) EMPS on (EMPS.BDCODEMP = TEMP.BDCODEMP) ';

  wwhere = 'TEMP.BDREF <= '||PRREFFIM;

  IF ((PRCODEMP IS NOT NULL) AND (prcodemp <> '')) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      wwhere = wwhere||PRCODEMP||' ';
    END

  IF ((PRCODCOL IS NOT NULL) AND (prcodcol <> '')) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      wwhere = wwhere||PRCODCOL||' ';
    END

  if (COALESCE(prCC, '') <> '') then
     begin
       prcc = UPPER(prcc);
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       wwhere = wwhere||replace(prcc, 'BDCODTPCC', 'TEMP.BDCODTPCC')||' ';
     end

  IF (wwhere <> '') THEN
    wwhere = ' where '||wwhere;

  -- Group by
  wwhere = wwhere||
           ' group by TEMP.BDCODEMP, TEMP.BDCODCOL, TEMP.BDREF, BDTIPO ';

  wsql = wsql||wwhere;
  wsql = wsql||' order by TEMP.BDCODEMP, TEMP.BDCODCOL, TEMP.BDREF, BDTIPO ';

  windjamant = 0;
  wcodemp = 0;
  wcodcol = 0;

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODEMP,
      :BDCODCOL,
      :BDREF,
      :BDBFGTS,
      :BDFGTS,
      :BDBFGTSFC,
      :BDFGTSFC,
      :BDBASEFGTSA13,
      :BDFGTSA13,
      :BDBASEFGTS13,
      :BDFGTS13,
      :BDBASEFGTSC13,
      :BDFGTSC13,
      :BDTIPO
    DO
      BEGIN
        wsqlAux = 'select first 1 BDCODIND from VRHF_BASE_TEMPVINC where BDCODEMP = '||bdcodemp||' and BDREFEMP <= '||bdref||' order by BDREFEMP DESC ';
        wcodind = NULL;
        EXECUTE STATEMENT wsqlaux INTO :wcodind;
        BDCODIND = wcodind;

        IF (wcodemp <> :bdcodemp OR (wcodcol <> :bdcodcol)) THEN
           BEGIN
             wtotalfgts = 0;
             wcontajam = 0;
             wvalormes1 = NULL;
             wvalormes2 = NULL;
      
             wcodemp = :bdcodemp;
             wcodcol = :bdcodcol;
           END
    

        wcontajam = wcontajam + 1;
    
        bdindicejam = 0;
    
        IF (wcontajam > 2) THEN
        BEGIN
          IF ((bdcodind IS NOT NULL) AND (:bdcodind > 0) AND (:bdref > 0)) THEN
          BEGIN
            wsqlaux = 'select x.bdvalind from TINDVAL x where x.bdcodind = '||:bdcodind||' and x.bdrefind = '||:bdref;
            EXECUTE STATEMENT wsqlaux INTO :bdindicejam;
          END
          ELSE
          BEGIN
            bdindicejam = 0;
          END
        END

        wsqlaux = 'select first 1 coalesce(bdindcomp, 0) bdindcomp from VRHF_BASE_TEMPGPS x where x.bdcodemp = '||wcodemp||' and x.bdrefemp <= '||:bdref||' order by bdcodemp, bdrefemp desc';
        EXECUTE STATEMENT wsqlaux INTO :BDPERCINDCOMP;

        BDVALORINDCOMP = 0;
        IF (BDPERCINDCOMP > 0) THEN
          BEGIN
            BDVALORINDCOMP = TRUNC((BDBFGTS * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBFGTSFC * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTSA13 * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTS13 * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTSC13 * (BDPERCINDCOMP / 100)), 2);
          END
    
        wtotalfgts = wtotalfgts + bdfgts + bdfgts13 + bdfgtsa13 + bdfgtsfc;
        bdsaldoantfgts = 0;
        bdsomafgts = bdfgts + bdfgts13 + bdfgtsa13 + bdfgtsfc;
    
        IF ((wvalormes1 IS NULL) AND (wvalormes2 IS NULL)) THEN
           wvalormes1 = wtotalfgts;
        ELSE
        IF ((wvalormes1 IS NOT NULL) AND (wvalormes2 IS NULL)) THEN
           wvalormes2 = wtotalfgts;
        ELSE
        IF ((wvalormes1 IS NOT NULL) AND (wvalormes2 IS NOT NULL)) THEN
          BEGIN
            bdsaldoantfgts = wvalormes1;
            wvalormes1 = wvalormes2;
            wvalormes2 = wtotalfgts;
          END
    
        IF (TRUNC((bdsaldoantfgts * CAST(bdindicejam AS NUMERIC(15, 6))), 2) >= 0) THEN
           BEGIN
             bdvalorjam = TRUNC(((bdsaldoantfgts + windjamant) * CAST(bdindicejam AS NUMERIC(15, 6))), 2);
             windjamant = bdvalorjam;
    
             IF (wvalormes2 IS NOT NULL) THEN
                wvalormes2 = wvalormes2 + windjamant;
           END
        ELSE
           BEGIN
             bdvalorjam = 0;
             windjamant = 0;
           END
    
    
        bdsaldofgts = wtotalfgts + bdvalorjam;
    
        wtotalfgts = wtotalfgts + bdvalorjam;
    
    --    if (prrefini > 0)  then
    --      begin
    --        if (bdref >= prrefini) then
    --           suspend;
    --      end
    --    else
        SUSPEND;
    
      END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_FICHAINSS) */
ALTER PROCEDURE VRHF_SP_FICHAINSS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDINSSC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WDATA DATE;
BEGIN

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);


  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'X.BDREF, '||
                'SUM(X.BDBINSSFN), '||
                'SUM(X.BDINSSFN), '||
                'SUM(X.BDBASEINSS13), '||
                'SUM(X.BDINSS13), '||
                'SUM(X.BDBASEINSSC13), '||
                'SUM(X.BDINSSC13) ';

  wsql = wsql||'from VW_UNION_INSS X '||

             'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
             'on (EMP.BDCODEMP = X.BDCODEMP) '||

             'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
             'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF (PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;


  -- Group by
  wwhere = wwhere||
           ' group by X.BDCODEMP, '||
                     'EMP.BDNOMEMP, '||
                     'X.BDCODCOL, '||
                     'COL.BDNOMCOL, '||
                     'X.BDREF ';

  wsql = wsql||wwhere;

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :BDCODCOL,
        :bdnomcol,
        :BDREF,
        :BDBINSS,
        :BDINSS,
        :BDBASEINSS13,
        :BDINSS13,
        :BDBASEINSSC13,
        :BDINSSC13
      DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Alter (VRHF_SP_FICHAIR) */
ALTER PROCEDURE VRHF_SP_FICHAIR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRTIPOCALC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF VARCHAR(10),
BDTIPOCALC INTEGER,
BDBRUTO NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDVALIR NUMERIC(15,6),
BDVALINSS NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WDATA DATE;
BEGIN

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);


  IF ((PRCODEMP IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       prcodemp = UPPER(prcodemp);
       IF (POSITION('TAB.BDCODEMP',prcodemp) > 0) THEN
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'TAB.BDCODEMP','EMP.BDCODEMP') INTO prcodemp;
          END
     END

  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'X.BDREF, '||
                'X.BDTIPOCALC, '||
                'SUM(X.BDBRUTO), '||
                'SUM(X.BDDEP), '||
                'SUM(X.BDVALIR), '||
                'SUM(X.BDVALINSS) ';


  wsql = wsql||'from VW_UNION_IR X '||

             'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
             'on (EMP.BDCODEMP = X.BDCODEMP) '||

             'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
             'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

  wwhere = '';

  IF ((PRCODEMP IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF ((PRCODCOL IS NOT NULL) AND (prcodcol <> '')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (prtipocalc IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDTIPOCALC = '||prtipocalc||') ';
     END


  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;


  -- Group by
  wwhere = wwhere||
           ' group by X.BDCODEMP, '||
                     'EMP.BDNOMEMP, '||
                     'X.BDCODCOL, '||
                     'COL.BDNOMCOL, '||
                     'X.BDREF, '||
                     'X.BDTIPOCALC ';

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
     INTO
        :bdcodemp,
        :bdnomemp,
        :bdcodcol,
        :bdnomcol,
        :bdref,
        :bdtipocalc,
        :bdbruto,
        :bddep,
        :bdvalir,
        :bdvalinss
      DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Alter (VRHF_SP_FICHAIR_ANUAL) */
ALTER PROCEDURE VRHF_SP_FICHAIR_ANUAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOBASE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDDATAADMCOL DATE,
BDDATARESCISAO DATE,
BDREF VARCHAR(10),
BDRENDTRIB NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDALUGUEIS NUMERIC(15,6),
BDPRIVPRIVADA NUMERIC(15,6),
BDDESPMEDICAS NUMERIC(15,6),
BDPENSAOALIM NUMERIC(15,6),
BDPENSAOJUDICIAL NUMERIC(15,6),
BDAJUDACUSTO NUMERIC(15,6),
BDLUCROPJ NUMERIC(15,6),
BDAVISOPREV NUMERIC(15,6),
BDRENDTRIB13 NUMERIC(15,6),
BDDEP13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDPENSAOALIM13 NUMERIC(15,6),
BDDATA DATE,
BDGRUPO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQLFUNC VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE I INTEGER;
DECLARE VARIABLE WREFAUX INTEGER;
DECLARE VARIABLE WDATAAUX DATE;
DECLARE VARIABLE WQBG INTEGER;
DECLARE VARIABLE WDATASAIDA DATE;
BEGIN

 wAno = pranobase;
 wMes = '12';

 EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);

 wsqlfunc = ' select T.BDCODEMP, ' ||
             ' EMPRESAS.BDNOMEMP, ' ||
             'EMPRESAS.BDCNPJEMP,' ||
             'T.BDCODCOL,' ||
             'vw_col.bdnomcol,' ||
             'vw_col.BDCPFCOL,' ||
             'vw_col.BDDATAADMCOL,' ||
             'TRESCISAO.BDDATARESCISAO' ||
             ' from VW_COLABORADORES_REF_ATUAL  t' ;

  wsqlfunc = wsqlfunc||' left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsqlfunc = wsqlfunc|| 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = t.bdcodemp and vw_col.bdcodcol = t.bdcodcol) ';

  wsqlfunc = wsqlfunc|| 'left outer join VRH_EMP_TRESCISAO TRESCISAO on (TRESCISAO.bdcodemp = t.bdcodemp and TRESCISAO.bdcodcol = t.bdcodcol) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsqlfunc = wsqlfunc||wwhere;

  -- FAZ UM FOR EM TODOS OS FUNCIONARIOS
  FOR EXECUTE STATEMENT wsqlfunc
    INTO :BDCODEMP, :bdnomemp, :bdcnpjemp, :bdcodcol , :bdnomcol, :bdcpfcol, :bddataadmcol, :bddatarescisao DO
    BEGIN

      i = 0;
      wrefaux = wano||'01';

      WHILE (i < 12) DO
        BEGIN
          i = i + 1;

          wsql = 'select X.BDREF, '||
                 'SUM(X.BDBRUTO), '||
                 'SUM(X.BDDEP), '||
                 'SUM(X.BDVAlIR), '||
                 'SUM(X.BDVALINSS) ';
            
                
          wsql = wsql||'from VW_UNION_IR X '||
                       'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
                       'on (EMP.BDCODEMP = X.BDCODEMP) '||
        
                       'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
                       'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

          wwhere = '';

          wwhere = wwhere||'(X.BDREF = '||wrefaux||')';

          wwhere = wwhere||' and (X.BDTIPOCALC = '||'1'||') ';

          wwhere = wwhere||' and x.bdcodemp = '||:bdcodemp;

          wwhere = wwhere||' and x.bdcodcol = '||:bdcodcol;


          IF (wwhere <> '') THEN
             wwhere = 'where '||wwhere;

           -- Group by
          wwhere = wwhere||
                         ' group by X.BDCODEMP, '||
                         'EMP.BDNOMEMP, '||
                         'X.BDCODCOL, '||
                         'COL.BDNOMCOL, '||
                         'X.BDREF, '||
                         'X.BDTIPOCALC ';

          wsql = wsql||wwhere;

          wqbg = 0;

          FOR EXECUTE STATEMENT wsql
            INTO
              :bdref,
              :bdrendtrib,
              :bddep,
              :bdirrf,
              :bdinss
            DO
          BEGIN
            wqbg = wqbg + 1;
          END

          IF (wqbg = 0) THEN
            BEGIN
              bdref = wrefaux;
              bdrendtrib = 0;
              bddep = 0;
              bdirrf = 0;
              bdinss = 0;
            END

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''0.030.0.1%'')')
            INTO bdpensaoalim;

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''0.030.0.0%'')')
            INTO bdpensaojudicial;

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''0.030.1.0%'')')
            INTO bddespmedicas;

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''0.040.0%'')')
            INTO bdajudacusto;

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''7.001.2.1%'')')
            INTO bdavisoprev;

            IF (bdalugueis IS NULL) THEN
               bdalugueis = 0;

            IF (bdprivprivada IS NULL) THEN
               bdprivprivada = 0;

            IF (bddespmedicas IS NULL) THEN
               bddespmedicas = 0;

            IF (bdpensaoalim IS NULL) THEN
               bdpensaoalim = 0;

            IF (bdpensaojudicial IS NULL) THEN
               bdpensaojudicial = 0;

            IF (bdajudacusto IS NULL) THEN
               bdajudacusto = 0;

            IF (bdlucropj IS NULL) THEN
               bdlucropj = 0;

            IF (bdavisoprev IS NULL) THEN
               bdavisoprev = 0;

            IF (bdpensaoalim13 IS NULL) THEN
               bdpensaoalim13 = 0;


            IF (i = 1) THEN
              BEGIN
                /* inicio calculo 13 salario */

                wsql = 'select SUM(X.BDBRUTO), '||
                       'SUM(X.BDDEP), '||
                       'SUM(X.BDVAlIR), '||
                       'SUM(X.BDVALINSS) ';
            
                
                wsql = wsql||'from VW_UNION_IR X '||
                         'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
                         'on (EMP.BDCODEMP = X.BDCODEMP) '||
        
                         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
                         'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

                wwhere = '';

                /* verbas de 13 salario de todo ano... */

                wwhere = wwhere||'(X.BDREF between '||wano||'01'||' and '||wano||'12'||') ';

                /* tipo de calculo 4 = Decimo terceiro salario */
                wwhere = wwhere||' and (X.BDTIPOCALC = '||'4'||') ';

                wwhere = wwhere||' and x.bdcodemp = '||:bdcodemp;

                wwhere = wwhere||' and x.bdcodcol = '||:bdcodcol;


                IF (wwhere <> '') THEN
                   wwhere = 'where '||wwhere;

                -- Group by
                wwhere = wwhere||
                         ' group by X.BDCODEMP, '||
                         'EMP.BDNOMEMP, '||
                         'X.BDCODCOL, '||
                         'COL.BDNOMCOL, '||
                         'X.BDREF, '||
                         'X.BDTIPOCALC ';

                wsql = wsql||wwhere;

                wqbg = 0;

                FOR EXECUTE STATEMENT wsql
                INTO
                  :bdrendtrib13,
                  :bddep13,
                  :bdirrf13,
                  :bdinss13
                DO
                BEGIN
                  wqbg = wqbg + 1;
                END

                IF (wqbg = 0) THEN
                  BEGIN
                    bdrendtrib13 = 0;
                    bddep13 = 0;
                    bdirrf13 = 0;
                    bdinss13 = 0;
                  END

                SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''5.001.0.1%'')')
                INTO bdpensaoalim13;

                IF (bdpensaoalim13 IS NULL) THEN
                   bdpensaoalim13 = 0;

              END

            wdatasaida = CAST(SUBSTRING(CAST(wrefaux AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wrefaux AS VARCHAR(6)) FROM 1 FOR 4) AS DATE);
            bddata = wdatasaida;
            bdgrupo = 1;

            SUSPEND;
            bdgrupo = 2;
            SUSPEND;

            wdataaux = CAST(SUBSTRING(CAST(wrefaux AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wrefaux AS VARCHAR(6)) FROM 1 FOR 4) AS DATE);

            wdataaux = addmonth(wdataaux, 1);

            wrefaux = SUBSTRING(CAST(wdataaux AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataaux AS VARCHAR(40)) FROM 6 FOR 2);

            bdalugueis = 0;
            bdprivprivada = 0;
            bddespmedicas = 0;
            bdpensaoalim = 0;
            bdpensaojudicial = 0;
            bdajudacusto = 0;
            bdlucropj = 0;
            bdavisoprev = 0;

        END /* laco dos 12 meses */

        /* zera os campos de 13 salario na troca de funcionario */
        bdrendtrib13 = 0;
        bddep13 = 0;
        bdirrf13 = 0;
        bdinss13 = 0;



    END /* FIM LACO DE FUNCIONARIO..... */


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Alter (VRHF_SP_FICHARAIS) */
ALTER PROCEDURE VRHF_SP_FICHARAIS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WDATA DATE;
BEGIN

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);


  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'X.BDREF, '||
                'SUM(X.BDBRAISFN), '||
                'SUM(X.BDBRAIS13), '||
                'SUM(X.BDBRAISA13), '||
                'SUM(X.BDBRAISC13) ';

  wsql = wsql||'from VW_UNION_RAIS X '||

             'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
             'on (EMP.BDCODEMP = X.BDCODEMP) '||

             'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
             'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF (PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;


  -- Group by
  wwhere = wwhere||
           ' group by X.BDCODEMP, '||
                     'EMP.BDNOMEMP, '||
                     'X.BDCODCOL, '||
                     'COL.BDNOMCOL, '||
                     'X.BDREF ';

  wsql = wsql||wwhere;

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :BDCODCOL,
        :bdnomcol,
        :BDREF,
        :BDBRAIS,
        :bdb13,
        :bdba13,
        :bdbc13
      DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Alter (VRHF_SP_FICHARAIS_NOVO) */
ALTER PROCEDURE VRHF_SP_FICHARAIS_NOVO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WANO integer;
declare variable WMES integer;
declare variable WDATA date;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
BEGIN

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);


  wsql = 'select x.BDCODEMP, x.BDCODCOL, x.BDREF,'||
         ' case when x.ORIGEM = 0 then x.BDBRAISFN else x.x1 end BDBRAISFN,'||
         ' case when x.ORIGEM = 0 then x.BDBRAIS13 else x.x2 end BDBRAIS13,'||
         ' case when x.ORIGEM = 0 then x.BDBRAISA13 else x.x3 end BDBRAISA13,'||
         ' case when x.ORIGEM = 0 then x.BDBRAISC13 else x.x4 end BDBRAISC13'||
         ' from ('||
         '        select BDCODEMP, BDCODCOL, BDREF,'||
         '               sum(BDBRAISFN) BDBRAISFN, sum(BDBRAIS13) BDBRAIS13, sum(BDBRAISA13) BDBRAISA13, sum(BDBRAISC13) BDBRAISC13, sum(x1) x1, sum(x2) x2, sum(x3) x3, sum(x4) x4,'||
         '               min(BDORIGEM) ORIGEM'||
         '               from ('||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0 x1,0 x2,0 x3,0 x4, BDTIPO, 0 BDORIGEM FROM VW_RAIS_FOL_NORMAL'||
         '        union all'||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_FOL_COMPLEMENTAR'||
         '        union all'||
         '        select BDCODEMP, BDCODCOL, BDREF, sum(BDBRAISFN), sum(BDBRAIS13), sum(BDBRAISA13), sum(BDBRAISC13), sum(X1) X1, sum(X2) X2, sum(X3) X3, sum(X4) X4, 0, min(BDORIGEM)'||
         '        from (select BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0 X1, 0 X2, 0 X3, 0 X4, 0 BDORIGEM'||
         '              from VW_RAIS_A13'||
         '              union all'||
         '              select BDCODEMP, BDCODCOL, BDREF, 0, 0, 0, 0, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 1 BDORIGEM'||
         '              from VW_FICHA_RAIS_AD13)'||
         '        group by BDCODEMP, BDCODCOL, BDREF'||
         '        union all'||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_13S'||
         '        union all'||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_C13'||
         '        union all'||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_FOL_AVULSA'||
         '        union all'||
         '        SELECT FF.BDCODEMP, FF.BDCODCOL, FF.BDREF, 0,0,0,0,FF.BDBRAISFN, FF.BDBRAIS13, FF.BDBRAISA13, FF.BDBRAISC13, ff.BDTIPO, 1 BDORIGEM from vw_ficha_rais2 FF'||
         '        )'||
         '        group by BDCODEMP, BDCODCOL, BDREF'||
         '      ) x ';

  wsql = wsql||' left outer join VW_VRH_EMP_TCOLCON_CAD COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF (PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  -- Group by
--  wwhere = wwhere||
--           ' group by X.BDCODEMP, '||
--                     'EMP.BDNOMEMP, '||
--                     'X.BDCODCOL, '||
--                     'COL.BDNOMCOL, '||
--                     'X.BDREF ';

  wsql = wsql||wwhere;
  wsql = wsql||' order by x.BDCODEMP, x.BDCODCOL';
  wempatu = 0;
  wcolatu = 0;

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDCODCOL,
        :BDREF,
        :BDBRAIS,
        :bdb13,
        :bdba13,
        :bdbc13
      DO
      begin
        if ((wempatu <> BDCODEMP) or (wcolatu <> BDCODCOL)) then
           begin
             wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||prreffim||' order by BDREFCOL DESC';
             execute statement wwhere into :BDNOMCOL;

             if (wempatu <> BDCODEMP) then
                begin
                  wwhere = 'select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||prreffim||' order by BDREFEMP DESC';
                  execute statement wwhere into :BDNOMEMP;
                end

              wempatu = BDCODEMP;
              wcolatu = BDCODCOL;
           end

  SUSPEND;
      end

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);

END
^

/* Alter (VRHF_SP_GPS) */
ALTER PROCEDURE VRHF_SP_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUTERCEIROS NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACUM VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALNOTAS NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
DECLARE VARIABLE wsqltipofolha VARCHAR(1000);
DECLARE VARIABLE wbdbasefunfn NUMERIC(15,6);
DECLARE VARIABLE wbdbasefunfc NUMERIC(15,6);
DECLARE VARIABLE wbdbasefunferfn NUMERIC(15,6);
DECLARE VARIABLE wbdbasefunferfc NUMERIC(15,6);
DECLARE VARIABLE wbdbasefun13rfn NUMERIC(15,6);
DECLARE VARIABLE wbdbasefun13rfc NUMERIC(15,6);
DECLARE VARIABLE wbdbasefun13 NUMERIC(15,6);
DECLARE VARIABLE wbdbasefunc13 NUMERIC(15,6);
DECLARE VARIABLE wbdbaseprofn NUMERIC(15,6);
DECLARE VARIABLE wbdbaseprofc NUMERIC(15,6);
DECLARE VARIABLE wbdbaseproferfn NUMERIC(15,6);
DECLARE VARIABLE wbdbaseproferfc NUMERIC(15,6);
DECLARE VARIABLE wbdbasepro13rfn NUMERIC(15,6);
DECLARE VARIABLE wbdbasepro13rfc NUMERIC(15,6);
DECLARE VARIABLE wbdbasepro13 NUMERIC(15,6);
DECLARE VARIABLE wbdbaseproc13 NUMERIC(15,6);
DECLARE VARIABLE wbdbaseautfn NUMERIC(15,6);
DECLARE VARIABLE wbdbaseautfc NUMERIC(15,6);
DECLARE VARIABLE wbdbaseautferfn NUMERIC(15,6);
DECLARE VARIABLE wbdbaseautferfc NUMERIC(15,6);
DECLARE VARIABLE wbdbaseaut13rfn NUMERIC(15,6);
DECLARE VARIABLE wbdbaseaut13rfc NUMERIC(15,6);
DECLARE VARIABLE wbdbaseaut13 NUMERIC(15,6);
DECLARE VARIABLE wbdbaseautc13 NUMERIC(15,6);
DECLARE VARIABLE wbdbasefpasfn NUMERIC(15,6);
DECLARE VARIABLE wbdbasefpasfc NUMERIC(15,6);
DECLARE VARIABLE wbdbasefpasferfn NUMERIC(15,6);
DECLARE VARIABLE wbdbasefpasferfc NUMERIC(15,6);
DECLARE VARIABLE wbdbasefpas13rfn NUMERIC(15,6);
DECLARE VARIABLE wbdbasefpas13rfc NUMERIC(15,6);
DECLARE VARIABLE wbdbasefpas13 NUMERIC(15,6);
DECLARE VARIABLE wbdbasefpasc13 NUMERIC(15,6);
DECLARE VARIABLE wbdbaseratapofn NUMERIC(15,6);
DECLARE VARIABLE wbdbaseratapofc NUMERIC(15,6);
DECLARE VARIABLE wbdbaseratapoferfn NUMERIC(15,6);
DECLARE VARIABLE wbdbaseratapoferfc NUMERIC(15,6);
DECLARE VARIABLE wbdbaseratapo13rfn NUMERIC(15,6);
DECLARE VARIABLE wbdbaseratapo13rfc NUMERIC(15,6);
DECLARE VARIABLE wbdbaseratapo13 NUMERIC(15,6);
DECLARE VARIABLE wbdbaseratapoc13 NUMERIC(15,6);
DECLARE VARIABLE wcodter INTEGER;
DECLARE VARIABLE wcodcol INTEGER;
DECLARE VARIABLE wordem INTEGER;
DECLARE VARIABLE wsqlaux VARCHAR(10000);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE waux NUMERIC(15,6);
DECLARE VARIABLE wsalvavalorcompensado NUMERIC(15,6);
DECLARE VARIABLE wvalacompgps NUMERIC(15,6);
DECLARE VARIABLE wvalcompensado NUMERIC(15,6);
DECLARE VARIABLE wperc NUMERIC(15,6);
DECLARE VARIABLE wvalbasecomp NUMERIC(15,6);
DECLARE VARIABLE wvalpodecomp NUMERIC(15,6);
DECLARE VARIABLE wvalacu NUMERIC(15,6);
DECLARE VARIABLE wtotacu NUMERIC(15,6);
DECLARE VARIABLE wvalacuter NUMERIC(15,6);
DECLARE VARIABLE wtotacuter NUMERIC(15,6);
DECLARE VARIABLE wrefutimal INTEGER;
DECLARE VARIABLE wcodperiodo INTEGER;
DECLARE VARIABLE wquota INTEGER;
DECLARE VARIABLE wauxdesc NUMERIC(15,2);
DECLARE VARIABLE wauxdesc2 VARCHAR(30);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wsqlaux2 VARCHAR(3000);
DECLARE VARIABLE wauxtotacu NUMERIC(15,6);
DECLARE VARIABLE wauxtotacuter NUMERIC(15,6);
DECLARE VARIABLE winicomp INTEGER;
DECLARE VARIABLE wfimcomp INTEGER;
DECLARE VARIABLE wtipocontab INTEGER;
DECLARE VARIABLE wsumvalfunemp NUMERIC(15,6);
DECLARE VARIABLE wsumbasefunemp NUMERIC(15,6);
DECLARE VARIABLE wsumvalproemp NUMERIC(15,6);
DECLARE VARIABLE wsumbaseproemp NUMERIC(15,6);
DECLARE VARIABLE wsumvalautemp NUMERIC(15,6);
DECLARE VARIABLE wsumbaseautemp NUMERIC(15,6);
DECLARE VARIABLE wsumbasefpas NUMERIC(15,6);
DECLARE VARIABLE wsumvalfpas NUMERIC(15,6);
DECLARE VARIABLE wsumbaserat NUMERIC(15,6);
DECLARE VARIABLE wsumvalrat NUMERIC(15,6);
BEGIN
  /* prtipogps
     0 = normal
     1 = folha complementar
     2 = 13 sal
     3 = comp. 13 sal
     4 = pr?via de rescis?o
  */
  /* prtipoemissao
     0 = por cc
     1 = agrupado
     3 = por tomador (utilizado na SEFIP)
  */
  /* prapenasgps
     0 = apenas gps
     1 = historicos compensacoes/nf/gps
  */
  /* PRPUXAFILIAIS
     0 = Nao
     1 = Sim
  */
  /*
    BDTIPOREG
    0 = GPS
    1 = nf
    2 = gps comp
    3 = compensacao
    4 = historico comp
    5 = historico nf
    6 = historico gps
    7 = registro acumulados
    8 = contabilizacao
  */

  IF (prtipogps IS NULL) THEN
     prtipogps = 0;

  IF (prcodimp IS NULL) THEN
     prcodimp = 0;

  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     BEGIN
       prcodemp = ''''||prcodemp||'''';
     END

  IF (prcodcol IS NULL) THEN
     prcodcol = 'null';
  ELSE
     prcodcol = ''''||prcodcol||'''';

  IF (prcodaut IS NULL) THEN
     prcodaut = 'null';
  ELSE
     prcodaut = ''''||prcodaut||'''';

  IF (prtipocol IS NULL) THEN
     prtipocol = 0;

  IF (pranomes IS NULL) THEN
     pranomes = 0;

  IF ((prtipoemissao IS NULL) OR (prtipoemissao = 1)) THEN
     prtipoemissao = 1;
  ELSE IF (prtipoemissao <> 3) THEN
     prtipoemissao = 4;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  IF (prapenasgps IS NULL) THEN
     pranomespag = 1;

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  wsql = 'SELECT bdcodemp, bdtipo, bdreffn, bdrefpag, bdcodcentro, bdcodtpcc, bdtotSeg, bdtotBase, bdSEGFUN, bdBaseFun, bdPercFun, bdSegPro, bdBasePro, bdPercPro, bdSegAut, bdBaseAut,'||
         'bdPercAut, bdbaseratapo, bdvalorratapo, bdsalfam, bdsalmaternidade, bdbasefpas, bdpercfpas, bdpercrat, BDVALOUTENTIDADE, bddescenqfed, bdsimplesgps, bdcodenqfed,'||
         'bdcodcol, bdcodter, '||
         'bdbasefunfn, bdbasefunfc, bdbasefunferfn, bdbasefunferfc, bdbasefun13rfn, bdbasefun13rfc, bdbasefun13, bdbasefunc13,'||
         'bdbaseprofn, bdbaseprofc, bdbaseproferfn, bdbaseproferfc, bdbasepro13rfn, bdbasepro13rfc, bdbasepro13, bdbaseproc13,'||
         'bdbaseautfn, bdbaseautfc, bdbaseautferfn, bdbaseautferfc, bdbaseaut13rfn, bdbaseaut13rfc, bdbaseaut13, bdbaseautc13,'||
         'bdbasefpasfn, bdbasefpasfc, bdbasefpasferfn, bdbasefpasferfc, bdbasefpas13rfn, bdbasefpas13rfc, bdbasefpas13, bdbasefpasc13,'||
         'bdbaseratapofn, bdbaseratapofc, bdbaseratapoferfn, bdbaseratapoferfc, bdbaseratapo13rfn, bdbaseratapo13rfc, bdbaseratapo13, bdbaseratapoc13';
  wsql = wsql||' FROM VRHF_SP_DADOS_CALC_GPS('||prcodemp||','||prcodcol||','||prcodaut||','||prtipocol||','||pranomes||','||pranomespag||',0,'||prtipogps||','||prpuxafiliais||','||prapenasgps||')';

  wsumvalfunemp = 0;
  wsumbasefunemp = 0;
  wsumvalproemp = 0;
  wsumbaseproemp = 0;
  wsumvalAUTemp = 0;
  wsumbaseAUTemp = 0;
  WSUMVALAUTEMP = 0;
  WSUMBASEAUTEMP = 0;
  wsumbasefpas = 0;
  wsumvalfpas = 0;
  wsumbaserat = 0;
  wsumvalrat = 0;

  FOR EXECUTE STATEMENT wsql INTO
      : bdcodemp,
      : WTIPOCONTAB,
      : bdreffn,
      : bdrefpag,
      : bdcodcentro,
      : bdcodtpcc,

      /*totais*/
      : bdtotSeg,
      : bdtotBase,

      /*colaboradores*/
      : bdSEGFUN,
      : bdBaseFun,
      : bdPercFun,

       /*prolaboristas*/
      : bdSegPro,
      : bdBasePro,
      : bdPercPro,

      /*autonomos*/
      : bdSegAut,
      : bdBaseAut,
      : bdPercAut,

      /* rat aposentadoria*/
      : bdbaseratapo,
      : bdvalorratapo,

      : bdsalfam,
      : bdsalmaternidade,

      /* base fpas*/
      : bdbasefpas,
      : bdpercfpas,

      /* rat */
      : bdpercrat,

      : BDVALOUTENTIDADE,

      : bddescenqfed,
      : bdsimplesgps,
      : bdcodenqfed,

      : wcodcol,
      : wcodter,

      : wbdbasefunfn,
      : wbdbasefunfc,
      : wbdbasefunferfn,
      : wbdbasefunferfc,
      : wbdbasefun13rfn,
      : wbdbasefun13rfc,
      : wbdbasefun13,
      : wbdbasefunc13,

      : wbdbaseprofn,
      : wbdbaseprofc,
      : wbdbaseproferfn,
      : wbdbaseproferfc,
      : wbdbasepro13rfn,
      : wbdbasepro13rfc,
      : wbdbasepro13,
      : wbdbaseproc13,

      : wbdbaseautfn,
      : wbdbaseautfc,
      : wbdbaseautferfn,
      : wbdbaseautferfc,
      : wbdbaseaut13rfn,
      : wbdbaseaut13rfc,
      : wbdbaseaut13,
      : wbdbaseautc13,

      : wbdbasefpasfn,
      : wbdbasefpasfc,
      : wbdbasefpasferfn,
      : wbdbasefpasferfc,
      : wbdbasefpas13rfn,
      : wbdbasefpas13rfc,
      : wbdbasefpas13,
      : wbdbasefpasc13,

      : wbdbaseratapofn,
      : wbdbaseratapofc,
      : wbdbaseratapoferfn,
      : wbdbaseratapoferfc,
      : wbdbaseratapo13rfn,
      : wbdbaseratapo13rfc,
      : wbdbaseratapo13,
      : wbdbaseratapoc13
      DO
  BEGIN
    bdcodcol = NULL;
    bdcodter = NULL;

    bdinicomp = NULL;
    bdfimcomp = NULL;
    bdtotcompensacao = NULL;
    bdtotvaloracumulado = 0;
    bdtotvaloracumuladoTerc = 0;
    bdvaloracumulado = 0;
    bdvaloracuterceiros = 0;
    bddescsalfam = 0;
    bddescdedgps = 0;
    bddescnotas = 0;
    bdtotdesccomp = 0;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* colaboradores */
    IF ((bdbaseFun = 0) OR (bdpercFun = 0)) THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdbaseFun * (bdpercFun / 100));
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
        END
    bdvalfunemp = waux;

    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumvalfunemp = wsumvalfunemp + bdvalfunemp;
         wsumbasefunemp = wsumbasefunemp + bdbaseFun;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbasefunemp = 0) OR (bdpercFun = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbasefunemp * (bdpercFun / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalfunemp) THEN
            BEGIN
              bdvalfunemp = bdvalfunemp + (waux - wsumvalfunemp);
--              wsumvalfunemp = bdvalfunemp;
              wsumvalfunemp = wsumvalfunemp + (waux - wsumvalfunemp);
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbasefun||','||bdvalfunemp||','||
                     wbdbasefunfn||','||wbdbasefunfc||','||wbdbasefunferfn||','||wbdbasefunferfc||','||wbdbasefun13rfn||','||wbdbasefun13rfc||','||wbdbasefun13||','||wbdbasefunc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalfunempfn, :bdvalfunempfc, :bdvalfunempferfn, :bdvalfunempferfc, :bdvalfunemp13fn, :bdvalfunemp13fc, :bdvalfunemp13, :bdvalfunempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* prolaboristas */
    IF ((bdbasepro = 0) OR (bdpercpro = 0))  THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdbasepro * (bdpercpro / 100));
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
       END
    bdvalproemp = waux;
    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumvalproemp = wsumvalproemp + bdvalproemp;
         wsumbaseproemp = wsumbaseproemp + bdbasepro;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbaseproemp = 0) OR (bdpercPRO = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbaseproemp * (bdpercPRO / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalproemp) THEN
            BEGIN
              bdvalproemp = bdvalproemp + (waux - wsumvalproemp);
              wsumvalproemp = bdvalproemp;
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbasepro||','||bdvalproemp||','||
                     wbdbaseprofn||','||wbdbaseprofc||','||wbdbaseproferfn||','||wbdbaseproferfc||','||wbdbasepro13rfn||','||wbdbasepro13rfc||','||wbdbasepro13||','||wbdbaseproc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalproempfn, :bdvalproempfc, :bdvalproempferfn, :bdvalproempferfc, :bdvalproemp13fn, :bdvalproemp13fc, :bdvalproemp13, :bdvalproempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* autonomos */
    IF ((bdbaseaut = 0) OR (bdpercaut = 0))  THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdpercaut / 100);
         waux =  CAST(bdbaseaut AS NUMERIC(15,2)) * waux;
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
       END
    bdvalautemp = waux;
    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumvalautemp = wsumvalautemp + bdvalautemp;
         wsumbaseautemp = wsumbaseautemp + bdbaseaut;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbaseautemp = 0) OR (bdpercaut = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbaseautemp * (bdpercaut / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalautemp) THEN
            BEGIN
              bdvalautemp = bdvalautemp + (waux - wsumvalautemp);
              wsumvalautemp = bdvalautemp;
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbaseaut||','||bdvalautemp||','||
                     wbdbaseautfn||','||wbdbaseautfc||','||wbdbaseautferfn||','||wbdbaseautferfc||','||wbdbaseaut13rfn||','||wbdbaseaut13rfc||','||wbdbaseaut13||','||wbdbaseautc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalautempfn, :bdvalautempfc, :bdvalautempferfn, :bdvalautempferfc, :bdvalautemp13fn, :bdvalautemp13fc, :bdvalautemp13, :bdvalautempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* valor fpas (terceiros) */
    IF (bdsimplesgps IN (1,2,5)) THEN
       bdpercfpas = 0;

    IF ((bdbasefpas = 0) OR (bdpercfpas = 0)) THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdbasefpas * (bdpercfpas / 100));
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
       END
    bdvalorfpas = waux;
    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumbasefpas = wsumbasefpas + bdbasefpas;
         wsumvalfpas = wsumvalfpas + bdvalorfpas;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbasefpas = 0) OR (bdpercfpas = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbasefpas * (bdpercfpas / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalfpas) THEN
            BEGIN
              bdvalorfpas = bdvalorfpas + (waux - wsumvalfpas);
              wsumvalfpas = bdvalorfpas;
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbasefpas||','||bdvalorfpas||','||
                     wbdbasefpasfn||','||wbdbasefpasfc||','||wbdbasefpasferfn||','||wbdbasefpasferfc||','||wbdbasefpas13rfn||','||wbdbasefpas13rfc||','||wbdbasefpas13||','||wbdbasefpasc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalfpasempfn, :bdvalfpasempfc, :bdvalfpasempferfn, :bdvalfpasempferfc, :bdvalfpasemp13fn, :bdvalfpasemp13fc, :bdvalfpasemp13, :bdvalfpasempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* valor rat*/
    IF (bdsimplesgps IN (1,2,5)) THEN
       bdpercrat = 0;

    IF ((bdbasefpas = 0) OR (bdpercrat = 0)) THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdbasefpas * (bdpercrat / 100));
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
       END
    bdvalorrat = waux;
    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumbaserat = wsumbaserat + bdbasefpas;
         wsumvalrat = wsumvalrat + bdvalorrat;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbaserat = 0) OR (bdpercrat = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbaserat * (bdpercrat / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalrat) THEN
            BEGIN
              bdvalorrat = bdvalorrat + (waux - wsumvalrat);
              wsumvalrat = bdvalorrat;
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbasefpas||','||bdvalorrat||','||
                     wbdbasefpasfn||','||wbdbasefpasfc||','||wbdbasefpasferfn||','||wbdbasefpasferfc||','||wbdbasefpas13rfn||','||wbdbasefpas13rfc||','||wbdbasefpas13||','||wbdbasefpasc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalratempfn, :bdvalratempfc, :bdvalratempferfn, :bdvalratempferfc, :bdvalratemp13fn, :bdvalratemp13fc, :bdvalratemp13, :bdvalratempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- rat aposentadoria

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbaseratapo||','||bdvalorratapo||','||
                     wbdbaseratapofn||','||wbdbaseratapofc||','||wbdbaseratapoferfn||','||wbdbaseratapoferfc||','||wbdbaseratapo13rfn||','||wbdbaseratapo13rfc||','||wbdbaseratapo13||','||wbdbaseratapoc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalratapoempfn, :bdvalratapoempfc, :bdvalratapoempferfn, :bdvalratapoempferfc, :bdvalratapoemp13fn, :bdvalratapoemp13fc, :bdvalratapoemp13, :bdvalratapoempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

    /*valor bruto sem terceiros*/
    bdvalorbruto = bdtotseg + -- seguradors
                 bdvalautemp + -- autonomos emp
                 bdvalproemp + -- prolabore emp
                 bdvalfunemp + -- colaboradores emp
                 bdvalorratapo + -- rat aposentadoria
                 bdvalorrat; -- rat emp

    IF (wtipocontab = 1) THEN
       BEGIN
         wsumvalfunemp = 0;
         wsumbasefunemp = 0;
         wsumvalproemp = 0;
         wsumbaseproemp = 0;
         WSUMVALAUTEMP = 0;
         WSUMBASEAUTEMP = 0;
         wsumbasefpas = 0;
         wsumvalfpas = 0;
         wsumbaserat = 0;
         wsumvalrat = 0;
         /* soma valor acumulado */
         /*busca a ultima gps emitida para buscar acumulados*/
             /*verifica se existe registro atual para pegar a ordem*/
         wtotacu = 0;
         wtotacuter = 0;
         wsqlaux = 'select first 1 x.bdordem from tdarfpadrao x '||
                   'where x.bdreferencia = '||pranomes||
                   ' and x.bdcodemp = '||bdcodemp||
                   ' and x.bdcodimp = '||prcodimp||
                   ' and x.bdrefpag = '||pranomespag||
                   ' and x.BDTIPOIMPOSTO = ';

         IF (prtipogps = 4) THEN
            wsqlaux = wsqlaux||'0';
         ELSE
            wsqlaux = wsqlaux||prtipogps;

         IF (prtipoemissao <> 0) THEN
            BEGIN
             IF (bdcodtpcc IS NULL) THEN
                BEGIN
                  wsqlaux = wsqlaux||
                            ' and x.BDCODTPCC is null';
                END
             ELSE
                BEGIN
                  wsqlaux = wsqlaux||
                            ' and x.BDCODTPCC = '||bdcodtpcc;
                END
           END

         wordem = NULL;
         EXECUTE STATEMENT wsqlaux INTO wordem;
         wsqlaux = 'select first 1 '||
                      'x.bdreferencia,'||
                      'x.bdordem,'||
                      'x.BDCODPERIODO,'||
                      'x.BDQUOTA from tdarfpadrao x ';
         IF (wordem IS NULL) THEN
            BEGIN
             wsqlaux = wsqlaux||
                       ' where '||
                       ' x.bdcodemp = '||bdcodemp||
                       ' and x.bdcodimp = '||prcodimp||
                       ' and x.bdrefpag <= '||pranomespag||
                       ' and x.BDTIPOIMPOSTO = ';

             IF (prtipogps = 4) THEN
                wsqlaux = wsqlaux||'0';
             ELSE
                wsqlaux = wsqlaux||prtipogps;
            END
         ELSE
            BEGIN
              wsqlaux = wsqlaux||
                        ' where '||
                        ' x.bdcodemp = '||bdcodemp||
                        ' and x.bdcodimp = '||prcodimp||
                        ' and ((x.bdrefpag < '||pranomespag||') or (x.bdrefpag = '||pranomespag||' and x.bdordem < '||wordem||'))'||
                        ' and x.BDTIPOIMPOSTO = ';

              IF (prtipogps = 4) THEN
                 wsqlaux = wsqlaux||'0';
              ELSE
                 wsqlaux = wsqlaux||prtipogps;
            END

         IF (prtipoemissao <> 0) THEN
            BEGIN
             IF (bdcodtpcc IS NULL) THEN
                BEGIN
                  wsqlaux = wsqlaux||
                            ' and x.BDCODTPCC is null';
                END
             ELSE
                BEGIN
                  wsqlaux = wsqlaux||
                            ' and x.BDCODTPCC = '||bdcodtpcc;
                END
            END
     
         wsqlaux = wsqlaux||' order by x.bdrefpag desc, x.bdordem desc';

         wrefutimal = NULL;
         EXECUTE STATEMENT wsqlaux INTO wrefutimal,wordem,wcodperiodo,wquota;
         IF (wtotacu IS NULL) THEN
            wtotacu = 0;

         IF (wtotacuter IS NULL) THEN
            wtotacuter = 0;

         IF ((wrefutimal IS NOT NULL) AND (wrefutimal > 0)) THEN
            BEGIN
              wsqlaux = 'select y.bdvalcampo6,y.bdvalcampo9 from VRHF_SP_HIST_ACUMU_GPS('||''''||'x.bdcodemp = '||bdcodemp||' and x.bdcodimp = '||prcodimp||' and x.bdreferencia = '||wrefutimal||
                        ' and x.bdordem = '||wordem||' and x.BDCODPERIODO = '||wcodperiodo||' and x.BDQUOTA = '||wquota||''''||') y';
     
              FOR EXECUTE STATEMENT wsqlaux INTO
                : wvalacu,
                : wvalacuter
              DO
                BEGIN
                  IF (wvalacu IS NOT NULL) THEN
                     wtotacu = wtotacu + wvalacu;
     
                  IF (wvalacuter IS NOT NULL) THEN
                     wtotacuter = wtotacuter + wvalacuter;
                END
            END
         bdvalorbruto = bdvalorbruto + wtotacu;

         /* fim soma acumulado */
         /* somavalor nota fiscal cooperativa */
         wsqlaux = 'select bdvalliqnf from VRHF_SP_TNFCOOP('||''''||'colcon.bdcodemp = '||bdcodemp||''''||','||bdreffn||',null,'||prtipoemissao||','||prpuxafiliais||')';
         wsqlaux = wsqlaux||' where '||prtipogps||' <> 1'; -- Notas fiscais Coop nao devem ser utilizadas para folha complementar e compl 13 sal e 13 sal
         wsqlaux = wsqlaux||' and '||prtipogps||' <> 2'; -- Notas fiscais Coop nao devem ser utilizadas para folha complementar e compl 13 sal e 13 sal
         wsqlaux = wsqlaux||' and '||prtipogps||' <> 3'; -- Notas fiscais Coop nao devem ser utilizadas para folha complementar e compl 13 sal e 13 sal
         IF (prtipoemissao = 4) THEN
            BEGIN
              IF (bdcodtpcc IS NULL) THEN
                 wsqlaux = wsqlaux||' and bdcodtpcc is null';
              ELSE
                 wsqlaux = wsqlaux||' and bdcodtpcc = '||bdcodtpcc;
            END
         waux = 0;
         EXECUTE STATEMENT wsqlaux INTO waux;
         bdnfcoop = 0;
         IF (waux IS NOT NULL) THEN
            bdnfcoop = waux;
         bdvalorbruto = bdvalorbruto + bdnfcoop;
         wvalbasecomp = bdvalorbruto;
     
         bdvalacompensar = 0;
         bdvalorliquido = bdvalorbruto;

         /* desconta nota fiscais */
         IF (prtipogps = 2) THEN
            wsqlaux = 'select nf.bdchave, nf.bdvaldescnf from vrhf_emp_tnotasfiscais nf'||
                  ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(nf.bdcodtpcc,nf.bdcodcentro) toma on'||
                  ' (toma.bdcodcencus = nf.bdcodtpcc and toma.bdcodcentro = nf.bdcodcentro)'||
                  ' where nf.bdcodemp = '||bdcodemp||
                  ' and nf.bdrefnf = '||CAST(SUBSTRING(CAST(pranomes-1 AS VARCHAR(6)) FROM 1 FOR 4)||'13' AS INTEGER);
         ELSE
            wsqlaux = 'select nf.bdchave, nf.bdvaldescnf from vrhf_emp_tnotasfiscais nf'||
                  ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(nf.bdcodtpcc,nf.bdcodcentro) toma on'||
                  ' (toma.bdcodcencus = nf.bdcodtpcc and toma.bdcodcentro = nf.bdcodcentro)'||
                  ' where nf.bdcodemp = '||bdcodemp||
                  ' and nf.bdrefnf = '||pranomes;

         wsqlaux = wsqlaux||' and '||prtipogps||' <> 1'|| -- Notas fiscais nao devem ser utilizadas para folha complementar e compl 13 sal
                  ' and '||prtipogps||' <> 3';            -- Notas fiscais nao devem ser utilizadas para folha complementar e compl 13 sal
         IF (prtipoemissao = 4) THEN
            BEGIN
              IF (bdcodtpcc IS NULL) THEN
                 wsqlaux = wsqlaux||' and toma.bdcodtpcc is null';
              ELSE
                 wsqlaux = wsqlaux||' and toma.bdcodtpcc = '||bdcodtpcc;
            END

         wvalcompensado = 0;
         wvalacompgps = 0;
     
         waux = 0;
         bdValNotas = 0;
         bddescnotas = 0;
         FOR EXECUTE STATEMENT wsqlaux INTO
           : bdchave,
           : waux
         DO
            BEGIN
              bdValNotas = bdValNotas + waux;
              IF (bdvalorliquido > waux) THEN
                 BEGIN
                   bdvalorliquido = bdvalorliquido - (waux);
                   bdvalcompensado = waux;
                   bddescnotas = bddescnotas + waux;
                   bdvalacompensar = 0;
                 END
              ELSE
                 BEGIN
                   bdvalcompensado = bdvalorliquido;
                   bddescnotas = bddescnotas + bdvalorliquido;
                   bdvalacompensar = ((waux) - bdvalorliquido);
                   bdvalorliquido = 0;
                 END
              bdtiporeg = 1;
     
              wvalacompgps = wvalacompgps + bdvalacompensar;
              wvalcompensado = wvalcompensado + bdvalcompensado;
              IF (prapenasgps = 1) THEN
                 SUSPEND;
            END

         bdchave = NULL;
         /* desconta maternidade e salario familia*/
         IF (bdsalmaternidade + bdsalfam > 0) THEN
            BEGIN
              IF (bdvalorliquido > bdsalmaternidade) THEN
                 BEGIN
                   bdvalorliquido = bdvalorliquido - (bdsalmaternidade);
                   bdvalacompensar = 0;
                   bdvalcompensado = (bdsalmaternidade);
                   bddescdedgps = bdsalmaternidade;
                 END
              ELSE
                 BEGIN
                   bdvalacompensar = ((bdsalmaternidade + bdsalfam) - bdvalorliquido);
                   bdvalcompensado = bdvalorliquido;
                   bddescdedgps = bdvalorliquido;
                   bdvalorliquido = 0;
                 END
     
              IF (bdvalorliquido > bdsalfam) THEN
                 BEGIN
                   bdvalorliquido = bdvalorliquido - (bdsalfam);
                   bdvalacompensar = 0;
                   bdvalcompensado = bdvalcompensado + bdsalfam;
                   bddescsalfam = bdsalfam;
                 END
              ELSE
                 BEGIN
                   bdvalacompensar = ((bdsalmaternidade + bdsalfam) - bdvalorliquido);
                   bdvalcompensado = bdvalcompensado + bdvalorliquido;
                   bddescsalfam = bdvalorliquido;
                   bdvalorliquido = 0;
                 END
     
              bdtiporeg = 2;
              wvalacompgps = wvalacompgps + bdvalacompensar;
              wvalcompensado = wvalcompensado + bdvalcompensado;
     
              IF (prapenasgps = 1) THEN
                 SUSPEND;
            END
         /* Compensacao */
         wsqlaux = 'select * from vrhf_sp_tcompensacaogps('||prcodimp||','||
                                                          bdcodemp||','||
                                                          prtipogps||','||
                                                          prtipoemissao||',';
     
         IF (bdcodtpcc IS NULL) THEN
            wsqlaux = wsqlaux||'null,0)';
         ELSE
            wsqlaux = wsqlaux||bdcodtpcc||',0)';
     
         waux = 0;
         bdinicomp = NULL;
         bdfimcomp = NULL;
         bdtotcompensacao = 0;
         bdtotdesccomp = 0;
         FOR EXECUTE STATEMENT wsqlaux INTO
           : bdtiporeg,
           : bdchave,
           : waux,
           : wperc,
           : winicomp,
           : wfimcomp
         DO
            BEGIN
              bdtotcompensacao = bdtotcompensacao + waux;
              IF ((bdfimcomp IS NULL) OR (wfimcomp > bdfimcomp)) THEN
                 bdfimcomp = wfimcomp;
     
              IF ((bdinicomp IS NULL) OR (winicomp < bdinicomp)) THEN
                 bdinicomp = winicomp;
     
              IF ((wperc = 0) OR (wperc IS NULL) OR (wperc = 100)) THEN
                 BEGIN
                   wvalpodecomp = wvalbasecomp;
                 END
              ELSE
                 BEGIN
                   wvalpodecomp = wvalbasecomp;
                 END
     
              IF (wvalpodecomp > waux) THEN
                 BEGIN
                   IF (bdvalorliquido > waux) THEN
                      BEGIN
                        bdvalorliquido = bdvalorliquido - (waux);
                        bdvalacompensar = 0;
                        bdvalcompensado = (waux);
                        bdtotdesccomp = bdtotdesccomp + waux;
                      END
                   ELSE
                      BEGIN
                        bdvalacompensar = ((waux) - bdvalorliquido);
                        bdvalcompensado = bdvalorliquido;
                        bdtotdesccomp = bdtotdesccomp + bdvalorliquido;
                        bdvalorliquido = 0;
                      END
                 END
              ELSE
                 BEGIN
                   IF (bdvalorliquido > wvalpodecomp) THEN
                      BEGIN
                        bdvalorliquido = bdvalorliquido - wvalpodecomp;
                        bdvalacompensar = waux - wvalpodecomp;
                        bdvalcompensado = wvalpodecomp;
                        bdtotdesccomp = bdtotdesccomp + wvalpodecomp;
                      END
                   ELSE
                      BEGIN
                        bdvalacompensar = waux - bdvalorliquido;
                        bdvalcompensado = bdvalorliquido;
                        bdtotdesccomp = bdtotdesccomp + bdvalorliquido;
                        bdvalorliquido = 0;
                      END
                 END
     
              wvalacompgps = wvalacompgps + bdvalacompensar;
              wvalcompensado = wvalcompensado + bdvalcompensado;
              IF (prapenasgps = 1) THEN
                 SUSPEND;
            END

         /*valor bruto com terceiros*/
         bdvalorbruto = bdvalorbruto + -- valorbruto
                      wtotacuter + -- valor terceiro acumulado
                      bdvalorfpas; -- valor fpas terceiro

         bdvalorcampo6 = bdvalorliquido;
         /* valor liquido com terceiros */
         bdvalorliquido = bdvalorliquido +
                          wtotacuter + -- valor terceiro acumulado
                          bdvalorfpas; -- valor fpas terceiro
     
         /*registro acumulados */
         bdtiporeg = 7;
         wsalvavalorcompensado = wvalcompensado;
         bddescacumdet = '';
         bddescacum = '';
         wauxtotacu = 0;
         wauxtotacuter = 0;
         IF ((wrefutimal IS NOT NULL) AND (wrefutimal > 0)) THEN
            BEGIN
              wsqlaux = 'select bdcodemp,bdcodimp,bdchavedarf, bdcodperiodo, bdordem, bdreferencia, bdquota, y.bdvalcampo6,y.bdvalcampo9 from VRHF_SP_HIST_ACUMU_GPS('||''''||'x.bdcodemp = '||bdcodemp||' and x.bdcodimp = '||prcodimp||' and x.bdreferencia = '||wrefutimal||
                        ' and x.bdordem = '||wordem||' and x.BDCODPERIODO = '||wcodperiodo||' and x.BDQUOTA = '||wquota||''''||') y'||
                        ' where y.bdvalcampo6 > 0 and y.bdvalcampo9 > 0 '||
                        ' order by bdreferencia,bdordem ';
     
              FOR EXECUTE STATEMENT wsqlaux INTO
                : bdcodempant,
                : bdcodimpant,
                : bdchavedarfant,
                : bdcodperiodoant,
                : bdordemant,
                : bdreferenciaant,
                : bdquotaant,
                : bdvaloracumulado,
                : bdvaloracuterceiros
              DO
                BEGIN
                  IF (bdvaloracumulado IS NULL) THEN
                     bdvaloracumulado = 0;
     
                  IF (bdvaloracuterceiros IS NULL) THEN
                     bdvaloracuterceiros = 0;
     
                  bdtotvaloracumulado = bdvaloracumulado;
                  bdtotvaloracumuladoTerc = bdvaloracuterceiros;
                  wauxtotacu = wauxtotacu + bdtotvaloracumulado;
                  wauxtotacuter = wauxtotacuter + bdtotvaloracumuladoTerc;
     
                  bdvaloracumuladousado = bdvaloracumulado;
                  bdvaloracuterceirosusado = bdvaloracuterceiros;
     
                  IF ((bdvaloracumuladousado > 0) OR (bdvaloracuterceirosusado > 0)) THEN
                     BEGIN
                       IF (bdvaloracumuladousado+bdvaloracuterceirosusado > 0) THEN
                          BEGIN
                            IF (bddescacum <> '') THEN
                               bddescacum = bddescacum||'; ';
                            wauxdesc = CAST(bdvaloracumuladousado+bdvaloracuterceirosusado - 0.005 AS NUMERIC(15,2)); /* cortar */
                            wauxdesc2 = wauxdesc;
     
                            wsqlaux2 = 'select POS from pos('||''''||'.'||''''||','||''''||wauxdesc2||''''||')';
                            EXECUTE STATEMENT wsqlaux2 INTO wpos;
                            wauxdesc2 = SUBSTRING(wauxdesc2 FROM 1 FOR wpos - 1)||','||SUBSTRING(wauxdesc2 FROM wpos + 1);
     
                            bddescacum = bddescacum||''||SUBSTRING(CAST(bdreferenciaant AS VARCHAR(6)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(bdreferenciaant AS VARCHAR(6)) FROM 1 FOR 4);
                            bddescacum = bddescacum||' R$ '||(wauxdesc2);
                          END
     
                       IF ((bdvaloracumuladousado > 0) OR (bdvaloracuterceirosusado > 0)) THEN
                          BEGIN
                            IF (bddescacumdet <> '') THEN
                               bddescacumdet = bddescacumdet||'; ';
         
                            bddescacumdet = bddescacumdet||''||SUBSTRING(CAST(bdreferenciaant AS VARCHAR(6)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(bdreferenciaant AS VARCHAR(6)) FROM 1 FOR 4);
                            IF (bdvaloracumuladousado > 0) THEN
                               BEGIN
                                 wauxdesc = CAST(bdvaloracumuladousado - 0.005 AS NUMERIC(15,2)); /* cortar */
                                 wauxdesc2 = wauxdesc;
     
                                 wsqlaux2 = 'select POS from pos('||''''||'.'||''''||','||''''||wauxdesc2||''''||')';
                                 EXECUTE STATEMENT wsqlaux2 INTO wpos;
                                 wauxdesc2 = SUBSTRING(wauxdesc2 FROM 1 FOR wpos - 1)||','||SUBSTRING(wauxdesc2 FROM wpos + 1);
     
                                 bddescacumdet = bddescacumdet||' R$ '||wauxdesc2;
     
                                 IF (bdvaloracuterceirosusado > 0) THEN
                                    bddescacumdet = bddescacumdet||' +';
                               END
     
                            IF (bdvaloracuterceirosusado > 0) THEN
                               BEGIN
                                 wauxdesc = CAST(bdvaloracuterceirosusado - 0.005 AS NUMERIC(15,2)); /* cortar */
                                 wauxdesc2 = wauxdesc;
     
                                 wsqlaux2 = 'select POS from pos('||''''||'.'||''''||','||''''||wauxdesc2||''''||')';
                                 EXECUTE STATEMENT wsqlaux2 INTO wpos;
                                 wauxdesc2 = SUBSTRING(wauxdesc2 FROM 1 FOR wpos - 1)||','||SUBSTRING(wauxdesc2 FROM wpos + 1);
                                 bddescacumdet = bddescacumdet||' R$ '||wauxdesc2||'(terc)';
                               END
                          END
                     END
     
                  IF (bdvaloracumulado <= wsalvavalorcompensado) THEN
                     BEGIN
                       wsalvavalorcompensado = wsalvavalorcompensado - bdvaloracumulado;
                       bdvaloracumulado = 0;
                     END
                  ELSE
                     BEGIN
                       bdvaloracumulado = bdvaloracumulado - wsalvavalorcompensado;
                       wsalvavalorcompensado = 0;
                     END
     
                  IF (prapenasgps = 1) THEN
                     SUSPEND;
                END
            END

         bdvaloracumuladousado = NULL;
         bdvaloracuterceirosusado = NULL;
         bdcodempant = NULL;
         bdcodimpant = NULL;
         bdcodperiodoant = NULL;
         bdordemant = NULL;
         bdreferenciaant = NULL;
         bdquotaant = NULL;
         bdchave = NULL;
     
         bdtotvaloracumulado = wauxtotacu;
         bdtotvaloracumuladoTerc = wauxtotacuter;
         bdvalacompensar = wvalacompgps;
         bdvalcompensado = wvalcompensado;
         bdvaloracumulado = wtotacu;
         bdvaloracuterceiros = wtotacuter;
     
         IF (bddescacumdet <> '') THEN
            BEGIN
              bddescacumdet = 'INSS Acum.: '||bddescacumdet||'.';
              bddescacum = 'INSS Acum.: '||bddescacum||'.';
            END
         bdtiporeg = 0;
       END
    ELSE
       BEGIN
         IF (wtipocontab = 2) THEN
            BEGIN
              bdtiporeg = 9;
              bdcodcol = wcodcol;
              bdcodter = wcodter;
            END
         ELSE
            bdtiporeg = 8;
       END

    IF ((prapenasgps = 1) OR (bdtiporeg = 0)) THEN
       SUSPEND;
    bddescacumdet = '';
    bddescacum = '';
  END
END
^

/* Alter (VRHF_SP_GPS_CONTRATANTE) */
ALTER PROCEDURE VRHF_SP_GPS_CONTRATANTE(PREMP INTEGER,
PRREF INTEGER,
PRTERC INTEGER,
PRTPCC INTEGER,
PRNRNF VARCHAR(15))
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wSql = 'select sum(BDVALNF)';
  wSql = wSql || 'from vrhf_emp_tnfcont ';

  wSql = wSql || 'where bdcodemp = '||:premp;
  wSql = wSql || ' and BDREFNF = '||:prref;

  IF (:prnrnf <> '') THEN
    wsql = wsql || ' AND BDNOTAFISCAL = '||:prnrnf;

  IF (:prterc <> 0) THEN
    wsql = wsql || ' AND BDCODTER = '||:prterc;

  IF (:prtpcc <> 0) THEN
    wsql = wsql || ' AND BDCODTPCC = '||:prtpcc;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);

END
^

/* Alter (VRHF_SP_GPS_FUNRURAL) */
ALTER PROCEDURE VRHF_SP_GPS_FUNRURAL(PREMP INTEGER,
PRREF INTEGER,
PRNRNF VARCHAR(15),
PRTIPOEMISSAO INTEGER,
PRCODIMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDVALOR NUMERIC(15,6),
BDVALTERC NUMERIC(15,6),
BDVALORACU NUMERIC(15,6),
BDVALACUTERC NUMERIC(15,6),
BDDESCNOTAS VARCHAR(5000),
BDBASECALC NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WBDTIPONF INTEGER;
DECLARE VARIABLE WSQLDESCNOTAS VARCHAR(2500);
DECLARE VARIABLE WNF VARCHAR(15);
DECLARE VARIABLE WVALNF NUMERIC(18,6);
BEGIN
  bdcodemp = premp;

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wSql = 'select sum(nf.BDVALNF * nf.BDPERCFPASNF / 100), sum(nf.BDVALNF * nf.BDPERCTERC / 100), nf.BDTIPONF ';
  wSql = wSql || 'from VRHF_EMP_TNFPRODRURAL nf ';

  IF (prcodimp IS NOT NULL) THEN
     BEGIN
       wSql = wSql || 'join sp_emppresa_imp('||prcodimp||','||prref||',null) emp on (nf.bdcodemp = emp.bdcodemp) ';
       wSql = wSql || 'where emp.bdempimp = '||:premp;
     END
  ELSE
     BEGIN
       wSql = wSql || 'where nf.bdcodemp = '||:premp;
     END
  wSql = wSql || ' and nf.BDREFNF = '||:prref;

  IF (:prnrnf <> '') THEN
    wsql = wsql || ' AND nf.BDNOTAFISCAL = '''||:prnrnf||'''';

  IF (:prtipoemissao = 1) THEN
     wsql = wsql || ' AND nf.BDTIPONF = 0';
  ELSE
     IF (:prtipoemissao = 2) THEN
        wsql = wsql || ' AND nf.BDTIPONF = 1';


  wsql = wsql||' group by nf.BDTIPONF';

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDVALOR, :bdvalterc, :WBDTIPONF
     DO
       BEGIN
         /* busca valor acumulado */
         SELECT SUM(x.bdvalacu),SUM(x.bdvalacuter) FROM VRHF_SP_ACU_GPS_FUNRURAL(:prcodimp,'bdcodemp = '||:bdcodemp,:WBDTIPONF+1,:prref) x
         INTO bdvaloracu, bdvalacuterc;

         BDVALOR = BDVALOR - 0.005;
         BDVALOR = CAST(BDVALOR AS NUMERIC(15,2));

         IF (bdvalterc > 0) THEN
           BEGIN
             bdvalterc = bdvalterc - 0.005;
             bdvalterc = CAST(bdvalterc AS NUMERIC(15,2));
           END

         /* Busca todas as notas para retornar a descri??o delas para o campo Observa??es  */
         wsqldescnotas = 'select nf.bdnotafiscal, nf.BDVALNF ';
         wsqldescnotas = wsqldescnotas || 'from VRHF_EMP_TNFPRODRURAL nf ';
         wsqldescnotas = wsqldescnotas || 'where nf.bdcodemp = '||:premp;
         wsqldescnotas = wsqldescnotas || ' and nf.BDREFNF = '||:prref;
       
         IF (:prnrnf <> '') THEN
            wsqldescnotas = wsqldescnotas || ' AND nf.BDNOTAFISCAL = '''||:prnrnf||'''';  --Sol. 19643 - Bruno L. R. - 03/08/2017
       
         IF (:prtipoemissao = 1) THEN
            wsqldescnotas = wsqldescnotas || ' AND nf.BDTIPONF = 0';
         ELSE
            IF (:prtipoemissao = 2) THEN
               wsqldescnotas = wsqldescnotas || ' AND nf.BDTIPONF = 1';
       
         BDDESCNOTAS = '';
         BDBASECALC  = 0;

         FOR EXECUTE STATEMENT wsqldescnotas INTO :wnf, :wvalnf DO
           BEGIN
             IF (BDDESCNOTAS <> '') THEN
                BDDESCNOTAS = BDDESCNOTAS||', ';
                
             BDDESCNOTAS = BDDESCNOTAS||wnf;
             BDBASECALC = BDBASECALC + wvalnf;
           END

         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);

END
^

/* Alter (VRHF_SP_GRCSCOLABORADOR) */
ALTER PROCEDURE VRHF_SP_GRCSCOLABORADOR(PREMPRESA VARCHAR(9999),
PRCOLABORADOR VARCHAR(9999),
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODSIND INTEGER,
BDCODCNAE INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND DM_BDBAIRRO,
BDCOMPLSIND DM_BDCOMPENDERECO,
BDNUMSIND INTEGER,
BDENTSIND VARCHAR(40),
BDDESCSIND VARCHAR(60),
BDLOGRSIND DM_LOGRADOURO,
BDENDSIND DM_BDENDERECO,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDCNPJ VARCHAR(20),
BDBAI DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCOMPL DM_BDCOMPENDERECO,
BDNUM INTEGER,
BDLOGR DM_LOGRADOURO,
BDEND VARCHAR(80),
BDNOM DM_BDNOMEMP,
BDCAPSOC NUMERIC(15,6))
 AS
DECLARE VARIABLE WGROUPBY VARCHAR(1000);
DECLARE VARIABLE WORDERBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
BEGIN
  IF (prreferencia IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, prultimodia);

  wSql = 'select '||
                 'TSINDTRAB.bdcodsintrab,'|| /*01*/
                 'TSINDTRAB.bddescsintrab,'|| /*02*/
                 'TSINDTRAB.BDCALCCODBARTRAB,'||--                 'TSINDTRAB.bdentsintrab,'|| /*03*/
                 'TSINDTRAB.BDLOGRSINTRAB,'||
                 'TSINDTRAB.bdendsintrab,'|| /*04*/
                 'TSINDTRAB.bdnrosintrab, '; /*05*/
  wSql = wSql || 'TSINDTRAB.bdcomplsintrab,'|| /*06*/
                  'TSINDTRAB.bdbaisintrab,'|| /*07*/
                  'TSINDTRAB.bdcepsintrab,'|| /*08*/
                  'TSINDTRAB.bdcnpjsintrab, '; /*09*/
  wSql = wSql || 'TCIDSIND.bdnomcid,'|| /*10*/
                 'TUFSIND.bdsiglauf, '; /*11*/
  wSql = wSql || 'TEMPREF.bdcodcnae,'|| /*12*/
                 'TCIDCOL.bdNOMCID,'|| /*13*/
                 'TUFCOL.bdsiglauf, '; /*14*/
  wsql = wsql || 'TBANCO.bdcodagban,'|| /*15    -   12821 - Camila - 18/11/2015 */
                 'TSINDTRAB.bdcodcedentetrab, '|| /*16*/
                 'TEMP.BDCNPJEMP, '; /*17*/

  wsql = wsql || 'tufcol.bdsiglauf, '||  /*18*/
                 'tcidcol.bdnomcid, '||   /*19*/
                 'TEMPREF.BDBAIEMP, '|| /*20*/
                 'TEMPREF.BDCEPEMP, '|| /*21*/
                 'TEMPREF.BDCOMPLEMP, '|| /*22*/
                 'TEMPREF.BDNUMEMP, '|| /*23*/
                 'TEMPREF.BDLOGREMP, '||
                 'TEMPREF.BDENDEMP, '|| /*24*/
                 'TEMPREF.BDNOMEMP, '; /*25*/

  wsql = wsql || 'TEMPGRCS.BDCAPSOCEMP ';  /*26*/

  wsql = wSql || ' from tempresas_ref TEMPREF ';

  wSql = wsql || ' left outer join tempresas TEMP on (TEMP.bdcodemp = TEMPREF.bdcodemp)';
  wSql = wsql || ' left outer join vrh_emp_tcolcon TCOLCON on (TCOLCON.bdcodemp = TCOLCON.bdcodemp)';
  wSql = wSql || ' left outer join VRH_EMP_TCOLCON_DOC TCOLCONDOC on (TCOLCONDOC.bdcodemp = TCOLCON.bdcodemp and'||
                 '                                                     TCOLCONDOC.bdcodcol = TCOLCON.bdcodcol) ';
  wSql = wSql || ' left outer join vw_vrh_emp_tcol_vinc TCOLVINC on (TCOLVINC.bdcodemp = TCOLCON.bdcodemp and'||
                 '                                                TCOLVINC.bdcodcol = TCOLCON.bdcodcol) ';
  wSql = wSql || ' left outer join vw_vrhf_base_tempgrcs TEMPGRCS on (TEMPGRCS.bdCODEMP = TEMPREF.bdcodemp) ';
  wsql = wSql || ' left outer join vrh_base_tsindtrab TSINDTRAB on (TSINDTRAB.bdcodsintrab = TCOLVINC.bdcodsintrab) ';
  -- 12821 - Camila - 18/11/2015: adicionado join com a tabela TBANCOS_AG
  wsql = wsql || ' left outer join tbancos_ag TBANCO on (TBANCO.bdcodban = TSINDTRAB.bdcodban and TBANCO.bdcodag = TSINDTRAB.bdcodag) ';
  wSql = wSql || ' left outer join tcidade tcidcol on (tCIDCOL.bdcodcid = TEMPREF.bdcodcid) ';
  wSql = wSql || ' left outer join tcidade tcidsind on (tCIDSIND.bdcodcid = TSINDTRAB.bdcodcid) ';
  wSql = wSql || ' left outer join tuf tufcol on (tufcol.bdcoduf = tcidcol.bdcoduf) ';
  wSql = wSql || ' left outer join tuf tufsind on (tufsind.bdcoduf = tcidsind.bdcoduf) ';
  wSql = wSql || ' left outer join vw_vrh_emp_tcolcon_vinc tcolcon_vinc on (tcolcon_vinc.bdcodemp = TCOLCON.bdcodemp and '||
                 ' tcolcon_vinc.bdcodcol = TCOLCON.bdcodcol) ';
  wwhere = '';

  IF (prempresa <> '') THEN
     wwhere = wwhere||prempresa||' ';

  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||' TSINDTRAB.bdcodsintrab is not null ';

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';
    
  wwhere = wwhere||'TEMPREF.BDREFEMP in'||
          '('||
          ' select MAX(Y.BDREFEMP)'||
          ' from TEMPRESAS_REF Y'||
          ' where Y.BDCODEMP = TEMPREF.bdcodemp and'||
          '       CAST(Y.BDREFEMP as VARCHAR(6)) <='||
          '          (select TRIM(rdb$get_context('''||'USER_SESSION'||''', '''||'W_ANOMES'||'''))'||
          '           from rdb$database'||
          '          )'||
          ' group by Y.BDCODEMP'||
          ')'||' ';


  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'TCOLVINC.bdCODSINTRAB = '||prsindicato||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wgroupby = '';

  worderby = '';
  wgroupby =     'group by TSINDTRAB.bdcodsintrab,'|| /*01*/
                 'TSINDTRAB.bddescsintrab,'|| /*02*/
                 'TSINDTRAB.BDCALCCODBARTRAB,'||--                 'TSINDTRAB.bdentsintrab,'|| /*03*/
                 'TSINDTRAB.BDLOGRSINTRAB,'||
                 'TSINDTRAB.bdendsintrab,'|| /*04*/
                 'TSINDTRAB.bdnrosintrab, '; /*05*/
  wgroupby = wgroupby || 'TSINDTRAB.bdcomplsintrab,'|| /*06*/
                  'TSINDTRAB.bdbaisintrab,'|| /*07*/
                  'TSINDTRAB.bdcepsintrab,'|| /*08*/
                  'TSINDTRAB.bdcnpjsintrab, '; /*09*/
  wgroupby = wgroupby || 'TCIDSIND.bdnomcid,'|| /*10*/
                 'TUFSIND.bdsiglauf, '; /*11*/
  wgroupby = wgroupby || 'TEMPREF.bdcodcnae,'|| /*12*/
                 'TCIDCOL.bdNOMCID,'|| /*13*/
                 'TUFCOL.bdsiglauf, '; /*14*/
  wgroupby = wgroupby || 'TBANCO.bdcodagban,'|| /*15     -   12821 - Camila - 18/11/2015 */
                 'TSINDTRAB.bdcodcedentetrab, '|| /*16*/
                 'TEMP.BDCNPJEMP, '; /*17*/

  wgroupby = wgroupby || 'tufcol.bdsiglauf, '||  /*18*/
                 'tcidcol.bdnomcid, '||   /*19*/
                 'TEMPREF.BDBAIEMP, '|| /*20*/
                 'TEMPREF.BDCEPEMP, '|| /*21*/
                 'TEMPREF.BDCOMPLEMP, '|| /*22*/
                 'TEMPREF.BDNUMEMP, '|| /*23*/
                 'TEMPREF.BDLOGREMP, '||
                 'TEMPREF.BDENDEMP, '|| /*24*/
                 'TEMPREF.BDNOMEMP, '; /*25*/

  wgroupby = wgroupby || 'TEMPGRCS.BDCAPSOCEMP ';  /*26*/

  wsql = wsql||wwhere||wgroupby||worderby;

  FOR EXECUTE STATEMENT wsql
      INTO :bdcodsind, /*01*/
           :bddescsind, /*02*/
           :bdentsind, /*03*/
           :bdlogrsind,
           :bdendsind, /*04*/
           :bdnumsind, /*05*/
           :bdcomplsind, /*06*/
           :bdbaisind, /*07*/
           :bdcepsind, /*08*/
           :bdcnpjsind, /*09*/
           :bdnomcidsind, /*10*/
           :bdsiglaufsind, /*11*/
           :bdcodcnae, /*12*/
           :bdnomcid, /*13*/
           :bdsiglauf, /*14*/
           :bdagencia, /*15*/
           :bdcedente, /*16*/
           :bdCNPJ, /*17*/
           :bdsiglauf, /*18*/
           :bdnomcid, /*19*/
           :bdbai, /*20*/
           :bdcep, /*21*/
           :bdcompl, /*22*/
           :bdnum, /*23*/
           :bdlogr,
           :bdend, /*24*/
           :bdnom, /*25*/
           :bdcapsoc /*26*/ DO
      BEGIN
        SUSPEND;
      END
END
^

/* Alter (VRHF_SP_GRCSEMPRESA) */
ALTER PROCEDURE VRHF_SP_GRCSEMPRESA(PRSINDICATO INTEGER,
PRREFEMP INTEGER,
PRCODEMP VARCHAR(10000),
PRULTIMODIA DATE)
 RETURNS(BDCODCNAE INTEGER,
BDVALORDOC NUMERIC(15,2),
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDBAI DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCOMPL DM_BDCOMPENDERECO,
BDNUM INTEGER,
BDEND DM_BDENDERECO,
BDCNPJ VARCHAR(18),
BDNOM DM_BDNOMEMP,
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND DM_BDBAIRRO,
BDCOMPLSIND DM_BDCOMPENDERECO,
BDNUMSIND INTEGER,
BDENTSIND VARCHAR(20),
BDDESCSIND VARCHAR(60),
BDENDSIND DM_BDENDERECO,
BDCAPSOC NUMERIC(15,2),
BDTIPOEMP CHAR,
BDTIPOCOL CHAR,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDSALBASE NUMERIC(15,2),
BDTOTCOLAPU INTEGER,
BDTOTCOLEMP INTEGER,
BDTOTREMU NUMERIC(15,2),
BDLOGRSIND DM_LOGRADOURO,
BDLOGR DM_LOGRADOURO)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(10000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
BEGIN
  bdtotcolapu = 0;
  bdtotcolemp = 0;
  bdtotremu = 0;

  IF (prrefemp IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefemp, NULL, prultimodia);

  wSql = 'select TSINDPAT.bddescsinpat, TSINDPAT.BDCALCCODBARRASINPAT, TSINDPAT.bdendsinpat, TSINDPAT.bdnumsinpat, ';
  wSql =  wSql || 'TSINDPAT.bdcomplsinpat, TSINDPAT.bdbaisinpat, TSINDPAT.bdcepsinpat, TSINDPAT.bdcnpjsinpat, ';
  wSql =  wSql || 'TCIDSIND.bdnomcid, TUFSIND.bdsiglauf, TEMPREF.bdNOMEMP, TEMP.bdCNPJEMP, ';
  wSql =  wSql || 'TEMPREF.bdENDEMP, TEMPREF.bdnumemp, TEMPREF.bdcomplemp, TEMPREF.bdcepemp, TEMPREF.bdbaiemp, ';
  wSql =  wSql || 'TEMPREF.bdcodcnae, TCIDEMP.bdNOMCID, TUFEMP.bdSIGLAUF, TEMPGRCS.BDCAPSOCEMP, ';
  wSql =  wSql || '(TEMPGRCS.BDCAPSOCEMP * (TCONTRSINDFAIX.bdaliqsind / 100)) + TCONTRSINDFAIX.bdparcadicsind bdVALORDOC ';
  wsql = wsql || ', '''||'X'||''' as bdtipoemp, ';
  wSql = wSql || 'TBANCO.bdcodagban, TSINDPAT.bdcodcedentesinpat, ';  -- 12821 - Camila - 18/11/2015
  wSql = wSql || 'tempref.BDLOGREMP, TSINDPAT.BDLOGRESINPAT ';

  wSql = wSql || 'from tempresas_ref TEMPREF ';
  wSql = wSql || 'left outer join TEMPRESAS TEMP on (TEMP.bdcodemp = TEMPREF.bdcodemp) ';
  wSql = wSql || 'left outer join vw_vrhf_base_tempgrcs TEMPGRCS on (TEMPGRCS.bdCODEMP = TEMPREF.bdcodemp) ';
  wSql = wSql || 'left outer join vrhf_base_tsindpatronal TSINDPAT on (TSINDPAT.bdcodsinpat = TEMPGRCS.bdcodsinpat) ';
  -- 12821 - Camila - 18/11/2015
  wsql = wSql || 'left outer join tbancos_ag TBANCO on (TBANCO.bdcodban = TSINDPAT.bdcodban and TBANCO.bdcodag = TSINDPAT.bdcodag) ';
  wSql = wSql || 'left outer join vrhf_tabelas_tcontrsindfaix TCONTRSINDFAIX on ';
  wSql = wSql || '(TCONTRSINDFAIX.bdrefcontrsind = TEMPREF.bdREFEMP and TCONTRSINDFAIX.bdcodcontrsind = TSINDPAT.bdcodcontrsind and ';
  wSql = wSql || 'TCONTRSINDFAIX.bdclainisind <= TEMPGRCS.bdcapsocemp and TCONTRSINDFAIX.bdclafimsind >= TEMPGRCS.BDCAPSOCEMP) ';
  wSql = wSql || 'left outer join tcidade tcidemp on (tCIDEMP.bdcodcid = TEMPREF.bdcodcid) ';
  wSql = wSql || 'left outer join tcidade tcidsind on (tCIDSIND.bdcodcid = TSINDPAT.bdcodcid) ';
  wSql = wSql || 'left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
  wSql = wSql || 'left outer join tuf tufsind on (tufsind.bdcoduf = tcidsind.bdcoduf) ';

  wwhere = '';

  IF (prcodemp <> '') THEN
     wwhere = wwhere||prcodemp||' ';

  IF (prSindicato > 0) THEN
     BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         wWhere = wWhere||'TEMPGRCS.bdcodsinpat = '||prsindicato||' ';
     END

  IF (wwhere <> '') THEN
      wwhere = wwhere||' and ';

  wwhere = wwhere||'TEMPREF.BDREFEMP in
          (
           select MAX(Y.BDREFEMP)
           from TEMPRESAS_REF Y
           where Y.BDCODEMP = TEMPREF.bdcodemp and
                 CAST(Y.BDREFEMP as VARCHAR(6)) <=
                     (select TRIM(rdb$get_context('''||'USER_SESSION'||''', '''||'W_ANOMES'||'''))
                      from rdb$database
                     )
            group by Y.BDCODEMP
           )'||' ';

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wOrderBy = '';

  wsql = wsql||wwhere||worderby;

  FOR EXECUTE STATEMENT wsql
      INTO :bddescsind,
           :bdentsind,
           :bdendsind,
           :bdnumsind,
           :bdcomplsind,
           :bdbaisind,
           :bdcepsind,
           :bdcnpjsind,
           :bdnomcidsind,
           :bdsiglaufsind,
           :bdnom,
           :bdcnpj,
           :bdend,
           :bdnum,
           :bdcompl,
           :bdcep,
           :bdbai,
           :bdcodcnae,
           :bdnomcid,
           :bdsiglauf,
           :bdcapsoc,
           :bdvalordoc,
           :bdtipoemp,
           :bdagencia,
           :bdcedente,
           :bdlogr,
           :BDLOGRSIND DO
      BEGIN
        SUSPEND;
      END
END
^

/* Alter (VRHF_SP_OUTRASINF_CALC) */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODUSU INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prRef, NULL, NULL);

  FOR SELECT BDCODUSU FROM sp_get_usuario
  INTO
    wcodusu
  DO

  wsql = 'select CC_REF.BDCODEMP, '||
                'CC_REF.BDCODCOL, '||
                'CC_REF.BDCODCLA, '||
                'CLASSE.BDDESCCLA, ' ||
                'CC_REF.BDGRUPOCLA, '||
                'CC_REF.BDCODMEN, '||
                'MENSAG.BDDESCMEN, '||
                'CC_REF.BDCODSINTRAB, '||
                'SINTRAB.BDDESCSINTRAB, '||
                'CC_REF.BDCODBAN, '||
                'BANCO.BDNOMBAN, '||
                'CC_REF.BDCODAG, '||
                'AGEN.BDNOMAG, '||
                'CC_REF.BDCTADEPCOL, '||
                'CC_REF.BDDIGCTADEPCOL, '||
                'CC_REF.BDTIPOCTACOL, '||
                'CC_REF.BDMODOPAGTOCOL, '||
                'CC_REF.BDCARTAOSALCOL, '||
                'CC_REF.BDFORMAPAGTOCOL, '||
                'CC_REF.BDNRODEPIRCOL, '||
                'CC_REF.BDBASEIRRFADCOL, '||
                'CC_REF.BDVALORPREVPRIVNCOL, '||
                'CC_REF.BDVALORPREVPRIV13COL, '||
                'CC_REF.BDDATAOPCAOFGTSCOL, '||
                'CC_REF.BDCTAFGTSCOL, '||
                'CC_REF.BDCATEGORIACOL, '||
                'CC_REF.BDPERCFGTSCOL, '||
                'CC_REF.BDOCORRENCIACOL, '||
                'CC_REF.BDPERCRATCOL, '||
                'CC_REF.BDPERCDESCFPASCOL, '||
                'CC_REF.BDBASEINSSNCOL, '||
                'CC_REF.BDVALORINSSNCOL, '||
                'CC_REF.BDBASEIRRFNCOL, '||
                'CC_REF.BDVALORIRRFNCOL, '||
                'CC_REF.BDBASEINSS13COL, '||
                'CC_REF.BDVALORINSS13COL, '||
                'CC_REF.BDBASEIRRF13COL, '||
                'CC_REF.BDVALORIRRF13COL, '||
                'CC_REF.BDTIPOCOL, '||
                'CC_REF.BDHORASMENSAISCOL, '||
                'CC_REF.BDHORASSEMANAISCOL, '||
                'CC_REF.BDHORASDIARIASCOL, '||
                'CC_REF.BDPERCINSALUBCOL, '||
                'CC_REF.BDINCIDINSALUBCOL, '||
                'CC_REF.BDPERCPERCULCOL, '||
                'CC_REF.BDINCIDPERICULCOL, '||
                'CC_REF.BDPERCNOTURNOCOL, '||
                'CC_REF.BDINCIDNOTURNOCOL, '||
                'CC_REF.BDNRODEPSALFAMCOL, '||
                'CC_REF.BDIGNORAFALTASFERCOL, '||
                'CC_REF.BDCALCADIANTACOL, '||
                'CC_REF.BDNAOARREDONDARCOL, '||
                'CC_REF.BDIMPETIQUETACOL, '||
                'CC_REF.BDCALCDSRRVCOL, '||
                'CC_REF.BDCALCDSRHECOL, '||
                'CC_REF.BDCALCDSRSALCOL, '||
                'CC_REF.BDCALCVALTRANSCOL, '||
                'CC_REF.BDCALCVALREFCOL, '||
                'CC_REF.BDCODGPS, '||
                'CC_REF.BDDESCINSSDOIRCOL, '||
                'COL.BDSEXOCOL, '||
                'COL.BDEMAILCOL, '||
                'COL.BDDATANASCCOL, '||
                'CC_REF.BDGRAUINSTCOL, '||
                'CC_REF.BDESTCIVCOL, '||
                'COL.BDDATAADMCOL, '||
                'COL.BDDATAADICCOL, '||
                'COL.BDCPFCOL, '||
                'COL.BDPISCOL, '||
                'COL.BDRESERVISTACOL, '||
                'COL.BDCTPSCOL, '||
                'COL.BDSERIECTPSCOL, '||
                'COL.BDDSERIECTPSCOL, '||
                'COL.BDCNHCOL, '||
                'COL.BDVENCCNHCOL, '||
                'COL.BDDEFFISICOCOL, '||
                'COL.BDDATAFIMPRAZO1COL, '||
                'COL.BDDATAFIMPRAZO2COL, '||
                'COL.BDALVARACOL, '||
                'COL.BDNOMCOL '||
         'from VW_COLABORADORES_REF_ATUAL CC_REF '||
         'left outer join VW_COLABORADORES COL '||
           'on (COL.BDCODEMP = CC_REF.BDCODEMP and COL.BDCODCOL = CC_REF.BDCODCOL) '||
         'left outer join VRH_BASE_TCLASSE CLASSE '||
           'on (CLASSE.BDCODCLA = CC_REF.BDCODCLA) '||
         'left outer join VRH_BASE_TMENSAGENS MENSAG '||
           'on (MENSAG.BDCODMEN = CC_REF.BDCODMEN) '||
         'left outer join VRH_BASE_TSINDTRAB SINTRAB '||
           'on (SINTRAB.BDCODSINTRAB = CC_REF.BDCODSINTRAB) '||
         'left outer join TBANCOS BANCO '||
           'on (BANCO.BDCODBAN = CC_REF.BDCODBAN) '||
         'left outer join TBANCOS_AG AGEN '||
           'on (AGEN.BDCODBAN = CC_REF.BDCODBAN and AGEN.BDCODAG = CC_REF.BDCODAG) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wwhere = PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||PRCODCOL;
     END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = CC_REF.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                      'from TEMPRESA_USUARIO Y '||
                                      'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     END




  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODEMP,
      :BDCODCOL,
      :BDCODCLA,
      :BDDESCCLA,
      :BDGRUPOCLA,
      :BDCODMEN,
      :BDDESCMEN,
      :BDCODSINTRAB,
      :BDDESCSINTRAB,
      :BDCODBAN,
      :BDNOMBAN,
      :BDCODAG,
      :BDNOMAG,
      :BDCTADEPCOL,
      :BDDIGCTADEPCOL,
      :BDTIPOCTACOL,
      :BDMODOPAGTOCOL,
      :BDCARTAOSALCOL,
      :BDFORMAPAGTOCOL,
      :BDNRODEPIRCOL,
      :BDBASEIRRFADCOL,
      :BDVALORPREVPRIVNCOL,
      :BDVALORPREVPRIV13COL,
      :BDDATAOPCAOFGTSCOL,
      :BDCTAFGTSCOL,
      :BDCATEGORIACOL,
      :BDPERCFGTSCOL,
      :BDOCORRENCIACOL,
      :BDPERCRATCOL,
      :BDPERCDESCFPASCOL,
      :BDBASEINSSNCOL,
      :BDVALORINSSNCOL,
      :BDBASEIRRFNCOL,
      :BDVALORIRRFNCOL,
      :BDBASEINSS13COL,
      :BDVALORINSS13COL,
      :BDBASEIRRF13COL,
      :BDVALORIRRF13COL,
      :BDTIPOCOL,
      :BDHORASMENSAISCOL,
      :BDHORASSEMANAISCOL,
      :BDHORASDIARIASCOL,
      :BDPERCINSALUBCOL,
      :BDINCIDINSALUBCOL,
      :BDPERCPERCULCOL,
      :BDINCIDPERICULCOL,
      :BDPERCNOTURNOCOL,
      :BDINCIDNOTURNOCOL,
      :BDNRODEPSALFAMCOL,
      :BDIGNORAFALTASFERCOL,
      :BDCALCADIANTACOL,
      :BDNAOARREDONDARCOL,
      :BDIMPETIQUETACOL,
      :BDCALCDSRRVCOL,
      :BDCALCDSRHECOL,
      :BDCALCDSRSALCOL,
      :BDCALCVALTRANSCOL,
      :BDCALCVALREFCOL,
      :BDCODGPS,
      :BDDESCINSSDOIRCOL,
      :BDSEXOCOL,
      :BDEMAILCOL,
      :BDDATANASCCOL,
      :BDGRAUINSTCOL,
      :BDESTCIVCOL,
      :BDDATAADMCOL,
      :BDDATAADICCOL,
      :BDCPFCOL,
      :BDPISCOL,
      :BDRESERVISTACOL,
      :BDCTPSCOL,
      :BDSERIECTPSCOL,
      :BDDSERIECTPSCOL,
      :BDCNHCOL,
      :BDVENCCNHCOL,
      :BDDEFFISICOCOL,
      :BDDATAFIMPRAZO1COL,
      :BDDATAFIMPRAZO2COL,
      :BDALVARACOL,
      :BDNOMCOL
    DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_OUTRASINF_CALC_ATIVOS) */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_ATIVOS(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODUSU INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prRef, NULL, NULL);

  FOR SELECT BDCODUSU FROM sp_get_usuario
  INTO
    wcodusu
  DO

  wsql = 'select CC_REF.BDCODEMP, '||
                'CC_REF.BDCODCOL, '||
                'CC_REF.BDCODCLA, '||
                'CC_REF.BDDESCCLA, ' ||
                'CC_REF.BDGRUPOCLA, '||
                'CC_REF.BDCODMEN, '||
                'MENSAG.BDDESCMEN, '||
                'CC_REF.BDCODSINTRAB, '||
                'SINTRAB.BDDESCSINTRAB, '||
                'CC_REF.BDCODBAN, '||
                'BANCO.BDNOMBAN, '||
                'CC_REF.BDCODAG, '||
                'AGEN.BDNOMAG, '||
                'CC_REF.BDCTADEPCOL, '||
                'CC_REF.BDDIGCTADEPCOL, '||
                'CC_REF.BDTIPOCTACOL, '||
                'CC_REF.BDMODOPAGTOCOL, '||
                'CC_REF.BDCARTAOSALCOL, '||
                'CC_REF.BDFORMAPAGTOCOL, '||
                'CC_REF.BDNRODEPIRCOL, '||
                'CC_REF.BDBASEIRRFADCOL, '||
                'CC_REF.BDVALORPREVPRIVNCOL, '||
                'CC_REF.BDVALORPREVPRIV13COL, '||
                'CC_REF.BDDATAOPCAOFGTSCOL, '||
                'CC_REF.BDCTAFGTSCOL, '||
                'CC_REF.BDCATEGORIACOL, '||
                'CC_REF.BDPERCFGTSCOL, '||
                'CC_REF.BDOCORRENCIACOL, '||
                'CC_REF.BDPERCRATCOL, '||
                'CC_REF.BDPERCDESCFPASCOL, '||
                'CC_REF.BDBASEINSSNCOL, '||
                'CC_REF.BDVALORINSSNCOL, '||
                'CC_REF.BDBASEIRRFNCOL, '||
                'CC_REF.BDVALORIRRFNCOL, '||
                'CC_REF.BDBASEINSS13COL, '||
                'CC_REF.BDVALORINSS13COL, '||
                'CC_REF.BDBASEIRRF13COL, '||
                'CC_REF.BDVALORIRRF13COL, '||
                'CC_REF.BDTIPOCOL, '||
                'CC_REF.BDHORASMENSAISCOL, '||
                'CC_REF.BDHORASSEMANAISCOL, '||
                'CC_REF.BDHORASDIARIASCOL, '||
                'CC_REF.BDPERCINSALUBCOL, '||
                'CC_REF.BDINCIDINSALUBCOL, '||
                'CC_REF.BDPERCPERCULCOL, '||
                'CC_REF.BDINCIDPERICULCOL, '||
                'CC_REF.BDPERCNOTURNOCOL, '||
                'CC_REF.BDINCIDNOTURNOCOL, '||
                'CC_REF.BDNRODEPSALFAMCOL, '||
                'CC_REF.BDIGNORAFALTASFERCOL, '||
                'CC_REF.BDCALCADIANTACOL, '||
                'CC_REF.BDNAOARREDONDARCOL, '||
                'CC_REF.BDIMPETIQUETACOL, '||
                'CC_REF.BDCALCDSRRVCOL, '||
                'CC_REF.BDCALCDSRHECOL, '||
                'CC_REF.BDCALCDSRSALCOL, '||
                'CC_REF.BDCALCVALTRANSCOL, '||
                'CC_REF.BDCALCVALREFCOL, '||
                'CC_REF.BDCODGPS, '||
                'CC_REF.BDDESCINSSDOIRCOL, '||
                'COL.BDSEXOCOL, '||
                'COL.BDEMAILCOL, '||
                'COL.BDDATANASCCOL, '||
                'CC_REF.BDGRAUINSTCOL, '||
                'CC_REF.BDESTCIVCOL, '||
                'COL.BDDATAADMCOL, '||
                'COL.BDDATAADICCOL, '||
                'COL.BDCPFCOL, '||
                'COL.BDPISCOL, '||
                'COL.BDRESERVISTACOL, '||
                'COL.BDCTPSCOL, '||
                'COL.BDSERIECTPSCOL, '||
                'COL.BDDSERIECTPSCOL, '||
                'COL.BDCNHCOL, '||
                'COL.BDVENCCNHCOL, '||
                'COL.BDDEFFISICOCOL, '||
                'COL.BDDATAFIMPRAZO1COL, '||
                'COL.BDDATAFIMPRAZO2COL, '||
                'COL.BDALVARACOL, '||
                'COL.BDNOMCOL '||
         'from VW_COLABORADORES_REF_ATUAL CC_REF '||
         'left outer join VW_COLABORADORES COL '||
           'on (COL.BDCODEMP = CC_REF.BDCODEMP and COL.BDCODCOL = CC_REF.BDCODCOL) '||
         'left outer join VRH_BASE_TCLASSE CLASSE '||
           'on (CLASSE.BDCODCLA = CC_REF.BDCODCLA) '||
         'left outer join VRH_BASE_TMENSAGENS MENSAG '||
           'on (MENSAG.BDCODMEN = CC_REF.BDCODMEN) '||
         'left outer join VRH_BASE_TSINDTRAB SINTRAB '||
           'on (SINTRAB.BDCODSINTRAB = CC_REF.BDCODSINTRAB) '||
         'left outer join TBANCOS BANCO '||
           'on (BANCO.BDCODBAN = CC_REF.BDCODBAN) '||
         'left outer join TBANCOS_AG AGEN '||
           'on (AGEN.BDCODBAN = CC_REF.BDCODBAN and AGEN.BDCODAG = CC_REF.BDCODAG) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wwhere = PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||PRCODCOL;
     END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = CC_REF.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                      'from TEMPRESA_USUARIO Y '||
                                      'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||' not exists(select W.BDCODCOL from VRH_EMP_TRESCISAO W where W.BDREFRESCISAO < '||prref||' and W.BDCODEMP = CC_REF.BDCODEMP and W.BDCODCOL = CC_REF.BDCODCOL) ';

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODEMP,
      :BDCODCOL,
      :BDCODCLA,
      :BDDESCCLA,
      :BDGRUPOCLA,
      :BDCODMEN,
      :BDDESCMEN,
      :BDCODSINTRAB,
      :BDDESCSINTRAB,
      :BDCODBAN,
      :BDNOMBAN,
      :BDCODAG,
      :BDNOMAG,
      :BDCTADEPCOL,
      :BDDIGCTADEPCOL,
      :BDTIPOCTACOL,
      :BDMODOPAGTOCOL,
      :BDCARTAOSALCOL,
      :BDFORMAPAGTOCOL,
      :BDNRODEPIRCOL,
      :BDBASEIRRFADCOL,
      :BDVALORPREVPRIVNCOL,
      :BDVALORPREVPRIV13COL,
      :BDDATAOPCAOFGTSCOL,
      :BDCTAFGTSCOL,
      :BDCATEGORIACOL,
      :BDPERCFGTSCOL,
      :BDOCORRENCIACOL,
      :BDPERCRATCOL,
      :BDPERCDESCFPASCOL,
      :BDBASEINSSNCOL,
      :BDVALORINSSNCOL,
      :BDBASEIRRFNCOL,
      :BDVALORIRRFNCOL,
      :BDBASEINSS13COL,
      :BDVALORINSS13COL,
      :BDBASEIRRF13COL,
      :BDVALORIRRF13COL,
      :BDTIPOCOL,
      :BDHORASMENSAISCOL,
      :BDHORASSEMANAISCOL,
      :BDHORASDIARIASCOL,
      :BDPERCINSALUBCOL,
      :BDINCIDINSALUBCOL,
      :BDPERCPERCULCOL,
      :BDINCIDPERICULCOL,
      :BDPERCNOTURNOCOL,
      :BDINCIDNOTURNOCOL,
      :BDNRODEPSALFAMCOL,
      :BDIGNORAFALTASFERCOL,
      :BDCALCADIANTACOL,
      :BDNAOARREDONDARCOL,
      :BDIMPETIQUETACOL,
      :BDCALCDSRRVCOL,
      :BDCALCDSRHECOL,
      :BDCALCDSRSALCOL,
      :BDCALCVALTRANSCOL,
      :BDCALCVALREFCOL,
      :BDCODGPS,
      :BDDESCINSSDOIRCOL,
      :BDSEXOCOL,
      :BDEMAILCOL,
      :BDDATANASCCOL,
      :BDGRAUINSTCOL,
      :BDESTCIVCOL,
      :BDDATAADMCOL,
      :BDDATAADICCOL,
      :BDCPFCOL,
      :BDPISCOL,
      :BDRESERVISTACOL,
      :BDCTPSCOL,
      :BDSERIECTPSCOL,
      :BDDSERIECTPSCOL,
      :BDCNHCOL,
      :BDVENCCNHCOL,
      :BDDEFFISICOCOL,
      :BDDATAFIMPRAZO1COL,
      :BDDATAFIMPRAZO2COL,
      :BDALVARACOL,
      :BDNOMCOL
    DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_OUTRASINF_CALC_AUT) */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_AUT(PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PREMPRESA INTEGER = 0)
 RETURNS(BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,2),
BDVALORPREVPRIVNCOL NUMERIC(15,2),
BDVALORPREVPRIV13COL NUMERIC(15,2),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,2),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,2),
BDPERCDESCFPASCOL NUMERIC(15,2),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,2),
BDHORASSEMANAISCOL NUMERIC(15,2),
BDHORASDIARIASCOL NUMERIC(15,2),
BDPERCINSALUBCOL NUMERIC(15,2),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,2),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,2),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODUSU INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prRef, NULL, NULL);

  FOR SELECT BDCODUSU FROM sp_get_usuario
  INTO
    wcodusu
  DO

/*00*/  wsql = 'select CC_REF.BDCODCOL,';
/*01*/  wsql = wsql||'CC_REF.BDCODCLA, ';
/*02*/  wsql = wsql||'CLASSE.BDDESCCLA, ';
/*03*/  wsql = wsql||'CC_REF.BDGRUPOCLA, ';
/*04*/  wsql = wsql||'CC_REF.BDCODMEN,';
/*05*/  wsql = wsql||'MENSAG.BDDESCMEN, ';
/*06*/  wsql = wsql||'CC_REF.BDCODSINTRAB,';
/*07*/  wsql = wsql||'SINTRAB.BDDESCSINTRAB, ';
/*08*/  wsql = wsql||'CC_REF.BDCODBAN, ';
/*09*/  wsql = wsql||'BANCO.BDNOMBAN, ';
/*10*/  wsql = wsql||'CC_REF.BDCODAG, ';
/*11*/  wsql = wsql||'AGEN.BDNOMAG, ';
/*12*/  wsql = wsql||'CC_REF.BDCTADEPCOL, ';
/*13*/  wsql = wsql||'CC_REF.BDDIGCTADEPCOL, ';
/*14*/  wsql = wsql||'CC_REF.BDTIPOCTACOL, ';
/*15*/  wsql = wsql||'CC_REF.BDMODOPAGTOCOL, ';
/*16*/  wsql = wsql||'CC_REF.BDCARTAOSALCOL, ';
/*17*/  wsql = wsql||'CC_REF.BDFORMAPAGTOCOL,';
/*18*/  wsql = wsql||'CC_REF.BDNRODEPIRCOL, ';
/*19*/  wsql = wsql||'CC_REF.BDBASEIRRFADCOL,';
/*20*/  wsql = wsql||'CC_REF.BDVALORPREVPRIVNCOL,';
/*21*/  wsql = wsql||'CC_REF.BDVALORPREVPRIV13COL,';
/*22*/  wsql = wsql||'CC_REF.BDDATAOPCAOFGTSCOL,';
/*23*/  wsql = wsql||'CC_REF.BDCTAFGTSCOL, ';
/*24*/  wsql = wsql||'CC_REF.BDCATEGORIACOL, ';
/*25*/  wsql = wsql||'CC_REF.BDPERCFGTSCOL, ';
/*26*/  wsql = wsql||'CC_REF.BDOCORRENCIACOL, ';
/*27*/  wsql = wsql||'CC_REF.BDPERCRATCOL, ';
/*28*/  wsql = wsql||'CC_REF.BDPERCDESCFPASCOL, ';
--/*29*/  wsql = wsql||'CC_REF.BDBASEINSSNCOL, ';
--/*30*/  wsql = wsql||'CC_REF.BDVALORINSSNCOL, ';
--/*31*/  wsql = wsql||'CC_REF.BDBASEIRRFNCOL, ';
--/*32*/  wsql = wsql||'CC_REF.BDVALORIRRFNCOL, ';
--/*33*/  wsql = wsql||'CC_REF.BDBASEINSS13COL, ';
--/*34*/  wsql = wsql||'CC_REF.BDVALORINSS13COL, ';
--/*35*/  wsql = wsql||'CC_REF.BDBASEIRRF13COL, ';
--/*36*/  wsql = wsql||'CC_REF.BDVALORIRRF13COL, ';
/*37*/  wsql = wsql||'CC_REF.BDTIPOCOL, ';
/*38*/  wsql = wsql||'CC_REF.BDHORASMENSAISCOL, ';
/*39*/  wsql = wsql||'CC_REF.BDHORASSEMANAISCOL, ';
/*40*/  wsql = wsql||'CC_REF.BDHORASDIARIASCOL, ';
/*41*/  wsql = wsql||'CC_REF.BDPERCINSALUBCOL, ';
/*42*/  wsql = wsql||'CC_REF.BDINCIDINSALUBCOL, ';
/*43*/  wsql = wsql||'CC_REF.BDPERCPERCULCOL, ';
/*44*/  wsql = wsql||'CC_REF.BDINCIDPERICULCOL, ';
/*45*/  wsql = wsql||'CC_REF.BDPERCNOTURNOCOL, ';
/*46*/  wsql = wsql||'CC_REF.BDINCIDNOTURNOCOL, ';
/*47*/  wsql = wsql||'CC_REF.BDNRODEPSALFAMCOL, ';
/*48*/  wsql = wsql||'CC_REF.BDIGNORAFALTASFERCOL, ';
/*49*/  wsql = wsql||'CC_REF.BDCALCADIANTACOL, ';
/*50*/  wsql = wsql||'CC_REF.BDNAOARREDONDARCOL, ';
/*51*/  wsql = wsql||'CC_REF.BDIMPETIQUETACOL, ';
/*52*/  wsql = wsql||'CC_REF.BDCALCDSRRVCOL, ';
/*53*/  wsql = wsql||'CC_REF.BDCALCDSRHECOL, ';
/*54*/  wsql = wsql||'CC_REF.BDCALCDSRSALCOL, ';
/*55*/  wsql = wsql||'CC_REF.BDCALCVALTRANSCOL, ';
/*56*/  wsql = wsql||'CC_REF.BDCALCVALREFCOL, ';
/*57*/  wsql = wsql||'CC_REF.BDCODGPS, ';
/*58*/  wsql = wsql||'CC_REF.BDDESCINSSDOIRCOL, ';
/*59*/  wsql = wsql||'COL.BDSEXOCOL, ';
/*60*/  wsql = wsql||'COL.BDEMAILCOL, ';
/*61*/  wsql = wsql||'COL.BDDATANASCCOL, ';
/*62*/  wsql = wsql||'COL.BDGRAUINSTCOL, ';
/*63*/  wsql = wsql||'COL.BDESTCIVCOL, ';
/*64*/  wsql = wsql||'COL.BDDATAADMCOL, ';
/*65*/  wsql = wsql||'COL.BDDATAADICCOL, ';
/*66*/  wsql = wsql||'COL.BDCPFCOL, ';
/*67*/  wsql = wsql||'COL.BDPISCOL, ';
/*68*/  wsql = wsql||'COL.BDRESERVISTACOL, ';
/*69*/  wsql = wsql||'COL.BDCTPSCOL, ';
/*70*/  wsql = wsql||'COL.BDSERIECTPSCOL, ';
/*71*/  wsql = wsql||'COL.BDDSERIECTPSCOL, ';
/*72*/  wsql = wsql||'COL.BDCNHCOL, ';
/*73*/  wsql = wsql||'COL.BDVENCCNHCOL, ';
/*74*/  wsql = wsql||'COL.BDDEFFISICOCOL, ';
/*75*/  wsql = wsql||'COL.BDDATAFIMPRAZO1COL, ';
/*76*/  wsql = wsql||'COL.BDDATAFIMPRAZO2COL, ';
/*77*/  wsql = wsql||'COL.BDALVARACOL, ';
/*78*/  wsql = wsql||'COL.BDNOMCOL ';
        wsql = wsql||'from ('||
                            'select * from VRH_BASE_TSERVTERC '||
                            'where BDREFPAGSERV >= '||prref;

        IF (prempresa > 0) THEN
           wsql = wsql||' and BDCODEMP = '||prempresa;

        wsql = wsql||') SERVICO ';
/*79*/  wsql = wsql||'left outer join VW_AUTONOMOS_REF_ATUAL CC_REF on (CC_REF.BDCODCOL = SERVICO.BDCODTER) ';
/*80*/  wsql = wsql||'left outer join VW_AUTONOMO COL ';
/*81*/  wsql = wsql||'on (COL.BDCODCOL = CC_REF.BDCODCOL) ';
/*82*/  wsql = wsql||'left outer join VRH_BASE_TCLASSE CLASSE ';
/*83*/  wsql = wsql||'on (CLASSE.BDCODCLA = CC_REF.BDCODCLA) ';
/*84*/  wsql = wsql||'left outer join VRH_BASE_TMENSAGENS MENSAG ';
/*85*/  wsql = wsql||'on (MENSAG.BDCODMEN = CC_REF.BDCODMEN) ';
/*86*/  wsql = wsql||'left outer join VRH_BASE_TSINDTRAB SINTRAB ';
/*87*/  wsql = wsql||'on (SINTRAB.BDCODSINTRAB = CC_REF.BDCODSINTRAB) ';
/*88*/  wsql = wsql||'left outer join TBANCOS BANCO ';
/*89*/  wsql = wsql||'on (BANCO.BDCODBAN = CC_REF.BDCODBAN) ';
/*90*/  wsql = wsql||'left outer join TBANCOS_AG AGEN ';
/*91*/  wsql = wsql||'on (AGEN.BDCODBAN = CC_REF.BDCODBAN and AGEN.BDCODAG = CC_REF.BDCODAG) ';

  wwhere = '';

/*  if (PRCODEMP is not null and PRCODEMP <> '') then
     wwhere = PRCODEMP;*/

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||PRCODCOL;
     END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||')) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                      'from TEMPRESA_USUARIO Y '||
                                      'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     END




  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
    INTO
/*      :BDCODEMP,*/
      :BDCODCOL,
      :BDCODCLA,
      :BDDESCCLA,
      :BDGRUPOCLA,
      :BDCODMEN,
      :BDDESCMEN,
      :BDCODSINTRAB,
      :BDDESCSINTRAB,
      :BDCODBAN,
      :BDNOMBAN,
      :BDCODAG,
      :BDNOMAG,
      :BDCTADEPCOL,
      :BDDIGCTADEPCOL,
      :BDTIPOCTACOL,
      :BDMODOPAGTOCOL,
      :BDCARTAOSALCOL,
      :BDFORMAPAGTOCOL,
      :BDNRODEPIRCOL,
      :BDBASEIRRFADCOL,
      :BDVALORPREVPRIVNCOL,
      :BDVALORPREVPRIV13COL,
      :BDDATAOPCAOFGTSCOL,
      :BDCTAFGTSCOL,
      :BDCATEGORIACOL,
      :BDPERCFGTSCOL,
      :BDOCORRENCIACOL,
      :BDPERCRATCOL,
      :BDPERCDESCFPASCOL,
--      :BDBASEINSSNCOL,
--      :BDVALORINSSNCOL,
--      :BDBASEIRRFNCOL,
--      :BDVALORIRRFNCOL,
--      :BDBASEINSS13COL,
--      :BDVALORINSS13COL,
--      :BDBASEIRRF13COL,
--      :BDVALORIRRF13COL,
      :BDTIPOCOL,
      :BDHORASMENSAISCOL,
      :BDHORASSEMANAISCOL,
      :BDHORASDIARIASCOL,
      :BDPERCINSALUBCOL,
      :BDINCIDINSALUBCOL,
      :BDPERCPERCULCOL,
      :BDINCIDPERICULCOL,
      :BDPERCNOTURNOCOL,
      :BDINCIDNOTURNOCOL,
      :BDNRODEPSALFAMCOL,
      :BDIGNORAFALTASFERCOL,
      :BDCALCADIANTACOL,
      :BDNAOARREDONDARCOL,
      :BDIMPETIQUETACOL,
      :BDCALCDSRRVCOL,
      :BDCALCDSRHECOL,
      :BDCALCDSRSALCOL,
      :BDCALCVALTRANSCOL,
      :BDCALCVALREFCOL,
      :BDCODGPS,
      :BDDESCINSSDOIRCOL,
      :BDSEXOCOL,
      :BDEMAILCOL,
      :BDDATANASCCOL,
      :BDGRAUINSTCOL,
      :BDESTCIVCOL,
      :BDDATAADMCOL,
      :BDDATAADICCOL,
      :BDCPFCOL,
      :BDPISCOL,
      :BDRESERVISTACOL,
      :BDCTPSCOL,
      :BDSERIECTPSCOL,
      :BDDSERIECTPSCOL,
      :BDCNHCOL,
      :BDVENCCNHCOL,
      :BDDEFFISICOCOL,
      :BDDATAFIMPRAZO1COL,
      :BDDATAFIMPRAZO2COL,
      :BDALVARACOL,
      :BDNOMCOL
    DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_QUADROHORARIOS) */
ALTER PROCEDURE VRHF_SP_QUADROHORARIOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRDIASEMANA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCIDADE VARCHAR(40),
BDUF VARCHAR(2),
BDBAIEMP DM_BDBAIRRO,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDPISCOL VARCHAR(14),
BDCODQH INTEGER,
BDDESQH DM_BDDESCQH,
BDDIA INTEGER,
BDHORAENT TIME,
BDHORASAI TIME)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WANO VARCHAR(4);
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WMES VARCHAR(2);
DECLARE VARIABLE WDIA VARCHAR(2);
BEGIN


  EXECUTE PROCEDURE sp_seta_competencia(pranomes, NULL, prultimodia);

  wmes = CAST(SUBSTRING(CAST(:pranomes AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:pranomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;


  wsql = 'select vw_vincdia.bdcodemp, empresas.bdnomemp , empresas.bdcnpjemp, empresas.BDNOMCID, empresas.bdsiglauf , empresas.bdbaiemp, empresas.bdlogremp,
          empresas.bdendemp, empresas.bdnumemp, empresas.bdcepemp, vw_vincdia.bdcodcol,col.bdnomcol, col.bdctpscol, col.bdseriectpscol, col.bdpiscol, vw_vincdia.bdcodqh, tqh.bddescqh,
          tqh_dias.bddiasemqh,  tqh_horas.bdqhhsent, tqh_horas.bdqhhssai
          from vw_tcolcon_vincdia vw_vincdia
          left outer join SP_CONSULTAEMPRESAS(' || pranomes || ', null, null) empresas on (empresas.bdcodemp = vw_vincdia.bdcodemp )
          left outer join vrh_sp_colcon(null,null,null,null,null, ' || pranomes || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) col  on (vw_vincdia.BDCODEMP = col.BDCODEMP and vw_vincdia.BDCODCOL = col.BDCODCOL)
          inner join vrh_base_tqh_dias tqh_dias on (tqh_dias.bdcodqh = vw_vincdia.bdcodqh)
          inner join vrh_base_tqh_horas tqh_horas on (tqh_horas.bdcodqhh = tqh_dias.bdcodqhh)
          inner join VRH_BASE_TQH tqh on (tqh.bdcodqh = vw_vincdia.bdcodqh)';

  wwhere = '(vw_vincdia.bdcodemp = ' || prcodemp || ')';


  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and (vw_vincdia.bdcodcol = ' || prcodcol || ')' ;
     END

  IF (prdiasemana IS NOT  NULL) THEN
     wwhere = wwhere|| ' and (tqh_dias.bddiasemqh = ' || prdiasemana || ')';

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  -- oder by
  wwhere = wwhere|| ' order by vw_vincdia.bdcodemp, vw_vincdia.bdcodcol, tqh_dias.bddiasemqh, tqh_horas.bdqhhsent  ';

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :bdcnpjemp,
        :bdcidade,
        :bduf,
        :bdbaiemp,
        :bdlogremp,
        :bdendemp,
        :bdnumemp,
        :bdcepemp,
        :BDCODCOL,
        :bdnomcol,
        :bdctpscol,
        :bdseriectpscol,
        :bdpiscol,
        :bdcodqh,
        :bddesqh,
        :bddia,
        :bdhoraent,
        :bdhorasai
      DO

    SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Alter (VRHF_SP_RECIBO_FERIAS) */
ALTER PROCEDURE VRHF_SP_RECIBO_FERIAS(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRDATAGOZOINI DATE,
PRDATAGOZOFIM DATE,
PRPERIODOAQUISITIVO DATE,
PRCODIGOFERIAS INTEGER,
PRTIPOCODVER INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE,
PRCOLETIVAS INTEGER,
PRAVISO INTEGER = 0,
PRIDADE21 INTEGER = 2100,
PRNOVORECIBO SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDNOMCIDEMP VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCHAVE INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDSIGLAUFCTPS VARCHAR(2),
BDDESCTFUC VARCHAR(40),
BDDATAADMCOL DATE,
BDINIPERAQUISFE DATE,
BDFIMPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERGOZOFE DATE,
BDFALTASFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDQTDABONOFE NUMERIC(18,6),
BDDATAPAGFE DATE,
BDCODVER INTEGER,
BDTIPOCODVER INTEGER,
BDORDEMVER INTEGER,
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDREFVFE NUMERIC(15,6),
BDVALVFE NUMERIC(15,6),
BDTIPOREFVER INTEGER,
BDREFPAGABOFE INTEGER,
BDINISWS DATE,
BDFIMSWS DATE,
BDVALLIQUIDO NUMERIC(15,6),
BDCALCA13FE VARCHAR(5),
BDSALINI NUMERIC(15,6),
BDDIASLICFE NUMERIC(18,6),
BDDATAAVISO DATE,
BDCLASSVER VARCHAR(20),
BDREFAUXVER NUMERIC(15,6),
BDCOLETIVAS VARCHAR(5),
BDDEPIR INTEGER,
BDDIASFERFE NUMERIC(18,6),
BDLOGOEMP BLOB SEGMENT SIZE 32720,
BDREFHOREMP DM_BOOLEAN,
BDCPFCOL VARCHAR(14),
BDDATARELABONO DATE)
 AS
declare variable WORDERBY varchar(10000);
declare variable WWHERE varchar(15000);
declare variable WWHEREAVISO varchar(15000);
declare variable WSQL varchar(30000);
declare variable WMES integer;
declare variable WANO integer;
declare variable WDIA integer;
declare variable WDATAAUX varchar(10);
declare variable WCHAVE integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WSQLAVISO varchar(30000);
declare variable WREFDADOSEMP integer;
declare variable WSQLDADOSEMP varchar(500);
declare variable WWHEREDADOSEMP varchar(500);
declare variable WCODEMPATU integer;
declare variable WCODCOLATU integer;
declare variable WINIPERAQUISATU date;
declare variable WCODFEATU integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDINIPERAQUISFE date;
declare variable WBDCODFE integer;
declare variable WBDCODVER integer;
declare variable WBDORDEMVER integer;
declare variable WCVER integer;
declare variable WCVER2 integer;
declare variable WEMPFERI integer;
BEGIN
   wrefdadosemp = 0;

   IF (prreferencia IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, PRULTIMODIA);

   wsql = 'select ';

   IF (prtipocodver IS NULL) THEN
      wsql = wsql || 'distinct ';

   wsql = wsql || 'adm.bdsalinicol, ';
   wsql = wsql || 'vw_col_ref_atual.bdcodemp, ';
   wsql = wsql || 'temp.bdnomemp, ';
   wsql = wsql || 'temp.bdlogremp, ';
   wsql = wsql || 'temp.bdendemp, ';
   wsql = wsql || 'temp.bdnumemp, ';
   wsql = wsql || 'temp.bdcomplemp, ';
   wsql = wsql || 'temp.bdbaiemp, ';
   wsql = wsql || 'tcidemp.bdnomcid, ';
   wsql = wsql || 'tufemp.bdsiglauf, ';
   wsql = wsql || 'emp.bdcnpjemp, ';
   wsql = wsql || 'vw_col_ref_atual.bdcodcol, ';
   wsql = wsql || 'COLCAD.bdnomcol, ';
   wsql = wsql || 'docref.bdctpscol, ';
   wsql = wsql || 'docref.bdseriectpscol, ';
   wsql = wsql || 'docref.bddseriectpscol, ';
   wsql = wsql || 'tuf_doc.bdsiglauf, ';
   wsql = wsql || 'vw_col_ref_atual.bddataadmcol, ';
   wsql = wsql || 'tfuc.bddesctfuc, ';
   wsql = wsql || 'tferias.bdiniperaquisfe, ';
   wsql = wsql || 'tferias.bdfimperaquisfe, ';
   wsql = wsql || 'tferias.bdcodfe, ';
   wsql = wsql || 'tferias.bdinipergozofe, ';
   wsql = wsql || 'tferias.bdfimpergozofe, ';
   wsql = wsql || 'tferias.bdfaltasfe, ';
   wsql = wsql || 'tferias.bdsalbasefe, ';
   wsql = wsql || 'tferias.bdsalbasehefe, ';
   wsql = wsql || 'tferias.bddatapagfe, ';
   wsql = wsql || 'tferias.bdqtdabonofe, ';
   wsql = wsql || 'tferias.bdliquido, ';
   wsql = wsql || 'tferias.bdcalca13fe, ';
   wsql = wsql || 'tdepcol.depir,';
   wsql = wsql || 'tferias.bdcoletivasfe ';

   IF (prtipocodver IS NOT NULL) THEN
      BEGIN
         wsql = wsql || ', tferias.bdcodver, ';
         wsql = wsql || 'tverbas.BDCLAVER, ';
         wsql = wsql || 'tverbas.bddescver, ';
         wsql = wsql || 'tverbas.bddescredver, ';
         wsql = wsql || 'tverbasref.bdtipocodver, ';
         wsql = wsql || 'tverbas.bdordemver, ';
         wsql = wsql || 'tferias.bdrefvfe, ';
         wsql = wsql || 'tferias.bdvalvfe, ';
         wsql = wsql || 'tferias.BDREFAUXVFE, ';
         wsql = wsql || 'tverbasref.bdtiporefver ';
      END
   wsql = wsql || ', tferias.BDREFPAGABOFE ';

   wsql = wsql || ', (select sum(coalesce(ref.bddiaslicfe,0)) bddiaslicfe from vrh_emp_tferiasref ref '||
                  '   where tferias.bdcodemp = ref.bdcodemp and tferias.bdcodcol = ref.bdcodcol and tferias.bdiniperaquisfe = '||
                  '   ref.bdiniperaquisfe and tferias.bdcodfe = ref.bdcodfe) bddiaslicfe ';

   wsql = wsql || ', (select sum(coalesce(ref.bddiasferfe,0)) bddiasferfe from vrh_emp_tferiasref ref '||
                  '   where tferias.bdcodemp = ref.bdcodemp and tferias.bdcodcol = ref.bdcodcol and tferias.bdiniperaquisfe = '||
                  '   ref.bdiniperaquisfe and tferias.bdcodfe = ref.bdcodfe) bddiasferfe ';

   wsql = wsql || ', tferias.bddataaviso ';

   wsql = wsql || ', img.bdlogoemp '; -- 14363 - Marcelo B. M. - 25/11/2016: retornar campo bdlogoemp
   wsql = wsql ||',EMPCALC.BDREFHOREMP ';
   wsql = wsql ||',colcondoc.BDCPFCOL ';

   wsql = wsql || ' from (select vw_col_ref_atual.* from vw_vrhf_ferias vw_col_ref_atual ';

   wsqlAviso = 'select av.bdcodemp, emp.bdnomemp, emp.bdlogremp, emp.bdendemp, emp.bdnumemp, emp.bdcomplemp, emp.bdbaiemp, cidemp.bdnomcid bdnomcidemp, ufemp.bdsiglauf bdsiglaufemp, '||
          ' temp.bdcnpjemp, av.bdcodcol, colcad.bdnomcol, 1 bdchave, docref.bdctpscol, docref.bdseriectpscol, docref.bddseriectpscol, '||
          ' ufdoc.bdsiglauf bdsiglaufctps, tfuc.bddesctfuc bddesctfuc, col.bddataadmcol,  vw_col_ref_atual.bdperaqui bdiniperaquisfe, vw_col_ref_atual.bdfimperaqui bdfimperaquisfe, vw_col_ref_atual.bdcodfe bdcodfe, '||
          ' vw_col_ref_atual.bdinigozo bdinipergozofe, vw_col_ref_atual.bdfimgozo bdfimpergozofe, 0 bdfaltasfe, calcdiacol.bdsalbasecol bdsalbasefe, null bdsalbasehefe, '||
          ' vw_col_ref_atual.bdqtdabono bdqtdabonofe, null bddatapagfe, null bdcodver, null BDCLAVER, null bdtipocodver, null bdordemver, null bddescver, null bddescredver, null bdrefvfe, '||
          ' null bdvalvfe, null BDREFAUXVFE, null bdtiporefver, vw_col_ref_atual.bdrefabono bdrefpagabofe, '||
          ' null bdinisws, null bdfimsws, '||
          ' null bdvalliquido, '||
          ' null bdcalca13fe, '||
          ' null bdcoletivasfe, '||
          ' part.bdsalinicol bdsalini, '||
          ' null bddiaslicfe, null bddiasferfe, vw_col_ref_atual.bddataaviso  '||
          ' from vrh_emp_tdet_avisoferias vw_col_ref_atual '||
          ' join vrh_emp_tavisoferias av on (vw_col_ref_atual.bdcodemp = av.bdcodemp and av.bdcodcol = vw_col_ref_atual.bdcodcol and av.bddataaviso = vw_col_ref_atual.bddataaviso) '||
          ' left outer join vw_tempresas_ref_join emp on (av.bdcodemp = emp.bdcodemp) '||
          ' left outer join tempresas temp on (temp.bdcodemp = av.bdcodemp) '||
          ' left outer join vrh_emp_tcolcon col on (av.bdcodemp = col.bdcodemp and av.bdcodcol = col.bdcodcol) '||
          ' left outer join vw_vrh_emp_tcolcon_cad colcad on (colcad.bdcodemp = col.bdcodemp and colcad.bdcodcol = col.bdcodcol) '||
          ' left outer join vw_vrh_emp_tcolcon_docref docref on (docref.bdcodemp = col.bdcodemp and docref.bdcodcol = col.bdcodcol) '||
          ' left outer join vrh_emp_tcolcon_partida part on (av.bdcodemp = part.bdcodemp and av.bdcodcol = part.bdcodcol) '||
          ' left outer join VRH_EMP_TCOL_DOC doc on (av.bdcodemp = doc.bdcodemp and av.bdcodcol = doc.bdcodcol) '||
          ' left outer join tuf ufdoc on (ufdoc.bdcoduf = docref.bdcoduf) '||
          ' left outer join vw_tcolcon_calcdia calcdiacol on (calcdiacol.BDCODEMP = av.BDCODEMP and calcdiacol.BDCODCOL = av.BDCODCOL) '||
          ' left outer join VW_TCOLCON_VINCDIA diacol on (diacol.BDCODEMP = av.BDCODEMP and diacol.BDCODCOL = av.BDCODCOL) '||
          ' left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = diacol.bdcodplafuc and tfuc.bdcodtfuc = diacol.bdcodtfuc) '||
          ' left outer join tcidade cidemp on (emp.bdcodcid = cidemp.bdcodcid) '||
          ' left outer join tuf ufemp on (ufemp.bdcoduf = cidemp.bdcoduf) '||
          ' left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = vw_col_ref_atual.BDCODEMP) '||
          ' left outer join VRH_EMP_TCOLCON_DOC colcondoc on (colcondoc.BDCODEMP = vw_col_ref_atual.BDCODEMP and colcondoc.BDCODCOL = vw_col_ref_atual.BDCODCOL) ';

   wwhere = '';
   WWHEREAVISO = '';

   IF (prempresa <> '') THEN
      BEGIN
        wwhere = wwhere||prempresa||' ';
        wwhereaviso = wwhereaviso||prempresa||' ';
      END

   IF (prcolaborador <> '') THEN
      BEGIN
        IF (wwhere <> '') THEN
           BEGIN
             wwhere = wwhere||' and ';
             wwhereaviso = wwhereaviso||' and ';
            END
        wwhere = wwhere||prcolaborador||' ';
        wwhereaviso = wwhereaviso||prcolaborador||' ';
     END

   IF (PRCOLETIVAS <> 1) THEN
     BEGIN
        IF ((prdatagozoini IS NOT NULL) AND (prdatagozofim IS NOT NULL)) THEN
          BEGIN
            IF (wwhere <> '') THEN
               BEGIN
                 wwhere = wwhere||' and ';
                 wwhereaviso = wwhereaviso||' and ';
               END
     
            wwhere = wwhere||'(((vw_col_ref_atual.bdinipergozofe >= '''||prdatagozoini||''''||')';
            wwhere = wwhere||' and ';
            wwhere = wwhere||'(vw_col_ref_atual.bdinipergozofe <= '''||prdatagozofim||''''||'))';
            wwhere = wwhere||' or ';
            wwhere = wwhere||'((vw_col_ref_atual.bdfimpergozofe >= '''||prdatagozoini||''''||')';
            wwhere = wwhere||' and ';
            wwhere = wwhere||'(vw_col_ref_atual.bdfimpergozofe <= '''||prdatagozofim||''''||')))';
     
            wwhereaviso = wwhereaviso||'(((vw_col_ref_atual.bdinigozo >= '''||prdatagozoini||''''||')';
            wwhereaviso = wwhereaviso||' and ';
            wwhereaviso = wwhereaviso||'(vw_col_ref_atual.bdinigozo <= '''||prdatagozofim||''''||'))';
            wwhereaviso = wwhereaviso||' or ';
            wwhereaviso = wwhereaviso||'((vw_col_ref_atual.bdfimgozo >= '''||prdatagozoini||''''||')';
            wwhereaviso = wwhereaviso||' and ';
            wwhereaviso = wwhereaviso||'(vw_col_ref_atual.bdfimgozo <= '''||prdatagozofim||''''||')))';
          END
           ELSE
             BEGIN
        
               IF (prperiodoaquisitivo IS NOT NULL) THEN
                 BEGIN
                   IF (wwhere <> '') THEN
                      BEGIN
                        wwhere = wwhere||' and ';
                        wwhereaviso = wwhereaviso||' and ';
                      END
                   wwhere = wwhere||'vw_col_ref_atual.bdiniperaquisfe = '''||prperiodoaquisitivo||''''||' ';
                   wwhereaviso = wwhereaviso||'vw_col_ref_atual.bdperaqui = '''||prperiodoaquisitivo||''''||' ';
                 END
        
        
             END

           IF (prcodigoferias IS NOT NULL AND prcodigoferias > 0) THEN
              BEGIN
                 IF (wwhere <> '') THEN
                    BEGIN
                      wwhere = wwhere||' and ';
                      wwhereaviso = wwhereaviso||' and ';
                    END
                 wwhere = wwhere||'vw_col_ref_atual.bdcodfe = '||prcodigoferias||' ';
                 wwhereaviso = wwhereaviso||'vw_col_ref_atual.bdcodfe = '||prcodigoferias||' ';
              END

     END

         
   IF (wwhere <> '') THEN
      BEGIN
        wwhere = ' where '||wwhere;
        wwhereaviso = ' where '||wwhereaviso;
      END

   wsql = wsql||wwhere;
   wsqlaviso = wsqlaviso||wwhereaviso;

   IF (wwhereaviso <> '') THEN
      wwhereaviso = ' and ';
   ELSE
      wwhereaviso = ' where ';

   wwhereaviso = wwhereaviso||' not exists (select * from vrh_emp_tferias fer where fer.bdcodemp = vw_col_ref_atual.bdcodemp and fer.bdcodcol = vw_col_ref_atual.bdcodcol '||
                             ' and fer.bdiniperaquisfe = vw_col_ref_atual.bdperaqui and fer.bdcodfe = vw_col_ref_atual.bdcodfe) ';

   wsqlaviso = wsqlaviso||wwhereaviso;

   wsql = wsql||') tferias ';
   wsql = wsql || 'join VRH_EMP_TCOLCON vw_col_ref_atual on (vw_col_ref_atual.BDCODEMP = tferias.BDCODEMP and vw_col_ref_atual.BDCODCOL = tferias.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = tferias.BDCODEMP and COLCAD.BDCODCOL = tferias.BDCODCOL) ';
   wsql = wsql || 'join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = vw_col_ref_atual.BDCODEMP and COL_DIAVINC.BDCODCOL = vw_col_ref_atual.BDCODCOL) ';
   wsql = wsql||'left outer join VW_TEMPRESAS_REF TEMP on (TEMP.BDCODEMP = TFERIAS.BDCODEMP) ';
   wsql = wsql||'left outer join TEMPRESAS EMP on (EMP.BDCODEMP = TFERIAS.BDCODEMP) ';

   wsql = wsql || 'left outer join vrh_emp_tcol_adm adm on (adm.bdcodemp = vw_col_ref_atual.bdcodemp and vw_col_ref_atual.bdcodcol = adm.bdcodcol) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOL_DOC COL_DOC on (COL_DOC.bdcodemp = vw_col_ref_atual.bdcodemp and vw_col_ref_atual.bdcodcol = COL_DOC.bdcodcol) ';
   wsql = wsql || 'left outer join vw_vrh_emp_tcolcon_docref docref on (docref.bdcodemp = vw_col_ref_atual.bdcodemp and docref.bdcodcol = vw_col_ref_atual.bdcodcol) ';
   wsql = wsql || 'left outer join tuf tuf_doc on (tuf_doc.bdcoduf = docref.bdcoduf) ';
   wsql = wsql || 'left outer join TCIDADE TCIDEMP on (TCIDEMP.BDCODCID = TEMP.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUFEMP on (TUFEMP.BDCODUF = TCIDEMP.BDCODUF) ';

   wsql = wsql || 'left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = COL_DIAVINC.bdcodplafuc and tfuc.bdcodtfuc = COL_DIAVINC.bdcodtfuc) ';

   -- 12149 - Camila - 29/10/2015: Altera??o realizada para retornar o n?mero de dependentes de IR (BDDEPIR)
   wsql = wsql || 'left outer join(select BDCODEMP, BDCODCOL, count(*) DEPIR from VW_VRH_EMP_TDEP_REF DEPIR where DEPIR.BDPARENESCODPN <> 3 and ' ||
                  '(select BDAAAAMM from AAAAMM(coalesce(DEPIR.BDDATANASCDPN, DEPIR.BDDATAENTREDPN))) <= ' || prreferencia || ' and ((DEPIR.BDDATABAUXADPN is null) ' ||
                  'or ((select BDAAAAMM from AAAAMM(DEPIR.BDDATABAUXADPN)) > ' || prreferencia || ')) and ((DEPIR.BDREFIRDPN is null) or (DEPIR.BDREFIRDPN = 0) or (DEPIR.BDREFIRDPN >= ' || prreferencia || ')) and ' ||
                  '((upper(DEPIR.BDINVALIDODPN) = ''TRUE'') or (DEPIR.BDREFIRDPN >= ' || prreferencia || ') or ((DEPIR.BDPARENESCODPN in (0, 4, 5, 6)) and ' ||
                  '(' || prreferencia || ' - cast((select BDAAAAMM from AAAAMM(DEPIR.BDDATANASCDPN)) as integer) < '||pridade21||')) or (DEPIR.BDPARENESCODPN in (1, 2))) group by DEPIR.BDCODEMP, DEPIR.BDCODCOL) ' ||
                  'TDEPCOL on (TDEPCOL.BDCODEMP = TFERIAS.BDCODEMP and TDEPCOL.BDCODCOL = TFERIAS.BDCODCOL)';

   IF (PRCOLETIVAS = 1) THEN
      BEGIN
        wsql = wsql || ' left outer join vrh_emp_tferias_coletivas col on (tferias.bdcodemp = col.bdcodemp and tferias.bdcodcol = col.bdcodcol and tferias.bdiniperaquisfe = col.bdiniperaquisfe and tferias.bdcodfe = col.bdcodfe) ';
      END

   IF (prtipocodver IS NOT NULL) THEN
      BEGIN
        wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = tferias.bdcodver) ';
        wsql = wsql || 'left outer join vw_verbas_ref_atual tverbasref on (tverbasref.bdcodver = tverbas.bdcodver) ';
      END

   wsql = wsql || ' left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = vw_col_ref_atual.BDCODEMP) ';
   wsql = wsql || ' left outer join TEMPRESAS_IMG img on (tferias.bdcodemp = img.bdcodemp) '; -- 14363 - Marcelo B. M. - 25/11/2016: retornar campo bdlogoemp
   wsql = wsql || ' left outer join VRH_EMP_TCOL_VINC lvinc on (tferias.bdcodemp = lvinc.bdcodemp and tferias.bdcodcol = lvinc.bdcodcol and lvinc.bdrefcol = '||prreferencia||') '; -- 17564 | Marcelo B. M. | 02/06/2017
   wsql = wsql || ' left outer join VRH_EMP_TCOLCON_VINC nvinc on (tferias.bdcodemp = nvinc.bdcodemp and tferias.bdcodcol = nvinc.bdcodcol and nvinc.bdrefcol = '||prreferencia||') '; -- 17564 | Marcelo B. M. | 02/06/2017
   wsql = wsql || ' left outer join VRH_EMP_TCOLCON_DOC colcondoc on (tferias.bdcodemp = colcondoc.bdcodemp and tferias.bdcodcol = colcondoc.bdcodcol) ';
   wsql = wsql || 'left outer join VRHF_EMP_TCOLCON_FGTSGPS CATEGORIA on (TFERIAS.BDCODEMP = CATEGORIA.BDCODEMP and TFERIAS.BDCODCOL = CATEGORIA.BDCODCOL and CATEGORIA.BDREFCOL = (select max(X.BDREFCOL) '||
                                                                                                                                                                                  ' from VRHF_EMP_TCOLCON_FGTSGPS X '||
                                                                                                                                                                                  ' WHERE '||
                                                                                                                                                                                  ' X.BDCODEMP = TFERIAS.BDCODEMP and '||
                                                                                                                                                                                  ' X.BDCODCOL = TFERIAS.BDCODCOL)) ';


   wwhere = '';


   IF (PRCOLETIVAS = 1) THEN
     BEGIN
       prcodigoferias = 0;
       IF (wwhere <> '') THEN
         wwhere = wwhere||' and ';
       wwhere = wwhere||'col.bdinifer = '''||prdatagozoini||''''||' ';
     END

   IF (prtipocodver IS NOT NULL) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         wwhere = wwhere||'tverbasref.bdtipocodver = '||prtipocodver||' ';
      END

   IF (prfuncao > 0) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';

        wwhere = wwhere||'tfuc.bdCODTFUC = '||prfuncao||' ';
      END

   IF (prSindicato > 0) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';

        wwhere = wwhere||'lvinc.bdCODSINTRAB = '||prsindicato||' '; -- 17564 | Marcelo B. M. | 02/06/2017
      END

   IF (prclasse > 0) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';

        wwhere = wwhere||'nvinc.bdCODCLA = '||prClasse||' '; -- 17564 | Marcelo B. M. | 02/06/2017
      END
   if (wwhere <> '') then
     wwhere = wwhere ||' AND (CATEGORIA.BDCATEGORIACOL <> 4 OR CATEGORIA.BDCATEGORIACOL IS NULL) AND (CATEGORIA.BDCATEGORIAESOCIAL <> 111 OR CATEGORIA.BDCATEGORIAESOCIAL IS NULL)';
   else
     wwhere = ' (CATEGORIA.BDCATEGORIACOL <> 4 OR CATEGORIA.BDCATEGORIACOL IS NULL) AND (CATEGORIA.BDCATEGORIAESOCIAL <> 111 OR CATEGORIA.BDCATEGORIAESOCIAL IS NULL)';


   worderby = '';
   IF (prordemimp IS NOT NULL) THEN
      BEGIN
        worderby = 'order by ';
        IF (prordemimp = 0) THEN
           BEGIN
             worderby = wOrderBy||'vw_col_ref_atual.bdcodemp, vw_col_ref_atual.bdcodcol, ferias.bdiniperaquisfe, ferias.bdcodfe, ferias.bdcodver ';
           END
        ELSE
           IF (prordemimp = 1) THEN
              BEGIN
                worderby = wOrderBy||'vw_col_ref_atual.bdcodemp, colcad.bdnomcol, ferias.bdiniperaquisfe, ferias.bdcodfe, ferias.bdcodver ';
              END
      END


   IF (wwhere <> '') THEN
      wwhere = ' where '||wwhere;

   worderby = ' order by vw_col_ref_atual.BDCODEMP, vw_col_ref_atual.BDCODCOL, tferias.BDCODVER ';

   wsql = wsql||wwhere||worderby;
   wchave = 1;
   wempatu = 0;
   wcolatu = 0;

   wsqldadosemp = 'select first 1 e2.BDNOMEMP, e2.BDLOGREMP, e2.BDENDEMP, e2.BDNUMEMP, e2.BDCOMPLEMP, e2.BDBAIEMP, c.BDNOMCID, u.BDSIGLAUF, e1.BDCNPJEMP from tempresas e1 ' ||
              'join tempresas_ref e2 on (e2.BDCODEMP = e1.BDCODEMP) '||
              'left outer join tcidade c on (c.BDCODCID = e2.BDCODCID) '||
              'left outer join tuf u on (c.BDCODUF = u.BDCODUF) ';

   wcodempatu = NULL;
   wcodcolatu = NULL;
   winiperaquisatu = NULL;
   wcodfeatu = NULL;
   wcver = 0;

   IF (prtipocodver IS NOT NULL) THEN
      BEGIN
         FOR EXECUTE STATEMENT wsql
            INTO
              :bdsalini,
              :bdcodemp,
              :bdnomemp,
              :bdlogremp,
              :bdendemp,
              :bdnumemp,
              :bdcomplemp,
              :bdbaiemp,
              :bdnomcidemp,
              :bdsiglaufemp,
              :bdcnpjemp,
              :bdcodcol,
              :bdnomcol,
              :bdctpscol,
              :bdseriectpscol,
              :bddseriectpscol,
              :bdsiglaufctps,
              :bddataadmcol,
              :bddesctfuc,
              :bdiniperaquisfe,
              :bdfimperaquisfe,
              :bdcodfe,
              :bdinipergozofe,
              :bdfimpergozofe,
              :bdfaltasfe,
              :bdsalbasefe,
              :bdsalbasehefe,
              :bddatapagfe,
              :bdqtdabonofe,
              :bdvalliquido,
              :bdcalca13fe,  
              :bddepir,
              :bdcoletivas,
              :bdcodver,
              :bdclassver,
              :bddescver,
              :bddescredver,
              :bdtipocodver,
              :bdordemver, 
              :bdrefvfe,
              :bdvalvfe,
              :bdrefauxver,
              :bdtiporefver,
              :BDREFPAGABOFE,
              :bddiaslicfe,
              :bddiasferfe,
              :bddataaviso,
              :bdlogoemp,  -- 14363 - Marcelo B. M. - 25/11/2016: retornar campo bdlogoemp
              :bdrefhoremp,
              :bdcpfcol DO
            BEGIN
              wbdcodemp = BDCODEMP;
              wbdcodcol = BDCODCOL;
              wbdiniperaquisfe = BDINIPERAQUISFE;
              wbdcodfe = BDCODFE;
              wbdcodver = BDCODVER;
              wbdordemver = BDORDEMVER;

              IF (wcodempatu IS NULL) THEN
                wcodempatu = BDCODEMP;
              IF (wcodcolatu IS NULL) THEN
                wcodcolatu = BDCODCOL;
              IF (winiperaquisatu IS NULL) THEN
                winiperaquisatu = BDINIPERAQUISFE;
              IF (wcodfeatu IS NULL) THEN
                wcodfeatu = BDCODFE;

              bddatarelabono = bdfimperaquisfe - 15;

              while (EXTRACT(WEEKDAY FROM :bddatarelabono) in (0,6)) do   /* Domingo e s?bado */
                bddatarelabono = bddatarelabono - 1;

              wwheredadosemp = 'select first 1 BDCODFERI '||
                               'from TFERIADOSNOVO '||
                               'where ((coalesce(BDTIPOFERI, 0) = 0 and coalesce(BDMESDIAFERI, 0) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                  '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';

              wempferi = null;
              execute statement wwheredadosemp into :wempferi;
              while (coalesce(wempferi, 0) <> 0) do
                begin
                  bddatarelabono = bddatarelabono - 1;
                  wwheredadosemp = 'select first 1 BDCODFERI '||
                                   'from TFERIADOSNOVO '||
                                   'where ((coalesce(BDTIPOFERI, 0) = 0 and coalesce(BDMESDIAFERI, 0) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                     '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';
    
                  wempferi = null;
                  execute statement wwheredadosemp into :wempferi;
                end

              IF (bdinipergozofe IS NULL) THEN
                 BEGIN
                   wmes = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS INTEGER);
                   wano = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                   wrefdadosemp = CAST((CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS VARCHAR(4)) || CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS VARCHAR(2))) AS INTEGER); /*10208 - Ramon*/

                   SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wdia;
                   wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                   bdinisws = CAST(wdataaux AS DATE);
                   wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/'||wdia||'/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                   bdfimsws = CAST(wdataaux AS DATE);
                 END
              ELSE
                 BEGIN
                   wrefdadosemp = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER); /*10208 - Ramon*/
                   bdinisws = bdinipergozofe;
                   bdfimsws = bdfimpergozofe;
                 END

              IF (wempatu = 0) THEN
                 wempatu = bdcodemp;

              IF (wcolatu = 0) THEN
                 wcolatu = bdcodcol;

              IF ((wempatu <> bdcodemp) OR (wcolatu <> bdcodcol)) THEN
                 BEGIN
                   wchave = 1;
                   wempatu = bdcodemp;
                   wcolatu = bdcodcol;
                 END

              bdchave = wchave;
              wchave = wchave + 1;

              wwheredadosemp = ' where e1.BDCODEMP = '||bdcodemp||' and e2.BDREFEMP = (select first 1 bdrefemp from tempresas_ref where bdcodemp = '||bdcodemp||' and bdrefemp <= '||wrefdadosemp||' order by bdrefemp desc)';
              --10208 - Ramon - Trazer os dados da empresa conforme a data inicial de gozo do colaborador, ou sua refer?ncia de pagamento de abono
              IF (wrefdadosemp > 0) THEN
                BEGIN
                  EXECUTE STATEMENT wsqldadosemp || wwheredadosemp
                  INTO
                    :bdnomemp,
                    :bdlogremp,
                    :bdendemp,
                    :bdnumemp,
                    :bdcomplemp,
                    :bdbaiemp,
                    :bdnomcidemp,
                    :bdsiglaufemp,
                    :bdcnpjemp;
                END

              IF (prnovorecibo = 1) THEN
                BEGIN
                  IF ((BDCODEMP <> wcodempatu) OR (BDCODCOL <> wcodcolatu) OR (BDINIPERAQUISFE <> winiperaquisatu) OR (BDCODFE <> wcodfeatu)) THEN
                    BEGIN
                      wcver2 = 0;
                      IF (prtipocodver = 0) THEN
                        BEGIN
                          SELECT COUNT(*)
                          FROM VRHF_EMP_TVERBAFE X
                          JOIN VW_TVERBAS_REF Y ON (Y.BDCODVER = X.BDCODVER)
                          WHERE X.BDCODEMP = :wcodempatu AND X.BDCODCOL = :wcodcolatu AND X.BDINIPERAQUISFE = :winiperaquisatu AND X.BDCODFE = :wcodfeatu AND Y.BDTIPOCODVER IN (1,3)
                          INTO :wcver2;
                        END
                      ELSE
                        BEGIN
                          SELECT COUNT(*)
                          FROM VRHF_EMP_TVERBAFE X
                          JOIN VW_TVERBAS_REF Y ON (Y.BDCODVER = X.BDCODVER)
                          WHERE X.BDCODEMP = :wcodempatu AND X.BDCODCOL = :wcodcolatu AND X.BDINIPERAQUISFE = :winiperaquisatu AND X.BDCODFE = :wcodfeatu AND Y.BDTIPOCODVER NOT IN (1,3)
                          INTO :wcver2;
                        END
    
                      WHILE (wcver < wcver2) DO
                        BEGIN
                          BDCODEMP = wcodempatu;
                          BDCODCOL = wcodcolatu;
                          BDINIPERAQUISFE = winiperaquisatu;
                          BDCODFE = wcodfeatu;
                          BDCODVER = 0;
                          BDORDEMVER = 9999999;
                          SUSPEND;
                          wcver = wcver + 1;
                        END
    
                      BDCODEMP = wbdcodemp;
                      BDCODCOL = wbdcodcol;
                      BDINIPERAQUISFE = wbdiniperaquisfe;
                      BDCODFE = wbdcodfe;
                      BDCODVER = wbdcodver;
                      BDORDEMVER = wbdordemver;
                      wcver = 0;
                      wcodempatu = BDCODEMP;
                      wcodcolatu = BDCODCOL;
                      winiperaquisatu = BDINIPERAQUISFE;
                      wcodfeatu = BDCODFE;
                    END

                  wcver = wcver + 1;
                END
              SUSPEND;
            END

         IF (prnovorecibo = 1) THEN
           BEGIN
             IF ((wcodempatu <> 0) AND (wcodcolatu <> 0) AND (winiperaquisatu IS NOT NULL) AND (wcodfeatu <> 0)) THEN
               BEGIN
                 wcver2 = 0;
                 IF (prtipocodver = 0) THEN
                   BEGIN
                     SELECT COUNT(*)
                     FROM VRHF_EMP_TVERBAFE X
                     JOIN VW_TVERBAS_REF Y ON (Y.BDCODVER = X.BDCODVER)
                     WHERE X.BDCODEMP = :wcodempatu AND X.BDCODCOL = :wcodcolatu AND X.BDINIPERAQUISFE = :winiperaquisatu AND X.BDCODFE = :wcodfeatu AND Y.BDTIPOCODVER IN (1,3)
                     INTO :wcver2;
                   END
                 ELSE
                   BEGIN
                     SELECT COUNT(*)
                     FROM VRHF_EMP_TVERBAFE X
                     JOIN VW_TVERBAS_REF Y ON (Y.BDCODVER = X.BDCODVER)
                     WHERE X.BDCODEMP = :wcodempatu AND X.BDCODCOL = :wcodcolatu AND X.BDINIPERAQUISFE = :winiperaquisatu AND X.BDCODFE = :wcodfeatu AND Y.BDTIPOCODVER NOT IN (1,3)
                     INTO :wcver2;
                   END

                 WHILE (wcver < wcver2) DO
                   BEGIN
                     BDCODEMP = wcodempatu;
                     BDCODCOL = wcodcolatu;
                     BDINIPERAQUISFE = winiperaquisatu;
                     BDCODFE = wcodfeatu;
                     BDCODVER = 0;
                     BDORDEMVER = 9999999;
                     SUSPEND;
                     wcver = wcver + 1;
                   END
               END
           END



        /* Inclui registros de aviso */
        IF (praviso = 1) THEN
           BEGIN
             FOR EXECUTE STATEMENT wSqlAviso INTO
               :bdcodemp, :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp,
               :bdcnpjemp, :bdcodcol, :bdnomcol, :bdchave, :bdctpscol, :bdseriectpscol, :bddseriectpscol,
               :bdsiglaufctps, :bddesctfuc, :bddataadmcol,  :bdiniperaquisfe, :bdfimperaquisfe, :bdcodfe,
               :bdinipergozofe, :bdfimpergozofe, :bdfaltasfe, :bdsalbasefe, :bdsalbasehefe,
               :bdqtdabonofe, :bddatapagfe, :bdcodver, :bdclassver, :bdtipocodver, :bdordemver, :bddescver, :bddescredver, :bdrefvfe,
               :bdvalvfe, :bdrefauxver, :bdtiporefver, :bdrefpagabofe, :bdinisws, :bdfimsws, :bdvalliquido, :bdcalca13fe, :bdcoletivas, :bdsalini, :bddiaslicfe, :bddiasferfe, 
               :bddataaviso
              DO
               BEGIN
                 IF (bdinipergozofe IS NULL) THEN
                    BEGIN
                      wmes = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS INTEGER);
                      wano = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                      wrefdadosemp = CAST((CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS VARCHAR(4)) || CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS VARCHAR(2))) AS INTEGER); /*10208 - Ramon*/
   
                      SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wdia;
                      wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                      bdinisws = CAST(wdataaux AS DATE);
                      wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/'||wdia||'/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                      bdfimsws = CAST(wdataaux AS DATE);
                    END
                 ELSE
                    BEGIN
                      wrefdadosemp = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER); /*10208 - Ramon*/
                      bdinisws = bdinipergozofe;
                      bdfimsws = bdfimpergozofe;
                    END

                 wwheredadosemp = ' where e1.BDCODEMP = '||bdcodemp||' and e2.BDREFEMP = (select first 1 bdrefemp from tempresas_ref where bdcodemp = '||bdcodemp||' and bdrefemp <= '||wrefdadosemp||' order by bdrefemp desc)';
                 --10208 - Ramon - Trazer os dados da empresa conforme a data inicial de gozo do colaborador, ou sua refer?ncia de pagamento de abono
                 IF (wrefdadosemp > 0) THEN
                   BEGIN
                     EXECUTE STATEMENT wsqldadosemp || wwheredadosemp
                     INTO
                       :bdnomemp,
                       :bdlogremp,
                       :bdendemp,
                       :bdnumemp,
                       :bdcomplemp,
                       :bdbaiemp,
                       :bdnomcidemp,
                       :bdsiglaufemp,
                       :bdcnpjemp;
                   END
                 SUSPEND;
               END

           END
      END
   ELSE
      BEGIN
         FOR EXECUTE STATEMENT wsql
            INTO
              :bdsalini,
              :bdcodemp,
              :bdnomemp,
              :bdlogremp,
              :bdendemp,
              :bdnumemp,
              :bdcomplemp,
              :bdbaiemp,
              :bdnomcidemp,
              :bdsiglaufemp,
              :bdcnpjemp,
              :bdcodcol,
              :bdnomcol,
              :bdctpscol,
              :bdseriectpscol,
              :bddseriectpscol,
              :bdsiglaufctps,
              :bddataadmcol,
              :bddesctfuc,
              :bdiniperaquisfe,
              :bdfimperaquisfe,
              :bdcodfe,
              :bdinipergozofe,
              :bdfimpergozofe,
              :bdfaltasfe,
              :bdsalbasefe,
              :bdsalbasehefe,
              :bddatapagfe,
              :bdqtdabonofe,
              :bdvalliquido,
              :bdcalca13fe, 
              :bddepir,
              :bdcoletivas,
              :BDREFPAGABOFE,
              :bddiaslicfe, 
              :bddiasferfe,
              :bddataaviso,
              :bdlogoemp,
              :bdrefhoremp,
              :bdcpfcol DO -- 14363 - Marcelo B. M. - 25/11/2016: retornar campo bdlogoemp
            BEGIN
              bddatarelabono = bdfimperaquisfe - 15;

              while (EXTRACT(WEEKDAY FROM :bddatarelabono) in (0,6)) do   /* Domingo e s?bado */
                bddatarelabono = bddatarelabono - 1;

              wwheredadosemp = 'select first 1 BDCODFERI '||
                               'from TFERIADOSNOVO '||
                               'where  ((coalesce(BDTIPOFERI, 0) = 0 and coalesce(BDMESDIAFERI, 0) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                  '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';

              wempferi = null;
              execute statement wwheredadosemp into :wempferi;
              while (coalesce(wempferi, 0) <> 0) do
                begin
                  bddatarelabono = bddatarelabono - 1;
                  wwheredadosemp = 'select first 1 BDCODFERI '||
                                   'from TFERIADOSNOVO '||
                                   'where ((coalesce(BDTIPOFERI, 0) = 0 and coalesce(BDMESDIAFERI, 0) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                      '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';
    
                  wempferi = null;
                  execute statement wwheredadosemp into :wempferi;
                end

              IF (bdinipergozofe IS NULL) THEN
                 BEGIN
                   wmes = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS INTEGER);
                   wano = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                   wrefdadosemp = CAST((CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS VARCHAR(4)) || CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS VARCHAR(2))) AS INTEGER); /*10208 - Ramon*/

                   SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wdia;
                   wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                   bdinisws = CAST(wdataaux AS DATE);
                   wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/'||wdia||'/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                   bdfimsws = CAST(wdataaux AS DATE);
                 END
              ELSE
                 BEGIN
                   wrefdadosemp = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER); /*10208 - Ramon*/
                   bdinisws = bdinipergozofe;
                   bdfimsws = bdfimpergozofe;
                 END

              IF (wempatu = 0) THEN
                 wempatu = bdcodemp;

              IF (wcolatu = 0) THEN
                 wcolatu = bdcodcol;

              IF ((wempatu <> bdcodemp) OR (wcolatu <> bdcodcol)) THEN
                 BEGIN
                   wchave = 1;
                   wempatu = bdcodemp;
                   wcolatu = bdcodcol;
                 END

              bdchave = wchave;
              wchave = wchave + 1;

              wwheredadosemp = ' where e1.BDCODEMP = '||bdcodemp||' and e2.BDREFEMP = (select first 1 bdrefemp from tempresas_ref where bdcodemp = '||bdcodemp||' and bdrefemp <= '||wrefdadosemp||' order by bdrefemp desc)';
              --10208 - Ramon - Trazer os dados da empresa conforme a data inicial de gozo do colaborador, ou sua refer?ncia de pagamento de abono
              IF (wrefdadosemp > 0) THEN
                BEGIN
                  EXECUTE STATEMENT wsqldadosemp || wwheredadosemp
                  INTO
                    :bdnomemp,
                    :bdlogremp,
                    :bdendemp,
                    :bdnumemp,
                    :bdcomplemp,
                    :bdbaiemp,
                    :bdnomcidemp,
                    :bdsiglaufemp,
                    :bdcnpjemp;
                END

              SUSPEND;
            END


        IF (praviso = 1) THEN
           BEGIN
             FOR EXECUTE STATEMENT wSqlAviso INTO
               :bdcodemp, :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp,
               :bdcnpjemp, :bdcodcol, :bdnomcol, :bdchave, :bdctpscol, :bdseriectpscol, :bddseriectpscol,
               :bdsiglaufctps, :bddesctfuc, :bddataadmcol,  :bdiniperaquisfe, :bdfimperaquisfe, :bdcodfe,
               :bdinipergozofe, :bdfimpergozofe, :bdfaltasfe, :bdsalbasefe, :bdsalbasehefe,
               :bdqtdabonofe, :bddatapagfe, :bdcodver, :bdclassver, :bdtipocodver, :bdordemver, :bddescver, :bddescredver, :bdrefvfe,
               :bdvalvfe, :bdrefauxver, :bdtiporefver, :bdrefpagabofe, :bdinisws, :bdfimsws, :bdvalliquido, :bdcalca13fe, :bdcoletivas, :bdsalini, :bddiaslicfe, :bddiasferfe,
               :bddataaviso
              DO
               BEGIN
                 IF (bdinipergozofe IS NULL) THEN
                    BEGIN
                      wmes = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS INTEGER);
                      wano = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                      wrefdadosemp = CAST((CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS VARCHAR(4)) || CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS VARCHAR(2))) AS INTEGER); /*10208 - Ramon*/
   
                      SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wdia;
                      wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                      bdinisws = CAST(wdataaux AS DATE);
                      wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/'||wdia||'/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                      bdfimsws = CAST(wdataaux AS DATE);
                    END
                 ELSE
                    BEGIN
                      wrefdadosemp = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER); /*10208 - Ramon*/
                      bdinisws = bdinipergozofe;
                      bdfimsws = bdfimpergozofe;
                    END

                   wwheredadosemp = ' where e1.BDCODEMP = '||bdcodemp||' and e2.BDREFEMP = (select first 1 bdrefemp from tempresas_ref where bdcodemp = '||bdcodemp||' and bdrefemp <= '||wrefdadosemp||' order by bdrefemp desc)';
                   --10208 - Ramon - Trazer os dados da empresa conforme a data inicial de gozo do colaborador, ou sua refer?ncia de pagamento de abono
                   IF (wrefdadosemp > 0) THEN
                     BEGIN
                       EXECUTE STATEMENT wsqldadosemp || wwheredadosemp
                       INTO
                         :bdnomemp,
                         :bdlogremp,
                         :bdendemp,
                         :bdnumemp,
                         :bdcomplemp,
                         :bdbaiemp,
                         :bdnomcidemp,
                         :bdsiglaufemp,
                         :bdcnpjemp;
                     END

                 SUSPEND;
               END

           END
      END
END
^

/* Alter (VRHF_SP_REL_DECLARA_RENDIMENTOS) */
ALTER PROCEDURE VRHF_SP_REL_DECLARA_RENDIMENTOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDTOTALRENDIMENTOS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDVAL13 NUMERIC(15,6),
BDVALPENALI NUMERIC(15,6),
BDVALIND NUMERIC(15,6),
BDVALDIR NUMERIC(15,6),
BDVALDME NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WANOMES INTEGER;
BEGIN
  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(wanomes, NULL, NULL);


  wsql = '  SELECT T.BDCODEMP, empresas.bdnomemp, empresas.bdcnpjemp, T.BDCODCOL, col.bdnomcol, col.bdcpfcol,
           sum(coalesce(T.bdbirrffn, 0.00) +  coalesce(T.BDINSSFN, 0.00) + coalesce(T.bdirrffn, 0.00) + coalesce(T.bddepfn, 0.00) +
               coalesce(FOLC.bdbirrffc, 0.00) +  coalesce(FOLC.bdinssfc, 0.00) + coalesce(FOLC.bdirrffc, 0.00) + coalesce(FOLC.bddepfc , 0.00) +
           coalesce(FERN.BDBASEIRFE + FERN.BDVALORINSSFE + FERN.BDDEPFE, 0.00)) BDTOTALRENDIMENTOS,

           SUM(coalesce(T.bdinssfn, 0.00) +  coalesce(FOLC.bdinssfc, 0.00)) AS BDINSS,
           SUM(coalesce(T.bdirrffn, 0.00) +  coalesce(FOLC.bdirrffc, 0.00)) AS BDIRRF,
           SUM(coalesce(T13.bdval13, 0.00) + coalesce(TC13.bdvalc13,  0.00)) AS BDVAL13,
           SUM(coalesce(TPEN.BDVALPEN, 0.00)) AS BDVALPEN_ALI,
           SUM(coalesce(INDR.BDVALIND, 0.00)) AS BDVAL_IND,
           SUM(coalesce(AJCUSTOS.BDVALDIR, 0.00)) AS BDVAL_DIR,
           SUM(coalesce(DESPM.BDVALDME, 0.00)) AS BDVAL_DMED '||

         ' from VRHF_EMP_TFOLHANORMAL T ' ||
         ' left outer join VRHF_EMP_TFOLHACOMP FOLC on (FOLC.BDCODEMP = T.BDCODEMP and FOLC.BDCODCOL = T.BDCODCOL and FOLC.BDREFFN = T.BDREFFN ) ' ||
         ' left outer join VRH_EMP_TFERIAS FERN on (FERN.BDCODEMP = T.BDCODEMP and FERN.BDCODCOL = T.BDCODCOL and t.bdreffn = CAST((substring((CAST(FERN.bddatapagfe AS VARCHAR(10))) from 1 for 4) || substring((CAST(FERN.bddatapagfe AS VARCHAR(10))) from 6 for 2)) AS INTEGER) )
           left outer join vrhf_emp_t13sal T13 on (T13.BDCODEMP = T.BDCODEMP and T13.BDCODCOL = T.BDCODCOL and T13.bdref13 = T.BDREFFN )
           left outer join vrhf_emp_tc13sal TC13 on (TC13.BDCODEMP = T.BDCODEMP and TC13.BDCODCOL = T.BDCODCOL and TC13.bdrefc13 = T.BDREFFN )
           left outer join VW_VALOR_MES_PENSAO_ALIMENTICIA TPEN on (TPEN.BDCODEMP = T.BDCODEMP and TPEN.BDCODCOL = T.BDCODCOL and TPEN.BDREFPEN = T.BDREFFN)
           left outer join VW_VALOR_MES_INDENIZACAO INDR on (INDR.BDCODEMP = T.BDCODEMP and INDR.BDCODCOL = T.BDCODCOL and INDR.BDREFIND = T.BDREFFN)
           left outer join VW_VALOR_MES_DIARIAS_ACUSTOS AJCUSTOS on (AJCUSTOS.BDCODEMP = T.BDCODEMP and AJCUSTOS.BDCODCOL = T.BDCODCOL and AJCUSTOS.BDREFDIR = T.BDREFFN)
           left outer join VW_VALOR_MES_DESPESAS_MEDICAS DESPM on (DESPM.BDCODEMP = T.BDCODEMP and DESPM.BDCODCOL = T.BDCODCOL and DESPM.BDREFDME = T.BDREFFN)
           left outer join vrh_sp_colcon(null,null,null,null,null, ' || prreffim || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) col  on (T.BDCODEMP = col.BDCODEMP and T.BDCODCOL = col.BDCODCOL)
           left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp )' ;

   wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and T.BDREFFN >= '''||:prrefini||''' ';
       ELSE
          wwhere = wwhere||' where T.BDREFFN >= '''||:prrefini||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and T.BDREFFN <= '''||:prreffim||''' ';
       ELSE
          wwhere = wwhere||' where T.BDREFFN <= '''||:prreffim||''' ';
    END

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = ' where ';

       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'col.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'col.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'col.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END



 wsql = wsql||wwhere || ' GROUP BY T.BDCODEMP, empresas.bdnomemp, empresas.bdcnpjemp, T.BDCODCOL, col.bdnomcol, col.bdcpfcol ORDER BY T.BDCODEMP, T.BDCODCOL ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :BDTOTALRENDIMENTOS,
    :bdinss,
    :bdirrf,
    :bdval13,
    :BDVALPENALI,
    :BDVALIND,
    :BDVALDIR,
    :BDVALDME
  DO
  IF (bdtotalrendimentos > 0) THEN
     SUSPEND;
END
^

/* Alter (VRHF_SP_REL_LIQUIDO_FOLHA) */
ALTER PROCEDURE VRHF_SP_REL_LIQUIDO_FOLHA(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRULTDIAMES DATE,
PRTABELA VARCHAR(300),
PRDATANULL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDCODAGBAN VARCHAR(5),
BDCODAGBANDV VARCHAR(2),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDDATAADMCOL DATE,
BDDESCTFUC VARCHAR(40),
BDREF INTEGER,
SALBASE NUMERIC(15,6),
PROVE NUMERIC(15,6),
DESCO NUMERIC(15,6),
LIQ NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRANOMES, NULL, PRULTDIAMES);

  wsql = 'select t.bdcodemp, '||
                'emp.bdnomemp, '||
                't.BDCODCOL, '||
                'col.bdnomcol, '||
                'col.bdcpfcol, '||
                'col.bdcodban, '||
                'CadBan.bdnomban, '||
                'col.bdcodag, '||
                'ban.bdcodagban, '||
                'ban.bdcodagbandv, '||
                'col.BDCTADEPCOL, '||
                'col.BDDIGCTADEPCOL, '||
                'col.BDTIPOCTACOL, '||
                'col.bddataadmcol, '||
                'colfunc.BDDESCTFUC, '||
                't.BDREF, '||
                't.BDSALBASE SALBASE , '||
                'SUM(t.BDPROVENTO) PROVE, '||
                'SUM(t.BDDESCONTO) DESCO, '||
                'SUM(t.BDPROVENTO) - SUM(t.BDDESCONTO) LIQ ';

  wsql = wsql||'from '||prtabela||'(';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||''''||prcodemp||''', ';
  ELSE
     wsql = wsql||'null, ';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||''''||prcodcol||''', ';
  ELSE
     wsql = wsql||'null, ';

  wsql = wsql||pranomes;

  IF (prdatanull IS NOT NULL) THEN
     wsql = wsql||', null) T ';
  ELSE
     wsql = wsql||') T ';

  wsql = wsql||'join VW_COLABORADORES_REF_ATUAL col '||
                 'on (T.BDCODEMP = col.BDCODEMP and T.BDCODCOL = col.BDCODCOL) ';
  wsql = wsql||'left outer join VW_VRH_EMP_TCOL_VINCDIA coldia '||
                 'on (T.BDCODEMP = coldia.BDCODEMP and T.BDCODCOL = coldia.BDCODCOL) ';
  wsql = wsql||'left outer join TBANCOS_AG BAN '||
                 'on (col.bdcodban = ban.bdcodban and  col.bdcodag = ban.bdcodag) ';
  wsql = wsql||'left outer join tBancos CadBan '||
                 'on (col.bdcodban = Cadban.bdcodban) ';
  wsql = wsql||'left outer join VW_TEMPRESAS_REF emp '||
                 'on (t.bdcodemp = emp.bdcodemp ) ';
  wsql = wsql||'left outer join VRH_FUNCOES_TFUC colfunc '||
                 'on (coldia.BDCODPLAFUC = colfunc.BDCODPLAFUC and coldia.BDCODTFUC = colfunc.BDCODTFUC) ';

  wsql = wsql||'group by t.BDCODEMP, emp.bdnomemp, T.BDCODCOL, col.bdnomcol, col.bddataadmcol, t.BDSALBASE, col.BDCODCOL, col.bdcodban, CadBan.bdnomban, col.bdcodag, '||
                        'col.BDCTADEPCOL, col.BDDIGCTADEPCOL, col.BDTIPOCTACOL, col.bdcpfcol, colfunc.BDDESCTFUC, t.bdref, ban.bdcodagban, ban.bdcodagbandv ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCPFCOL,
    :BDCODBAN,
    :BDNOMBAN,
    :BDCODAG,
    :BDCODAGBAN,
    :BDCODAGBANDV,
    :BDCTADEPCOL,
    :BDDIGCTADEPCOL,
    :BDTIPOCTACOL,
    :BDDATAADMCOL,
    :BDDESCTFUC,
    :BDREF,
    :SALBASE,
    :PROVE,
    :DESCO,
    :LIQ
  DO
  SUSPEND;
END
^

/* Alter (VRHF_SP_REL_PREVIA_RESC) */
ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDCAMPO29 NUMERIC(15,2),
BDCAMPO30 NUMERIC(15,2),
BDCAMPO30REF INTEGER,
BDCAMPO31 NUMERIC(15,2),
BDCAMPO31REF INTEGER,
BDCAMPO32 NUMERIC(15,2),
BDCAMPO32REF INTEGER,
BDCAMPO33 NUMERIC(15,2),
BDCAMPO33REF INTEGER,
BDCAMPO34 NUMERIC(15,2),
BDCAMPO34REF INTEGER,
BDCAMPO35 NUMERIC(15,2),
BDCAMPO35REF INTEGER,
BDCAMPO36 NUMERIC(15,2),
BDCAMPO36REF INTEGER,
BDCAMPO37 NUMERIC(15,2),
BDCAMPO38 NUMERIC(15,2),
BDCAMPO39 NUMERIC(15,2),
BDCAMPO40 NUMERIC(15,2),
BDCAMPO40REF INTEGER,
BDCAMPO41 NUMERIC(15,2),
BDCAMPO42 NUMERIC(15,2),
BDCAMPO43 NUMERIC(15,2),
BDCAMPO44 NUMERIC(15,2),
BDCAMPO45 NUMERIC(15,2),
BDCAMPO46BRUTO NUMERIC(15,2),
BDCAMPO47 NUMERIC(15,2),
BDCAMPO48 NUMERIC(15,2),
BDCAMPO49 NUMERIC(15,2),
BDCAMPO50 NUMERIC(15,2),
BDCAMPO51 NUMERIC(15,2),
BDCAMPO52 NUMERIC(15,2),
BDCAMPO53 NUMERIC(15,2),
BDCAMPO54TOTDED NUMERIC(15,2),
BDCAMPO55LIQREC NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WDATAINICIAL VARCHAR(10);
DECLARE VARIABLE WDATAFINAL VARCHAR(10);
DECLARE VARIABLE WTOTALBRUTO NUMERIC(15,2);
DECLARE VARIABLE WTOTALDEDUCOES NUMERIC(15,2);
DECLARE VARIABLE WDATARESC INTEGER;
BEGIN

  wmes = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);
  wdatainicial = wmes||'/'||'01'||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;
  wdatafinal = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  wsql =   ' SELECT RESC.bdcodemp, EMPR.bdnomemp , emp.bdcnpjemp, RESC.bdcodcol, colcad.bdnomcol,  colcon_doc.bdcpfcol,
            empr.bdlogremp, empr.bdendemp , empr.bdnumemp, empr.bdbaiemp, cidemp.bdnomcid, ufemp.bdsiglauf, empr.bdcepemp, empr.bdcodcnae,
            docref.bdpiscol, colcad.bdlogrcol, colcad.bdendcol, colcad.bdnumcol, colcad.bdbaicol, colcad.bdcepcol,
            spcidadecol.bdnomcid, spufcol.bdsiglauf , docref.bdctpscol, docref.bdseriectpscol,
            colcon.bddatanasccol, col_parent.bdnommaecol, colcon.bddataadmcol, colcon_fgts.bdcategoriacol, RESC.bddataavprevioprev, RESC.bdchaveindentificacaoprev,
            preresc.bddescpres, preresc.bdcodsaque, resc.bddatarescisaoprev, resc.bddatapagrescisaoprev

           from vrh_emp_trescisao_previa RESC
           join tempresas emp on (emp.bdcodemp = RESC.bdcodemp)
           join VW_TEMPRESAS_REF empr on (empr.bdcodemp = RESC.bdcodemp )
           join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = resc.bdcodpres)
           join vrh_emp_tcolcon colcon on (colcon.bdcodemp = resc.bdcodemp and colcon.bdcodcol = resc.bdcodcol)
           left outer join vw_vrh_emp_tcolcon_cad colcad on (colcad.bdcodemp = resc.bdcodemp and colcad.bdcodcol = resc.bdcodcol)
           join vrh_emp_tcolcon_doc colcon_doc on (colcon_doc.bdcodemp = resc.bdcodemp and colcon_doc.bdcodcol = resc.bdcodcol)
           left outer join vrh_emp_tcol_doc col_doc on (col_doc.bdcodemp = resc.bdcodemp and col_doc.bdcodcol = resc.bdcodcol)
           left outer join vrh_emp_tcol_parent col_parent on (col_parent.bdcodemp = resc.bdcodemp and col_parent.bdcodcol = resc.bdcodcol)
           left outer join vw_vrhf_emp_tcolcon_fgtsgps colcon_fgts on (colcon_fgts.bdcodemp = resc.bdcodemp and colcon_fgts.bdcodcol = resc.bdcodcol)
           left outer join tcidade spcidadecol on (spcidadecol.bdcodcid = colcad.bdcodcid)
           left outer join tuf spufcol on (spufcol.bdcoduf = spcidadecol.bdcoduf)
           left outer join tcidade cidemp on (cidemp.bdcodcid = empr.bdcodcid)
           left outer join tuf ufemp on (ufemp.bdcoduf = cidemp.bdcoduf)  
           left outer join vw_colaboradores_ref_atual refatu on (refatu.bdcodemp = RESC.bdcodemp and refatu.bdcodcol = RESC.BDCODCOL)
           left outer join vw_tcolcon_vincdia vincdia on (vincdia.bdcodemp = RESC.bdcodemp and vincdia.bdcodcol = RESC.bdcodcol)
           join vw_vrh_emp_tcolcon_docref docref on (docref.bdcodemp = resc.bdcodemp and docref.bdcodcol = resc.bdcodcol)';          --Sol:16861 Marcelo B. M. 23/01/2017

  wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.bddatarescisaoprev >= '''||:wdatainicial||''' ';
       ELSE
          wwhere = wwhere||' where RESC.bddatarescisaoprev >= '''||:wdatainicial||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.bddatarescisaoprev <= '''||:wdatafinal||''' ';
       ELSE
          wwhere = wwhere||' where RESC.bddatarescisaoprev <= '''||:wdatafinal||''' ';
    END


  IF (prempresa <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'vincdia.bdcodtfuc = '||prfuncao||' ';  -- funcionario Sol:16861 Marcelo B. M. 23/01/2017
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'refatu.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC. Sol:16861 Marcelo B. M. 23/01/2017
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'refatu.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc Sol:16861 Marcelo B. M. 23/01/2017
     END



 wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdbaiemp,
    :bdnomcid,
    :bdsiglaufemp,
    :bdcepemp,
    :bdcodcnae,
    :bdpiscol,
    :bdlogrcol,
    :bdendcol,
    :bdnumcol,
    :bdbaicol,
    :bdcepcol,
    :bdnomcidcol,
    :bdsiglaufcol,
    :bdctpscol,
    :bdseriectpscol,
    :bddatanasccol,
    :bdnommaecol,
    :bddataadmcol,
    :bdcategoriacol,
    :bddataavprevio,
    :bdchaveindentificacao,
    :bddescpres,
    :bdcodsaque, 
    :bddatarescisao,
    :bddatapagrescisao
    DO

    BEGIN

      wdataresc = CAST((SUBSTRING((CAST(:bddatarescisao AS VARCHAR(10))) FROM 1 FOR 4) || SUBSTRING((CAST(:bddatarescisao AS VARCHAR(10))) FROM 6 FOR 2)) AS INTEGER);

      wTotalBruto = 0;
      wTotalDeducoes = 0;

      bdcampo29 = 0;    bdcampo30 = 0;      bdcampo30ref = 0;  bdcampo31 = 0;     bdcampo31ref = 0;
      bdcampo32 = 0;    bdcampo32ref = 0;   bdcampo33 = 0;     bdcampo33ref = 0;  bdcampo34 = 0;
      bdcampo34ref = 0; bdcampo35 = 0;      bdcampo35ref = 0;  bdcampo36 = 0;     bdcampo36ref = 0;  bdcampo37 = 0;
      bdcampo38 = 0;    bdcampo39 = 0;      bdcampo40 = 0;     bdcampo41 = 0;     bdcampo42 = 0;     bdcampo43 = 0;
      bdcampo44 = 0;    bdcampo45 = 0;      bdcampo46bruto = 0;bdcampo47 = 0;     bdcampo48 = 0;     bdcampo49 = 0;
      bdcampo50 = 0;    bdcampo51 = 0;      bdcampo52 = 0;     bdcampo53 = 0;     bdcampo54totded = 0;

      -- CAMPO 29
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.001.2.1%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)

         INTO
         :bdcampo29;

      IF (:bdcampo29 IS NULL) THEN
         bdcampo29 = 0;

      wTotalBruto = wTotalBruto + bdcampo29;

      -- campo 30
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.001.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo30,
      :bdcampo30ref;

      IF (:bdcampo30 IS NULL) THEN
        BEGIN
          bdcampo30 = 0;
          bdcampo30ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo30;

      -- campo 31

      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.050.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo31,
      :bdcampo31ref;

      IF (:bdcampo31 IS NULL) THEN
        BEGIN
          bdcampo31 = 0;
          bdcampo31ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo31;

      -- campo 32
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.060.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo32,
      :bdcampo32ref;

      IF (:bdcampo32 IS NULL) THEN
        BEGIN
          bdcampo32 = 0;
          bdcampo32ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo32;

      -- campo 33
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.030.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo33,
      :bdcampo33ref;

      IF (:bdcampo33 IS NULL) THEN
        BEGIN
          bdcampo33 = 0;
          bdcampo33ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo33;

      -- campo 34
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.010.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo34,
      :bdcampo34ref;

      IF (:bdcampo34 IS NULL) THEN
        BEGIN
         bdcampo34 = 0;
         bdcampo34ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo34;

      -- campo 35
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.012.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo35,
      :bdcampo35ref;

      IF (:bdcampo35 IS NULL) THEN
        BEGIN
         bdcampo35 = 0;
         bdcampo35ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo35;

      -- campo 36
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.050.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo36,
      :bdcampo36ref;

      IF (:bdcampo36 IS NULL) THEN
        BEGIN
         bdcampo36 = 0;
         bdcampo36ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo36;

     -- CAMPO 37
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.002.0.2%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo37;

      IF (:bdcampo37 IS NULL) THEN
         bdcampo37 = 0;                             

      wTotalBruto = wTotalBruto + bdcampo37;

      -- CAMPO 38
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.001.3.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo38;

      IF (:bdcampo38 IS NULL) THEN
         bdcampo38 = 0;

      wTotalBruto = wTotalBruto + bdcampo38;

      -- campo 39
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.003.0.0%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO
      :bdcampo39;

      IF (:bdcampo39 IS NULL) THEN
         bdcampo39 = 0;

      wTotalBruto = wTotalBruto + bdcampo39;

     -- campo 40
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.006%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo40,
      :bdcampo40ref;

      IF (:bdcampo40 IS NULL) THEN
        BEGIN
          bdcampo40 = 0;
          bdcampo40ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo40;

      -- campo 41
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.002.0.0%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO

      :bdcampo41;

      IF (:bdcampo41 IS NULL) THEN
         bdcampo41 = 0;

      wTotalBruto = wTotalBruto + bdcampo41;

      -- campo 42
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.001.1.2%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO

      :bdcampo42;

      IF (:bdcampo42 IS NULL) THEN
         bdcampo42 = 0;

      wTotalBruto = wTotalBruto + bdcampo42;

      -- campo 43
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.032.0.0%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO
      :bdcampo43;

      IF (:bdcampo43 IS NULL) THEN
         bdcampo43 = 0;

      wTotalBruto = wTotalBruto + bdcampo43;

      -- campo 44
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.032.1%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO
      :bdcampo44;

      IF (:bdcampo44 IS NULL) THEN
         bdcampo44 = 0;

      wTotalBruto = wTotalBruto + bdcampo44;

      bdcampo46bruto = wTotalBruto; -- Total bruto Campo 46


   -- campo 47
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.010.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo47;

      IF (:bdcampo47 IS NULL) THEN
         bdcampo47 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo47;

   -- campo 48
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.010.0.7%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo48;

      IF (:bdcampo48 IS NULL) THEN
         bdcampo48 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo48;

   -- campo 49
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.061%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo49;

      IF (:bdcampo49 IS NULL) THEN
         bdcampo49 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo49;

   -- campo 50
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.010.1.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo50;

      IF (:bdcampo50 IS NULL) THEN
         bdcampo50 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo50;

   -- campo 51
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.001.1.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo51;

      IF (:bdcampo51 IS NULL) THEN
         bdcampo51 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo51;


      bdcampo54totded = wtotaldeducoes;
      bdcampo55liqrec = bdcampo46bruto - bdcampo54totded; -- Total liquido campo 55


       SUSPEND;

     END
END
^

/* Alter (VRHF_SP_REL_PREVIA_RESC2) */
ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDORDEMVER INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WDATAINICIAL VARCHAR(10);
DECLARE VARIABLE WDATAFINAL VARCHAR(10);
DECLARE VARIABLE WDATARESC INTEGER;
BEGIN

  wmes = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);
  wdatainicial = wmes||'/'||'01'||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;
  wdatafinal = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  wsql =   'select RESC.bdcodemp, EMPRESAS.bdnomemp , empresas.bdcnpjemp, RESC.bdcodcol, spcolcon.bdnomcol,  spcolcon.bdcpfcol,
            empresas.bdlogremp, empresas.bdendemp , empresas.bdnumemp, empresas.bdbaiemp, empresas.bdnomcid, empresas.bdsiglauf, empresas.bdcepemp, empresas.bdcodcnae,
            spcolcon.bdpiscol, spcolcon.bdlogrcol, spcolcon.bdendcol, spcolcon.bdnumcol, spcolcon.bdbaicol, spcolcon.bdcepcol,
            spcidadecol.bdnomcid, spcidadecol.bdsiglauf , spcolcon.bdctpscol, spcolcon.bdseriectpscol,
            spcolcon.bddatanasccol, spcolcon.bdnommaecol, spcolcon.bddataadmcol, spcolcon.bdcategoriacol, RESC.bddataavprevioprev, RESC.bdchaveindentificacaoprev,
            preresc.bddescpres, preresc.bdcodsaque, resc.bddatarescisaoprev, resc.bddatapagrescisaoprev,
            fn.bdref, fn.bdcodver, fn.bddescver, fn.bddescredver, fn.bdrefv, fn.bdprovento, fn.bddesconto, tverbas.bdordemver

           from vrh_emp_trescisao_previa RESC
           join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = resc.bdcodpres)
           join vrh_sp_colcon(null,null,null,null,null, ' || prreffim || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) spcolcon  on
              (RESC.BDCODEMP = spcolcon.BDCODEMP and RESC.BDCODCOL = spcolcon.BDCODCOL)
           left outer join SP_CONSULTACIDADE(null) spcidadecol on (spcidadecol.bdcodcid = spcolcon.bdcodcid)
           left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = RESC.bdcodemp )
           left outer join vrhf_sp_cons_calc_previa_resc(null,null,'||  'CAST((substring((CAST(resc.bddatarescisaoprev AS VARCHAR(10))) from 1 for 4) || substring((CAST(resc.bddatarescisaoprev AS VARCHAR(10))) from 6 for 2)) AS INTEGER)' ||') FN on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol)
           join vrh_base_tverbas tverbas on (fn.bdcodver = tverbas.bdcodver)' ;

  wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.bddatarescisaoprev >= '''||:wdatainicial||''' ';
       ELSE
          wwhere = wwhere||' where RESC.bddatarescisaoprev >= '''||:wdatainicial||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.bddatarescisaoprev <= '''||:wdatafinal||''' ';
       ELSE
          wwhere = wwhere||' where RESC.bddatarescisaoprev <= '''||:wdatafinal||''' ';
    END


  IF (prempresa <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'spcolcon.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'spcolcon.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'spcolcon.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END

  IF (prtipofiltro = 1) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'fn.bdprovento > 0 ';
     END

  IF (prtipofiltro = 2) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'fn.bddesconto > 0 ';
     END

 wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdbaiemp,
    :bdnomcid,
    :bdsiglaufemp,
    :bdcepemp,
    :bdcodcnae,
    :bdpiscol,
    :bdlogrcol,
    :bdendcol,
    :bdnumcol,
    :bdbaicol,
    :bdcepcol,
    :bdnomcidcol,
    :bdsiglaufcol,
    :bdctpscol,
    :bdseriectpscol,
    :bddatanasccol,
    :bdnommaecol,
    :bddataadmcol,
    :bdcategoriacol,
    :bddataavprevio,
    :bdchaveindentificacao,
    :bddescpres,
    :bdcodsaque, 
    :bddatarescisao,
    :bddatapagrescisao,
    :bdref,
    :bdcodver,
    :bddescver,
    :bddescredver,
    :bdrefv,
    :bdprovento,
    :bddesconto,
    :bdordemver
    DO

   SUSPEND;



END
^

/* Alter (VRHF_SP_REL_RECIBO_RESCISAO) */
ALTER PROCEDURE VRHF_SP_REL_RECIBO_RESCISAO(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFOLHA INTEGER,
PRDATAINI INTEGER,
PRDATAFIM INTEGER)
 RETURNS(BDMAIORREMUNERACAOANT NUMERIC(18,6),
BDCODTIPOCONTRATO INTEGER,
BDDESCTIPOCONTRATO VARCHAR(150),
BDCODSINTRAB INTEGER,
BDCODCEDENTETRAB VARCHAR(20),
BDCNPJSINTRAB VARCHAR(18),
BDDESCSINTRAB VARCHAR(60),
BDPERTRCTRESC NUMERIC(15,6),
BDPERFGTSRESC NUMERIC(15,6),
BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL DM_DIGSERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDVINCEMPCOL INTEGER,
BDSIGLAUFCTPS VARCHAR(2),
BDSIGLAHNET VARCHAR(3),
BDDESCHNET VARCHAR(200),
BDDESCCATEGORIA VARCHAR(300),
BDSALBASE NUMERIC(18,6),
BDDATAOPCAOFGTS DATE,
BDTIPOCOL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WDATAINICIAL VARCHAR(10);
DECLARE VARIABLE WDATAFINAL VARCHAR(10);
BEGIN

  wmes = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
--  wanomes = cast((substring(cast(:prrefini as varchar(6)) from 5 for 2)||substring(cast(:prrefini as varchar(6)) from 1 for 4)) as INTEGER);
  wdatainicial = wmes||'/'||'01'||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
--  wanomes = cast((substring(cast(:prreffim as varchar(6)) from 5 for 2)||substring(cast(:prreffim as varchar(6)) from 1 for 4)) as INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

--  wultdia = wmes||'/'||wdia||'/'||wano;
  wdatafinal = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(:prreffim, NULL, NULL);

  wsql =   ' select RESC.bdcodemp,
                    EMPRESAS.bdnomemp ,
                    emp.bdcnpjemp,
                    RESC.bdcodcol,
                    colcad.bdnomcol,
                    doc.bdcpfcol,
                    empresas.bdlogremp,
                    empresas.bdendemp ,
                    empresas.bdnumemp,
                    empresas.bdbaiemp,
                    cidemp.bdnomcid,
                    ufemp.bdsiglauf,
                    empresas.bdcepemp,
                    empresas.bdcodcnae,
                    docref.bdpiscol,
                    colcad.bdlogrcol,
                    colcad.bdendcol,
                    colcad.bdnumcol,
                    colcad.bdbaicol,
                    colcad.bdcepcol,
                    cidcol.bdnomcid,
                    ufcol.bdsiglauf ,
                    docref.bdctpscol,
                    docref.bdseriectpscol,
                    docref.bddseriectpscol,
                    colcon.bddatanasccol,
                    parcol.bdnommaecol,
                    colcon.bddataadmcol,
                    fgtscol.bdcategoriacol,'||
                    'case when RESC.bddataavprevio is null then RESC.bddataavprevio else RESC.BDDATANOTIF end bdDT, '|| --RESC.bddataavprevio,
                    'RESC.bdchaveindentificacao,
                    preresc.bddescpres,
                    preresc.bdcodsaque,
                    resc.bddatarescisao,
                    resc.bddatapagrescisao,

                    tcon_vinc.bdcodsintrab,
                    sind.bdcalccodbartrab,
                    sind.bdcnpjsintrab,
                    sind.bddescsintrab,

                    resc.bdpertrctresc,
                    resc.bdperfgtsresc,

                    resc.bdcodtipocontrato,
                    tipcon.bddescricao,

                    mrem.bdmaiorremuneracao,
                    case
                      when RESC.BDVINCEMPCOL = 1  then 15
                      when RESC.BDVINCEMPCOL = 2  then 20
                      when RESC.BDVINCEMPCOL = 3  then 25
                      when RESC.BDVINCEMPCOL = 4  then 30
                      when RESC.BDVINCEMPCOL = 5  then 31
                      when RESC.BDVINCEMPCOL = 6  then 35
                      when RESC.BDVINCEMPCOL = 7  then 40
                      when RESC.BDVINCEMPCOL = 8  then 50
                      when RESC.BDVINCEMPCOL = 9  then 55
                      when RESC.BDVINCEMPCOL = 10 then 60
                      when RESC.BDVINCEMPCOL = 11 then 65
                      when RESC.BDVINCEMPCOL = 12 then 70
                      when RESC.BDVINCEMPCOL = 13 then 75
                      when RESC.BDVINCEMPCOL = 14 then 80
                      when RESC.BDVINCEMPCOL = 15 then 90
                      when RESC.BDVINCEMPCOL = 16 then 95
                      when RESC.BDVINCEMPCOL = 17 then 96
                      when RESC.BDVINCEMPCOL = 18 then 97
                      else                             10
                    end BDVINCEMPCOL,
                    ufctps.bdsiglauf,
                    HNET.BDSIGLAHNET,
                    case
                      when PRERESC.BDCODPRES in (75,76) then PRERESC.BDDESCPRES
                      else HNET.BDDESCHNET
                    end BDDESCHNET,
                    CATEG.BDDESCCATEGORIA,
                    fn.BDSALBASE,
                    RESC.bddataopcaofgts,
                    colcalc.bdtipocol

             from (select RESC.* from VWRH_TRESCISAO_ADM_COL RESC';

  wwhere = '';
  IF (prempresa <> '') THEN
     BEGIN
       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere||
         ') RESC ';

/*    if (prtipofolha is not null and prtipofolha = 1) then
       begin
         wsql = wsql||'join VWRH_UNION_FC_FCT_CALC fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol and fn.bdreffn = resc.bdrefrescisao ';

         if (prdataini is not null and prdataini <> 0 and prdatafim is not null and prdatafim <> 0) then
            wsql = wsql||' and fn.bddtcomp >= '||prdataini||' and fn.bddtcomp <= '||prdatafim||') ';
         else
            wsql = wsql||') ';
       end*/
    IF (prtipofolha IS NOT NULL AND prtipofolha = 1) THEN
       BEGIN
         wsql = wsql||'join VWRH_UNION_FC_FCT_MES_BASES fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol ';

         IF (prdataini IS NOT NULL AND prdataini <> 0 AND prdatafim IS NOT NULL AND prdatafim <> 0) THEN
            wsql = wsql||' and fn.BDREFFC >= '||prdataini||' and fn.BDREFFC <= '||prdatafim||') ';
         ELSE
            wsql = wsql||') ';
       END
    ELSE
    IF ((prtipofolha IS NULL) OR (prtipofolha = 0)) THEN
       BEGIN
         wsql = wsql||'join VWRH_UNION_FN_FT_MES_BASES fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol and fn.bdreffn = resc.bdrefrescisao) ';
       END

    wsql = wsql||'left outer join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = resc.bdcodpres)
             join VW_TEMPRESAS_REF empresas on (empresas.bdcodemp = RESC.bdcodemp )
             join tempresas emp on (emp.bdcodemp = resc.bdcodemp)
             join vrh_emp_tcolcon colcon on (colcon.bdcodemp = resc.bdcodemp and colcon.bdcodcol = resc.bdcodcol)
             left outer join vw_vrh_emp_tcolcon_cad colcad on (colcad.bdcodemp = resc.bdcodemp and colcad.bdcodcol = resc.bdcodcol)
             left outer join vw_vrh_emp_tcolcon_docref docref on (docref.bdcodemp = resc.bdcodemp and docref.bdcodcol = resc.bdcodcol)
             left outer join VRH_BASE_THOMOLOGANET HNET on (HNET.bdcodhnet = preresc.bdcodhnet)
             left outer join VWRH_MAIORREMUNERACAO_DEMITIDOS mrem on (resc.bdcodemp = mrem.bdcodemp and resc.bdcodcol = mrem.bdcodcol and ((select (select aaa.bdaaaamm from aaaamm(BDNOVADATA) aaa) from DIMINUI_MESES(resc.bddatarescisao,1))) = mrem.bdreffn)
             left outer join vrh_emp_tcolcon_doc doc on (doc.bdcodemp = resc.bdcodemp and doc.bdcodcol = resc.bdcodcol)
             left outer join VRH_EMP_TCOL_DOC doccol on (doccol.bdcodemp = resc.bdcodemp and doccol.bdcodcol = resc.bdcodcol)
             left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS fgtscol on (fgtscol.bdcodemp = resc.bdcodemp and fgtscol.bdcodcol = resc.bdcodcol)
             left outer join VRH_BASE_TCATEGORIA CATEG on (CATEG.bdcodcategoria = fgtscol.bdcategoriacol)
             left outer join vrh_emp_tcol_parent parcol on (parcol.bdcodemp = resc.bdcodemp and parcol.bdcodcol = resc.bdcodcol) '||
            'left outer join vw_vrhf_emp_tcol_calc colcalc on (colcalc.BDCODEMP = RESC.BDCODEMP and colcalc.BDCODCOL = RESC.BDCODCOL) ' ;
  IF (prclasse > 0) THEN
     wsql = wsql||
             'left outer join VW_vrh_emp_tcolcon_vinc tcolcon_vinc on (tcolcon_vinc.bdcodemp = resc.bdcodemp and tcolcon_vinc.bdcodcol = resc.bdcodcol) ';
             
  wsql = wsql||
             'left outer join VW_VRH_EMP_TCOL_VINC tcon_vinc on (tcon_vinc.bdcodemp = resc.bdcodemp and tcon_vinc.bdcodcol = resc.bdcodcol) ';

  IF (prfuncao > 0) THEN
     wsql = wsql||'left outer join VW_TCOLCON_VINCDIA vincdia on (vincdia.bdcodemp = resc.bdcodemp and vincdia.bdcodcol = resc.bdcodcol) ';

  wsql = wsql||'left outer join vrh_base_tsindtrab sind on (sind.bdcodsintrab = tcon_vinc.bdcodsintrab)
             left outer join vrh_tipo_contrato_exp tipcon on (tipcon.bdcodtipocontrato = resc.bdcodtipocontrato)
             left outer join tcidade cidemp on (empresas.bdcodcid = cidemp.bdcodcid)
             left outer join tcidade cidcol on (cidcol.bdcodcid = colcad.bdcodcid)
             left outer join tuf ufemp on (ufemp.bdcoduf = cidemp.bdcoduf)
             left outer join tuf ufcol on (ufcol.bdcoduf = cidcol.bdcoduf)
             left outer join tuf ufctps on (ufctps.bdcoduf = docref.bdcoduf) ';




  wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.BDDATARESCISAO >= '''||:wdatainicial||''' ';
       ELSE
          wwhere = wwhere||' where RESC.BDDATARESCISAO >= '''||:wdatainicial||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.BDDATARESCISAO <= '''||:wdatafinal||''' ';
       ELSE
          wwhere = wwhere||' where RESC.BDDATARESCISAO <= '''||:wdatafinal||''' ';
    END


  IF (prempresa <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'vincdia.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'tcon_vinc.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'tcolcon_vinc.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END



 wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdbaiemp,
    :bdnomcid,
    :bdsiglaufemp,
    :bdcepemp,
    :bdcodcnae,
    :bdpiscol,
    :bdlogrcol,
    :bdendcol,
    :bdnumcol,
    :bdbaicol,
    :bdcepcol,
    :bdnomcidcol,
    :bdsiglaufcol,
    :bdctpscol,
    :bdseriectpscol,
    :BDDSERIECTPSCOL,
    :bddatanasccol,
    :bdnommaecol,
    :bddataadmcol,
    :bdcategoriacol,
    :bddataavprevio,
    :bdchaveindentificacao,
    :bddescpres,
    :bdcodsaque, 
    :bddatarescisao,
    :bddatapagrescisao,
    :bdcodsintrab,
    :bdcodcedentetrab,
    :bdcnpjsintrab,
    :bddescsintrab,
    :bdpertrctresc,
    :bdperfgtsresc,
    :BDCODTIPOCONTRATO,
    :BDDESCTIPOCONTRATO,
    :bdmaiorremuneracaoant,
    :bdvincempcol,
    :bdsiglaufctps,
    :bdsiglahnet,
    :bddeschnet,
    :bddesccategoria,
    :bdsalbase,
    :bddataopcaofgts,
    :bdtipocol
    DO
    BEGIN
      SUSPEND;
    END

END
^

/* Alter (VRHF_SP_REL_RECIBO_RESCISAO2) */
ALTER PROCEDURE VRHF_SP_REL_RECIBO_RESCISAO2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER,
PRTIPOFOLHA INTEGER,
PRDTPGTO INTEGER,
PRDTPGTOFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL INTEGER,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL DM_DIGSERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDREFRESCISAO INTEGER,
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(18,6),
BDREFAUXV NUMERIC(18,6),
BDHEVER NUMERIC(18,6),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDORDEMVER INTEGER,
BDCLAVER VARCHAR(20),
BDPERCINSALUBCOL NUMERIC(18,6),
BDPERCPERICULCOL NUMERIC(18,6),
BDPERCNOTURNOCOL NUMERIC(18,6),
BDHORASDIARIASCOL NUMERIC(18,6),
BDSIGLAUFCTPS VARCHAR(2),
BDTIPOREFVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDCLAVERAUX VARCHAR(20),
BDDESCVERAUX VARCHAR(70),
BDPROVENTOOUTROS NUMERIC(18,6),
BDDESCONTOOUTROS NUMERIC(18,6),
BDTIPOCOL INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WMES integer;
declare variable WANO integer;
declare variable WDIA integer;
declare variable WDATAINICIAL varchar(10);
declare variable WDATAFINAL varchar(10);
BEGIN

  wmes = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
--  wanomes = cast((substring(cast(:prrefini as varchar(6)) from 5 for 2)||substring(cast(:prrefini as varchar(6)) from 1 for 4)) as INTEGER);
  wdatainicial = wmes||'/'||'01'||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
--  wanomes = cast((substring(cast(:prreffim as varchar(6)) from 5 for 2)||substring(cast(:prreffim as varchar(6)) from 1 for 4)) as INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wdatafinal = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(:prreffim, NULL, NULL);

/*  wsql =   ' select RESC.bdcodemp, EMPRESAS.bdnomemp , empresas.bdcnpjemp, RESC.bdcodcol, spcolcon.bdnomcol,  spcolcon.bdcpfcol,
            empresas.bdlogremp, empresas.bdendemp , empresas.bdnumemp, empresas.bdbaiemp, empresas.bdnomcid, empresas.bdsiglauf, empresas.bdcepemp, empresas.bdcodcnae,
            spcolcon.bdpiscol, spcolcon.bdlogrcol, spcolcon.bdendcol, spcolcon.bdnumcol, spcolcon.bdbaicol, spcolcon.bdcepcol,
            spcidadecol.bdnomcid, spcidadecol.bdsiglauf , spcolcon.bdctpscol, spcolcon.bdseriectpscol,
            spcolcon.bddatanasccol, spcolcon.bdnommaecol, spcolcon.bddataadmcol, spcolcon.bdcategoriacol, RESC.bddataavprevio, RESC.bdchaveindentificacao,
            preresc.bddescpres, preresc.bdcodsaque, resc.bddatarescisao, resc.bddatapagrescisao,
            fn.bdref, fn.bdcodver, fn.bddescver, fn.bddescredver, fn.bdrefv, fn.bdprovento, fn.bddesconto, tverbas.bdordemver

           from vrh_emp_trescisao RESC
           left outer join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = resc.bdcodpres)
           left outer join vrh_sp_colcon(null,null,null,null, ' || prreffim || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) spcolcon  on
           (RESC.BDCODEMP = spcolcon.BDCODEMP and RESC.BDCODCOL = spcolcon.BDCODCOL)
           left outer join SP_CONSULTACIDADE(null) spcidadecol on (spcidadecol.bdcodcid = spcolcon.bdcodcid)
           left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = RESC.bdcodemp )
           left outer join VRHF_SP_CONS_CALC_FOLHANORMAL(null,null,'||  'CAST((substring((CAST(resc.bddatarescisao AS VARCHAR(10))) from 1 for 4) || substring((CAST(resc.bddatarescisao AS VARCHAR(10))) from 6 for 2)) AS INTEGER)' ||') FN on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol)
           left outer join vrh_base_tverbas tverbas on (fn.bdcodver = tverbas.bdcodver)' ;*/

  wsql = 'select RESC.bdcodemp,
                 EMPRESAS.bdnomemp ,
                 emp.bdcnpjemp,
                 RESC.bdcodcol,
                 colcad.bdnomcol,
                 doc.bdcpfcol,
                 empresas.bdlogremp,
                 empresas.bdendemp ,
                 empresas.bdnumemp,
                 empresas.bdbaiemp,
                 cidemp.bdnomcid,
                 ufemp.bdsiglauf,
                 empresas.bdcepemp,
                 empresas.bdcodcnae,
                 docref.bdpiscol,
                 colcad.bdlogrcol,
                 colcad.bdendcol,
                 colcad.bdnumcol,
                 colcad.bdbaicol,
                 colcad.bdcepcol,
                 cidcol.bdnomcid,
                 ufcol.bdsiglauf ,
                 docref.bdctpscol,
                 docref.bdseriectpscol,
                 docref.bddseriectpscol,
                 colcon.bddatanasccol,
                 parcol.bdnommaecol,
                 colcon.bddataadmcol,
                 fgtscol.bdcategoriacol,'||
                 'case when RESC.bddataavprevio is null then RESC.bddataavprevio else RESC.BDDATANOTIF end bdDT, '|| --RESC.bddataavprevio,
                 'RESC.bdchaveindentificacao,
                 resc.bdrefrescisao,
                 preresc.bddescpres,
                 preresc.bdcodsaque,
                 resc.bddatarescisao,
                 resc.bddatapagrescisao,
                 fn.bdreffn,
                 fn.bdcodver,
                 tverbas.bddescver,
                 tverbas.bddescredver,
                 case when substring(tverbas.bdclaver from 1 for 7) = ''9.010.0'' then fn.bdrefvfn_max else fn.bdrefvfn_sum end,
                 case when substring(tverbas.bdclaver from 1 for 7) = ''9.010.0'' then fn.bdrefauxvfn_sum else case when verref.BDDEDFORMREFAUXVER = ''TRUE'' then fn.bdrefauxvfn_sum else fn.bdrefauxvfn_max end end,
                 verref.bdhever,
                 case when coalesce(verref.bdtipocodver, 0) = 0 then fn.bdvalvfn
                      when coalesce(verref.bdtipocodver, 0) <> 0 then 0
                 end bdprovento,
                 case when coalesce(verref.bdtipocodver, 0) = 1 then fn.bdvalvfn
                      when coalesce(verref.bdtipocodver, 0) <> 1 then 0
                 end bddesconto,
                 tverbas.bdordemver,
                 tverbas.bdclaver,
                 tcol_calc.bdpercinsalubcol,
                 tcol_calc.bdpercperculcol,
                 case when (sind.BDPERCNOTST is not null) and (sind.BDPERCNOTST <> 0) then sind.BDPERCNOTST else tcol_calc.bdpercnoturnocol end BDPERCNOT,
                 tcol_calc.bdhorasdiariascol,
                 ufctps.bdsiglauf,
                 verref.bdtiporefver,
                 empref.bdrefhoremp,
                 class.bdclaver bdclaveraux,
                 class.bddescver bddescveraux,
                 case when coalesce(verref.bdtipocodver, 0) = 2 then fn.bdvalvfn
                      when coalesce(verref.bdtipocodver, 0) <> 2 then 0
                 end bdproventooutros,
                 case when coalesce(verref.bdtipocodver, 0) = 3 then fn.bdvalvfn
                      when coalesce(verref.bdtipocodver, 0) <> 3 then 0
                 end bddescontooutros,
                 colcalc.bdtipocol

          from ( select RESC.* from vrh_emp_trescisao RESC';

  wwhere = '';
  IF (prempresa <> '') THEN
     BEGIN
       wwhere = wwhere||prempresa||' ';
     END

  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;
  wsql = wsql||
          ') RESC ';

 IF ((prtipofolha IS NULL) OR (prtipofolha = 0)) THEN
    wsql = wsql||' join vwrh_union_fn_ft_mes fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol and fn.bdreffn = resc.bdrefrescisao)';
 ELSE
    BEGIN
      wsql = wsql||' join VWRH_UNION_FC_FCT_CALC fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol ';

      IF (prrefini IS NOT NULL AND prreffim IS NOT NULL) THEN
         wsql = wsql||' and fn.bdreffn >= '||prrefini||' and fn.bdreffn <= '||prreffim||') ';
      ELSE
         wsql = wsql||') ';
    END

  wsql = wsql||
          'join vrh_emp_tcolcon colcon on (colcon.bdcodemp = resc.bdcodemp and colcon.bdcodcol = resc.bdcodcol)
          left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = RESC.BDCODEMP and COLCAD.BDCODCOL = RESC.BDCODCOL)
          left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = RESC.BDCODEMP and DOCREF.BDCODCOL = RESC.BDCODCOL)
          join VW_TEMPRESAS_REF empresas on (empresas.bdcodemp = RESC.bdcodemp )
          join tempresas emp on (emp.bdcodemp = resc.bdcodemp)
          join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = resc.bdcodpres)
          left outer join VW_VRHF_BASE_TEMPCALC empref on (empref.bdcodemp = resc.bdcodemp)
          left outer join vrh_emp_tcolcon_doc doc on (doc.bdcodemp = resc.bdcodemp and doc.bdcodcol = resc.bdcodcol)
          left outer join VRH_EMP_TCOL_DOC doccol on (doccol.bdcodemp = resc.bdcodemp and doccol.bdcodcol = resc.bdcodcol)
          left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS fgtscol on (fgtscol.bdcodemp = resc.bdcodemp and fgtscol.bdcodcol = resc.bdcodcol)
          left outer join vrh_emp_tcol_parent parcol on (parcol.bdcodemp = resc.bdcodemp and parcol.bdcodcol = resc.bdcodcol)
          left outer join VW_VRH_EMP_TCOL_VINC tcon_vinc on (tcon_vinc.bdcodemp = resc.bdcodemp and tcon_vinc.bdcodcol = resc.bdcodcol)
          left outer join VW_vrh_emp_tcolcon_vinc tcolcon_vinc on (tcolcon_vinc.bdcodemp = resc.bdcodemp and tcolcon_vinc.bdcodcol = resc.bdcodcol) '||
         'left outer join vw_vrhf_emp_tcol_calc colcalc on (colcalc.BDCODEMP = RESC.BDCODEMP and colcalc.BDCODCOL = RESC.BDCODCOL) ' ;

  IF (prfuncao > 0) THEN
     wsql = wsql||
                'left outer join VW_TCOLCON_VINCDIA vincdia on (vincdia.bdcodemp = resc.bdcodemp and vincdia.bdcodcol = resc.bdcodcol) ';

  wsql = wsql||
             'left outer join VW_VRHF_EMP_TCOL_CALC tcol_calc on (tcol_calc.bdcodemp = resc.bdcodemp and tcol_calc.bdcodcol = resc.bdcodcol)
              left outer join VW_VRH_BASE_TSINDTREF sind on (sind.BDCODSINTRAB = tcon_vinc.BDCODSINTRAB) ';

  wsql = wsql||' join vrh_base_tverbas tverbas on (fn.bdcodver = tverbas.bdcodver)
                 left outer join vw_verbas_ref_atual verref on (verref.bdcodver = tverbas.bdcodver)
                 left outer join tcidade cidemp on (empresas.bdcodcid = cidemp.bdcodcid)
                 left outer join tcidade cidcol on (cidcol.bdcodcid = colcad.bdcodcid)
                 left outer join tuf ufemp on (ufemp.bdcoduf = cidemp.bdcoduf)
                 left outer join tuf ufcol on (ufcol.bdcoduf = cidcol.bdcoduf)
                 left outer join tuf ufctps on (ufctps.bdcoduf = docref.bdcoduf)
                 left outer join vrh_base_tverbas class on (class.bdclaver = substring(tverbas.bdclaver from 1 for 5)) ';

  wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.BDDATARESCISAO >= '''||:wdatainicial||''' ';
       ELSE
          wwhere = wwhere||' where RESC.BDDATARESCISAO >= '''||:wdatainicial||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.BDDATARESCISAO <= '''||:wdatafinal||''' ';
       ELSE
          wwhere = wwhere||' where RESC.BDDATARESCISAO <= '''||:wdatafinal||''' ';
    END


  IF (prempresa <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'vincdia.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'tcon_vinc.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'tcolcon_vinc.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END

  IF (prtipofiltro = 1) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||' coalesce(verref.bdtipocodver, 0) in (0,2) ';
     END

  IF (prtipofiltro = 2) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||' coalesce(verref.bdtipocodver, 0) in (1,3) ';
     END

 IF ((NOT ((prtipofolha IS NULL) OR (prtipofolha = 0))) AND (prdtpgto IS NOT NULL)) THEN
    BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
        ELSE
           wwhere = wwhere||' where ';
        wwhere = wwhere||' fn.bddtcomp >= '||PRDTPGTO||' and fn.bddtcomp <= '||PRDTPGTOFIM;
    END

 wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdbaiemp,
    :bdnomcid,
    :bdsiglaufemp,
    :bdcepemp,
    :bdcodcnae,
    :bdpiscol,
    :bdlogrcol,
    :bdendcol,
    :bdnumcol,
    :bdbaicol,
    :bdcepcol,
    :bdnomcidcol,
    :bdsiglaufcol,
    :bdctpscol,
    :bdseriectpscol,
    :BDDSERIECTPSCOL,
    :bddatanasccol,
    :bdnommaecol,
    :bddataadmcol,
    :bdcategoriacol,
    :bddataavprevio,
    :bdchaveindentificacao,
    :bdrefrescisao,
    :bddescpres,
    :bdcodsaque, 
    :bddatarescisao,
    :bddatapagrescisao,
    :bdref,
    :bdcodver,
    :bddescver,
    :bddescredver,
    :bdrefv,
    :bdrefauxv,
    :bdhever,
    :bdprovento,
    :bddesconto,
    :bdordemver,
    :bdclaver,
    :bdpercinsalubcol,
    :bdpercpericulcol,
    :bdpercnoturnocol,
    :bdhorasdiariascol,
    :bdsiglaufctps,
    :bdtiporefver,
    :bdrefhoremp,
    :bdclaveraux,
    :bddescveraux,
    :bdproventooutros,
    :bddescontooutros,
    :bdtipocol
    DO

   SUSPEND;
END
^

/* Alter (VRHF_SP_RETORNAEMPRESA_GPS) */
ALTER PROCEDURE VRHF_SP_RETORNAEMPRESA_GPS(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDSIMPLESGPS INTEGER)
 AS
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

/*  select BDSIMPLESGPS from VW_VRHF_BASE_TEMPGPSx where bdcodemp = :premp
  into
    :BDSIMPLESGPS;*/

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_SALARIOS_CONTRIB) */
ALTER PROCEDURE VRHF_SP_SALARIOS_CONTRIB(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRBANCO INTEGER,
PRAGENCIA INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDNOMCIDEMP VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAINSS DATE,
BDREFINSS INTEGER,
BDBASEINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,2),
BDCODEMPAUX INTEGER,
BDCODCOLAUX INTEGER,
BDDATAINSSAUX DATE,
BDVALORINSSAUX NUMERIC(15,6),
BDBASEINSSAUX NUMERIC(15,6),
BDREFINSSAUX INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLAUX VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WWHEREAUX VARCHAR(15000);
DECLARE VARIABLE WORDERBY VARCHAR(10000);
BEGIN
   IF (prreferencia IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, PRULTIMODIA);


   wWhere = '';

   IF (prEmpresa <> '') THEN
      wWhere = wWhere || prEmpresa || ' ';

   IF (prColaborador <> '') THEN
     BEGIN
       IF (wWhere <> '') THEN
         wWhere = wWhere || ' and ';
       wWhere = wWhere || prColaborador || ' ';
     END

   wOrderBy = '';
   IF (prOrdemImp IS NOT NULL) THEN
     BEGIN
       wOrderBy = 'order by ';
        
       IF (prOrdemImp = 0) THEN
         wOrderBy = wOrderBy || 'BDCODEMP, BDCODCOL, BDREFINSS ';
       ELSE IF (prOrdemImp = 1) THEN
         wOrderBy = wOrderBy || 'BDCODEMP, BDNOMCOL, BDREFINSS ';
     END

   wSqlAux = '';
   wWhereAux = '';
   IF (prFuncao > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'TFUC.BDCODTFUC = ' || prFuncao || ' ';

       wSqlAux = wSqlAux || 'left outer join VW_TCOLCON_VINCDIA COL_DIA on (COL_DIA.BDCODEMP = FOL.BDCODEMP and COL_DIA.BDCODCOL = FOL.BDCODCOL) ';
       wSqlAux = wSqlAux || 'left outer join VRH_FUNCOES_TFUC TFUC on (TFUC.BDCODPLAFUC = COL_DIA.BDCODPLAFUC and TFUC.BDCODTFUC = COL_DIA.BDCODTFUC) ';
     END

   IF (prSindicato > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'COL_VINC.BDCODSINTRAB = ' || prSindicato || ' ';

       wSqlAux = wSqlAux || 'left outer join VW_VRH_EMP_TCOL_VINC COL_VINC on (COL_VINC.BDCODEMP = FOL.BDCODEMP and COL_VINC.BDCODCOL = FOL.BDCODCOL) ';
     END

   IF (prClasse > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'COLCON_VINC.BDCODCLA = ' || prClasse || ' ';

       wSqlAux = wSqlAux || 'left outer join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC on (COLCON_VINC.BDCODEMP = FOL.BDCODEMP and COLCON_VINC.BDCODCOL = FOL.BDCODCOL) ';
     END

   IF (prBanco > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'COLCON_BANCO.BDCODBAN = ' || prBanco || ' ';

       wSqlAux = wSqlAux || 'left outer join VW_VRHF_EMP_TCOLCON_BANCO COLCON_BANCO on (COLCON_BANCO.BDCODEMP = FOL.BDCODEMP and COLCON_BANCO.BDCODCOL = FOL.BDCODCOL) ';
     END

   IF (prAgencia > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'COLCON_BANCO.BDCODAG = ' || prAgencia || ' ';

       IF (NOT (prBanco > 0)) THEN
         wSqlAux = wSqlAux || 'left outer join VW_VRHF_EMP_TCOLCON_BANCO COLCON_BANCO on (COLCON_BANCO.BDCODEMP = FOL.BDCODEMP and COLCON_BANCO.BDCODCOL = FOL.BDCODCOL) ';
     END

   wsql = 'select ';
   wsql = wsql || 'BDCODEMP, ';
   wsql = wsql || 'BDNOMEMP, ';
   wsql = wsql || 'BDLOGREMP, ';
   wsql = wsql || 'BDENDEMP, ';
   wsql = wsql || 'BDNUMEMP, ';
   wsql = wsql || 'BDCOMPLEMP, ';
   wsql = wsql || 'BDBAIEMP, ';
   wsql = wsql || 'BDNOMCID, ';
   wsql = wsql || 'BDSIGLAUFEMP, ';
   wsql = wsql || 'BDCNPJEMP, ';
   wsql = wsql || 'BDCODCOL, ';
   wsql = wsql || 'BDNOMCOL, ';
   wsql = wsql || 'BDDATAADMCOL, ';
   wsql = wsql || 'BDCPFCOL, ';
   wsql = wsql || 'BDPISCOL, ';
   wsql = wsql || 'BDCTPSCOL, ';
   wsql = wsql || 'BDSERIECTPSCOL, ';
   wsql = wsql || 'BDDSERIECTPSCOL, ';
   wsql = wsql || 'BDSIGLAUFDOC, ';
   wsql = wsql || 'BDDATARESCISAO, ';
   wsql = wsql || 'NULL BDDATAINSS, ';
   wsql = wsql || 'BDREFINSS, ';
   wsql = wsql || 'SUM(coalesce(BDBASEINSS, 0)) BDBASEINSS, ';
   wsql = wsql || 'SUM(coalesce(BDVALORINSS, 0)) BDVALORINSS ';

   wsql = wsql || 'from ( ';

   wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(FOL.BDREFFN, 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBINSSFN, 0) + coalesce(FOL.BDBINSSFEFOLFN, 0) + coalesce(FOL.BDBINSS13FN, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDINSSFN, 0) + coalesce(FOL.BDINSSFEFOLFN, 0) + coalesce(FOL.BDINSS13FN, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHANORMAL FOL ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
     wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFFN <= ' || prReferencia || ') ';
   ELSE
     wsql = wsql || 'where (FOL.BDREFFN <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(FOL.BDREFTOMADOR, 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBINSSFT, 0) + coalesce(FOL.BDBINSSFEFOLFT, 0) + coalesce(FOL.BDBINSS13FT, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDINSSFT, 0) + coalesce(FOL.BDINSSFEFOLFT, 0) + coalesce(FOL.BDINSS13FT, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHATOMADOR FOL ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
     wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';
   ELSE
     wsql = wsql || 'where (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(substring(FOL.BDREFFC from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBINSSFC, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDINSSFC, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHACOMP FOL ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
     wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFFN <= ' || prReferencia || ') ';
   ELSE
     wsql = wsql || 'where (FOL.BDREFFN <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(substring(FOL.BDREFTOMADOR from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBINSSFC, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDINSSFC, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLTOMCOMP FOL ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
     wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';
   ELSE
     wsql = wsql || 'where (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(substring(FOL.BDREF13 from 1 for 4) || 13, 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBASEINSS13, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDVALORINSS13, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_T13SAL FOL ';
   wsql = wsql || 'left outer join VRHF_EMP_TC13SAL CFOL on (CFOL.BDCODEMP = FOL.BDCODEMP and CFOL.BDCODCOL = FOL.BDCODCOL and CFOL.BDREFC13 <= ' || prReferencia || ') ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
      wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREF13 <= ' || prReferencia || ') ';
   ELSE
      wsql = wsql || 'where (FOL.BDREF13 <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || ') CALC ';

   wsql = wsql || 'group by BDCODEMP, BDNOMEMP, BDLOGREMP, BDENDEMP, BDNUMEMP, BDCOMPLEMP, BDBAIEMP, BDNOMCID, BDSIGLAUFEMP, BDCNPJEMP, BDCODCOL, BDNOMCOL, BDDATAADMCOL, BDCPFCOL, BDPISCOL, ';
   wsql = wsql || '         BDCTPSCOL, BDSERIECTPSCOL, BDDSERIECTPSCOL, BDSIGLAUFDOC, BDDATARESCISAO, BDDATAINSS, BDREFINSS ';
   wsql = wsql || wOrderBy;


   FOR EXECUTE STATEMENT wsql
     INTO
          :bdcodemp,
          :bdnomemp,
          :bdlogremp,
          :bdendemp,
          :bdnumemp,
          :bdcomplemp,
          :bdbaiemp,
          :bdnomcidemp,
          :bdsiglaufemp,
          :bdcnpjemp,
          :bdcodcol,
          :bdnomcol,
          :bddataadmcol,
          :bdcpfcol,
          :bdpiscol,
          :bdctpscol,
          :bdseriectpscol,
          :bddseriectpscol,
          :bdsiglaufctps,
          :bddatarescisao,
          :bddatainss,
          :bdrefinss,
          :bdbaseinss,
          :bdvalorinss DO
   SUSPEND;
END
^

/* Alter (VRHF_SP_TCALC_AUTONOMO) */
ALTER PROCEDURE VRHF_SP_TCALC_AUTONOMO(PRCODEMP VARCHAR(32700),
PRCODTER VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER)
 RETURNS(BDGRUPOCLA INTEGER,
BDCODTER INTEGER,
BDCODEMP INTEGER,
BDCODSERV INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDANOMES INTEGER,
BDBASEIR NUMERIC(15,6),
BDFAIXAIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDBASEINSS NUMERIC(15,6),
BDFAIXAINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDVALORDEP NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDCATEGORIACOL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WWHERET VARCHAR(32000);
DECLARE VARIABLE WCODEMPAUT INTEGER;
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */


  -- A implementa??o a seguir foi feita por causa de performance.
  -- S? vai retornar alguma coisa de aut?nomos se passar no filtro inicial
  IF (prrefini IS NOT NULL) THEN
    BEGIN
      wcodempaut = NULL;
      wsql = 'select first 1 colcon.BDCODEMP from VRHF_BASE_CALC_TERC colcon where ';

      IF (prreffim IS NOT NULL) THEN
        wsql = wsql||'colcon.bdrefinssserv >= '||prrefini||' and colcon.bdrefinssserv <= '||prreffim;
      ELSE
        wsql = wsql||'colcon.bdrefinssserv = '||prrefini||' ';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;
    
      IF (prcodter IS NOT NULL AND prcodter <> '') THEN
        wsql = wsql||' and '||prcodter;
    END
  ELSE
    wcodempaut = 1;

  EXECUTE STATEMENT wsql INTO :wcodempaut;

  wsql = '';

  IF (wcodempaut IS NOT NULL AND wcodempaut <> 0) THEN
    BEGIN
      wwheret = '';
    
      IF (prcodemp IS NOT NULL) THEN
         BEGIN
           IF (wwheret <> '') THEN
              BEGIN
                wwheret = wwheret||' and ';
              END
           ELSE
              BEGIN
                wwheret = wwheret||' where ';
              END
    
           wwheret = wwhereT||prcodemp;
         END
    
      IF (prcodter IS NOT NULL) THEN
         BEGIN
    --       if (upper(substring(prcodter from 1 for 15)) = 'COLCON.BDCODCOL') then
    --          prcodter = 'colcon.bdcodter'||substring(prcodter from 16);
    
           IF (wwheret <> '') THEN
              BEGIN
                wwheret = wwheret||' and ';
              END
           ELSE
              BEGIN
                wwheret = wwheret||' where ';
              END
    
           wwheret = wwhereT||prcodter;
         END
    
      IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
         BEGIN
           IF (wwheret <> '') THEN
              BEGIN
                wwheret = wwheret||' and ';
              END
           ELSE
              BEGIN
                wwheret = wwheret||' where ';
              END
    
           wwheret = wwhereT||'cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) >= '||prrefini||' and '||'cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) <= '||prreffim;
         END
      ELSE
         BEGIN
           IF (prrefini IS NOT NULL) THEN
              BEGIN
                IF (wwheret <> '') THEN
                   BEGIN
                     wwheret = wwheret||' and ';
                   END
                ELSE
                   BEGIN
                     wwheret = wwheret||' where ';
                   END
    
                wwheret = wwhereT||'cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) = '||prrefini;
              END
           ELSE
              BEGIN
                IF (prreffim IS NOT NULL) THEN
                   BEGIN
                     IF (wwheret <> '') THEN
                        BEGIN
                          wwheret = wwheret||' and ';
                        END
                     ELSE
                        BEGIN
                          wwheret = wwheret||' where ';
                        END
    
                     wwheret = wwhereT||'cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) = '||prreffim;
                   END
              END
         END
    
      /* Procedure Text VRHF_SP_TIPO_TOMADOR_GPS*/
      IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
         BEGIN
              wsql = 'select ter.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, cast(null as integer),'||
                     '       max(cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)) bdanomes,'||
                     '       sum(COLCON.bdbaseinss), max(COLCON.bdfaixainss), sum(COLCON.bdvalorinss),'||
                     '       sum(COLCON.bdbaseir), max(COLCON.bdfaixair), sum(COLCON.bdvalorir),'||
                     '       sum(COLCON.bdbaseratapo), sum(COLCON.bdvalorratapo), sum(COLCON.bdvalordep), sum(colcon.BDVALOUTENTIDADES), pf.bdCodCentro, toma.bdCODTPCC,'||
                     '       sum(colcon.bdcreditoserv), sum(colcon.bddebitoserv), max(coalesce(ter.bdocorrenciacol,0)) BDOCORRENCIACOL, max(coalesce(ter.bdcategoriacol,0)) BDCATEGORIACOL '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
                     ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro) toma on'||
                     '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' join vw_autonomos_ref_atual ter on (colcon.bdcodter = ter.bdcodcol)'||
                     wwheret||
                     'group by ter.bdgrupocla, colcon.bdcodemp, colcon.bdcodter, cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer), pf.bdCodCentro, toma.bdCODTPCC';
         END
      ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
         BEGIN
              wsql = 'select ter.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, cast(null as integer),'||
                     '       max(cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)) bdanomes,'||
                     '       sum(COLCON.bdbaseinss), max(COLCON.bdfaixainss), sum(COLCON.bdvalorinss),'||
                     '       sum(COLCON.bdbaseir), max(COLCON.bdfaixair), sum(COLCON.bdvalorir),'||
                     '       sum(COLCON.bdbaseratapo), sum(COLCON.bdvalorratapo), sum(COLCON.bdvalordep), sum(colcon.BDVALOUTENTIDADES), pf.bdCodCentro, toma.bdCODTPCC,'||
                     '       sum(colcon.bdcreditoserv), sum(colcon.bddebitoserv), max(coalesce(ter.bdocorrenciacol,0)) BDOCORRENCIACOL, max(coalesce(ter.bdcategoriacol,0)) BDCATEGORIACOL '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
                     ' left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on'||
                     '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' join vw_autonomos_ref_atual ter on (colcon.bdcodter = ter.bdcodcol)'||
                     wwheret||
                     'group by ter.bdgrupocla, colcon.bdcodemp, colcon.bdcodter, cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer), pf.bdCodCentro, toma.bdCODTPCC';
         END
      ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
         BEGIN
              wsql = 'select ter.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, cast(null as integer),'||
                     '       max(cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)) bdanomes,'||
                     '       sum(COLCON.bdbaseinss), max(COLCON.bdfaixainss), sum(COLCON.bdvalorinss),'||
                     '       sum(COLCON.bdbaseir), max(COLCON.bdfaixair), sum(COLCON.bdvalorir),'||
                     '       sum(COLCON.bdbaseratapo), sum(COLCON.bdvalorratapo), sum(COLCON.bdvalordep), sum(colcon.BDVALOUTENTIDADES), pf.bdCodCentro, pf.bdCODTPCC,'||
                     '       sum(colcon.bdcreditoserv), sum(colcon.bddebitoserv), max(coalesce(ter.bdocorrenciacol,0)) BDOCORRENCIACOL, max(coalesce(ter.bdcategoriacol,0)) BDCATEGORIACOL '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
    --                 ' left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on'||
    --                 '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' join vw_autonomos_ref_atual ter on (colcon.bdcodter = ter.bdcodcol)'||
                     wwheret||
                     'group by ter.bdgrupocla, colcon.bdcodemp, colcon.bdcodter, cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer), pf.bdCodCentro, pf.bdCODTPCC';
         END
      ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
         BEGIN
              wsql = 'select ter.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, cast(null as integer), '||
                     '       max(cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)) bdanomes,'||
                     '       sum(COLCON.bdbaseinss), max(COLCON.bdfaixainss), sum(COLCON.bdvalorinss),'||
                     '       sum(COLCON.bdbaseir), max(COLCON.bdfaixair), sum(COLCON.bdvalorir),'||
                     '       sum(COLCON.bdbaseratapo), sum(COLCON.bdvalorratapo), sum(COLCON.bdvalordep), sum(colcon.BDVALOUTENTIDADES), cast(null as integer), cast(null as integer),'||
                     '       sum(colcon.bdcreditoserv), sum(colcon.bddebitoserv), max(coalesce(ter.bdocorrenciacol,0)) BDOCORRENCIACOL, max(coalesce(ter.bdcategoriacol,0)) BDCATEGORIACOL '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
    --                 ' left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on'||
    --                 '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' join vw_autonomos_ref_atual ter on (colcon.bdcodter = ter.bdcodcol)'||
                     wwheret||
                     ' group by ter.bdgrupocla, colcon.bdcodemp, colcon.bdcodter, cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)';
         END
      ELSE
         BEGIN
              wsql = 'select ter.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, colcon.bdcodserv, '||
    --                 '       201005 bdanomes,'||
                     '       cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) bdanomes,'||
                     '       COLCON.bdbaseinss, COLCON.bdfaixainss, COLCON.bdvalorinss,'||
                     '       COLCON.bdbaseir, COLCON.bdfaixair, COLCON.bdvalorir,'||
                     '       COLCON.bdbaseratapo, COLCON.bdvalorratapo, COLCON.bdvalordep, colcon.BDVALOUTENTIDADES, pf.bdCodCentro, pf.bdCODTPCC,'||
                     '       colcon.bdcreditoserv, colcon.bddebitoserv, coalesce(ter.bdocorrenciacol,0) BDOCORRENCIACOL, coalesce(ter.bdcategoriacol,0) BDCATEGORIACOL '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
    --                 ' left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on'||
    --                 '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' join vw_autonomos_ref_atual ter on (colcon.bdcodter = ter.bdcodcol)'||
                      wwheret;
         END
    
      FOR EXECUTE STATEMENT wsql INTO
        : bdgrupocla,
        : bdcodemp,
        : bdcodter,
        : bdcodserv,
        : bdanomes,
        : bdbaseinss,
        : bdfaixainss,
        : bdvalorinss,
        : bdbaseir,
        : bdfaixair,
        : bdvalorir,
        : bdvalorratapo,
        : bdbaseratapo,
        : bdvalordep,
        : bdvaloutentidades,
        : bdcodcentro,
        : bdcodtpcc,
        : bdcredito,
        : bddebito,
        : bdocorrenciacol,
        : bdcategoriacol DO
      BEGIN
        SUSPEND;
      END
  END
END
^

/* Alter (VRHF_SP_TCOMPENSACAOGPS) */
ALTER PROCEDURE VRHF_SP_TCOMPENSACAOGPS(PRCODIMP INTEGER,
PRCODEMP INTEGER,
PRTIPOGPS INTEGER,
PRTIPOEMISSAO INTEGER,
PRCODTPCC INTEGER,
PRRETORNACOMPENSACAO INTEGER,
PRANOMES INTEGER,
PRCHAVEDARF INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCHAVE INTEGER,
BDVALOR NUMERIC(15,6),
BDPERC NUMERIC(15,6),
BDMESINI INTEGER,
BDMESFIM INTEGER,
BDVALORREAJUSTE NUMERIC(15,6),
BDVALORSEMREAJUSTE NUMERIC(15,6))
 AS
DECLARE VARIABLE WCHAVEDARF INTEGER;
DECLARE VARIABLE WAUXTOMADOR VARCHAR(32000);
DECLARE VARIABLE WAUXTOMADOR2 VARCHAR(3200);
DECLARE VARIABLE WWHEREHISTTROCA VARCHAR(3200);
DECLARE VARIABLE WWHEREHIST VARCHAR(3200);
DECLARE VARIABLE WSQLAUX VARCHAR(32000);
DECLARE VARIABLE WANOMESAUX INTEGER;
DECLARE VARIABLE WPERCREAJUSTE NUMERIC(15,6);
DECLARE VARIABLE WFOLHANORAL INTEGER;
DECLARE VARIABLE WTIPOIMPOSTO INTEGER;
DECLARE VARIABLE WMESDEC VARCHAR(2);
DECLARE VARIABLE WANODEC VARCHAR(4);
BEGIN
   /* prretornacompensacao
     0 = todos
     1 = Nao retornar a compensacao
   */

    WANOMESAUX = pranomes;

    IF (prretornacompensacao IS NULL) THEN
       prretornacompensacao = 0;

    IF (prtipoemissao = 3) THEN
       BEGIN
         wauxtomador = ' left outer join vrhf_sp_tomador(comp.bdcodtpcc,comp.bdcodcentro) toma on';
         wauxtomador2 = ' left outer join vrhf_sp_tomador(darf.bdcodtpcc,darf.bdcodcentro) toma on';
       END
    ELSE
       BEGIN
         wauxtomador = ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(comp.bdcodtpcc,comp.bdcodcentro) toma on';
         wauxtomador2 = ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(darf.bdcodtpcc,darf.bdcodcentro) toma on';
       END

    /*Verifica se foi emitida a GPS 13 se n?o foi buscar da Folha normal*/
    wfolhanoral = 0;
    IF ((SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '12') AND (prtipogps = 0)) THEN
       BEGIN
         SELECT FIRST 1 bdcodemp FROM tdarfpadrao darf
         WHERE darf.bdcodemp = :prcodemp
         AND darf.bdcodimp = :prcodimp
         AND darf.bdreferencia = :pranomes
         AND darf.bdtipoimposto = 2 INTO wfolhanoral;

         IF (wfolhanoral = 0) THEN
            wfolhanoral = 1;
       END

    wwherehist = '';
    WWHEREHISTTROCA = '';
    IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) > '12') THEN
       BEGIN
         wwherehist = ' and 0 = 1';
       END
    ELSE IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '01') THEN
       BEGIN
         wwherehist = ' and ((darf.bdreferencia = '||SUBSTRING(CAST(pranomes-2 AS VARCHAR(6)) FROM 1 FOR 4)||'12';
         wwherehist = wwherehist||' and darf.bdtipoimposto = 0) ';
         wwherehist = wwherehist||' or darf.bdreferencia = '||SUBSTRING(CAST(pranomes-1 AS VARCHAR(6)) FROM 1 FOR 4)||'14';
         wwherehist = wwherehist||')';
         WWHEREHISTTROCA = ' or (comp.bdchavedarf is null and comp.bdreferencia = '||pranomes||')';
       END
    ELSE
       BEGIN
         WWHEREHISTTROCA = ' or (comp.bdchavedarf is null and comp.bdreferencia = '||pranomes||')';
         IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '12' AND ((prtipogps = 2) OR (wfolhanoral = 1)) )  THEN
            BEGIN
              wwherehist = wwherehist||' and ( darf.bdreferencia = '||(pranomes-1);
              IF (wfolhanoral = 0) THEN
                 BEGIN
                   wwherehist = wwherehist||' or ( darf.bdreferencia = '||SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'13)';
                   wanomesaux = CAST(SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'13' AS INTEGER);
                 END
            END
         ELSE
         IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '12' AND prtipogps = 0)  THEN
            BEGIN
              wwherehist = wwherehist||' and ((darf.bdreferencia = '||(pranomes)||') and  (darf.bdtipoimposto <> 0)';
            END
         ELSE
            BEGIN
              wwherehist = wwherehist||' and ( darf.bdreferencia = '||(pranomes-1);

              IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '12') THEN
                 BEGIN
                   wwherehist = wwherehist||' or ( darf.bdreferencia = '||SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'13)';
                 END
            END

         wwherehist = wwherehist||')';
       END

   /* Verifica a ultima gps emitida na competencia para n?o carrega valores restantes de varias guias */
  wchavedarf = prchavedarf;

    /* desconta compensacao */
    /* 3 = Compensacao*/
   wsqlaux = 'select 3, comp.bdchave,comp.bdvaldesccgps - (select coalesce(sum(r.bdvalor),0) from vrh_emp_rcomp r where r.bdchave = comp.bdchave and r.bdcodemp = comp.bdcodemp),comp.bdpercgps,comp.bdrefinicgps,bdreffimcgps,0 bdtipoimposto from vrhf_emp_tcompgps comp'||
             wauxtomador||
             --' left outer join VRHF_SP_TIPO_TOMADOR_GPS(comp.bdcodtpcc,comp.bdcodcentro) toma on'||
             ' (toma.bdcodcencus = comp.bdcodtpcc and toma.bdcodcentro = comp.bdcodcentro)'||
             ' where comp.bdcodemp = '||prcodemp||
             ' and ((comp.bdrefcgps = '||WANOMESAUX||')';

    IF ((prtipogps = 2) AND (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) <> '12')) THEN
      BEGIN
        wsqlaux = wsqlaux||' or (comp.bdrefcgps = '||CAST(SUBSTRING(CAST(WANOMESAUX AS VARCHAR(6)) FROM 1 FOR 4)||'13' AS INTEGER)||')';
      END

    wsqlaux = wsqlaux||') and '||prtipogps||' <> 3'; -- Compensacao nao devem ser utilizadas para folha complementar e compl 13 sal e 13 sal
    IF (prtipoemissao IN (3,4)) THEN
       BEGIN
         IF (prcodtpcc IS NULL) THEN
            wsqlaux = wsqlaux||' and toma.bdcodtpcc is null';
         ELSE
            wsqlaux = wsqlaux||' and toma.bdcodtpcc = '||prcodtpcc;
       END

    IF (COALESCE(wchavedarf,0) > 0) THEN
       BEGIN
         wsqlaux = wsqlaux||' and not exists(select * from vrhf_emp_thistcomp x where x.bdcodemp = comp.bdcodemp and x.bdchave = comp.bdchave and x.bdchavedarf <= '||wchavedarf||')';
         wsqlaux = wsqlaux||' union all ';
         /* 4 = historico comp*/
         wsqlaux = wsqlaux||' select 4, comp.bdchave,comp.bdvalacompensar - (select coalesce(sum(r.bdvalor),0) from vrh_emp_hrcomp r where r.bdchavedarfhistcomp = comp.bdchavedarfhistcomp and r.bdcodemp = comp.bdcodemp)'||
                            ' ,compx.bdpercgps,darf.BDREFERENCIA,darf.BDREFERENCIA, COALESCE(darf.BDTIPOIMPOSTO,0) from vrhf_emp_thistcomp comp'||
                            ' left outer join tdarfpadrao darf on (darf.bdcodemp = comp.bdcodemp and darf.bdchavedarf = comp.bdchavedarf) '||
                            ' left outer join vrhf_emp_tcompgps compx on (compx.bdcodemp = comp.bdcodempcompgps and compx.bdchave = comp.bdchave)'||
                            wauxtomador2||
                            ' (toma.bdcodcencus = darf.bdcodtpcc and toma.bdcodcentro = darf.bdcodcentro)'||
                            ' where comp.bdcodemp = '||prcodemp||
                            ' and ((darf.bdcodimp = '||prcodimp||
                            ' and darf.bdchavedarf = '||wchavedarf;
         wsqlaux = wsqlaux||')'||WWHEREHISTTROCA||')';
         wsqlaux = wsqlaux||' union all ';
         /* 5 = historico nf */
         wsqlaux = wsqlaux||' select 5, comp.bdchave,comp.bdvalacompensar - (select coalesce(sum(r.bdvalor),0) from vrh_emp_hrnf r where r.bdcodemp = comp.bdcodemp and r.bdchavedarfhistnf = comp.bdchavedarfhistnf)'||
                            ' ,100,darf.BDREFERENCIA,darf.BDREFERENCIA, COALESCE(darf.BDTIPOIMPOSTO,0) from vrhf_emp_thistnf comp'||
                            ' left outer join tdarfpadrao darf on (darf.bdcodemp = comp.bdcodemp and darf.bdchavedarf = comp.bdchavedarf)'||
                            wauxtomador2||
                            ' (toma.bdcodcencus = darf.bdcodtpcc and toma.bdcodcentro = darf.bdcodcentro)'||
                            ' where comp.bdcodemp = '||prcodemp||
                            ' and ((darf.bdcodimp = '||prcodimp||
                            ' and darf.bdchavedarf = '||wchavedarf;
         wsqlaux = wsqlaux||')'||WWHEREHISTTROCA||')';
         wsqlaux = wsqlaux||' union all ';
         /* 6 = historico gps */
         wsqlaux = wsqlaux||' select 6, 0, comp.bdvalacompensar - (select coalesce(sum(r.bdvalor),0) from vrh_emp_hrded r where r.bdchavedarfhistgps = comp.bdchavedarfhistgps and r.bdcodemp = comp.bdcodemp) '||
                            ',100,darf.BDREFERENCIA,darf.BDREFERENCIA, COALESCE(darf.BDTIPOIMPOSTO,0) from vrhf_emp_thistoricogps comp'||
                            ' left outer join tdarfpadrao darf on (darf.bdcodemp = comp.bdcodemp and darf.bdchavedarf = comp.bdchavedarf)'||
                            wauxtomador2||
                            ' (toma.bdcodcencus = darf.bdcodtpcc and toma.bdcodcentro = darf.bdcodcentro)'||
                            ' where comp.bdcodemp = '||prcodemp||
                            ' and ((darf.bdcodimp = '||prcodimp||
                            ' and darf.bdchavedarf = '||wchavedarf;
         wsqlaux = wsqlaux||')'||WWHEREHISTTROCA||')';
       END
    wpercreajuste = -1;

    /* 3 = Compensacao*/
    /* 4 = historico comp*/
    /* 5 = historico nf */
    /* 6 = historico gps */
    FOR EXECUTE STATEMENT wsqlaux INTO
      : bdtiporeg,
      : bdchave,
      : bdvalor,
      : bdperc,
      : bdmesini,
      : bdmesfim,
      : wtipoimposto
    DO
      BEGIN
        IF (bdvalor IS NULL) THEN
           bdvalor = 0;

        IF (bdperc IS NULL) THEN
           bdperc = 0;

        IF (bdvalor > 0) THEN
           BEGIN
             bdvalorsemreajuste = bdvalor;
             bdvalorreajuste = 0;
             IF ((pranomes > bdmesini) AND (bdtiporeg <> 3)) THEN
                BEGIN
                  IF (wpercreajuste = -1) THEN
                     BEGIN
                        SELECT COALESCE(ind.bdvalind,0) bdvalind FROM vw_vrhf_base_tempvinc vinc
                             LEFT OUTER JOIN tindval ind ON (vinc.bdcodindgps = ind.bdcodind)
                               WHERE vinc.bdcodemp = :prcodemp AND ind.bdrefind = :bdmesini INTO wpercreajuste;

                        IF ((wpercreajuste IS NULL) OR (wpercreajuste < 0)) THEN
                           wpercreajuste = 0;
                     END

                  bdvalorreajuste = 0;
                  IF (wpercreajuste > 0) THEN
                     BEGIN
                       bdvalorreajuste = (bdvalorsemreajuste * wpercreajuste) / 100;
                       bdvalorreajuste = CAST(bdvalorreajuste AS NUMERIC(15,2));
                     END
                END
             ELSE
             IF ((pranomes = bdmesini) AND (bdtiporeg <> 3) AND (wtipoimposto = 2)) THEN
                BEGIN
                  IF (wpercreajuste = -1) THEN
                     BEGIN
                        IF (CAST(SUBSTRING(:BDMESINI FROM 5 FOR 2) AS INTEGER) = 1) THEN
                          BEGIN
                            wanodec = CAST((CAST(SUBSTRING(:BDMESINI FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4));
                            wmesdec = '12';
                          END
                        ELSE
                          BEGIN
                            wanodec = SUBSTRING(:BDMESINI FROM 1 FOR 4);
                            wmesdec = TRIM(CAST((CAST(SUBSTRING(:BDMESINI FROM 5 FOR 2) AS INTEGER) - 1) AS VARCHAR(2)));
                            WHILE (strlen(:wmesdec) < 2) DO
                              wmesdec = '0'||wmesdec;
                          END


                        SELECT COALESCE(ind.bdvalind,0) bdvalind FROM vw_vrhf_base_tempvinc vinc
                             LEFT OUTER JOIN tindval ind ON (vinc.bdcodindgps = ind.bdcodind)
                               WHERE vinc.bdcodemp = :prcodemp AND ind.bdrefind = :wanodec||:wmesdec INTO wpercreajuste;

                        IF ((wpercreajuste IS NULL) OR (wpercreajuste < 0)) THEN
                           wpercreajuste = 0;
                     END

                  bdvalorreajuste = 0;
                  IF (wpercreajuste > 0) THEN
                     BEGIN
                       bdvalorreajuste = (bdvalorsemreajuste * wpercreajuste) / 100;
                       bdvalorreajuste = CAST(bdvalorreajuste AS NUMERIC(15,2));
                     END
                END

             bdvalor = bdvalorsemreajuste + bdvalorreajuste;

             IF ((prretornacompensacao = 0) OR (bdtiporeg <> 3)) THEN
                SUSPEND;
           END
      END
END
^

/* Alter (VRHF_SP_TFOLHA_NORMAL) */
ALTER PROCEDURE VRHF_SP_TFOLHA_NORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = null,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = null)
 RETURNS(BDGRUPOCLA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDREFFN INTEGER,
BDDATABAIXAFN DATE,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDBASEPISFEFN NUMERIC(15,6),
BDBASEPIS13FN NUMERIC(15,6),
BDBSALMATEMPFN NUMERIC(15,6),
BDSALMATEMPFN NUMERIC(15,6),
BDBRATAPOFN NUMERIC(15,6),
BDBRATAPOFEFN NUMERIC(15,6),
BDBRATAPO13FN NUMERIC(15,6),
BDBINSSFEFOLFN NUMERIC(15,6),
BDINSSFEFOLFN NUMERIC(15,6),
BDALIQINSSFEFOLFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCREDITOFN NUMERIC(15,6),
BDDEBITOFN NUMERIC(15,6),
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6),
BDBMATEMPFNFN NUMERIC(15,6),
BDBMATEMP13FN NUMERIC(15,6),
BDVMATEMPFNFN NUMERIC(15,6),
BDVMATEMP13FN NUMERIC(15,6),
BDLIQUIDOFN NUMERIC(18,6),
BDDATAPGTO DATE,
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDCODCONTTI INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WWHERET varchar(32700);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  /* Procedure Text */
  wsql = 'select f.bdgrupocla, colcon.BDCODEMP, colcon.BDCODCOL, colcon.BDREFFN, colcon.BDDATABAIXAFN, colcon.BDBFGTSFN,'||
         'colcon.BDFGTSFN, colcon.BDFGTSCSFN, colcon.BDBFGTS13FN, colcon.BDFGTS13FN, colcon.BDFGTS13CSFN, colcon.BDMAIORREMFN,'||
         'colcon.BDBINSSFN, colcon.BDALIQINSSFN, colcon.BDINSSFN, colcon.BDBIRRFFN, colcon.BDALIQIRRFFN, colcon.BDIRRFFN,'||
         'colcon.BDBINSS13FN, colcon.BDALIQINSS13FN, colcon.BDINSS13FN, colcon.BDBIRRF13FN, colcon.BDALIQIRRF13FN,'||
         'colcon.BDIRRF13FN, colcon.BDBSALFAMFN, colcon.BDSALFAMFN, colcon.BDBRAISFN, colcon.BDSALBASEFN, colcon.BDDEPFN,'||
         'colcon.BDBASEPISFN, colcon.BDBASEPISFEFN, colcon.BDBASEPIS13FN, colcon.BDBSALMATEMPFN, colcon.BDSALMATEMPFN, colcon.BDBRATAPOFN, colcon.BDBRATAPOFEFN, colcon.BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFN,'||
         'colcon.BDINSSFEFOLFN, colcon.BDALIQINSSFEFOLFN, colcon.bdcreditofn, COLCON.bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNFN,COLCON.BDBSALMATEMP13FN,COLCON.BDVSALMATEMPFNFN,COLCON.BDVSALMATEMP13FN, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFN, COLCON.BDINSSAPFN, COLCON.BDBINSS13APFN, COLCON.BDINSS13APFN, cast(null as INTEGER) BDCODCONTTI '||
         ' from vrhf_emp_tfolhanormal COLCON, '||
         ' tempresas emp, '||
         ' VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f ';


  IF ((prpuxafiliais = 1) AND ((prcodemp IS NOT NULL) AND (prcodemp <> ''))) THEN
     BEGIN
       prcodemp = UPPER(prcodemp);

       IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ') INTO wwheren;
            prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
          END
       ELSE
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
          END
     END

  wwheren = ' where colcon.bdcodemp = x.bdcodemp and colcon.bdcodcol = x.bdcodcol and X.bdcodcla = f.bdcodcla and colcon.bdcodemp = emp.bdcodemp and COALESCE(COLCON.BDTAGFN,0) = 0 ';
  wwheret = ' where colcon.bdcodemp = x.bdcodemp and colcon.bdcodcol = x.bdcodcol and X.bdcodcla = f.bdcodcla and colcon.bdcodemp = emp.bdcodemp and COALESCE(COLCON.BDTAGFT,0) = 0 ';

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       wwheren = wwheren||' and '||prcodemp;
       wwheret = wwhereT||' and '||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       wwheren = wwheren||' and '||prcodcol;
       wwheret = wwhereT||' and '||prcodcol;
     END

  IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
     BEGIN
       wwheren = wwheren||'and COLCON.BDREFFN >= '||prrefini||' and '||'COLCON.BDREFFN <= '||prreffim;
       wwheret = wwhereT||'and COLCON.BDREFTOMADOR >= '||prrefini||' and '||'COLCON.BDREFTOMADOR <= '||prreffim;
     END
  ELSE
     BEGIN
       IF (prrefini IS NOT NULL) THEN
          BEGIN
            wwheren = wwheren||' and COLCON.BDREFFN = '||prrefini;
            wwheret = wwhereT||' and COLCON.BDREFTOMADOR = '||prrefini;
          END
       ELSE
          BEGIN
            IF (prreffim IS NOT NULL) THEN
               BEGIN
                 wwheren = wwheren||' and COLCON.BDREFFN = '||prreffim;
                 wwheret = wwhereT||' and COLCON.BDREFTOMADOR = '||prreffim;
               END
          END
     END

  wsql = wsql||wwheren;


  wsql = wsql||' union all '||
         'select f.bdgrupocla, colcon.BDCODEMP, colcon.BDCODCOL, colcon.BDREFFN, colcon.BDDATABAIXAFN, colcon.BDBFGTSFN,'||
         'colcon.BDFGTSFN, colcon.BDFGTSCSFN, colcon.BDBFGTS13FN, colcon.BDFGTS13FN, colcon.BDFGTS13CSFN, colcon.BDMAIORREMFN,'||
         'colcon.BDBINSSFN, colcon.BDALIQINSSFN, colcon.BDINSSFN, colcon.BDBIRRFFN, colcon.BDALIQIRRFFN, colcon.BDIRRFFN,'||
         'colcon.BDBINSS13FN, colcon.BDALIQINSS13FN, colcon.BDINSS13FN, colcon.BDBIRRF13FN, colcon.BDALIQIRRF13FN,'||
         'colcon.BDIRRF13FN, colcon.BDBSALFAMFN, colcon.BDSALFAMFN, colcon.BDBRAISFN, colcon.BDSALBASEFN, colcon.BDDEPFN,'||
         'colcon.BDBASEPISFN, colcon.BDBASEPISFEFN, colcon.BDBASEPIS13FN, colcon.BDBSALMATEMPFN, colcon.BDSALMATEMPFN, colcon.BDBRATAPOFN, colcon.BDBRATAPOFEFN, colcon.BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFN,'||
         'colcon.BDINSSFEFOLFN, colcon.BDALIQINSSFEFOLFN, colcon.bdcreditofn, COLCON.bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNFN,COLCON.BDBSALMATEMP13FN,COLCON.BDVSALMATEMPFNFN,COLCON.BDVSALMATEMP13FN, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFN, COLCON.BDINSSAPFN, COLCON.BDBINSS13APFN, COLCON.BDINSS13APFN, COLCON.BDCODCONTTI '||
         ' from vrhf_emp_tfolhaint COLCON, '||
         ' tempresas emp, '||
         ' VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f ';


  wsql = wsql||wwheren;


  IF ((prcodtpcc IS NULL) OR (prcodtpcc = '')) THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdGrupocla,
         :bdcodemp,
         :bdcodcol,
         :bdreffn,
         :bddatabaixafn,
         :bdbfgtsfn,
         :bdfgtsfn,
         :bdfgtscsfn,
         :bdbfgts13fn,
         :bdfgts13fn,
         :bdfgts13csfn,
         :bdmaiorremfn,
         :bdbinssfn,
         :bdaliqinssfn,
         :bdinssfn,
         :bdbirrffn,
         :bdaliqirrffn,
         :bdirrffn,
         :bdbinss13fn,
         :bdaliqinss13fn,
         :bdinss13fn,
         :bdbirrf13fn,
         :bdaliqirrf13fn,
         :bdirrf13fn,
         :bdbsalfamfn,
         :bdsalfamfn,
         :bdbraisfn,
         :bdsalbasefn,
         :bddepfn,
         :bdbasepisfn,
         :bdbasepisFEfn,
         :bdbasepis13fn,
         :bdbsalmatempfn,
         :bdsalmatempfn,
         :bdbratapofn,
         :bdbratapoFEfn,
         :bdbratapo13fn,
         :bdbinssfefolfn,
         :bdinssfefolfn,
         :bdaliqinssfefolfn,
         :bdcreditofn,
         :bddebitofn,
         :bdBFGTSFEFN,
         :BDFGTSFEFN,
         :BDBMATEMPFNFN,
         :BDBMATEMP13FN,
         :BDVMATEMPFNFN,
         :BDVMATEMP13FN,
         :BDLIQUIDOFN,
         :BDDATAPGTO,
         :BDBINSSAPFN,
         :BDINSSAPFN,
         :BDBINSS13APFN,
         :BDINSS13APFN,
         :BDCODCONTTI
       DO
         BEGIN
           bdcalctomador = 'False';

           if (bdcodcontti is null) then
              bdcodcontti = 0;
           SUSPEND;
         END
    END

  BDBMATEMPFNFN = 0;
  BDBMATEMP13FN = 0;
  BDVMATEMPFNFN = 0;
  BDVMATEMP13FN = 0;
  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.bdCodCentrotoma BDCODCENTRO, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.BDLIQUIDO), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) '||
              'from (';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdcodtpcctoma, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'pf.bdCodCentro bdcodcentro, pf.bdCODTPCC bdcodtpcc, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp)'||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdcodtpcctoma, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'pf.bdCodCentro bdcodcentro, pf.bdCODTPCC bdcodtpcc, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomint COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp)'||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret;



       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentroTOMA, COLCON.bdCODTPCCTOMA';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.BDCODCENTROTOMA bdCodCentro, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.Bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) '||
              'from ( ';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC BDCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC BDCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomint COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret;

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentrotoma,COLCON.bdCODTPCCtoma ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL,COLCON.BDCODCONTTI,COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT),sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) '||
              'from ( ';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT,COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(pf.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTRO, pf.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomador COLCON, tempresas emp, vrhf_emp_tprepfn pf, VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f '||
              wwheret||
                'and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
                'and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
                'and (X.bdcodcla = f.bdcodcla)';

       wsql = wsql||' union all '||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT,COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(pf.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTRO, pf.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomint COLCON, tempresas emp, vrhf_emp_tprepfn pf, VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f '||
              wwheret||
                'and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
                'and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
                'and (X.bdcodcla = f.bdcodcla)';

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||'group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentro, COLCON.bdCODTPCC ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL,COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT),'||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT),'||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT),'||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT),'||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT),'||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT),'||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT),'||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT),'||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT),'||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT),'||
                'cast(null as integer), cast(null as integer),'||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT),'||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT),'||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT),sum(COLCON.bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) '||
              'from (';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from '||
                'vrhf_emp_tfolhatomador COLCON, tempresas emp, '||
                'VW_VRH_EMP_TCOLCON_VINC X, '||
                'VRH_BASE_TCLASSE f, '||
                'vrhf_emp_tprepfn pf '||
              wwheret||
                'and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
                'and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
                'and (f.BDCODCLA = X.BDCODCLA)';

       wsql = wsql||' union all '||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from '||
                'vrhf_emp_tfolhatomint COLCON, tempresas emp, '||
                'VW_VRH_EMP_TCOLCON_VINC X, '||
                'VRH_BASE_TCLASSE f, '||
                'vrhf_emp_tprepfn pf '||
              wwheret||
                'and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
                'and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
                'and (f.BDCODCLA = X.BDCODCLA)';

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI,COLCON.BDREFTOMADOR, COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, '||
                'COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT, '||
                'COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, COLCON.BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from ( ';

          wsql = wsql||'select '||
                 'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI,COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT,'||
                 'COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT,'||
                 'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                 'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT,'||
                 'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT,'||
                 'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, pf.bdCodCentro, pf.bdCODTPCC,'||
                 'colcon.bdCreditoFT, colcon.bdDebitoFT,'||
                 'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                 'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                 'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
                 ' from vrhf_emp_tfolhatomador COLCON, tempresas emp, vrhf_emp_tprepfn pf, VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f '||
                 wwheret||
                 ' and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem)'||
                 ' and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol)'||
                 ' and (X.bdcodcla = f.bdcodcla)';

          wsql = wsql||'union all select '||
                 'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI,COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT,'||
                 'COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT,'||
                 'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                 'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT,'||
                 'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT,'||
                 'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, pf.bdCodCentro, pf.bdCODTPCC,'||
                 'colcon.bdCreditoFT, colcon.bdDebitoFT,'||
                 'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                 'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                 'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
                 ' from vrhf_emp_tfolhatomint COLCON, tempresas emp, vrhf_emp_tprepfn pf, VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f '||
                 wwheret||
                 ' and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem)'||
                 ' and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol)'||
                 ' and (X.bdcodcla = f.bdcodcla)';

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;
     END

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdgrupocla,
    :bdcodemp, --BDCODEMP,
    :bdcodcol, -- BDCODCOL,
    :bdcodcontti, 
    :bdreffn, -- BDREFTOMADOR,
    :bdordem, -- BDORDEM,
    :bddatabaixafn, -- BDDATABAIXAFT,
    :bdbfgtsfn, -- BDBFGTSFT,
    :bdfgtsfn, -- BDFGTSFT,
    :bdfgtscsfn, -- BDFGTSCSFT,
    :bdbfgts13fn, --- BDBFGTS13FT,
    :bdfgts13fn, -- BDFGTS13FT,
    :bdfgts13csfn, -- BDFGTS13CSFT,'||
    :bdmaiorremfn, -- 'BDMAIORREMFT,
    :bdbinssfn, -- BDBINSSFT,
    :bdaliqinssfn, -- BDALIQINSSFT,
    :bdinssfn, -- BDINSSFT,
    :bdbirrffn, -- BDBIRRFFT,
    :bdaliqirrffn, -- BDALIQIRRFFT,
    :bdirrffn, -- BDIRRFFT,
    :bdbinss13fn, -- BDBINSS13FT,
    :bdaliqinss13fn, -- BDALIQINSS13FT,
    :bdinss13fn, -- BDINSS13FT,'||
    :bdbirrf13fn, -- 'BDBIRRF13FT,
    :bdaliqirrf13fn, -- BDALIQIRRF13FT,
    :bdirrf13fn, -- BDIRRF13FT,
    :bdbsalfamfn, -- BDBSALFAMFT,
    :bdsalfamfn, --BDSALFAMFT,
    :bdbraisfn, -- BDBRAISFT,
    :bdsalbasefn, -- BDSALBASEFT,
    :bddepfn, -- BDDEPFT,
    :bdbasepisfn, -- BDBASEPISFT,
    :bdbasepisFEfn, -- BDBASEPISFEFT,
    :bdbasepis13fn, -- BDBASEPIS13FT,
    :bdbsalmatempfn, -- BDBSALMATEMPFT,'||
    :bdsalmatempfn, -- 'BDSALMATEMPFT,
    :bdbratapofn, -- BDBRATAPOFT,
    :bdbratapoFEfn, -- BDBRATAPOFEFT,
    :bdbratapo13fn, -- BDBRATAPO13FT,
    :bdbinssfefolfn, -- BDBINSSFEFOLFT,
    :bdinssfefolfn, -- BDALIQINSSFEFOLFT'||
    :bdaliqinssfefolfn, -- BDINSSFEFOLFT,
    :bdCodCentro, -- bdCodCentro
    :bdCODTPCC, -- BDCODTPCC
    :bdcreditofn,
    :bddebitofn,
    :bdBFGTSFEFN,
    :BDFGTSFEFN,
    :BDBMATEMPFNFN,
    :BDBMATEMP13FN,
    :BDVMATEMPFNFN,
    :BDVMATEMP13FN,
    :BDLIQUIDOFN,
    :BDDATAPGTO,
    :BDBINSSAPFN,
    :BDINSSAPFN,
    :BDBINSS13APFN,
    :BDINSS13APFN
  DO
    BEGIN
      bdcalctomador = 'True';
      if (bdcodcontti is null) then
         bdcodcontti = 0;
      SUSPEND;
    END
END
^

/* Alter (VRHF_SP_TFOLHA_NORMAL_PREV_RESC) */
ALTER PROCEDURE VRHF_SP_TFOLHA_NORMAL_PREV_RESC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = NULL)
 RETURNS(BDGRUPOCLA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDREFFN INTEGER,
BDDATABAIXAFN DATE,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDBASEPISFEFN NUMERIC(15,6),
BDBASEPIS13FN NUMERIC(15,6),
BDBSALMATEMPFN NUMERIC(15,6),
BDSALMATEMPFN NUMERIC(15,6),
BDBRATAPOFN NUMERIC(15,6),
BDBRATAPOFEFN NUMERIC(15,6),
BDBRATAPO13FN NUMERIC(15,6),
BDBINSSFEFOLFN NUMERIC(15,6),
BDINSSFEFOLFN NUMERIC(15,6),
BDALIQINSSFEFOLFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCREDITOFN NUMERIC(15,6),
BDDEBITOFN NUMERIC(15,6),
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6),
BDBMATEMPFNFN NUMERIC(15,6),
BDBMATEMP13FN NUMERIC(15,6),
BDVMATEMPFNFN NUMERIC(15,6),
BDVMATEMP13FN NUMERIC(15,6),
BDLIQUIDOFN NUMERIC(18,6),
BDDATAPGTO DATE,
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHEREN VARCHAR(32700);
DECLARE VARIABLE WWHERET VARCHAR(32700);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  /* Procedure Text */
  wsql = 'select f.bdgrupocla, colcon.BDCODEMP, colcon.BDCODCOL, prevresc.bdrefrescisaoprev, colcon.BDDATABAIXAFNPR, colcon.BDBFGTSFNPR,'||
         'colcon.BDFGTSFNPR, colcon.BDFGTSCSFNPR, colcon.BDBFGTS13FNPR, colcon.BDFGTS13FNPR, colcon.BDFGTS13CSFNPR, colcon.BDMAIORREMFNPR,'||
         'colcon.BDBINSSFNPR, colcon.BDALIQINSSFNPR, colcon.BDINSSFNPR, colcon.BDBIRRFFNPR, colcon.BDALIQIRRFFNPR, colcon.BDIRRFFNPR,'||
         'colcon.BDBINSS13FNPR, colcon.BDALIQINSS13FNPR, colcon.BDINSS13FNPR, colcon.BDBIRRF13FNPR, colcon.BDALIQIRRF13FNPR,'||
         'colcon.BDIRRF13FNPR, colcon.BDBSALFAMFNPR, colcon.BDSALFAMFNPR, colcon.BDBRAISFNPR, colcon.BDSALBASEFNPR, colcon.BDDEPFNPR,'||
         'colcon.BDBASEPISFNPR, 0 BDBASEPISFEFN, 0 BDBASEPIS13FN, colcon.BDBSALMATEMPFNPR, colcon.BDSALMATEMPFNPR, colcon.BDBRATAPOFNPR, 0 BDBRATAPOFEFN, 0 BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFNPR,'||
         'colcon.BDINSSFEFOLFNPR, colcon.BDALIQINSSFEFOLFNPR, 0 bdcreditofn, 0 bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNPR,0 BDBSALMATEMP13FN,COLCON.BDSALMATEMPFNPR, 0 BDVSALMATEMP13FN, 0 BDLIQUIDO, CAST(null as DATE) BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFNPR, COLCON.BDINSSAPFNPR, COLCON.BDBINSS13APFNPR, COLCON.BDINSS13APFNPR '||
         ' from vrhf_emp_tfolhanormal_prev_resc COLCON, '||
         ' vrh_emp_trescisao_previa prevresc, '||
         ' tempresas emp, '||
         ' VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f ';


  IF ((prpuxafiliais = 1) AND ((prcodemp IS NOT NULL) AND (prcodemp <> ''))) THEN
     BEGIN
       prcodemp = UPPER(prcodemp);

       IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ') INTO wwheren;
            prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
          END
       ELSE
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
          END
     END

  wwheren = ' where colcon.bdcodemp = x.bdcodemp and colcon.bdcodcol = x.bdcodcol and X.bdcodcla = f.bdcodcla and colcon.bdcodemp = emp.bdcodemp and colcon.bdcodemp = prevresc.bdcodemp and colcon.bdcodcol = prevresc.bdcodcol ';
  wwheret = ' where colcon.bdcodemp = x.bdcodemp and colcon.bdcodcol = x.bdcodcol and X.bdcodcla = f.bdcodcla and colcon.bdcodemp = emp.bdcodemp and colcon.bdcodemp = prevresc.bdcodemp and colcon.bdcodcol = prevresc.bdcodcol ';

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       wwheren = wwheren||' and '||prcodemp;
       wwheret = wwhereT||' and '||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       wwheren = wwheren||' and '||prcodcol;
       wwheret = wwhereT||' and '||prcodcol;
     END

  IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
     BEGIN
       wwheren = wwheren||'and prevresc.BDREFRESCISAOPREV >= '||prrefini||' and '||'prevresc.BDREFRESCISAOPREV <= '||prreffim;
       wwheret = wwhereT||'and prevresc.BDREFRESCISAOPREV >= '||prrefini||' and '||'prevresc.BDREFRESCISAOPREV <= '||prreffim;
     END
  ELSE
     BEGIN
       IF (prrefini IS NOT NULL) THEN
          BEGIN
            wwheren = wwheren||' and prevresc.BDREFRESCISAOPREV= '||prrefini;
            wwheret = wwhereT||' and prevresc.BDREFRESCISAOPREV = '||prrefini;
          END
       ELSE
          BEGIN
            IF (prreffim IS NOT NULL) THEN
               BEGIN
                 wwheren = wwheren||' and prevresc.BDREFRESCISAOPREV = '||prreffim;
                 wwheret = wwhereT||' and prevresc.BDREFRESCISAOPREV = '||prreffim;
               END
          END
     END

  IF ((prcodtpcc IS NULL) OR (prcodtpcc = '')) THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql||wwheren
       INTO
         :bdGrupocla,
         :bdcodemp,
         :bdcodcol,
         :bdreffn,
         :bddatabaixafn,
         :bdbfgtsfn,
         :bdfgtsfn,
         :bdfgtscsfn,
         :bdbfgts13fn,
         :bdfgts13fn,
         :bdfgts13csfn,
         :bdmaiorremfn,
         :bdbinssfn,
         :bdaliqinssfn,
         :bdinssfn,
         :bdbirrffn,
         :bdaliqirrffn,
         :bdirrffn,
         :bdbinss13fn,
         :bdaliqinss13fn,
         :bdinss13fn,
         :bdbirrf13fn,
         :bdaliqirrf13fn,
         :bdirrf13fn,
         :bdbsalfamfn,
         :bdsalfamfn,
         :bdbraisfn,
         :bdsalbasefn,
         :bddepfn,
         :bdbasepisfn,
         :bdbasepisFEfn,
         :bdbasepis13fn,
         :bdbsalmatempfn,
         :bdsalmatempfn,
         :bdbratapofn,
         :bdbratapoFEfn,
         :bdbratapo13fn,
         :bdbinssfefolfn,
         :bdinssfefolfn,
         :bdaliqinssfefolfn,
         :bdcreditofn,
         :bddebitofn,
         :bdBFGTSFEFN,
         :BDFGTSFEFN,
         :BDBMATEMPFNFN,
         :BDBMATEMP13FN,
         :BDVMATEMPFNFN,
         :BDVMATEMP13FN,
         :BDLIQUIDOFN,
         :BDDATAPGTO,
         :BDBINSSAPFN,
         :BDINSSAPFN,
         :BDBINSS13APFN,
         :BDINSS13APFN
       DO
         BEGIN
           bdcalctomador = 'False';
           SUSPEND;
         END
    END

  BDBMATEMPFNFN = 0;
  BDBMATEMP13FN = 0;
  BDVMATEMPFNFN = 0;
  BDVMATEMP13FN = 0;
  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFTPR), '||
                'sum(COLCON.BDFGTSFTPR), sum(COLCON.BDFGTSCSFTPR), sum(COLCON.BDBFGTS13FTPR), sum(COLCON.BDFGTS13FTPR), '||
                'sum(COLCON.BDFGTS13CSFTPR),sum(COLCON.BDMAIORREMFTPR), sum(COLCON.BDBINSSFTPR), max(COLCON.BDALIQINSSFTPR), '||
                'sum(COLCON.BDINSSFTPR), sum(COLCON.BDBIRRFFTPR), max(COLCON.BDALIQIRRFFTPR), sum(COLCON.BDIRRFFTPR), '||
                'sum(COLCON.BDBINSS13FTPR), max(COLCON.BDALIQINSS13FTPR), sum(COLCON.BDINSS13FTPR), '||
                'sum(COLCON.BDBIRRF13FTPR), max(COLCON.BDALIQIRRF13FTPR), sum(COLCON.BDIRRF13FTPR), sum(COLCON.BDBSALFAMFTPR), '||
                'sum(COLCON.BDSALFAMFTPR), sum(COLCON.BDBRAISFTPR), max(COLCON.BDSALBASEFTPR), '||
                'sum(COLCON.BDDEPFTPR), sum(COLCON.BDBASEPISFTPR), sum(COLCON.BDBASEPISFEFTPR), sum(COLCON.BDBASEPIS13FTPR), sum(COLCON.BDBSALMATEMPFTPR), '||
                'sum(COLCON.BDSALMATEMPFTPR), sum(COLCON.BDBRATAPOFTPR), sum(COLCON.BDBRATAPOFEFTPR), sum(COLCON.BDBRATAPO13FTPR), '||
                'sum(COLCON.BDBINSSFEFOLFTPR), sum(COLCON.BDINSSFEFOLFTPR), max(COLCON.BDALIQINSSFEFOLFTPR), '||
                'COLCON.bdCodCentrotoma BDCODCENTRO, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFTPR), sum(colcon.bdDebitoFTPR), '||
                'sum(colcon.bdBFGTSFEFTPR), sum(COLCON.BDFGTSFEFTPR), '||
                'sum(colcon.BDBSALMATEMPFNFTPR),sum(colcon.BDBSALMATEMP13FTPR),sum(colcon.BDVSALMATEMPFNFTPR),sum(colcon.BDVSALMATEMP13FTPR), sum(COLCON.BDLIQUIDOFTPR), MAX(COLCON.BDDATAPGTOFTPR), '||
                'sum(COLCON.BDBINSSAPFTPR), sum(COLCON.BDINSSAPFTPR), sum(COLCON.BDBINSS13APFTPR), sum(COLCON.BDINSS13APFTPR) '||
              'from (';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDBFGTSFTPR, '||
                'COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, '||
                'COLCON.BDFGTS13CSFTPR,COLCON.BDMAIORREMFTPR, COLCON.BDBINSSFTPR, COLCON.BDALIQINSSFTPR, '||
                'COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                'COLCON.BDBINSS13FTPR, COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, '||
                'COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, '||
                'COLCON.BDDEPFTPR, COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, '||
                'pf.bdCodCentro bdcodcentrotoma, toma.bdCODTPCC bdcodtpcctoma, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR, 0 BDVSALMATEMP13FTPR, '||
                'pf.bdCodCentro bdcodcentro, pf.bdCODTPCC bdcodtpcc, COLCON.BDLIQUIDOFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from vrhf_emp_tfoltom_prev_resc COLCON '||
              ' join vrh_emp_trescisao_previa prevresc on (prevresc.bdcodemp = colcon.bdcodemp and prevresc.bdcodcol = colcon.bdcodcol) '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp)'||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFRESCISAOPREV,COLCON.bdCodCentroTOMA, COLCON.bdCODTPCCTOMA';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFTPR), '||
                'sum(COLCON.BDFGTSFTPR), sum(COLCON.BDFGTSCSFTPR), sum(COLCON.BDBFGTS13FTPR), sum(COLCON.BDFGTS13FTPR), '||
                'sum(COLCON.BDFGTS13CSFTPR),sum(COLCON.BDMAIORREMFTPR), sum(COLCON.BDBINSSFTPR), max(COLCON.BDALIQINSSFTPR), '||
                'sum(COLCON.BDINSSFTPR), sum(COLCON.BDBIRRFFTPR), max(COLCON.BDALIQIRRFFTPR), sum(COLCON.BDIRRFFTPR), '||
                'sum(COLCON.BDBINSS13FTPR), max(COLCON.BDALIQINSS13FTPR), sum(COLCON.BDINSS13FTPR), '||
                'sum(COLCON.BDBIRRF13FTPR), max(COLCON.BDALIQIRRF13FTPR), sum(COLCON.BDIRRF13FTPR), sum(COLCON.BDBSALFAMFTPR), '||
                'sum(COLCON.BDSALFAMFTPR), sum(COLCON.BDBRAISFTPR), max(COLCON.BDSALBASEFTPR), '||
                'sum(COLCON.BDDEPFTPR), sum(COLCON.BDBASEPISFTPR), sum(COLCON.BDBASEPISFEFTPR), sum(COLCON.BDBASEPIS13FTPR), sum(COLCON.BDBSALMATEMPFTPR), '||
                'sum(COLCON.BDSALMATEMPFTPR), sum(COLCON.BDBRATAPOFTPR), sum(COLCON.BDBRATAPOFEFTPR), sum(COLCON.BDBRATAPO13FTPR), '||
                'sum(COLCON.BDBINSSFEFOLFTPR), sum(COLCON.BDINSSFEFOLFTPR), max(COLCON.BDALIQINSSFEFOLFTPR), '||
                'COLCON.BDCODCENTROTOMA bdCodCentro, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFTPR), sum(colcon.bdDebitoFTPR), '||
                'sum(colcon.bdBFGTSFEFTPR), sum(COLCON.BDFGTSFEFTPR), '||
                'sum(colcon.BDBSALMATEMPFNFTPR),sum(colcon.BDBSALMATEMP13FTPR),sum(colcon.BDVSALMATEMPFNFTPR),sum(colcon.BDVSALMATEMP13FTPR), sum(COLCON.BdliquidoFTPR), MAX(COLCON.BDDATAPGTOFTPR), '||
                'sum(COLCON.BDBINSSAPFTPR), sum(COLCON.BDINSSAPFTPR), sum(COLCON.BDBINSS13APFTPR), sum(COLCON.BDINSS13APFTPR) '||
              'from ( ';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDBFGTSFTPR, '||
                'COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, '||
                'COLCON.BDFGTS13CSFTPR,COLCON.BDMAIORREMFTPR, COLCON.BDBINSSFTPR, COLCON.BDALIQINSSFTPR, '||
                'COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                'COLCON.BDBINSS13FTPR, COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, '||
                'COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, '||
                'COLCON.BDDEPFTPR, COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, '||
                'pf.bdCodCentro bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, pf.BDCODCENTRO BDCODCENTRO, pf.BDCODTPCC BDCODTPCC, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR,0 BDVSALMATEMP13FTPR, COLCON.bdliquidoFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from vrhf_emp_tfoltom_prev_resc COLCON '||
              ' join vrh_emp_trescisao_previa prevresc on (prevresc.bdcodemp = colcon.bdcodemp and prevresc.bdcodcol = colcon.bdcodcol) '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFRESCISAOPREV,COLCON.bdCodCentrotoma,COLCON.bdCODTPCCtoma ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFTPR), '||
                'sum(COLCON.BDFGTSFTPR), sum(COLCON.BDFGTSCSFTPR), sum(COLCON.BDBFGTS13FTPR), sum(COLCON.BDFGTS13FTPR), '||
                'sum(COLCON.BDFGTS13CSFTPR),sum(COLCON.BDMAIORREMFTPR), sum(COLCON.BDBINSSFTPR), max(COLCON.BDALIQINSSFTPR), '||
                'sum(COLCON.BDINSSFTPR), sum(COLCON.BDBIRRFFTPR), max(COLCON.BDALIQIRRFFTPR), sum(COLCON.BDIRRFFTPR), '||
                'sum(COLCON.BDBINSS13FTPR), max(COLCON.BDALIQINSS13FTPR), sum(COLCON.BDINSS13FTPR), '||
                'sum(COLCON.BDBIRRF13FTPR), max(COLCON.BDALIQIRRF13FTPR), sum(COLCON.BDIRRF13FTPR), sum(COLCON.BDBSALFAMFTPR), '||
                'sum(COLCON.BDSALFAMFTPR), sum(COLCON.BDBRAISFTPR), max(COLCON.BDSALBASEFTPR), '||
                'sum(COLCON.BDDEPFTPR), sum(COLCON.BDBASEPISFTPR), sum(COLCON.BDBASEPISFEFTPR), sum(COLCON.BDBASEPIS13FTPR), sum(COLCON.BDBSALMATEMPFTPR), '||
                'sum(COLCON.BDSALMATEMPFTPR), sum(COLCON.BDBRATAPOFTPR),sum(COLCON.BDBRATAPOFEFTPR), sum(COLCON.BDBRATAPO13FTPR), '||
                'sum(COLCON.BDBINSSFEFOLFTPR), sum(COLCON.BDINSSFEFOLFTPR), max(COLCON.BDALIQINSSFEFOLFTPR), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'sum(colcon.bdCreditoFTPR), sum(colcon.bdDebitoFTPR), '||
                'sum(colcon.bdBFGTSFEFTPR), sum(COLCON.BDFGTSFEFTPR), '||
                'sum(colcon.BDBSALMATEMPFNFTPR),sum(colcon.BDBSALMATEMP13FTPR),sum(colcon.BDVSALMATEMPFNFTPR),sum(colcon.BDVSALMATEMP13FTPR), sum(COLCON.bdliquidoFTPR), MAX(COLCON.BDDATAPGTOFTPR), '||
                'sum(COLCON.BDBINSSAPFTPR), sum(COLCON.BDINSSAPFTPR), sum(COLCON.BDBINSS13APFTPR), sum(COLCON.BDINSS13APFTPR) '||
              'from ( ';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDBFGTSFTPR, '||
                'COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, '||
                'COLCON.BDFGTS13CSFTPR,COLCON.BDMAIORREMFTPR, COLCON.BDBINSSFTPR, COLCON.BDALIQINSSFTPR, '||
                'COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                'COLCON.BDBINSS13FTPR, COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, '||
                'COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, '||
                'COLCON.BDDEPFTPR, COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR,COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, '||
                'pf.bdCodCentro, pf.bdCODTPCC, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR,0 BDVSALMATEMP13FTPR, COLCON.bdliquidoFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from vrhf_emp_tfoltom_prev_resc COLCON, vrh_emp_trescisao_previa prevresc, tempresas emp, vrhf_emp_tprepfn pf, VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f '||
              wwheret||
                'and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
                'and (colcon.bdcodemp = prevresc.bdcodemp and colcon.bdcodcol = prevresc.bdcodcol) '||
                'and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
                'and (X.bdcodcla = f.bdcodcla))  COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||'group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFRESCISAOPREV,COLCON.bdCodCentro, COLCON.bdCODTPCC ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFTPR),'||
                'sum(COLCON.BDFGTSFTPR), sum(COLCON.BDFGTSCSFTPR), sum(COLCON.BDBFGTS13FTPR), sum(COLCON.BDFGTS13FTPR),'||
                'sum(COLCON.BDFGTS13CSFTPR),sum(COLCON.BDMAIORREMFTPR), sum(COLCON.BDBINSSFTPR), max(COLCON.BDALIQINSSFTPR),'||
                'sum(COLCON.BDINSSFTPR), sum(COLCON.BDBIRRFFTPR), max(COLCON.BDALIQIRRFFTPR), sum(COLCON.BDIRRFFTPR),'||
                'sum(COLCON.BDBINSS13FTPR), max(COLCON.BDALIQINSS13FTPR), sum(COLCON.BDINSS13FTPR),'||
                'sum(COLCON.BDBIRRF13FTPR), max(COLCON.BDALIQIRRF13FTPR), sum(COLCON.BDIRRF13FTPR), sum(COLCON.BDBSALFAMFTPR),'||
                'sum(COLCON.BDSALFAMFTPR), sum(COLCON.BDBRAISFTPR), max(COLCON.BDSALBASEFTPR),'||
                'sum(COLCON.BDDEPFTPR), sum(COLCON.BDBASEPISFTPR), sum(COLCON.BDBASEPISFEFTPR), sum(COLCON.BDBASEPIS13FTPR), sum(COLCON.BDBSALMATEMPFTPR),'||
                'sum(COLCON.BDSALMATEMPFTPR), sum(COLCON.BDBRATAPOFTPR), sum(COLCON.BDBRATAPOFEFTPR), sum(COLCON.BDBRATAPO13FTPR),'||
                'sum(COLCON.BDBINSSFEFOLFTPR), sum(COLCON.BDINSSFEFOLFTPR), max(COLCON.BDALIQINSSFEFOLFTPR),'||
                'cast(null as integer), cast(null as integer),'||
                'sum(colcon.bdCreditoFTPR), sum(colcon.bdDebitoFTPR),'||
                'sum(colcon.bdBFGTSFEFTPR), sum(COLCON.BDFGTSFEFTPR),'||
                'sum(colcon.BDBSALMATEMPFNFTPR),sum(colcon.BDBSALMATEMP13FTPR),sum(colcon.BDVSALMATEMPFNFTPR),sum(colcon.BDVSALMATEMP13FTPR),sum(COLCON.bdliquidoFTPR), MAX(COLCON.BDDATAPGTOFTPR), '||
                'sum(COLCON.BDBINSSAPFTPR), sum(COLCON.BDINSSAPFTPR), sum(COLCON.BDBINSS13APFTPR), sum(COLCON.BDINSS13APFTPR) '||
              'from (';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDBFGTSFTPR, '||
                'COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, '||
                'COLCON.BDFGTS13CSFTPR,COLCON.BDMAIORREMFTPR, COLCON.BDBINSSFTPR, COLCON.BDALIQINSSFTPR, '||
                'COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                'COLCON.BDBINSS13FTPR, COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, '||
                'COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, '||
                'COLCON.BDDEPFTPR, COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR, 0 BDVSALMATEMP13FTPR, '||
                'pf.BDCODCENTRO, pf.BDCODTPCC, COLCON.bdliquidoFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from '||
                'vrhf_emp_tfoltom_prev_resc COLCON, vrh_emp_trescisao_previa prevresc, tempresas emp, '||
                'VW_VRH_EMP_TCOLCON_VINC X, '||
                'VRH_BASE_TCLASSE f, '||
                'vrhf_emp_tprepfn pf '||
              wwheret||
                'and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
                'and (colcon.bdcodemp = prevresc.bdcodemp and colcon.bdcodcol = prevresc.bdcodcol) '||
                'and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
                'and (f.BDCODCLA = X.BDCODCLA)) COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFRESCISAOPREV ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, COLCON.BDORDEM, COLCON.BDDATABAIXAFTPR, COLCON.BDBFGTSFTPR, COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, '||
                'COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, COLCON.BDFGTS13CSFTPR, '||
                'COLCON.BDMAIORREMFTPR, COLCON.BDBINSSFTPR, COLCON.BDALIQINSSFTPR, COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, COLCON.BDBINSS13FTPR, '||
                'COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, COLCON.BDDEPFTPR, '||
                'COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                'colcon.BDBSALMATEMPFNFTPR,colcon.BDBSALMATEMP13FTPR,colcon.BDVSALMATEMPFNFTPR,colcon.BDVSALMATEMP13FTPR, COLCON.bdliquidoFTPR, COLCON.BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from ( ';

          wsql = wsql||'select '||
                 'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDORDEM, COLCON.BDDATABAIXAFTPR, COLCON.BDBFGTSFTPR, COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, COLCON.BDFGTS13CSFTPR,'||
                 'COLCON.BDMAIORREMFTPR, COLCON.BDBINSSFTPR, COLCON.BDALIQINSSFTPR, COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, COLCON.BDBINSS13FTPR, COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR,'||
                 'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, COLCON.BDDEPFTPR, '||
                 'COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR,'||
                 'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR,'||
                 'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, pf.bdCodCentro, pf.bdCODTPCC,'||
                 'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR,'||
                 'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                 '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR,0 BDVSALMATEMP13FTPR, COLCON.bdliquidoFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                 'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
                 ' from vrhf_emp_tfoltom_prev_resc COLCON, vrh_emp_trescisao_previa prevresc, tempresas emp, vrhf_emp_tprepfn pf, VW_VRH_EMP_TCOLCON_VINC X, VRH_BASE_TCLASSE f '||
                 wwheret||
                 ' and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem)'||
                 ' and (colcon.bdcodemp = prevresc.bdcodemp and colcon.bdcodcol = prevresc.bdcodcol) '||
                 ' and (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol)'||
                 ' and (X.bdcodcla = f.bdcodcla)) COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;
     END

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdgrupocla,
    :bdcodemp, --BDCODEMP,
    :bdcodcol, -- BDCODCOL,
    :bdreffn, -- BDREFTOMADOR,
    :bdordem, -- BDORDEM,
    :bddatabaixafn, -- BDDATABAIXAFT,
    :bdbfgtsfn, -- BDBFGTSFT,
    :bdfgtsfn, -- BDFGTSFT,
    :bdfgtscsfn, -- BDFGTSCSFT,
    :bdbfgts13fn, --- BDBFGTS13FT,
    :bdfgts13fn, -- BDFGTS13FT,
    :bdfgts13csfn, -- BDFGTS13CSFT,'||
    :bdmaiorremfn, -- 'BDMAIORREMFT,
    :bdbinssfn, -- BDBINSSFT,
    :bdaliqinssfn, -- BDALIQINSSFT,
    :bdinssfn, -- BDINSSFT,
    :bdbirrffn, -- BDBIRRFFT,
    :bdaliqirrffn, -- BDALIQIRRFFT,
    :bdirrffn, -- BDIRRFFT,
    :bdbinss13fn, -- BDBINSS13FT,
    :bdaliqinss13fn, -- BDALIQINSS13FT,
    :bdinss13fn, -- BDINSS13FT,'||
    :bdbirrf13fn, -- 'BDBIRRF13FT,
    :bdaliqirrf13fn, -- BDALIQIRRF13FT,
    :bdirrf13fn, -- BDIRRF13FT,
    :bdbsalfamfn, -- BDBSALFAMFT,
    :bdsalfamfn, --BDSALFAMFT,
    :bdbraisfn, -- BDBRAISFT,
    :bdsalbasefn, -- BDSALBASEFT,
    :bddepfn, -- BDDEPFT,
    :bdbasepisfn, -- BDBASEPISFT,
    :bdbasepisFEfn, -- BDBASEPISFEFT,
    :bdbasepis13fn, -- BDBASEPIS13FT,
    :bdbsalmatempfn, -- BDBSALMATEMPFT,'||
    :bdsalmatempfn, -- 'BDSALMATEMPFT,
    :bdbratapofn, -- BDBRATAPOFT,
    :bdbratapoFEfn, -- BDBRATAPOFEFT,
    :bdbratapo13fn, -- BDBRATAPO13FT,
    :bdbinssfefolfn, -- BDBINSSFEFOLFT,
    :bdinssfefolfn, -- BDALIQINSSFEFOLFT'||
    :bdaliqinssfefolfn, -- BDINSSFEFOLFT,
    :bdCodCentro, -- bdCodCentro
    :bdCODTPCC, -- BDCODTPCC
    :bdcreditofn,
    :bddebitofn,
    :bdBFGTSFEFN,
    :BDFGTSFEFN,
    :BDBMATEMPFNFN,
    :BDBMATEMP13FN,
    :BDVMATEMPFNFN,
    :BDVMATEMP13FN,
    :BDLIQUIDOFN,
    :BDDATAPGTO,
    :BDBINSSAPFN,
    :BDINSSAPFN,
    :BDBINSS13APFN,
    :BDINSS13APFN
  DO
    BEGIN
      bdcalctomador = 'True';
      SUSPEND;
    END
END
^

/* Alter (VRHF_SP_TFOLHACOMP) */
ALTER PROCEDURE VRHF_SP_TFOLHACOMP(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(28000),
PRREFINICOMP INTEGER,
PRREFFIMCOMP INTEGER,
PRREFINIPAG INTEGER,
PRREFFIMPAG INTEGER,
PRAGRUPATOMADOR INTEGER,
PRTIPOFC INTEGER = 0,
PRSEPARCALC INTEGER = 0,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDREFFN INTEGER,
BDREFFC INTEGER,
BDREFCOMP INTEGER,
BDDATAPAGFC DATE,
BDDATABAIXAFC DATE,
BDBFGTSFC NUMERIC(15,6),
BDFGTSFC NUMERIC(15,6),
BDFGTSCSFC NUMERIC(15,6),
BDBFGTS13FC NUMERIC(15,6),
BDFGTS13FC NUMERIC(15,6),
BDFGTS13CSFC NUMERIC(15,6),
BDMAIORREMFC NUMERIC(15,6),
BDBINSSFC NUMERIC(15,6),
BDALIQINSSFC NUMERIC(15,6),
BDINSSFC NUMERIC(15,6),
BDBIRRFFC NUMERIC(15,6),
BDALIQIRRFFC NUMERIC(15,6),
BDIRRFFC NUMERIC(15,6),
BDBINSS13FC NUMERIC(15,6),
BDALIQINSS13FC NUMERIC(15,6),
BDINSS13FC NUMERIC(15,6),
BDBIRRF13FC NUMERIC(15,6),
BDALIQIRRF13FC NUMERIC(15,6),
BDIRRF13FC NUMERIC(15,6),
BDBSALFAMFC NUMERIC(15,6),
BDSALFAMFC NUMERIC(15,6),
BDBRAISFC NUMERIC(15,6),
BDSALBASEFC NUMERIC(15,6),
BDDEPFC NUMERIC(15,6),
BDBASEPISFC NUMERIC(15,6),
BDBASEPISFEFC NUMERIC(15,6),
BDBASEPIS13FC NUMERIC(15,6),
BDBSALMATEMPFC NUMERIC(15,6),
BDSALMATEMPFC NUMERIC(15,6),
BDBRATAPOFC NUMERIC(15,6),
BDBRATAPOFEFC NUMERIC(15,6),
BDBRATAPO13FC NUMERIC(15,6),
BDBINSSFEFOLFC NUMERIC(15,6),
BDINSSFEFOLFC NUMERIC(15,6),
BDALIQINSSFEFOLFC NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFEFC NUMERIC(15,6),
BDFGTSFEFC NUMERIC(15,6),
BDCODTIPOFC INTEGER,
BDBINSSMVFC NUMERIC(18,6),
BDBINSSMV13FC NUMERIC(18,6),
BDINSSMVFC NUMERIC(18,6),
BDINSSMV13FC NUMERIC(18,6),
BDBINSSAPFC NUMERIC(18,6),
BDBINSS13APFC NUMERIC(18,6),
BDINSSAPFC NUMERIC(18,6),
BDINSS13APFC NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDINSSFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDLIQUIDOFC NUMERIC(18,6),
BDDATAGRRF DATE)
 AS
DECLARE VARIABLE WDATAPAG VARCHAR(50);
DECLARE VARIABLE WORDEMDATAPAG VARCHAR(50);
DECLARE VARIABLE WAUXWHERETOM VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHEREN VARCHAR(32700);
DECLARE VARIABLE WWHERET VARCHAR(32000);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
     5 = Agrupa por calculo
  */

  IF (prpuxafiliais = 1) THEN
     BEGIN
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            prcodemp = UPPER(prcodemp);
     
            IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ') INTO wwheren;
                 prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
               END
            ELSE
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
               END
          END
     END

  /* Procedure Text */
  wsql = 'select COLCON.bdcodemp,'||
         ' COLCON.BDCODEMP,'||
         ' COLCON.BDCODCOL,'||
         ' COLCON.BDREFFN,'||
         ' COLCON.BDREFCOMP,'||
         ' COLCON.BDDATAPAGFC,'||
         ' COLCON.BDDATABAIXAFC,'||
         ' COLCON.BDBFGTSFC,'||
         ' COLCON.BDFGTSFC,'||
         ' COLCON.BDFGTSCSFC,'||
         ' COLCON.BDBFGTS13FC,'||
         ' COLCON.BDFGTS13FC,'||
         ' COLCON.BDFGTS13CSFC,'||
         ' COLCON.BDMAIORREMFC,'||
         ' COLCON.BDBINSSFC,'||
         ' COLCON.BDALIQINSSFC,'||
         ' COLCON.BDINSSFC,'||
         ' COLCON.BDBIRRFFC,'||
         ' COLCON.BDALIQIRRFFC,'||
         ' COLCON.BDIRRFFC,'||
         ' COLCON.BDBINSS13FC,'||
         ' COLCON.BDALIQINSS13FC,'||
         ' COLCON.BDINSS13FC,'||
         ' COLCON.BDBIRRF13FC,'||
         ' COLCON.BDALIQIRRF13FC,'||
         ' COLCON.BDIRRF13FC,'||
         ' COLCON.BDBSALFAMFC,'||
         ' COLCON.BDSALFAMFC,'||
         ' COLCON.BDBRAISFC,'||
         ' COLCON.BDSALBASEFC,'||
         ' COLCON.BDDEPFC,'||
         ' COLCON.BDBASEPISFC,'||
         ' COLCON.BDBASEPISFEFC,'||
         ' COLCON.BDBASEPIS13FC,'||
         ' COLCON.BDBSALMATEMPFC,'||
         ' COLCON.BDSALMATEMPFC,'||
         ' COLCON.BDBRATAPOFC,'||
         ' COLCON.BDBRATAPOFEFC,'||
         ' COLCON.BDBRATAPO13FC,'||
         ' COLCON.BDBINSSFEFOLFC,'||
         ' COLCON.BDINSSFEFOLFC,'||
         ' COLCON.BDALIQINSSFEFOLFC,'||
         ' COLCON.BDCREDITOFC,'||
         ' COLCON.BDDEBITOFC,'||
         ' COLCON.bdbfgtsfefc,'||
         ' COLCON.bdfgtsfefc,'||
         ' COLCON.BDREFFC,'||
         ' COLCON.BDCODTIPOFC,'||
         ' COLCON.BDBINSSMVFC,'||
         ' COLCON.BDBINSSMV13FC, '||
         ' COLCON.BDINSSMVFC,'||
         ' COLCON.BDINSSMV13FC, '||
         ' COLCON.BDBINSSAPFC, '||
         ' COLCON.BDBINSS13APFC, '||
         ' COLCON.BDINSSAPFC, '||
         ' COLCON.BDINSS13APFC, '||
         ' FOLN.BDBINSSFN, '||
         ' FOLN.BDINSSFN, '||
         ' FOLN.BDBINSS13FN, '||
         ' FOLN.BDINSS13FN, '||
         ' FOLN.BDBINSSAPFN, '||
         ' FOLN.BDBINSS13APFN, '||
         ' FOLN.BDINSSAPFN, '||
         ' FOLN.BDINSS13APFN, '||
         ' ((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO ' ||
         '   from VRHF_EMP_TVERBAFC FCV ' ||
         '   join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
         '                                  V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) ' ||
         '   where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and ' ||
         '         FCV.BDREFFN = COLCON.BDREFFN and FCV.BDREFFC = COLCON.BDREFFC) - ' ||
         '  (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO ' ||
         '   from VRHF_EMP_TVERBAFC FCV ' ||
         '   join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
         '                                  V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) ' ||
         '   where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and ' ||
         '         FCV.BDREFFN = COLCON.BDREFFN and FCV.BDREFFC = COLCON.BDREFFC)) BDLIQUIDO, '||
         ' COLCON.BDDATAGRRFFC '||
         ' from vrhf_emp_tfolhacomp COLCON'||
         ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
         ' join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN) ';

  wwheren = '';
  wwheret = '';

  IF (((pragrupatomador >= 3) AND (pragrupatomador <= 4)) OR (pragrupatomador = 1)) THEN
     wauxwheretom = ' where ';
  ELSE
     wauxwheretom = ' and ';

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||prcodemp;
       wwheret = wwhereT||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||prcodcol;
       wwheret = wwhereT||prcodcol;
     END

  IF ((prrefinicomp IS NOT NULL) AND (prreffimcomp IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||'COLCON.BDREFFN >= '||prrefinicomp||' and '||'COLCON.BDREFFN <= '||prreffimcomp;
       wwheret = wwhereT||'COLCON.BDREFTOMADOR >= '||prrefinicomp||' and '||'COLCON.BDREFTOMADOR <= '||prreffimcomp;
     END
  ELSE
     BEGIN
       IF (prrefinicomp IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||wauxwheretom;
               END

            wwheren = wwheren||'COLCON.BDREFFN = '||prrefinicomp;
            wwheret = wwhereT||'COLCON.BDREFTOMADOR = '||prrefinicomp;
          END
       ELSE
          BEGIN
            IF (prreffimcomp IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||wauxwheretom;
                    END

                 wwheren = wwheren||'COLCON.BDREFFN = '||prreffimcomp;
                 wwheret = wwhereT||'COLCON.BDREFTOMADOR = '||prreffimcomp;
               END
          END
     END

  IF ((prrefinipag IS NOT NULL) AND (prrefinipag <> 0) AND (prreffimpag IS NOT NULL) AND (prreffimpag <> 0)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag;
       wwheret = wwhereT||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag;
     END
  ELSE
     BEGIN
       IF (prrefinipag IS NOT NULL AND prrefinipag <> 0) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||wauxwheretom;
               END

            wwheren = wwheren||'COLCON.BDREFCOMP = '||prrefinipag;
            wwheret = wwhereT||'COLCON.BDREFCOMP = '||prrefinipag;
          END
       ELSE
          BEGIN
            IF (prreffimpag IS NOT NULL AND prreffimpag <> 0) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||wauxwheretom;
                    END

                 wwheren = wwheren||'COLCON.BDREFCOMP = '||prreffimpag;
                 wwheret = wwhereT||'COLCON.BDREFCOMP = '||prreffimpag;
               END
          END
     END

  IF (prtipofc > 0) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||'coalesce(COLCON.BDCODTIPOFC,1) = '||prtipofc;
       wwheret = wwhereT||'coalesce(COLCON.BDCODTIPOFC,1) = '||prtipofc;
     END

  IF ((prcodtpcc IS NULL) OR (prcodtpcc = '')) THEN
     BEGIN
       bdcalctomador = 'False';
     
       FOR EXECUTE STATEMENT wsql||wwheren
       INTO
         :bdcodemp,
         :BDCODEMP,
         :BDCODCOL,
         :BDREFFN,
         :BDREFCOMP,
         :BDDATAPAGFC,
         :BDDATABAIXAFC,
         :BDBFGTSFC,
         :BDFGTSFC,
         :BDFGTSCSFC,
         :BDBFGTS13FC,
         :BDFGTS13FC,
         :BDFGTS13CSFC,
         :BDMAIORREMFC,
         :BDBINSSFC,
         :BDALIQINSSFC,
         :BDINSSFC,
         :BDBIRRFFC,
         :BDALIQIRRFFC,
         :BDIRRFFC,
         :BDBINSS13FC,
         :BDALIQINSS13FC,
         :BDINSS13FC,
         :BDBIRRF13FC,
         :BDALIQIRRF13FC,
         :BDIRRF13FC,
         :BDBSALFAMFC,
         :BDSALFAMFC,
         :BDBRAISFC,
         :BDSALBASEFC,
         :BDDEPFC,
         :BDBASEPISFC,
         :BDBASEPISFEFC,
         :BDBASEPIS13FC,
         :BDBSALMATEMPFC,
         :BDSALMATEMPFC,
         :BDBRATAPOFC,
         :BDBRATAPOFEFC,
         :BDBRATAPO13FC,
         :BDBINSSFEFOLFC,
         :BDINSSFEFOLFC,
         :BDALIQINSSFEFOLFC,
         :bdcredito,
         :bddebito,
         :bdbfgtsfefc,
         :bdfgtsfefc,
         :BDREFFC,
         :BDCODTIPOFC,
         :BDBINSSMVFC,
         :BDBINSSMV13FC,
         :BDINSSMVFC,
         :BDINSSMV13FC,
         :BDBINSSAPFC,
         :BDBINSS13APFC,
         :BDINSSAPFC,
         :BDINSS13APFC,
         :BDBINSSFN,
         :BDINSSFN,
         :BDBINSS13FN,
         :BDINSS13FN,
         :BDBINSSAPFN,
         :BDBINSS13APFN,
         :BDINSSAPFN,
         :BDINSS13APFN,
         :BDLIQUIDOFC,
         :BDDATAGRRF
       DO
         BEGIN
           SUSPEND;
         END
     END

            WDATAPAG = 'colcon.BDDATAPAGFC';
            wordemdatapag = '';
  IF ((prseparcalc = 0) OR (prseparcalc IS NULL)) THEN
     BEGIN
       IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador >= 1)) THEN
          BEGIN
            WDATAPAG = 'max(colcon.BDDATAPAGFC)';
            wordemdatapag = '';
          END
       ELSE
          BEGIN
            WDATAPAG = 'colcon.BDDATAPAGFC';
            wordemdatapag = '';
          END
     END
  ELSE
     BEGIN
       WDATAPAG = 'colcon.BDDATAPAGFC';
       wordemdatapag = ', colcon.BDDATAPAGFC';
     END

  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 5)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||','||
                'cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'cast(null as integer), cast(null as integer), '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'colcon.BDREFFC, max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
                'sum(COLCON.bdliquido), max(COLCON.bddatagrrffc) '||
              'from (';
              
       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC,COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, colcon.bddatapagfc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM)) BDLIQUIDO, '||
                'case when pf.BDCODTPCC is null then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.BDDATAGRRFFC '||
              'from vrhf_emp_tfoltomcomp COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM) '||
              'join vrhf_emp_tprepfn pf on (pf.BDCODEMP = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.BDORDEM = COLCON.BDORDEM) '||
              'where colcon.bdcodemp is not null '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR, colcon.BDREFFC, COLCON.BDREFCOMP'||wordemdatapag;
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||','||
                'CAST(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'case when COLCON.bdCODTPCCtoma is null then null else COLCON.bdCodCentrotoma end bdCodCentro, COLCON.bdCODTPCCtoma bdCODTPCC, '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13ft), '||
                'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';
              
       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'case when toma.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when pf.BDCODTPCC is null then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, COLCON.bddatapagfc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC '||
              'from vrhf_emp_tfoltomcomp COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM) '||
              'left outer join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR,COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, COLCON.bdCODTPCCtoma '||wordemdatapag;
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||', '||
                'cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'case when COLCON.bdCODTPCCtoma is null then null else COLCON.bdCodCentrotoma end bdCodCentro, COLCON.bdCODTPCCtoma bdCODTPCC, '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
                'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';
 
       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC, COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'case when toma.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when pf.BDCODTPCC is null then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, colcon.bddatapagfc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC '||
              'from vrhf_emp_tfoltomcomp COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM) '||
              'left outer join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret||') COLCON ';
            
       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, COLCON.bdCODTPCCtoma'||wordemdatapag;
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||','||
                'cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'case when COLCON.bdCODTPCC is null then null else COLCON.bdCodCentro end bdCodCentro, COLCON.bdCODTPCC, '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
                'sum(COLCON.bdliquido), max(COLCON.bddatagrrffc) '||
              'from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'case when pf.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentro, pf.bdCODTPCC, COLCON.bddatapagfc, '||
                'colcon.bdcreditofc, colcon.bddebitofc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft,  foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC '||
              'from vrhf_emp_tfoltomcomp COLCON, '||
              'VRHF_EMP_TFOLHATOMADOR FOLN, '||
              'vrhf_emp_tprepfn pf, '||
              'tempresas emp '||
              'where  (colcon.bdcodemp = emp.bdcodemp) and (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM) and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              wwheret||') COLCON ';
            
       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentro, COLCON.bdCODTPCC '||wordemdatapag;
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||', '||
                'cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'cast(null as integer), cast(null as integer), '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
                'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, COLCON.bddatapagfc, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, case when pf.bdcodtpcc is null then null else pf.bdcodcentro end bdcodcentro, pf.bdcodtpcc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC '||
              'from vrhf_emp_tfoltomcomp COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = colcon.bdcodemp and pf.bdcodcol = colcon.bdcodcol and pf.bdordem = colcon.bdordem) '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR, COLCON.BDREFCOMP'||wordemdatapag;
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||', '||
                'COLCON.BDORDEM, COLCON.BDDATABAIXAFC, COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, COLCON.BDFGTS13CSFC, '||
                'COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, COLCON.BDDEPFC, '||
                'COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, case when COLCON.bdCODTPCC is null then null else COLCON.bdCodCentro end bdCodCentro, COLCON.bdCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'COLCON.bdbinssft, COLCON.bdinssft, COLCON.bdbinss13ft, COLCON.bdinss13ft, '||
                'colcon.bdbinssapft, colcon.bdbinss13apft, colcon.bdinssapft, colcon.bdinss13apft, '||
                'COLCON.bdliquido, COLCON.BDDATAGRRFFC '||
              'from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.bddatapagfc, '||
                'COLCON.BDORDEM, COLCON.BDDATABAIXAFC, COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, COLCON.BDFGTS13CSFC, '||
                'COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, COLCON.BDDEPFC, '||
                'COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, case when pf.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentro, pf.bdCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMADOR FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC '||
              'from vrhf_emp_tfoltomcomp COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'where (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

     END

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcodcol,
    :bdreffn,
    :BDREFCOMP,
    :BDDATAPAGFC,
    :bdordem,
    :bddatabaixafC,
    :bdbfgtsfC,
    :bdfgtsfc,
    :bdfgtscsfc,
    :bdbfgts13fc,
    :bdfgts13fc,
    :bdfgts13csfc,
    :bdmaiorremfc,
    :bdbinssfc,
    :bdaliqinssfc,
    :bdinssfc,
    :bdbirrffc,
    :bdaliqirrffc,
    :bdirrffc,
    :bdbinss13fc,
    :bdaliqinss13fc,
    :bdinss13fc,
    :bdbirrf13fc,
    :bdaliqirrf13fc,
    :bdirrf13fc,
    :bdbsalfamfc,
    :bdsalfamfc,
    :bdbraisfc,
    :bdsalbasefc,
    :bddepfc,
    :bdbasepisfc,
    :bdbasepisFEfc,
    :bdbasepis13fc,
    :bdbsalmatempfc,
    :bdsalmatempfc,
    :bdbratapofc,
    :bdbratapoFEfc,
    :bdbratapo13fc,
    :bdbinssfefolfc,
    :bdinssfefolfc,
    :bdaliqinssfefolfc,
    :bdCodCentro,
    :bdCODTPCC,
    :bdcredito,
    :bddebito,
    :bdBFGTSFEfc,
    :bdFGTSFEfc,
    :BDREFFC,
    :BDCODTIPOFC,
    :BDBINSSMVFC,
    :BDBINSSMV13FC,
    :BDINSSMVFC,
    :BDINSSMV13FC,
    :BDBINSSAPFC,
    :BDBINSS13APFC,
    :BDINSSAPFC,
    :BDINSS13APFC,
    :BDBINSSFN,
    :BDINSSFN,
    :BDBINSS13FN,
    :BDINSS13FN,
    :BDBINSSAPFN,
    :BDBINSS13APFN,
    :BDINSSAPFN,
    :BDINSS13APFN,
    :BDLIQUIDOFC,
    :BDDATAGRRF
  DO
    BEGIN
      bdcalctomador = 'True';
      SUSPEND;
    END
END
^

/* Alter (VRHF_SP_TODAS_GPS) */
ALTER PROCEDURE VRHF_SP_TODAS_GPS(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(22000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCHAVEDARF INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODIMP INTEGER;
DECLARE VARIABLE WWHEREEMP VARCHAR(30000);
DECLARE VARIABLE WCODIMPANT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLGPS VARCHAR(30000);
DECLARE VARIABLE WPARAMETROS VARCHAR(30000);
BEGIN
  /* PRTIPOCOL
     0 = Todos
     1 = Colaboradores
     2 = Autonomos
   */

  /* Procedure Text */
  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     prcodemp = ''''||prcodemp||'''';

  IF (pranomes IS NULL) THEN
     pranomes = 0;

  wsql = 'select bdCODIMP,BDCODEMP from sp_tempresaimposto_ref('||prcodemp||','||pranomes||',0)'||
         ' where BDDOCARRECADACAO = 12'||
         ' order by bdCODIMP,BDCODEMP';
--  select * from vrhf_sp_calc_gps(9053,'colcon.bdcodemp = 3',null,201005,201005,0,0,0)

  wparametros = '';
  IF (prcodcol IS NULL) THEN
     wparametros = 'null,';
  ELSE
     wparametros = ''''||prcodcol||''''||',';

  IF (prcodaut IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     wparametros = wparametros||''''||prcodaut||''''||',';

  IF (prtipocol IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     wparametros = wparametros||prtipocol||',';

  IF (pranomes IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     BEGIN
       wparametros = wparametros||pranomes||',';
       EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);
     END

  IF (pranomespag IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     BEGIN
       wparametros = wparametros||pranomespag||',';
       EXECUTE PROCEDURE sp_seta_competencia(pranomespag,NULL,NULL);
     END

  IF (prapenasgps IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     wparametros = wparametros||prapenasgps||',';

  IF (prtipogps IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     wparametros = wparametros||prtipogps||',';

  IF (prpuxafiliais IS NULL) THEN
     wparametros = wparametros||'null)';
  ELSE
     wparametros = wparametros||prpuxafiliais||')';

  wcodimpant = -1;
  wwhereemp = '';
  FOR EXECUTE STATEMENT wsql INTO wcodimp,wcodemp DO
  BEGIN
--    suspend;
     IF ((wcodimpant = -1) OR (wcodimp = wcodimpant)) THEN
        BEGIN
          wcodimpant = wcodimp;
          IF (wwhereemp <> '') THEN
             wwhereemp = wwhereemp||',';

          wwhereemp = wwhereemp||wcodemp;
        END
     ELSE
        BEGIN
          wsqlgps = 'select '||
                    ' bdtiporeg, bdcodemp, bdreffn, bdrefpag, bdcodtpcc, bdtotseg, bdtotbase, bdsegfun, bdbasefun,'||
                    ' bdpercfun, bdvalfunemp, bdsegpro, bdbasepro, bdpercpro, bdvalproemp, bdsegaut, bdbaseaut, bdpercaut,'||
                    ' bdvalautemp, bdsalfam, bdsalmaternidade, bdbaseratapo, bdvalorratapo, bdbasefpas, bdpercfpas, bdvalorfpas,'||
                    ' bdpercrat, bdvalorrat, bdvalorbruto, bdvalorliquido, bdnfcoop, bdchave, bdvalcompensado, bdvalacompensar,'||
                    ' bdvaloracumulado, bdvaloracumuladousado, bdvaloracumuterceiro, bdvaloracuterceirosusado, bdcodempant,'||
                    ' bdcodimpant, bdcodperiodoant, bdordemant, bdreferenciaant, bdquotaant, bddescacumdet, bddescacu,'||
                    ' bdvalorcampo6, bdvalornotas, bdtotvaloracumulado, bdtotvaloracumuladoterc, bdinicomp, bdfimcomp, bdtotcompensacao, '||
                    ' BDDESCNOTAS, BDTOTDESCCOMP, bddescsalfam, bddescdedgps, BDVALOUTENTIDADES, bdsimplesgps, bdcodenqfed,'||
                    ' bddescenqfed, BDCHAVEDARF '||
                    ' from vrhf_sp_calc_gps('||wcodimpant||','||''''||'colcon.bdcodemp in ('||wwhereemp||')'||''''||','||wparametros;



          FOR EXECUTE STATEMENT wsqlgps INTO
              :bdtiporeg, :bdcodemp, :bdreffn, :bdrefpag, :bdcodtpcc, :bdtotseg, :bdtotbase, :bdsegfun, :bdbasefun,
              :bdpercfun, :bdvalfunemp, :bdsegpro, :bdbasepro, :bdpercpro, :bdvalproemp, :bdsegaut, :bdbaseaut, :bdpercaut,
              :bdvalautemp, :bdsalfam, :bdsalmaternidade, :bdbaseratapo, :bdvalorratapo, :bdbasefpas, :bdpercfpas, :bdvalorfpas,
              :bdpercrat, :bdvalorrat, :bdvalorbruto, :bdvalorliquido, :bdnfcoop, :bdchave, :bdvalcompensado, :bdvalacompensar,
              :bdvaloracumulado, :bdvaloracumuladousado, :bdvaloracumuterceiro, :bdvaloracuterceirosusado, :bdcodempant,
              :bdcodimpant, :bdcodperiodoant, :bdordemant, :bdreferenciaant, :bdquotaant, :bddescacumdet, :bddescacu,
              :bdvalorcampo6, :bdvalornotas, :bdtotvaloracumulado, :bdtotvaloracumuladoterc, :bdinicomp, :bdfimcomp,
              :bdtotcompensacao, :bddescnotas,: bdtotdesccomp, :bddescsalfam, :bddescdedgps, :BDVALOUTENTIDADES, :bdsimplesgps, :bdcodenqfed,
              :bddescenqfed, :BDCHAVEDARF  DO
              SUSPEND;

          wcodimpant = wcodimp;
          wwhereemp = ''||wcodemp;
        END
  END

  IF (wcodimpant <> -1) THEN
     BEGIN
          wsqlgps = 'select '||
                    ' bdtiporeg, bdcodemp, bdreffn, bdrefpag, bdcodtpcc, bdtotseg, bdtotbase, bdsegfun, bdbasefun,'||
                    ' bdpercfun, bdvalfunemp, bdsegpro, bdbasepro, bdpercpro, bdvalproemp, bdsegaut, bdbaseaut, bdpercaut,'||
                    ' bdvalautemp, bdsalfam, bdsalmaternidade, bdbaseratapo, bdvalorratapo, bdbasefpas, bdpercfpas, bdvalorfpas,'||
                    ' bdpercrat, bdvalorrat, bdvalorbruto, bdvalorliquido, bdnfcoop, bdchave, bdvalcompensado, bdvalacompensar,'||
                    ' bdvaloracumulado, bdvaloracumuladousado, bdvaloracumuterceiro, bdvaloracuterceirosusado, bdcodempant,'||
                    ' bdcodimpant, bdcodperiodoant, bdordemant, bdreferenciaant, bdquotaant, bddescacumdet, bddescacu,'||
                    ' bdvalorcampo6, bdvalornotas, bdtotvaloracumulado, bdtotvaloracumuladoterc, bdinicomp, bdfimcomp, bdtotcompensacao, '||
                    ' BDDESCNOTAS,BDTOTDESCCOMP, bddescsalfam, bddescdedgps, BDVALOUTENTIDADES, bdsimplesgps, bdcodenqfed,'||
                    ' bddescenqfed, BDCHAVEDARF '||
                    ' from vrhf_sp_calc_gps('||wcodimpant||','||''''||'colcon.bdcodemp in ('||wwhereemp||')'||''''||','||wparametros;


          FOR EXECUTE STATEMENT wsqlgps INTO
              :bdtiporeg, :bdcodemp, :bdreffn, :bdrefpag, :bdcodtpcc, :bdtotseg, :bdtotbase, :bdsegfun, :bdbasefun,
              :bdpercfun, :bdvalfunemp, :bdsegpro, :bdbasepro, :bdpercpro, :bdvalproemp, :bdsegaut, :bdbaseaut, :bdpercaut,
              :bdvalautemp, :bdsalfam, :bdsalmaternidade, :bdbaseratapo, :bdvalorratapo, :bdbasefpas, :bdpercfpas, :bdvalorfpas,
              :bdpercrat, :bdvalorrat, :bdvalorbruto, :bdvalorliquido, :bdnfcoop, :bdchave, :bdvalcompensado, :bdvalacompensar,
              :bdvaloracumulado, :bdvaloracumuladousado, :bdvaloracumuterceiro, :bdvaloracuterceirosusado, :bdcodempant,
              :bdcodimpant, :bdcodperiodoant, :bdordemant, :bdreferenciaant, :bdquotaant, :bddescacumdet, :bddescacu,
              :bdvalorcampo6, :bdvalornotas, :bdtotvaloracumulado, :bdtotvaloracumuladoterc, :bdinicomp, :bdfimcomp,
              :bdtotcompensacao,:BDDESCNOTAS,:BDTOTDESCCOMP, :bddescsalfam, :bddescdedgps, :BDVALOUTENTIDADES, :bdsimplesgps, :bdcodenqfed,
              :bddescenqfed, :BDCHAVEDARF DO
              SUSPEND;
     END
END
^

/* Alter (VRHF_SP_TOTAL_COL_ATIVOS) */
ALTER PROCEDURE VRHF_SP_TOTAL_COL_ATIVOS(PRCODEMP INTEGER,
PRREF INTEGER,
PRDATAADMISSAO DATE)
 RETURNS(TTATIVOS INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(15000);
BEGIN


  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

    wSql = 'select ';
--    if (:PRCODEMP is not null) then
      wSql = wSql || 'count(COL.BDCODEMP) TTATIVOS';
--    else
--      wSql = wSql || 'col.bdcodemp, count(COL.BDCODEMP) ';

    wSql = wSql || ' from vw_colaboradores COL ';
    wSql = wSql || ' left outer join VW_EMPRESAS_REF_ATUAL EMP on (COL.bdcodemp = EMP.bdcodemp) ';
--    if (:PRCODEMP is not null) then
--      begin
        wSql = wSql ||'where col.bdcodemp = '||:PRCODEMP;
--        wSql = wSql ||' and  ( col.bddataadmcol <= '||:prdataini||')';
--      end
--    else
      wSql = wSql ||' and  ( col.bddataadmcol <= '''||:prdataadmissao||''')';


    wSql = wSql || ' AND (  not exists ( select REC.BDCODEMP, REC.BDCODCOL from vrh_emp_trescisao REC where REC.BDCODEMP = COL.BDCODEMP and ';
    wSql = wSql || ' REC.BDCODCOL = COL.BDCODCOL and ';
    wSql = wSql || ' CAST((SUBSTRING(CAST(REC.BDDATARESCISAO as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(REC.BDDATARESCISAO as VARCHAR(10)) from 6 for 2)) As INTEGER) <= '||prref||')) ';
    wSql = wSql || ' AND (not exists ( select TRA.bdcodemporig, TRA.bdcodcolorig from vrh_emp_ttranscol TRA';
    wSql = wSql || ' where TRA.bdcodemporig = COL.BDCODEMP and TRA.bdcodcolorig = COL.BDCODCOL))';

--    if (:PRCODEMP is null) then
--       wSql = wSql || ' group by col.bdcodemp';


  FOR EXECUTE STATEMENT wsql
      INTO
        :TTATIVOS
     DO
       BEGIN
         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_TPREPFB_CC) */
ALTER PROCEDURE VRHF_SP_TPREPFB_CC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6),
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140))
 AS
DECLARE VARIABLE wref INTEGER;
DECLARE VARIABLE wsqlemp VARCHAR(32700);
DECLARE VARIABLE wsql VARCHAR(32700);
BEGIN
  /* Procedure Text */
  wsql = '';
  wsql = wsql||'select';
  wsql = wsql||' pfn.bdcodemp,';
  wsql = wsql||' pfn.bdcodcol,';
  wsql = wsql||' pfn.bdordem,';
  wsql = wsql||' pfn.bdcodcentro,';
  wsql = wsql||' pfn.bdcodtpcc,';
  wsql = wsql||' pfn.bddataentrada,';
  wsql = wsql||' pfn.bdhoraentrada,';
  wsql = wsql||' pfn.bdtipo,';
  wsql = wsql||' pfn.bdqtdtempo,';
  wsql = wsql||' cc.BDCTALON,';
  wsql = wsql||' cc.BDTIPCTA,';
  wsql = wsql||' cc.BDNOMCTA,';
  wsql = wsql||' cc.BDAPECTA,';
  wsql = wsql||' cc.BDFILTROGER,';
  wsql = wsql||' cc.BDCLANOM';
  wsql = wsql||' from vrhf_EMP_tprepfn pfn ';
  wsql = wsql||' left outer join centros_tpcc cc on (cc.bdcodcentro = pfn.bdcodcentro and cc.bdcodtpcc = pfn.bdcodtpcc) ';

  FOR EXECUTE STATEMENT wsql INTO
    :bdcodemp,
    :bdcodcol,
    :bdordem,
    :bdcodcentro,
    :bdcodtpcc,
    :bddataentrada,
    :bdhoraentrada,
    :bdtipo,
    :bdqtdtempo,
    :BDCTALON,
    :BDTIPCTA,
    :BDNOMCTA,
    :BDAPECTA,
    :BDFILTROGER,
    :BDCLANOM
  DO
  BEGIN
    IF (:bdcodtpcc IS NULL) THEN
       BEGIN
          FOR SELECT bdaaaamm FROM aaaamm(:bddataentrada) INTO wref DO
            BEGIN
            END

          EXECUTE PROCEDURE sp_seta_competencia(wref, NULL, NULL);
          wsqlEmp = 'select emp.bdnomemp from SP_TEMPRESAS_REF('||wRef||') emp'||
                    ' where emp.bdcodemp = '||:bdcodemp;
          FOR EXECUTE STATEMENT wsqlEmp INTO :BDNOMCTA DO
            BEGIN
            END
          EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
       END

    SUSPEND;
  END

END
^

/* Alter (VRHF_SP_TPREPFN_CC_REF) */
ALTER PROCEDURE VRHF_SP_TPREPFN_CC_REF(PRREF INTEGER,
PREMPRESA VARCHAR(32700),
PRCOLABORADOR VARCHAR(32700),
PRTEMPO INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRFERIAS SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6),
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140),
BDTEMPO INTEGER,
BDTEMPOFN INTEGER)
 AS
DECLARE VARIABLE WDATARESC DATE;
DECLARE VARIABLE WSQLEMP VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WULTDIA DATE;
DECLARE VARIABLE WEMPRESA INTEGER;
DECLARE VARIABLE WFUNCIONARIO INTEGER;
DECLARE VARIABLE WHORASAIDACC TIME;
DECLARE VARIABLE WULTDIAMES DATE;
DECLARE VARIABLE WPRIDIAMES DATE;
DECLARE VARIABLE WDATAENTAUX DATE;
DECLARE VARIABLE WHORAENTAUX TIME;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WULTDIASET VARCHAR(10);
DECLARE VARIABLE WPRIMDIASET VARCHAR(10);
DECLARE VARIABLE WPROPTOM INTEGER;
DECLARE VARIABLE WPROPFER INTEGER;
DECLARE VARIABLE WESTADEFERIAS INTEGER;
BEGIN
  /* Procedure Text */
  wano = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wmes = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);
  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdiaset = wmes||'/'||wdia||'/'||wano;
  wPrimDiaset = wmes||'/01/'||wano;

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wPrimDiaset AS DATE), CAST(wultdiaset AS DATE));

  IF (prempresa IS NOT NULL) THEN
     prempresa = ''''||prempresa||'''';

  IF (prcolaborador IS NOT NULL) THEN
     prcolaborador = ''''||prcolaborador||'''';

  IF (prempresa IS NULL) THEN
     prempresa = 'null';

  IF (prcolaborador IS NULL) THEN
     prcolaborador = 'null';

  wsql = '';
  wsql = wsql||'select';
  wsql = wsql||' pfn.bdcodemp,';
  wsql = wsql||' pfn.bdcodcol,';
  wsql = wsql||' pfn.bdordem,';
  wsql = wsql||' pfn.bdcodcentro,';
  wsql = wsql||' pfn.bdcodtpcc,';
  wsql = wsql||' pfn.bddataentrada,';
  wsql = wsql||' pfn.bdhoraentrada,';
  wsql = wsql||' pfn.bdtipo,';
  wsql = wsql||' pfn.bdqtdtempo,';
  wsql = wsql||' cc.BDCTALON,';
  wsql = wsql||' cc.BDTIPCTA,';
  wsql = wsql||' cc.BDNOMCTA,';
  wsql = wsql||' cc.BDAPECTA,';
  wsql = wsql||' cc.BDFILTROGER,';
  wsql = wsql||' cc.BDCLANOM';
  IF (prdatafim IS NOT NULL) THEN
     IF ((prref IS NOT NULL) AND (CAST(wultdiaset AS DATE) < prdatafim)) THEN
        wsql = wsql||' from vrhf_sp_tprepfn_ref('||prref||','||prempresa||','||prcolaborador||',cast('||''''||CAST(:prdataini AS VARCHAR(10))||''''||' as date),cast('||''''||wultdiaset||''''||' as date)) pfn';
     ELSE
        wsql = wsql||' from vrhf_sp_tprepfn_ref('||prref||','||prempresa||','||prcolaborador||',cast('||''''||CAST(:prdataini AS VARCHAR(10))||''''||' as date),cast('||''''||CAST(:prdatafim AS VARCHAR(10))||''''||' as date)) pfn';
  ELSE
     wsql = wsql||' from vrhf_sp_tprepfn_ref('||prref||','||prempresa||','||prcolaborador||',null,null) pfn';
  wsql = wsql||' left outer join centros_tpcc cc on (cc.bdcodcentro = pfn.bdcodcentro and cc.bdcodtpcc = pfn.bdcodtpcc)';
  wsql = wsql||' order by pfn.bdcodemp,pfn.bdcodcol,pfn.bddataentrada,pfn.bdhoraentrada';

  wempresa = 0;
  wfuncionario = 0;
  wproptom = 0;
--  SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES'))) AS DATE) FROM rdb$database INTO wdataaux;

  FOR EXECUTE STATEMENT wsql INTO
    :bdcodemp,
    :bdcodcol,
    :bdordem,
    :bdcodcentro,
    :bdcodtpcc,
    :bddataentrada,
    :bdhoraentrada,
    :bdtipo,
    :bdqtdtempo,
    :BDCTALON,
    :BDTIPCTA,
    :BDNOMCTA,
    :BDAPECTA,
    :BDFILTROGER,
    :BDCLANOM
  DO
  BEGIN
    bdTempo = 0;
    IF ((wempresa <> bdcodemp) OR (wfuncionario <> bdcodcol))THEN
       BEGIN
          wempresa = bdcodemp;
          wfuncionario = bdcodcol;
          SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE) FROM rdb$database INTO wultdiames;
          SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE) FROM rdb$database INTO wultdia;
--          SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES'))) AS DATE) FROM rdb$database INTO wdataatu;
          SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES'))) AS DATE) FROM rdb$database INTO wpridiames;

          wdataresc = NULL;
          wsqlemp = 'select first 1 colcon.bddatarescisao from vrh_emp_trescisao colcon where colcon.bdcodemp = '||:bdcodemp||' and colcon.bdcodcol = '||:bdcodcol||' and colcon.bdrefrescisao = '||:prref;
          EXECUTE STATEMENT wsqlemp INTO :wdataresc;
          IF (prferias = 1) THEN
             wproptom = 0;
          ELSE
             SELECT BDPROPTOMEMP, BDPROPFEREMP FROM VW_VRHF_BASE_TEMPPROP WHERE BDCODEMP = :bdcodemp INTO :wproptom, :wpropfer;
          -- 30 dias
          IF (wproptom = 1) THEN
             BEGIN
               westadeferias = NULL;
               SELECT FIRST 1 BDCODEMP FROM vrh_emp_tferias WHERE BDCODEMP = :bdcodemp AND bdcodcol = :bdcodcol AND ((BDREFINIFE = :prref) OR (BDREFFIMFE = :prref)) INTO :westadeferias;
               IF (westadeferias IS NOT NULL AND westadeferias = :BDCODEMP AND wpropfer = 0) THEN
                 BEGIN
                   IF (CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
                      BEGIN
                        wultdia = CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
                        wultdiames = CAST((SUBSTRING(CAST(:wultdiames AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
                      END
                 END
             END
       END

    IF (:bdcodtpcc IS NULL) THEN
       BEGIN
          wsqlEmp = 'select first 1 emp.bdnomemp from vw_empresas_ref_atual emp where emp.bdcodemp = '||:bdcodemp;

          EXECUTE STATEMENT wsqlEmp INTO :BDNOMCTA;
       END

     IF (prtempo >= 1) THEN
        BEGIN
          wultdia = NULL;
          SELECT FIRST 1 bddataentrada,bdhoraentrada data FROM vrhf_emp_tprepfn pf
             WHERE (pf.bddataentrada+pf.bdhoraentrada > (:bddataentrada+:bdhoraentrada)) AND
                   (pf.bdcodemp = :bdcodemp) AND (pf.bdcodcol = : bdcodcol)
                   ORDER BY bddataentrada+bdhoraentrada INTO :wultdia,:WHORASAIDACC;

          IF ((wultdia IS NULL) OR (wultdia > wultdiames) ) THEN
             BEGIN
               SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE) FROM rdb$database INTO wultdia;

               IF (wproptom = 1) THEN
                  BEGIN
                    IF (westadeferias IS NOT NULL AND westadeferias = :BDCODEMP AND wpropfer = 0) THEN
                      BEGIN
                        IF (CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
                           BEGIN
                             wultdia = CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
                           END
                      END
                  END

               --if (prtempo < 2) then
               --   select PRDIASEGUINTE from dia_seguinte(:wultdia) into wultdia;
               whorasaidacc = CAST('23:59' AS TIME);
             END

           IF ((wdataresc IS NOT NULL) AND (wultdia > wdataresc)) THEN
             BEGIN
               wultdia = wdataresc;

               --if (prtempo < 2) then
               --   select PRDIASEGUINTE from dia_seguinte(:wultdia) into wultdia;
               whorasaidacc = CAST('23:59' AS TIME);
             END

          wdataentaux = :bddataentrada;
          whoraentaux = :bdhoraentrada;

          IF (prtempo >= 1) THEN
             BEGIN
               IF (:wdataentaux < wpridiames) THEN
                  wdataentaux = wpridiames;

               IF (prdataini > :wdataentaux) THEN
                  wdataentaux = prdataini;

               IF ((prdatafim IS NOT NULL) AND (wultdia > prdatafim)) THEN
                  BEGIN
                    wultdia = prdatafim;
                    -- N?o pode ir para o dia seguinte quando ? informado a data final
--                    select PRDIASEGUINTE from dia_seguinte(:wultdia) into wultdia;
                    whorasaidacc = CAST('23:59' AS TIME);
                  END

               WHILE (wdataentaux <= wultdia) DO
                 BEGIN
                   IF ((wdataentaux = :bddataentrada) AND (wdataentaux = wultdia)) THEN
                      BEGIN
                        bdtempo = bdtempo + CAST((whorasaidacc - whoraentaux) AS INTEGER);
                      END
                   ELSE IF (wdataentaux = :bddataentrada) THEN
                      BEGIN
                        bdtempo = bdtempo + CAST((CAST('23:59' AS TIME) - whoraentaux) AS INTEGER) + 60;
                      END
                   ELSE IF (wdataentaux = wultdia) THEN
                      BEGIN
                        bdtempo = bdtempo + CAST((whorasaidacc - CAST('00:00' AS TIME)) AS INTEGER);
                        IF (whorasaidacc = '23:59') THEN
                           bdtempo = bdtempo + 60;
                      END
                   ELSE
                      BEGIN
                        bdtempo = bdtempo + CAST((CAST('23:59' AS TIME) - CAST('00:00' AS TIME)) AS INTEGER) + 60;
                      END

                   SELECT PRDIASEGUINTE FROM dia_seguinte(:wdataentaux) INTO wdataentaux;
                 END

               bdtempo = bdtempo / 60;
               bdtempofn = bdtempo;
               /*if (:bddataentrada < wpridiames) then
                  begin
                    select bdtempo from VRHF_SP_TTEMPOTRAB(:bdcodemp,:bdcodcol,:wpridiames,cast('00:00' as time),:wultdia,:whorasaidacc) into :bdtempofn;
                  end
               else
                  begin
                    select bdtempo from VRHF_SP_TTEMPOTRAB(:bdcodemp,:bdcodcol,:bddataentrada,:bdhoraentrada,:wultdia,:whorasaidacc) into :bdtempofn;
                  end*/
             END
          ELSE IF (:bddataentrada < wpridiames) THEN
             BEGIN
               SELECT bdtempo FROM VRHF_SP_TTEMPOTRAB(:bdcodemp,:bdcodcol,:wpridiames,CAST('00:00' AS TIME),:wultdia,:whorasaidacc) INTO :bdtempo;
               bdtempofn = bdtempo;
             END
          ELSE
             BEGIN
               SELECT bdtempo FROM VRHF_SP_TTEMPOTRAB(:bdcodemp,:bdcodcol,:bddataentrada,:bdhoraentrada,:wultdia,:whorasaidacc) INTO :bdtempo;
               bdtempofn = bdtempo;
             END
        END

    SUSPEND;
  END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_TPREPFN_REF) */
ALTER PROCEDURE VRHF_SP_TPREPFN_REF(PRREFERENCIA INTEGER,
PREMPRESA VARCHAR(32700),
PRCOLABORADOR VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERECOL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANOS VARCHAR(4);
DECLARE VARIABLE WAUX VARCHAR(32700);
DECLARE VARIABLE WSQLANT VARCHAR(32700);
DECLARE VARIABLE WSQLCOL VARCHAR(32700);
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WMESS VARCHAR(2);
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WULTDIA INTEGER;
DECLARE VARIABLE WULTDIAS VARCHAR(2);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WANOMES VARCHAR(6);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WDIASEMANA INTEGER;
DECLARE VARIABLE WANTERIOR SMALLINT;
DECLARE VARIABLE WHORAINI TIME;
DECLARE VARIABLE WSQLHORA VARCHAR(3200);
BEGIN
  IF (prdatafim IS NOT NULL) THEN
     SELECT bdaaaamm FROM aaaamm(:prdatafim) INTO wanomes;
  ELSE
     wanomes = CAST(prreferencia AS VARCHAR(6));

  wmess = SUBSTRING(wanomes FROM 5 FOR 2);
  wanos = SUBSTRING(wanomes FROM 1 FOR 4);

  wmes = CAST(wmess AS SMALLINT);
  wano = CAST(wanos AS INTEGER);

  wwhere = '';

  IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa;
     END

  IF ((prcolaborador IS NOT NULL) AND (prcolaborador <> '')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador;
     END

  IF (prdatafim IS NOT NULL) THEN
     BEGIN
       wultdias = EXTRACT(DAY FROM prdatafim);
     END
  ELSE
     BEGIN
       SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wultdia;
       wultdias = CAST(wultdia AS VARCHAR(2));
     END

  wwhere = ' '||wwhere;

  IF (prdatafim IS NOT NULL) THEN
     BEGIN
       wdataini = wmess||'/01/'||wanos;
       IF (CAST(wDataIni AS DATE) < :prdataini) THEN
          wdataini = CAST(:prdataini AS VARCHAR(10));
     END
  ELSE
     BEGIN
       wdataini = wmess||'/01/'||wanos;
     END
  wDataFim = wmess||'/'||wultdias||'/'||wanos;
  /* Procedure Text */

  wSql = 'select BDCODEMP, BDCODCOL, BDORDEM, BDCODCENTRO, BDCODTPCC, BDDATAENTRADA, BDHORAENTRADA, BDTIPO, BDQTDTEMPO from vrhf_emp_tprepfn prepcalc where prepcalc.bddataentrada >= '||
         ''''||wdataini||''''||
         ' and (prepcalc.bddataentrada <= '||
         ''''||wDataFim||''''||
         ')';

  WSQLANT = 'select first 1 BDCODEMP, BDCODCOL, BDORDEM, BDCODCENTRO, BDCODTPCC, BDDATAENTRADA, BDHORAENTRADA, BDTIPO, BDQTDTEMPO from vrhf_emp_tprepfn prepcalc where prepcalc.bddataentrada < '||
         ''''||wdataini||'''';

  WWHERECOL = '';
  IF (prempresa IS NOT NULL) THEN
     WWHERECOL = ' and '||prempresa;
  IF (prcolaborador IS NOT NULL) THEN
     WWHERECOL = WWHERECOL||' and '||prcolaborador;

  IF (prempresa IS NOT NULL) THEN
     prempresa = ''''||prempresa||'''';

  IF (prcolaborador IS NOT NULL) THEN
     prcolaborador = ''''||prcolaborador||'''';

  IF (prempresa IS NULL) THEN
     prempresa = 'null';

  IF (prcolaborador IS NULL) THEN
     prcolaborador = 'null';

--  wsqlcol = 'select bdcodemp, bdcodcol from vrh_sp_colcon('||prempresa||','
--                                                           ||prcolaborador||','
--                                                           ||'null'||','||'null'||','||'null'||','||prreferencia
--                                                           ||','||''''||wdatafim||''''
--                                                           ||',1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0)';


  wsqlcol = 'select colcon.bdcodemp,colcon.bdcodcol from vrh_emp_tcolcon colcon'||
            ' left outer join vrh_emp_trescisao res on (colcon.bdcodemp = res.bdcodemp and colcon.bdcodcol = res.bdcodcol)'||
            ' where colcon.bddataadmcol <= '||''''||wdatafim||''''||WWHERECOL||
            ' and ((res.BDDATARESCISAO is null) or (res.bdrefrescisao >= '||wanomes||'))'||
            ' and exists (select * from vrhf_emp_tprepfn a where colcon.bdcodemp = a.bdcodemp and colcon.bdcodcol = a.bdcodcol)';

  wdiasemana = EXTRACT(WEEKDAY FROM CAST(wdataini AS DATE));

  FOR EXECUTE STATEMENT wsqlcol INTO :wempatu,:wcolatu DO
    BEGIN
      wsqlhora = 'select first 1 tqh.bdqhhsent from VRH_EMP_TCOL_VINCDIA cd'||
                 ' left outer join vrh_base_tqh_dias qh on (cd.bdcodqh = qh.bdcodqh and cd.bdcodpqua = qh.bdcodpqua)'||
                 ' left outer join vrh_base_tqh_horario qhh on (qh.bdcodqh = qhh.bdcodqhh)'||
                 ' left outer join vrh_base_tqh_horas tqh on (qh.bdcodqhh = tqh.bdcodqhh and tqh.bdcodqhhs = qh.bddiasemqh)'||
                 ' where cd.bdcodemp = '||wempatu||' and cd.bdcodcol = '||wcolatu||
                 ' and cd.bddatacol <= cast('||''''||wDataini||''''||'as date) and tqh.bdcodqhhs ='||wdiasemana||
                 ' order by cd.bddatacol desc';

      EXECUTE STATEMENT wsqlhora INTO :whoraini;

      IF (whoraini IS NULL) THEN
         whoraini = CAST('00:00' AS TIME);

      wwhere = ' and prepcalc.bdcodemp = '||wempatu||' and prepcalc.bdcodcol = '||wcolatu;

      waux = wsql||wwhere||' order by prepcalc.bddataentrada, prepcalc.bdhoraentrada';

      wanterior = 0;

      FOR EXECUTE STATEMENT waux
      INTO
        :bdcodemp,
        :bdcodcol,
        :bdordem,
        :bdcodcentro,
        :bdcodtpcc,
        :bddataentrada,
        :bdhoraentrada,
        :bdtipo,
        :bdqtdtempo
      DO
        BEGIN
          IF ((bddataentrada = CAST(wdataini AS DATE)) AND (bdhoraentrada <= whoraini)) THEN
             BEGIN
               wanterior = 1;
             END
          SUSPEND;
        END

      IF (wanterior = 0) THEN
         BEGIN
           waux = WSQLANT||wwhere||' order by prepcalc.bddataentrada desc, prepcalc.bdhoraentrada desc';
           FOR EXECUTE STATEMENT waux
           INTO
             :bdcodemp,
             :bdcodcol,
             :bdordem,
             :bdcodcentro,
             :bdcodtpcc,
             :bddataentrada,
             :bdhoraentrada,
             :bdtipo,
             :bdqtdtempo
           DO
           SUSPEND;
         END
    END

END
^

/* Alter (VRHF_SP_TVERBAFC) */
ALTER PROCEDURE VRHF_SP_TVERBAFC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(25000),
PRREFINICOMP INTEGER,
PRREFFIMCOMP INTEGER,
PRREFINIPAG INTEGER,
PRREFFIMPAG INTEGER,
PRAGRUPATOMADOR INTEGER,
PRSEPARARCALC INTEGER = 0,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = NULL)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFCOMP INTEGER,
BDREFVFC NUMERIC(15,6),
BDREFAUXVFC NUMERIC(15,6),
BDVALVFC NUMERIC(15,6),
BDIGNREFVFC VARCHAR(5),
BDIGNREFAVFC VARCHAR(5),
BDIGNVALVFC VARCHAR(5),
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDREFFC INTEGER)
 AS
DECLARE VARIABLE WDATAPAG VARCHAR(50);
DECLARE VARIABLE WGROUPBYDATAPAG VARCHAR(50);
DECLARE VARIABLE WAUXWHERETOM VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHEREN VARCHAR(32700);
DECLARE VARIABLE WWHERET VARCHAR(32700);
DECLARE VARIABLE WAUX1 NUMERIC(15,6);
DECLARE VARIABLE WAUX2 NUMERIC(15,6);
DECLARE VARIABLE WAUXTIPO INTEGER;
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  /* Procedure Text */
  wsql = 'select COLCON.bdcodver, COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdreffn, COLCON.BDREFCOMP, COLCON.bdrefvfc,'||
         'COLCON.bdrefauxvfc, COLCON.bdvalvfc, COLCON.bdignrefvfc, COLCON.bdignrefavfc, COLCON.bdignvalvfc, COLCON.BDREFFC'||
         ' from vrhf_emp_tverbafc COLCON '||
         ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';

  IF (prpuxafiliais = 1) THEN
     BEGIN
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            prcodemp = UPPER(prcodemp);
     
            IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ') INTO wwheren;
                 prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
               END
            ELSE
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
               END
          END
     END

  wwheren = '';
  wwheret = '';

  IF ((pragrupatomador >= 3) AND (pragrupatomador <= 4)) THEN
     wauxwheretom = ' where ';
  ELSE
     wauxwheretom = ' and ';

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||prcodemp;
       wwheret = wwhereT||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||prcodcol;
       wwheret = wwhereT||prcodcol;
     END

  IF ((prrefinicomp IS NOT NULL) AND (prreffimcomp IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||'COLCON.BDREFFN >= '||prrefinicomp||' and '||'COLCON.BDREFFN <= '||prreffimcomp;
       wwheret = wwhereT||'COLCON.BDREFTOMADOR >= '||prrefinicomp||' and '||'COLCON.BDREFTOMADOR <= '||prreffimcomp;
     END
  ELSE
     BEGIN
       IF (prrefinicomp IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||wauxwheretom;
               END

            wwheren = wwheren||'COLCON.BDREFFN = '||prrefinicomp;
            wwheret = wwhereT||'COLCON.BDREFTOMADOR = '||prrefinicomp;
          END
       ELSE
          BEGIN
            IF (prreffimcomp IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||wauxwheretom;
                    END

                 wwheren = wwheren||'COLCON.BDREFFN = '||prreffimcomp;
                 wwheret = wwhereT||'COLCON.BDREFTOMADOR = '||prreffimcomp;
               END
          END
     END

  IF ((prrefinipag IS NOT NULL) AND (prreffimpag IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag;
       wwheret = wwhereT||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFTOMADOR <= '||prreffimpag;
     END
  ELSE
     BEGIN
       IF (prrefinipag IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||wauxwheretom;
               END

            wwheren = wwheren||'COLCON.BDREFCOMP = '||prrefinipag;
            wwheret = wwhereT||'COLCON.BDREFCOMP = '||prrefinipag;
          END
       ELSE
          BEGIN
            IF (prreffimpag IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||wauxwheretom;
                    END

                 wwheren = wwheren||'COLCON.BDREFCOMP = '||prreffimpag;
                 wwheret = wwhereT||'COLCON.BDREFCOMP = '||prreffimpag;
               END
          END
     END


  IF ((prcodtpcc IS NULL) OR (prcodtpcc = '')) THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql||wwheren
       INTO
         :bdcodver,
         :bdcodemp,
         :bdcodcol,
         :bdreffn,
         :BDREFCOMP,
         :bdrefvfc,
         :bdrefauxvfc,
         :bdvalvfC,
         :bdignrefvfc,
         :bdignrefavfc,
         :bdignvalvfc,
         :BDREFFC
       DO
         BEGIN
           bdcalctomador = 'FALSE';
           SUSPEND;
         END
     END

  IF (prreffimpag IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffimpag, NULL, NULL);
  ELSE IF (prrefinipag IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefinipag, NULL, NULL);


   IF ((PRSEPARARCALC IS NULL) OR (PRSEPARARCALC = 0))  THEN
      BEGIN
        IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador >= 1)) THEN
           BEGIN
             wdatapag = 'max(colcon.BDREFFC)';
             wgroupbydatapag = '';
           END
        ELSE
           BEGIN
             wdatapag = 'colcon.BDREFFC';
             wgroupbydatapag = '';
           END
      END
   ELSE
      BEGIN
        wdatapag = 'colcon.BDREFFC';
        wgroupbydatapag = ',colcon.BDREFFC';
      END

  --wsql2 = '';
--  if ((wwheret is null) or (wwheret = '') ) then
--     wwheret = ' where 0 = 0';

  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, cast(null as integer), '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, sum(COLCON.BDREFVFC), max(COLCON.BDREFAUXVFC), '||
                'max(COLCON.BDREFVFC), sum(COLCON.BDREFAUXVFC), max(colcon.bdtiporefver), '||
                'sum(COLCON.BDVALVFC), max(COLCON.BDIGNREFVFC), max(COLCON.BDIGNREFAVFC), max(COLCON.BDIGNVALVFC), '||
                'colcon.bdCodCentrotoma bdcodcentro , colcon.bdCODTPCCtoma bdcodtpcc, '||
                wdatapag||
              ' from ( ';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, COLCON.BDREFFC, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'toma.bdCodCentro bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, pf.BDCODCENTRO, pf.BDCODTPCC '||
              'from vrhf_emp_tverbafctomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'left outer join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (colcon.bdcodver = tv.bdcodver) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          BEGIN
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          END

       wsql = wsql||'group by COLCON.BDCODVER,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR,COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, colcon.bdCODTPCCtoma'||wgroupbydatapag;
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, cast(null as integer), '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, sum(COLCON.BDREFVFC), max(COLCON.BDREFAUXVFC), '||
                'max(COLCON.BDREFVFC), sum(COLCON.BDREFAUXVFC), max(COLCON.bdtiporefver), '||
                'sum(COLCON.BDVALVFC), max(COLCON.BDIGNREFVFC), max(COLCON.BDIGNREFAVFC), max(COLCON.BDIGNVALVFC), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC,'||
                wdatapag||' from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, COLCON.BDREFFC, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.bdCodCentro, toma.bdCODTPCC '||
              'from vrhf_emp_tverbafctomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'left outer join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (colcon.bdcodver = tv.bdcodver) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          BEGIN
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          END

       wsql = wsql||' group by COLCON.BDCODVER, colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentro, COLCON.bdCODTPCC'||wgroupbydatapag;
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, cast(null as integer), '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, sum(COLCON.BDREFVFC), max(COLCON.BDREFAUXVFC), '||
                'max(COLCON.BDREFVFC), sum(COLCON.BDREFAUXVFC), max(COLCON.bdtiporefver), '||
                'sum(COLCON.BDVALVFC), max(COLCON.BDIGNREFVFC), max(COLCON.BDIGNREFAVFC), max(COLCON.BDIGNVALVFC), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                wdatapag||
                ' from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFC, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.bdCodCentro, pf.bdCODTPCC '||
              'from vrhf_emp_tverbafctomador COLCON, vrhf_emp_tprepfn pf, VW_VERBAS_REF_ATUAL tv, tempresas emp '||
              'where (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) and (colcon.bdcodver = tv.bdcodver) and (colcon.bdcodemp = emp.bdcodemp)'||
              wwheret||') COLCON ';

        IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          BEGIN
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          END

        wsql = wsql||'group by COLCON.BDCODVER,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR,colcon.BDREFCOMP,COLCON.bdCodCentro, COLCON.bdCODTPCC'||wgroupbydatapag;
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, cast(null as integer), '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, sum(COLCON.BDREFVFC), max(COLCON.BDREFAUXVFC), '||
                'max(COLCON.BDREFVFC), sum(COLCON.BDREFAUXVFC), max(COLCON.bdtiporefver), '||
                'sum(COLCON.BDVALVFC), max(COLCON.BDIGNREFVFC), max(COLCON.BDIGNREFAVFC), max(COLCON.BDIGNVALVFC), '||
                'cast(null as integer), cast(null as integer), '||
              wdatapag||
              ' from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFFC, '||
                'COLCON.BDREFVFC, COLCON.BDREFAUXVFC, tv.bdtiporefver, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.BDCODCENTRO, pf.BDCODTPCC '||
              'from '||
                'vrhf_emp_tverbafctomador COLCON, tempresas emp, '||
                'VW_VERBAS_REF_ATUAL tv, '||
                'vrhf_emp_tprepfn pf '||
              'where (colcon.bdcodver = tv.bdcodver) and (colcon.bdcodemp = emp.bdcodemp) and (COLCON.BDCODEMP = pf.BDCODEMP and COLCON.BDCODCOL = pf.BDCODCOL and COLCON.BDORDEM = pf.BDORDEM) '||
              wwheret||') COLCON ';

        IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          BEGIN
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          END

        wsql = wsql||'group by COLCON.BDCODVER,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFTOMADOR,colcon.BDREFCOMP'||wgroupbydatapag;
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.bdtiporefver, COLCON.BDVALVFC, '||
                'COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                wdatapag||
              ' from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, tv.bdtiporefver, COLCON.BDVALVFC, '||
                'COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, COLCON.BDREFFC, '||
                'pf.bdCodCentro, pf.bdCODTPCC '||
              'from '||
                'vrhf_emp_tverbafctomador COLCON, tempresas emp, '||
                'vrhf_emp_tprepfn pf, '||
                'VW_VERBAS_REF_ATUAL tv '||
              'where (colcon.bdcodemp = emp.bdcodemp) and (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
                    'and (colcon.bdcodver = tv.bdcodver) '||
              wwheret||') COLCON ';

        IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          BEGIN
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          END
     END

  IF (wsql <> '') THEN
     BEGIN
       bdcalctomador = 'TRUE';
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodver,
         :bdcodemp,
         :bdcodcol,
         :bdOrdem,
         :bdreffn,
         :BDREFCOMP,
         :bdrefvfc,
         :bdrefauxvfc,
         :waux1,
         :waux2,
         :wauxtipo,
         :bdvalvfc,
         :bdignrefvfc,
         :bdignrefavfc,
         :bdignvalvfc,
         :bdcodcentro,
         :bdcodtpcc,
         :BDREFFC
       DO
         BEGIN
           IF (wauxtipo = 4) THEN
              BEGIN
                BDREFVFC = waux1;
                bdrefauxvfc = waux2;
              END
           SUSPEND;
         END
     END

END
^

/* Alter (VRHF_SP_TVERBAFN) */
ALTER PROCEDURE VRHF_SP_TVERBAFN(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = null,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(2788) = null)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(15,6),
BDREFAUXVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNREFAVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCODCONTTI INTEGER)
 AS
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WWHERET varchar(32700);
declare variable WMAXREF numeric(15,6);
declare variable WSUMREF numeric(15,6);
declare variable WTIPOREF integer;
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e Tomador/centro custo
     3 = Agrupo por referencia e Tomador
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  /* Procedure Text */
  wsql = 'select COLCON.bdcodver, COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdreffn, COLCON.bdrefvfn,'||
         'COLCON.bdrefauxvfn, COLCON.bdvalvfn, COLCON.bdignrefvfn, COLCON.bdignrefavfn, COLCON.bdignvalvfn, cast(null as INTEGER) BDCODCONTTI '||
         ' from vrhf_emp_tverbafn COLCON';

  IF (prpuxafiliais = 1) THEN
     BEGIN
       wsql = wsql||' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            prcodemp = UPPER(prcodemp);
     
            IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ') INTO wwheren;
                 prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
               END
            ELSE
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
               END
          END
     END

  wwheren = '';
  wwheret = '';

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||prcodemp;
       wwheret = wwhereT||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||prcodcol;
       wwheret = wwhereT||prcodcol;
     END

  IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||'BDREFFN >= '||prrefini||' and '||'BDREFFN <= '||prreffim;
       wwheret = wwhereT||'BDREFTOMADOR >= '||prrefini||' and '||'BDREFTOMADOR <= '||prreffim;
     END
  ELSE
     BEGIN
       IF (prrefini IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||' where ';
               END

            wwheren = wwheren||'BDREFFN = '||prrefini;
            wwheret = wwhereT||'BDREFTOMADOR = '||prrefini;
          END
       ELSE
          BEGIN
            IF (prreffim IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||' where ';
                    END

                 wwheren = wwheren||'BDREFFN = '||prreffim;
                 wwheret = wwhereT||'BDREFTOMADOR = '||prreffim;
               END
          END
     END

  wsql = wsql||wwheren;


  wsql = wsql||' union all ';


  wsql = wsql||'select COLCON.bdcodver, COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdreffn, COLCON.bdrefvfn,'||
         'COLCON.bdrefauxvfn, COLCON.bdvalvfn, COLCON.bdignrefvfn, COLCON.bdignrefavfn, COLCON.bdignvalvfn, COLCON.BDCODCONTTI '||
         ' from vrhf_emp_tverbaint COLCON';

  IF (prpuxafiliais = 1) THEN
     BEGIN
       wsql = wsql||' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            prcodemp = UPPER(prcodemp);
     
            IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ') INTO wwheren;
                 prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
               END
            ELSE
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
               END
          END
     END

  wsql = wsql||wwheren;

  IF ((prcodtpcc IS NULL) OR (prcodtpcc = '')) THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodver,
         :bdcodemp,
         :bdcodcol,
         :bdreffn,
         :bdrefvfn,
         :bdrefauxvfn,
         :bdvalvfn,
         :bdignrefvfn,
         :bdignrefavfn,
         :bdignvalvfn,
         :bdcodcontti
       DO
         BEGIN
           bdcalctomador = 'FALSE';

           if (bdcodcontti is null) then
              bdcodcontti = 0;
           SUSPEND;
         END
    END

  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE IF (prrefini IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);


  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador IN (1,2,3,4))) THEN
     BEGIN
       wwheret = replace(wwheret, 'BDREFTOMADOR', 'COLCON.BDREFTOMADOR');

       wsql = 'select BDCODVER,BDCODEMP,BDCODCOL,BDORDEM,BDREFTOMADOR,BDREFVFT_SUM,BDREFVFT_MAX,BDREFAUXVFT,BDVALVFT,BDIGNREFVFT,BDIGNREFAVFT,'||
              'BDIGNVALVFT,BDCODCENTRO,BDCODTPCC,BDTIPOREFVER,BDCODCONTTI from SP_VRHF_AGRUPA_VERBAS_FT('||pragrupatomador||','''||wwheret||''',';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||''''||prcodtpcc||''') ';
       ELSE
          wsql = wsql||'null) ';

     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, COLCON.BDREFVFT,COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                'COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT, '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, VERREF.BDTIPOREFVER, cast(null as INTEGER) BDCODCONTTI '||
              'from ( ';

       wsql = wsql||'select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem,'||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT,'||
              'COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT, '||
              'pf.bdCodCentro, pf.bdCODTPCC '||
              ' from vrhf_emp_tverbatomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              ' join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              wwheret||') COLCON ';
       wsql = wsql||
              'left outer join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = COLCON.BDCODVER) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;


       wsql = wsql||' union all select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, COLCON.BDREFVFT,COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                'COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT, '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, VERREF.BDTIPOREFVER, COLCON.BDCODCONTTI '||
              'from ( ';

       wsql = wsql||'select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem,'||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT,'||
              'COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT, '||
              'pf.bdCodCentro, pf.bdCODTPCC, COLCON.BDCODCONTTI '||
              ' from vrhf_emp_tverbatomint COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              ' join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              wwheret||') COLCON ';
       wsql = wsql||
              'left outer join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = COLCON.BDCODVER) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;
     END

  IF (wsql <> '') THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodver,
         :bdcodemp,
         :bdcodcol,
         :bdOrdem,
         :bdreffn,
         :wsumref,
         :wmaxref,
         :bdrefauxvfn,
         :bdvalvfn,
         :bdignrefvfn,
         :bdignrefavfn,
         :bdignvalvfn,
         :bdcodcentro,
         :bdcodtpcc,
         :wtiporef,
         :bdcodcontti
       DO
         BEGIN
           bdcalctomador = 'TRUE';

           IF (wtiporef = 4) THEN
              bdrefvfn = wmaxref;
           ELSE
              bdrefvfn = wsumref;

           if (bdcodcontti is null) then
              bdcodcontti = 0;

           SUSPEND;
         END
     END
END
^

/* Alter (VRHF_SP_UNION_VERBAS_SIM_NAO) */
ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF BLOB,
BDFORMVAL BLOB,
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WSQLFUNC VARCHAR(15000);
DECLARE VARIABLE WDATAINI VARCHAR(8);
DECLARE VARIABLE WDATAFIM VARCHAR(8);
DECLARE VARIABLE WDTAUX VARCHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(NULL, prdataini, prdatafim);

  wdtaux = CAST(prdataini AS VARCHAR(10));
  wdataini = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wdtaux = CAST(prdatafim AS VARCHAR(10));
  wdatafim = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);


  wsql = 'select t.BDCODEMP, '||
                'empresas.BDNOMEMP, '||
                'empresas.bdcnpjemp, '||
                't.BDCODCOL, '||
                'vw_col.bdnomcol,'||
                'COL_DIAVINC.BDCODPLAFUC,'||
                'COL_DIAVINC.BDCODTFUC,'||
                't.BDCODSINTRAB, '||
                't.BDCODVER, '||
                'tverbas.BDDESCVER,'||
                't.BDANOINI, '||
                't.BDMESINI, '||
                't.BDDIAINI, '||
                't.BDANOFIM, '||
                't.BDMESFIM, '||
                't.BDDIAFIM, '||
                't.BDFORMULAREF, '||
                't.BDFORMULAVAL, '||
                't.BDDESCCOND, '||
                't.BDLOCAL, '||
                't.BDSIMNAO ';

  wsql = wsql||'from vw_union_verbas_sim_nao t ';

  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql|| 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = t.bdcodemp and vw_col.bdcodcol = t.bdcodcol) ';

  wsql = wsql || 'left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = t.BDCODEMP and
                                                                     COL_DIAVINC.BDCODCOL = t.BDCODCOL) ';

  wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wsql = wsql||' and '||PRCODEMP;

  IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
     wsql = wsql||' and '||prcodsintrab;

  IF (prlocal IS NOT NULL AND prlocal <> '') THEN
     wsql = wsql||' and '||prlocal;

  IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
     wsql = wsql||' and '||prsimnao;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     wsql = wsql||' and '||PRCODCOL;

  wSql = wSQl ||' and bdlocal = ''FUNC''';


  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :bdcodcol,
    :bdnomcol,
    :BDCODPLAFUC,
    :BDCODTFUC,
    :bdcodsind,
    :BDCODVER,
    :BDDESCVER,
    :BDANOINI,
    :BDMESINI,
    :BDDIAINI,
    :BDANOFIM,
    :BDMESFIM,
    :BDDIAFIM,
    :BDFORMREF,
    :BDFORMVAL,
    :BDDESCCOND,
    :bdlocal,
    :BDSIMNAO
  DO
  SUSPEND;

-- exit;

  /* inicio verbas sim nao empresa... */

  wsql = 'select t.BDCODEMP, '||
                'empresas.BDNOMEMP, '||
                'empresas.bdcnpjemp, '||
                't.BDCODCOL, '||
                'vw_col.bdnomcol,'||
                'COL_DIAVINC.BDCODPLAFUC,'||
                'COL_DIAVINC.BDCODTFUC,'||
                't.BDCODSINTRAB, '||
                't.BDCODVER, '||
                'tverbas.BDDESCVER,'||
                't.BDANOINI, '||
                't.BDMESINI, '||
                't.BDDIAINI, '||
                't.BDANOFIM, '||
                't.BDMESFIM, '||
                't.BDDIAFIM, '||
                't.BDFORMULAREF, '||
                't.BDFORMULAVAL, '||
                't.BDDESCCOND, '||
                't.BDLOCAL, '||
                't.BDSIMNAO ';

  wsql = wsql||'from vw_union_verbas_sim_nao t ';

  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql|| 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = t.bdcodemp and vw_col.bdcodcol = t.bdcodcol) ';

  wsql = wsql || 'left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = t.BDCODEMP and
                                                                     COL_DIAVINC.BDCODCOL = t.BDCODCOL) ';

  wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';

  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wsql = wsql||' and '||PRCODEMP;

  IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
     wsql = wsql||' and '||prcodsintrab;

  IF (prlocal IS NOT NULL AND prlocal <> '') THEN
     wsql = wsql||' and '||prlocal;

  IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
     wsql = wsql||' and '||prsimnao;

  wSql = wSQl ||' and bdlocal = ''EMP''';


  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :bdnomemp, :bdcnpjemp, :bdcodcol, :bdnomcol, :BDCODPLAFUC, :BDCODTFUC, :bdcodsind, :BDCODVER, :BDDESCVER, :BDANOINI,
    :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMREF, :BDFORMVAL, :BDDESCCOND, :bdlocal, :BDSIMNAO
  DO
  BEGIN

    wsqlfunc = ' select BDCODEMP, BDCODCOL from VW_COLABORADORES_REF_ATUAL  t' ;

    wsqlfunc = wsqlfunc ||' WHERE t.BDCODEMP = '|| :bdcodemp ;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     wsqlfunc = wsqlfunc||' and '||PRCODCOL;

    -- FAZ UM FOR EM TODOS OS FUNCIONARIOS REFERENTE A EMPRESA ATUAL PARA LANCAR AS VERBAS POR EMPRESA
    FOR EXECUTE STATEMENT wsqlfunc
      INTO :BDCODEMP, :bdcodcol  DO
      BEGIN

       SUSPEND;
      END
  END

  /* FINAL verbas sim nao empresa... */

  EXIT;

 /* inicio verbas sim nao sindicato... */

  wsql = 'select t.BDCODEMP, '||
                't.BDCODCOL, '||
                't.BDCODSINTRAB, '||
                't.BDCODVER, '||
                'tverbas.BDDESCVER,'||
                't.BDANOINI, '||
                't.BDMESINI, '||
                't.BDDIAINI, '||
                't.BDANOFIM, '||
                't.BDMESFIM, '||
                't.BDDIAFIM, '||
                't.BDFORMULAREF, '||
                't.BDFORMULAVAL, '||
                't.BDDESCCOND, '||
                't.BDLOCAL, '||
                't.BDSIMNAO ';
  wsql = wsql||'from vw_union_verbas_sim_nao t ';

  wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
     wsql = wsql||' and '||prcodsintrab;

  IF (prlocal IS NOT NULL AND prlocal <> '') THEN
     wsql = wsql||' and '||prlocal;

  IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
     wsql = wsql||' and '||prsimnao;

  wSql = wSQl ||' and bdlocal = ''SIND''';


  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :bdcodcol, :bdcodsind, :BDCODVER, :bddescver, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMREF, :BDFORMVAL,:BDDESCCOND, :bdlocal, :BDSIMNAO  DO
  BEGIN

    wsqlfunc = ' select BDCODEMP, BDCODCOL from VW_COLABORADORES_REF_ATUAL  t' ;

    wsqlfunc = wsqlfunc ||' WHERE t.bdcodsintrab = '|| :bdcodsind ;

    IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
       wsqlfunc = wsqlfunc||' and '||PRCODEMP;

    IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
       wsqlfunc = wsqlfunc||' and '||PRCODCOL;

    -- FAZ UM FOR EM TODOS OS FUNCIONARIOS REFERENTE O SINDICATO ATUAL PARA LANCAR AS VERBAS POR SINDICATO
    FOR EXECUTE STATEMENT wsqlfunc
      INTO :BDCODEMP, :bdcodcol  DO
      BEGIN

       SUSPEND;
      END
  END

  /* FINAL verbas sim nao sindicato... */

--  exit;


 /* inicio verbas sim nao FUNCOES... */

  wsql = 'select t.BDCODEMP, '||
                't.BDCODCOL, '||
                't.BDCODSINTRAB, '||
                't.BDCODVER, '||
                'tverbas.BDDESCVER,'||
                't.BDANOINI, '||
                't.BDMESINI, '||
                't.BDDIAINI, '||
                't.BDANOFIM, '||
                't.BDMESFIM, '||
                't.BDDIAFIM, '||
                't.BDFORMULAREF, '||
                't.BDFORMULAVAL, '||
                't.BDDESCCOND, '||
                't.BDLOCAL, '||
                't.BDSIMNAO ';
  wsql = wsql||'from vw_union_verbas_sim_nao t ';

  wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';

  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
     wsql = wsql||' and '||prcodsintrab;

  IF (prlocal IS NOT NULL AND prlocal <> '') THEN
     wsql = wsql||' and '||prlocal;

  IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
     wsql = wsql||' and '||prsimnao;

  wSql = wSQl ||' and bdlocal = ''FUNCAO''';


  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :bdcodcol, :bdcodsind, :BDCODVER, :bddescver, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMREF, :BDFORMVAL,:BDDESCCOND, :bdlocal, :BDSIMNAO  DO
  BEGIN

    wsqlfunc = ' select BDCODEMP, BDCODCOL from VW_COLABORADORES_REF_ATUAL  t' ;

    wsqlfunc = wsqlfunc ||' WHERE t.bdcodsintrab = '|| :bdcodsind ;

    IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
       wsqlfunc = wsqlfunc||' and '||PRCODCOL;

    -- FAZ UM FOR EM TODOS OS FUNCIONARIOS REFERENTE a funcao ATUAL PARA LANCAR AS VERBAS POR funcao
    FOR EXECUTE STATEMENT wsqlfunc
      INTO :BDCODEMP, :bdcodcol  DO
      BEGIN

       SUSPEND;
      END
  END

  /* FINAL verbas sim nao FUNCOES... */




  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_UNION_VERBAS_SIM_NAO_2) */
ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO_2(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WSQLFUNC VARCHAR(15000);
DECLARE VARIABLE WDATAINI VARCHAR(8);
DECLARE VARIABLE WDATAFIM VARCHAR(8);
DECLARE VARIABLE WDTAUX VARCHAR(10);
DECLARE VARIABLE WWHERE VARCHAR(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(NULL, prdataini, prdatafim);

  wdtaux = CAST(prdataini AS VARCHAR(10));
  wdataini = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wdtaux = CAST(prdatafim AS VARCHAR(10));
  wdatafim = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wsqlfunc = ' select T.BDCODEMP, ' ||
             ' EMPRESAS.BDNOMEMP, ' ||
             'EMPRESAS.BDCNPJEMP,' ||
             'T.BDCODCOL,' ||
             'vw_col.bdnomcol,' ||
             'COL_DIAVINC.BDCODPLAFUC,' ||
             'COL_DIAVINC.BDCODTFUC,' ||
             't.BDCODSINTRAB' ||
             ' from VW_COLABORADORES_REF_ATUAL  t' ;

  wsqlfunc = wsqlfunc||' left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsqlfunc = wsqlfunc|| 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = t.bdcodemp and vw_col.bdcodcol = t.bdcodcol) ';

  wsqlfunc = wsqlfunc || 'left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = t.BDCODEMP and
                                                                     COL_DIAVINC.BDCODCOL = t.BDCODCOL) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsqlfunc = wsqlfunc||wwhere;

  -- FAZ UM FOR EM TODOS OS FUNCIONARIOS
  FOR EXECUTE STATEMENT wsqlfunc
    INTO :BDCODEMP, :bdnomemp, :bdcnpjemp, :bdcodcol , :bdnomcol, :BDCODPLAFUC, :bdcodtfuc, :bdcodsind DO
    BEGIN

      wwhere = '';

      wsql = 'select t.BDCODVER, '||
             'tverbas.BDDESCVER,'||
             't.BDANOINI, '||
             't.BDMESINI, '||
             't.BDDIAINI, '||
             't.BDANOFIM, '||
             't.BDMESFIM, '||
             't.BDDIAFIM, '||
             't.BDFORMULAREF, '||
             't.BDFORMULAVAL, '||
             't.BDDESCCOND, '||
             't.BDLOCAL, '||
             't.BDSIMNAO ';

      wsql = wsql||'from vw_union_verbas_sim_nao t ';

      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


      wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                    '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                    '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

      wsql = wsql||' and t.bdcodemp = '||:bdcodemp;

      IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
         wsql = wsql||' and '||prcodsintrab;

      IF (prlocal IS NOT NULL AND prlocal <> '') THEN
         wsql = wsql||' and '||prlocal;

      IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
         wsql = wsql||' and '||prsimnao;

      wsql = wsql||' and t.bdcodcol = '||:bdcodcol;

      wSql = wSQl ||' and bdlocal = ''FUNC''';

      /* laco de verbas sim nao por funcionario */

      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODVER,
        :BDDESCVER,
        :BDANOINI,
        :BDMESINI,
        :BDDIAINI,
        :BDANOFIM,
        :BDMESFIM,
        :BDDIAFIM,
        :BDFORMREF,
        :BDFORMVAL,
        :BDDESCCOND,
        :bdlocal,
        :BDSIMNAO
      DO
      SUSPEND;

    /* final laco verbas sim nao funcionario */

    /* inicio verbas sim nao empresa */

      wwhere = '';

      wsql = 'select t.BDCODVER, '||
             'tverbas.BDDESCVER,'||
             't.BDANOINI, '||
             't.BDMESINI, '||
             't.BDDIAINI, '||
             't.BDANOFIM, '||
             't.BDMESFIM, '||
             't.BDDIAFIM, '||
             't.BDFORMULAREF, '||
             't.BDFORMULAVAL, '||
             't.BDDESCCOND, '||
             't.BDLOCAL, '||
             't.BDSIMNAO ';

      wsql = wsql||'from vw_union_verbas_sim_nao t ';

      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


      wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                    '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                    '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

      wsql = wsql||' and t.bdcodemp = '||:bdcodemp;

      IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
         wsql = wsql||' and '||prcodsintrab;

      IF (prlocal IS NOT NULL AND prlocal <> '') THEN
         wsql = wsql||' and '||prlocal;

      IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
         wsql = wsql||' and '||prsimnao;

      wSql = wSQl ||' and bdlocal = ''EMP''';

      /* laco de verbas sim nao por EMPRESA */

      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODVER,
        :BDDESCVER,
        :BDANOINI,
        :BDMESINI,
        :BDDIAINI,
        :BDANOFIM,
        :BDMESFIM,
        :BDDIAFIM,
        :BDFORMREF,
        :BDFORMVAL,
        :BDDESCCOND,
        :bdlocal,
        :BDSIMNAO
      DO
      SUSPEND;

      /* fim verbas sim nao por empresa */

    /* inicio verbas sim nao sindicato */

      wwhere = '';

      wsql = 'select t.BDCODVER, '||
             'tverbas.BDDESCVER,'||
             't.BDANOINI, '||
             't.BDMESINI, '||
             't.BDDIAINI, '||
             't.BDANOFIM, '||
             't.BDMESFIM, '||
             't.BDDIAFIM, '||
             't.BDFORMULAREF, '||
             't.BDFORMULAVAL, '||
             't.BDDESCCOND, '||
             't.BDLOCAL, '||
             't.BDSIMNAO ';

      wsql = wsql||'from vw_union_verbas_sim_nao t ';

      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


      wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                    '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                    '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

      IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
         wsql = wsql||' and '||prcodsintrab;

      IF (prlocal IS NOT NULL AND prlocal <> '') THEN
         wsql = wsql||' and '||prlocal;

      IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
         wsql = wsql||' and '||prsimnao;

      wSql = wSQl ||' and bdlocal = ''SIND''';

      IF (:bdcodsind IS NOT NULL) THEN
         wsql = wsql ||' and t.bdcodsintrab = '|| :bdcodsind;
      ELSE
         wsql = wsql ||' and t.bdcodsintrab = '|| 999999;

      /* laco de verbas sim nao por SINDICATO */

      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODVER,
        :BDDESCVER,
        :BDANOINI,
        :BDMESINI,
        :BDDIAINI,
        :BDANOFIM,
        :BDMESFIM,
        :BDDIAFIM,
        :BDFORMREF,
        :BDFORMVAL,
        :BDDESCCOND,
        :bdlocal,
        :BDSIMNAO
      DO
      SUSPEND;

      /* fim verbas sim nao por SINDICATO */

      /* inicio verbas sim nao funcao */

      wwhere = '';

      wsql = 'select t.BDCODVER, '||
             'tverbas.BDDESCVER,'||
             't.BDANOINI, '||
             't.BDMESINI, '||
             't.BDDIAINI, '||
             't.BDANOFIM, '||
             't.BDMESFIM, '||
             't.BDDIAFIM, '||
             't.BDFORMULAREF, '||
             't.BDFORMULAVAL, '||
             't.BDDESCCOND, '||
             't.BDLOCAL, '||
             't.BDSIMNAO ';

      wsql = wsql||'from vw_union_verbas_sim_nao t ';

      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


      wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                    '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                    '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

      IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
         wsql = wsql||' and '||prcodsintrab;

      IF (prlocal IS NOT NULL AND prlocal <> '') THEN
         wsql = wsql||' and '||prlocal;

      IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
         wsql = wsql||' and '||prsimnao;

      wSql = wSQl ||' and bdlocal = ''FUNCAO''';

      IF (:bdcodplafuc IS NOT NULL) THEN
         wsql = wsql ||' and T.BDCODPLAFUC = '|| :bdcodplafuc;
      ELSE
         wsql = wsql ||' and T.BDCODPLAFUC = '|| 999999;

      IF (:bdcodtfuc IS NOT NULL) THEN
         wsql = wsql ||' and T.BDCODFUNCAO = '|| :bdcodtfuc;
      ELSE
         wsql = wsql ||' and T.BDCODFUNCAO= '|| 999999;

      /* laco de verbas sim nao por funcao */

      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODVER,
        :BDDESCVER,
        :BDANOINI,
        :BDMESINI,
        :BDDIAINI,
        :BDANOFIM,
        :BDMESFIM,
        :BDDIAFIM,
        :BDFORMREF,
        :BDFORMVAL,
        :BDDESCCOND,
        :bdlocal,
        :BDSIMNAO
      DO
      SUSPEND;

      /* fim verbas sim nao por funcao */

    END /* fim laco do funcinario */

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_VERBAS_FN_FC) */
ALTER PROCEDURE VRHF_SP_VERBAS_FN_FC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRCLASSVERBAS VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WDATA DATE;
BEGIN
  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'X.BDREF, '||
                'Y.BDCODVER, '||
                'SUM(X.BDREFV), '||
                'SUM(X.BDREFAUXV), '||
                'SUM(X.BDVALV), '||
                'MAX(X.BDBFGTS), '||
                'MAX(X.BDFGTS), '||
                'MAX(X.BDFGTSCS), '||
                'MAX(X.BDBFGTS13), '||
                'MAX(X.BDFGTS13), '||
                'MAX(X.BDFGTS13CS), '||
                'MAX(X.BDMAIORREM), '||
                'MAX(X.BDBINSS), '||
                'MAX(X.BDALIQINSS), '||
                'MAX(X.BDINSS), '||
                'MAX(X.BDBIRRF), '||
                'MAX(X.BDALIQIRRF), '||
                'MAX(X.BDIRRF), '||
                'MAX(X.BDBINSS13), '||
                'MAX(X.BDALIQINSS13), '||
                'MAX(X.BDINSS13), '||
                'MAX(X.BDBIRRF13), '||
                'MAX(X.BDALIQIRRF13), '||
                'MAX(X.BDIRRF13), '||
                'MAX(X.BDBSALFAM), '||
                'MAX(X.BDSALFAM), '||
                'MAX(X.BDBRAIS), '||
                'MAX(X.BDSALBASE), '||
                'MAX(X.BDDEP), '||
                'Y.BDDESCVER, '||
                'y.bddescredver, '||
                'Y.BDCLAVER, '||
                'X.BDIGNREFAV, '||
                'X.BDIGNREFV, '||
                'X.BDIGNVALV, '||
                'X.BDTIPO ';

  wsql = wsql||'from SP_VRHF_VERBAS_FN_FC X '||
               'left outer join VRH_BASE_TVERBAS Y '||
                 'on (X.BDCODVER = Y.BDCODVER) ' ||

             'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
             'on (EMP.BDCODEMP = X.BDCODEMP) '||

             'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
             'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';


  wwhere = '';

  IF (PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF (PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (PRCLASSVERBAS IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCLASSVERBAS||') ';
     END 

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||'group by X.BDCODEMP, '||
                        'EMP.BDNOMEMP, '||
                        'X.BDCODCOL, '||
                        'COL.BDNOMCOL, '||
                        'X.BDREF, '||
                        'Y.BDCODVER, '||
                        'Y.BDDESCVER, '||
                        'Y.BDDESCREDVER, '||
                        'Y.BDCLAVER, ' ||
                        'X.BDIGNREFV, '||
                        'X.BDIGNVALV, '||
                        'X.BDTIPO ';

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :BDCODCOL,
        :bdnomcol,
        :BDREF,
        :BDCODVER,
        :BDREFV,
        :BDREFAUXV,
        :BDVALV,
        :BDBFGTS,
        :BDFGTS,
        :BDFGTSCS,
        :BDBFGTS13,
        :BDFGTS13,
        :BDFGTS13CS,
        :BDMAIORREM,
        :BDBINSS,
        :BDALIQINSS,
        :BDINSS,
        :BDBIRRF,
        :BDALIQIRRF,
        :BDIRRF,
        :BDBINSS13,
        :BDALIQINSS13,
        :BDINSS13,
        :BDBIRRF13,
        :BDALIQIRRF13,
        :BDIRRF13,
        :BDBSALFAM,
        :BDSALFAM,
        :BDBRAIS,
        :BDSALBASE,
        :BDDEP,
        :bddescver,
        :BDDESCREDVER,
        :BDCLAVER,
        :BDIGNREFAV,
        :BDIGNREFV,
        :BDIGNVALV,
        :BDTIPO
      DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_VERBAS_FOL_NORMAL_AUT) */
ALTER PROCEDURE VRHF_SP_VERBAS_FOL_NORMAL_AUT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRFILTRO VARCHAR(2000),
PRCODTPCC VARCHAR(10000),
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(772) = null)
 RETURNS(BDCODPLAFUC INTEGER,
BDCODSINTRAB INTEGER,
BDCODCLA INTEGER,
BDDESCENQFED VARCHAR(10),
BDTEMGRRF INTEGER,
BDBSALFAM NUMERIC(18,6),
BDDATARESCISAO DATE,
BDDESCRICAOMOTRES VARCHAR(300),
BDTIPOMOV INTEGER,
BDTIPO_COL INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDCNPJEMP VARCHAR(18),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCOMPLEMP DM_BDCOMPENDERECO,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDPERCRATCOL NUMERIC(18,6),
BDDESCTFUC VARCHAR(150),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCODENQFED INTEGER,
BDSIMPLESGPS INTEGER,
BDCTPSCOL DM_BDCTPS,
BDCODCBO INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREFFN INTEGER,
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(80),
BDREFV NUMERIC(18,6),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDSALBASE NUMERIC(18,6),
BDBINSS NUMERIC(18,6),
BDBFGTS NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDBIRRF NUMERIC(18,6),
BDBRAIS NUMERIC(18,6),
BDDESCREDVER VARCHAR(80),
BDIRRF NUMERIC(18,6),
BDGRUPOCLA INTEGER,
BDBINSS13 NUMERIC(18,6),
BDBFGTS13 NUMERIC(18,6),
BDBIRRF13 NUMERIC(18,6),
BDVFGTS13 NUMERIC(18,6),
BDBINSSFEFOL NUMERIC(18,6),
BDVINSSFEFOL NUMERIC(18,6),
BDBFGTSFEFOL NUMERIC(18,6),
BDVFGTSFEFOL NUMERIC(18,6),
BDDESCCC VARCHAR(80),
BDPISVER VARCHAR(5),
BDCLAVER VARCHAR(20),
BDBFGTSMESANT NUMERIC(18,6),
BDFGTSMESANT NUMERIC(18,6),
BDBFGTSMES NUMERIC(18,6),
BDFGTSMES NUMERIC(18,6),
BDSALDO NUMERIC(18,6),
BDFGTS40 NUMERIC(18,6),
BDFGTS10 NUMERIC(18,6),
BDTOTALGRRF NUMERIC(18,6),
BDORDEMVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDTIPOCODVER INTEGER,
BDCODTFUC INTEGER,
BDTIPOREFVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDVALMVINSSTER NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDDATAPGTO DATE,
BDCCATVCONCOM DM_BOOLEAN,
BDBFGTSMESPOST NUMERIC(18,6),
BDFGTSMESPOST NUMERIC(18,6),
BDINSSFN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDMVINSSTER NUMERIC(18,6),
BDHORASMENSAISCOL NUMERIC(18,6),
BDFGTSIND NUMERIC(18,6),
BDDATAGRRF DATE,
BDBASEINSSMV NUMERIC(18,6),
BDBASEIRRFMV NUMERIC(18,6),
BDVALORINSSMV NUMERIC(18,6),
BDVALORIRRFMV NUMERIC(18,6),
BDPERCMULTA40 NUMERIC(15,2),
BDPERCMULTA10 NUMERIC(15,2),
BDCODCONTTI INTEGER)
 AS
declare variable WCODAUT varchar(10000);
declare variable WSQLAUXDAT varchar(5000);
declare variable WAAAAMM varchar(6);
declare variable WULDIAMES varchar(15);
declare variable WSQL varchar(32700);
declare variable WREFAUX varchar(10);
declare variable WCODEMP varchar(32000);
declare variable WCODCOL varchar(32000);
declare variable WREFINI varchar(10);
declare variable WREFFIM varchar(10);
declare variable WCODTPCC varchar(10000);
declare variable WCALCFGTSMESANT DM_BOOLEAN;
declare variable WTEMAUT integer;
BEGIN
  /* prTIPOCOL
     0 = Todos
     1 = Colaboradores
     2 = Autonomos
  */

  BDVALMVINSSTER = 0;

  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE IF (prrefini IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);

 IF (prcodemp IS NULL) THEN
    wcodemp = 'null';
 ELSE
    wcodemp = ''''||prcodemp||'''';

 IF (prcodcol IS NULL) THEN
    wcodcol = 'null';
 ELSE
    wcodcol = ''''||prcodcol||'''';

 IF (prcodaut IS NULL) THEN
    wcodaut = 'null';
 ELSE
    wcodaut = ''''||prcodaut||'''';

 IF (prcodtpcc IS NULL) THEN
    wcodtpcc = 'null';
 ELSE
    wcodtpcc = ''''||prcodtpcc||'''';

 IF (prtipocol IS NULL) THEN
    prtipocol = 0;

 IF (prrefini IS NULL) THEN
    wrefini = ' null ';
 ELSE
    wrefini = ''||prrefini;

 IF (prreffim IS NULL) THEN
    wreffim = ' null ';
 ELSE
    wreffim = ''||prreffim;

 IF (prreffim IS NOT NULL) THEN
    BEGIN
      wrefaux = wreffim;
    END
 ELSE IF (prrefini IS NOT NULL) THEN
    BEGIN
      wrefaux = wrefini;
    END
 ELSE
    BEGIN
      wrefaux = 'null';
    END

 wsql = '';
 IF (wrefaux <> 'null') THEN
    wsql = 'select cast(ultdia as varchar(2)) from ULTIMO_DIA_MES('||SUBSTRING(wrefaux FROM 5 FOR 2)||','||SUBSTRING(wrefaux FROM 1 FOR 4)||')';

 IF (wsql <> '') THEN
    BEGIN
      EXECUTE STATEMENT wsql INTO wuldiames;
      wuldiames = SUBSTRING(wrefaux FROM 5 FOR 2)||'/'||wuldiames||'/'||SUBSTRING(wrefaux FROM 1 FOR 4);
      wuldiames = ''''||wuldiames||'''';
    END

 IF ((prfiliais IS NOT NULL) OR (prfiliais <> '')) THEN
    prfiliais = ''''||prfiliais||'''';
 ELSE
    prfiliais = 'null';

 wsql = 'select '||
/*01*/       '0 Tipo_Col, '||
/*02*/       'T.BDCODEMP Codigo_Empresa,'||
/*03*/       'T.BDCODCOL Codigo_Colaborador,'||
/*04*/       'EMP.BDNOMEMP Nome_Empresa,'||
/*05*/       'EMP.BDENDEMP Endereco_Empresa,'||
/*06*/       'EMP.BDNUMEMP Numero_Empresa,'||
/*07*/       'EMP.BDBAIEMP Bairro_Empresa,'||
/*08*/       'EMP.BDCEPEMP Cep_Empresa,'||
/*09*/       'tEMP.BDCNPJEMP Cnpj_Empresa,'||
/*10*/       'cidEMP.BDNOMCID Cidade_Empresa,'||
/*11*/       'ufEMP.BDSIGLAUF UF_Empresa,'||
/*12*/       'EMP.BDCOMPLEMP Compl_Empresa ,'||
/*13*/       'COLCAD.BDNOMCOL Nome_Colaborador,'||
/*14*/       'COL.BDDATAADMCOL Admissao_Colaborador, '||
/*15*/       'gpscol.bdpercratcol Rat_Apo_Col ,'||
--/*16*/       'colfunc.BDDESCTFUC Funcao_Colaborador,'||
/*17*/       'doccol.BDCPFCOL Cpf_Colaborador ,'||
/*18*/       'DOCREF.BDPISCOL Pis_Colaborador ,'||
/*19*/       'tenq.bdcodenqfed,'||
/*20*/       'gps.bdsimplesgps,'||
/*21*/       'DOCREF.bdctpscol CTPS_Col,'||
--/*22*/       'COLFUNC.bdcodcbo CBO_Col,'||
/*23*/       't.BDCODCENTRO Codigo_Plano_CC ,'||
/*24*/       't.BDCODTPCC Codigo_CC ,'||
/*25*/       't.bdrefFN Referencia,'||
/*26*/       'T.BDCODVER Codigo_Verba,'||
/*27*/       'T.BDDESCVER Descricao_Verba,'||
/*28*/       'T.BDREFV Referencia_Verba,'||
/*29*/       'T.BDPROVENTO Proventos_Folha ,'||
/*30*/       'T.BDDESCONTO Descontos_Folha,'||
/*31*/       'T.BDSALBASE,'||
/*32*/       'T.BDBINSS,'||
/*33*/       'T.BDBFGTS,'||
/*34*/       't.BDFGTS,'||
/*35*/       't.BDBIRRF,'||
/*36*/       't.BDBRAIS,'||
/*37*/       't.BDDESCREDVER,'||
/*38*/       't.bdirrf,'||
--/*39*/       'gcla.bdgrupocla,'||
/*40*/       't.bdbINSS13,'||
/*41*/       't.bdbFGTS13,'||
/*42*/       't.bdbIRRF13,'||
/*43*/       'cc.bdnomcta,'||
/*44*/       't.BDPISVER,'||
/*45*/       't.BDCLAVER,'||
/*46*/       't.bdfgts13,'||
/*47*/       't.BDBINSSFEFOL,'||
/*48*/       't.BDINSSFEFOL,'||
/*49*/       't.BDBFGTSFEFOL,'||
/*50*/       't.BDFGTSFEFOL,'||
/*51*/       'resc.bddatarescisao,'||
/*52*/       'pres.bddescpres,'||
/*53*/       'pres.bdtipomov,'||
/*54*/       't.bdbSalFam,'||
/*55*/       'DESCFED.BDDESCENQFED,'||
--/*56*/       'vic.bdcodcla,'||
/*57*/       'vinc.BDCODSINTRAB,'||
--/*58*/       'null bdcodplafuc,'||
/*59*/       't.BDORDEMVER,'||
/*60*/       't.BDORDEMTIPOCODVER,'||
/*61*/       't.BDTIPOCODVER,'||
--/*62*/       'null BDCODTFUC, '||
/*63*/       'T.bdtiporefver, '||
/*64*/       'T.bdrefhoremp, '||
/*65*/       'resc.BDCALCFGTSMESANT, '||
/*66*/       'T.BDREFAUXV, '||
/*67*/       'T.BDDATAPGTO, '||
/*67*/       'gps.BDCCATVCONCOM, '||
             'T.BDINSS, '||
             'T.BDINSS13, '||
             'T.BDBINSSAPFN, '||
             'T.BDINSSAPFN, '||
             'T.BDBINSS13APFN, '||
             'T.BDINSS13APFN, '||
             'RESC.BDDATAPAGGRFC, '||
             'T.BDCODCONTTI '||
        ' from VRHF_SP_CALC_FOLHANORMAL ('||wcodemp||','||wcodcol||', '||wrefini||', '||wreffim||', '||pragrupatomador||','||wcodtpcc||
                                         ','||prpuxafiliais||','||prfiliais||') T';


-- wsql = wsql||' left outer join SP_CONSULTAEMPRESAS('||wrefaux||', T.bdcodemp ,  null ) emp on  (T.bdcodemp = emp.bdcodemp)';
 wsql = wsql||' join vw_tempresas_ref emp on (emp.bdcodemp = t.bdcodemp)';
 wsql = wsql||' join tempresas temp on (temp.bdcodemp = t.bdcodemp)';
 wsql = wsql||' join vrh_emp_tcolcon col on (T.BDCODEMP = col.BDCODEMP and T.BDCODCOL = col.BDCODCOL) ';
 wsql = wsql||' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (T.BDCODEMP = COLCAD.BDCODEMP and T.BDCODCOL = COLCAD.BDCODCOL) ';
 wsql = wsql||' left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (T.BDCODEMP = DOCREF.BDCODEMP and T.BDCODCOL = DOCREF.BDCODCOL) ';

 wsql = wsql||' left outer join vrh_emp_tcolcon_doc doccol on (T.BDCODEMP = doccol.BDCODEMP and T.BDCODCOL = doccol.BDCODCOL) ';
 wsql = wsql||' left outer join vrh_emp_tcol_doc doc on (T.BDCODEMP = doc.BDCODEMP and T.BDCODCOL = doc.BDCODCOL) ';
-- wsql = wsql||' left outer join vw_vrh_emp_tcolcon_vinc vic on (T.BDCODEMP = vic.BDCODEMP and T.BDCODCOL = vic.BDCODCOL) ';
-- wsql = wsql||' left outer join VRH_BASE_TCLASSE gcla on (vic.bdcodcla = gcla.bdcodcla) ';
 wsql = wsql||' left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS gpscol on (T.BDCODEMP = gpscol.BDCODEMP and T.BDCODCOL = gpscol.BDCODCOL) ';
 wsql = wsql||' left outer join vrh_emp_trescisao resc on (T.BDCODEMP = resc.BDCODEMP and T.BDCODCOL = resc.BDCODCOL) ';
 wsql = wsql||' left outer join vrh_base_tprepresc pres on (resc.bdcodpres = pres.bdcodpres) ';
 wsql = wsql||' left outer join VW_VRH_EMP_TCOL_VINC vinc on (T.BDCODEMP = vinc.BDCODEMP and T.BDCODCOL = vinc.BDCODCOL) ';
 wsql = wsql||' left outer join tcidade cidemp on (cidemp.bdcodcid = emp.bdcodcid)';
 wsql = wsql||' left outer join tuf ufemp on (cidemp.bdcoduf = ufemp.bdcoduf)';

 wsql = wsql||' left outer join vw_tenqfed TENQ on (TENQ.bdcodemp = t.bdcodemp)';
 wsql = wsql||' left outer join VW_VRHF_BASE_TEMPGPS gps on (gps.bdcodemp = t.bdcodemp)';

-- wsql = wsql||' left outer join VRH_FUNCOES_TFUC colfunc on  (vdia.BDCODPLAFUC = colfunc.BDCODPLAFUC and vdia.BDCODTFUC = colfunc.BDCODTFUC)';
 wsql = wsql||' left outer join centros_tpcc cc on (cc.bdcodcentro = t.bdcodcentro and cc.bdcodtpcc = t.bdcodtpcc)';
 wsql = wsql||' left outer join TCADENQFED DESCFED on (TENQ.BDCODENQFED = DESCFED.BDCODENQFED)';

 IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
    BEGIN
       wsql = wsql||:prfiltro;
    END

 BDVALMVINSSTER = 0;
 BDMVINSSTER    = 0;

 IF (prtipocol<>2) THEN
 FOR EXECUTE STATEMENT wsql INTO
/*01*/ : bdtipo_col ,
/*02*/ : bdcodemp ,
/*03*/ : bdcodcol ,
/*04*/ : bdnomemp ,
/*05*/ : bdendemp ,
/*06*/ : bdnumemp ,
/*07*/ : bdbaiemp ,
/*08*/ : bdcepemp ,
/*09*/ : bdcnpjemp ,
/*10*/ : bdnomcid ,
/*11*/ : bdsiglauf ,
/*12*/ : bdcomplemp ,
/*13*/ : bdnomcol ,
/*14*/ : bddataadmcol ,
/*15*/ : bdpercratcol ,
--/*16*/ : bddesctfuc ,
/*17*/ : bdcpfcol ,
/*18*/ : bdpiscol ,
/*19*/ : bdcodenqfed ,
/*20*/ : bdsimplesgps ,
/*21*/ : bdctpscol ,
--/*22*/ : bdcodcbo ,
/*23*/ : bdcodcentro ,
/*24*/ : bdcodtpcc ,
/*25*/ : bdreffn,
/*26*/ : BDCODVER,
/*27*/ : BDDESCVER,
/*28*/ : BDREFV,
/*29*/ : BDPROVENTO,
/*30*/ : BDDESCONTO,
/*31*/ : BDSALBASE,
/*32*/ : BDBINSS,
/*33*/ : BDBFGTS,
/*34*/ : BDFGTS,
/*35*/ : BDBIRRF,
/*36*/ : BDBRAIS,
/*37*/ : bddescredver,
/*38*/ : bdirrf,
--/*39*/ : bdgrupocla,
/*40*/ : bdbINSS13,
/*41*/ : bdbFGTS13,
/*42*/ : bdbIRRF13,
/*43*/ : BDDESCCC,
/*44*/ : bdpisver,
/*45*/ : bdclaver,
/*46*/ : BDVFGTS13,
/*47*/ : BDBINSSFEFOL,
/*48*/ : BDVINSSFEFOL,
/*49*/ : BDBFGTSFEFOL,
/*50*/ : BDVFGTSFEFOL,
/*51*/ : bddatarescisao,
/*52*/ : bddescricaomotres,
/*53*/ : bdtipomov,
/*54*/ : bdbsalfam,
/*55*/ : BDDESCENQFED,
--/*56*/ : bdcodcla,
/*57*/ : BDCODSINTRAB,
--/*58*/ : bdcodplafuc,
/*59*/ : bdordemver,
/*60*/ : bdordemtipocodver,
/*61*/ : bdtipocodver,
--/*62*/ : bdcodtfuc,
/*63*/ : bdtiporefver,
/*64*/ : bdrefhoremp,
/*65*/ : wcalcfgtsmesant,
/*66*/ : BDREFAUXV,
/*66*/ : BDDATAPGTO,
       : BDCCATVCONCOM,
       : BDINSSFN,
       : BDINSS13FN,
       : BDBINSSAPFN,
       : BDINSSAPFN,
       : BDBINSS13APFN,
       : BDINSS13APFN,
       : BDDATAGRRF,
       : BDCODCONTTI
   DO
   BEGIN
     wsqlauxdat = 'SELECT first 1 X.BDCODPLAFUC, X.BDCODTFUC, Z.BDDESCTFUC, Z.BDCODCBO '||
                  'from vrh_emp_tcol_vincdia X '||
                  'left outer join VRH_FUNCOES_TFUC Z on (Z.BDCODPLAFUC = X.BDCODPLAFUC and Z.BDCODTFUC = X.BDCODTFUC) '||
                  'where X.BDCODEMP =  '||:bdcodemp||' and X.BDCODCOL = '||:bdcodcol||' and SUBSTRING(CAST(X.BDDATACOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDDATACOL AS VARCHAR(10)) FROM 6 FOR 2) <= '||:prrefini||' '||
                  'order by X.BDDATACOL DESC';
     EXECUTE STATEMENT wsqlauxdat INTO :bdcodplafuc, :bdcodtfuc, :bddesctfuc, :bdcodcbo;

     wsqlauxdat = 'SELECT first 1 X.BDCODCLA, Z.BDGRUPOCLA '||
                  'from vrh_emp_tcolcon_vinc X '||
                  'left outer join VRH_BASE_TCLASSE Z on (Z.BDCODCLA = X.BDCODCLA) '||
                  'where X.BDCODEMP =  '||:bdcodemp||' and X.BDCODCOL = '||:bdcodcol||' and X.BDREFCOL <= '||:prrefini||' '||
                  'order by X.BDREFCOL DESC';
     EXECUTE STATEMENT wsqlauxdat INTO :bdcodcla, :bdgrupocla;

     wsqlauxdat = 'SELECT first 1 X.BDHORASMENSAISCOL '||
                  'from VRHF_EMP_TCOL_CALC X '||
                  'where X.BDCODEMP =  '||:bdcodemp||' and X.BDCODCOL = '||:bdcodcol||' and X.BDREFCOL <= '||:prrefini||' '||
                  'order by X.BDREFCOL DESC';
     EXECUTE STATEMENT wsqlauxdat INTO :bdhorasmensaiscol;

     bdcodserv = bdreffn;
     bdbfgtsmesant = 0;
     bdfgtsmesant = 0;
     bdbfgtsmes = 0;
     bdfgtsmes = 0;
     bdsaldo = 0;
     bdfgts40 = 0;
     bdfgts10 = 0;
     bdtotalgrrf = 0;
     bdtemgrrf = 0;
     bdbfgtsmespost = 0;
     bdfgtsmespost = 0;
     bdfgtsind = 0;
     bdpercmulta10 = 0;
     bdpercmulta40 = 0;

     IF (bddatarescisao IS NOT NULL) THEN
        BEGIN
          wsqlauxdat = 'select bdaaaamm from aaaamm(cast('||''''||CAST(bddatarescisao AS VARCHAR(10))||''''||' as date))';

          EXECUTE STATEMENT wsqlauxdat INTO waaaamm;

          IF (waaaamm <> bdreffn) THEN
             BEGIN
               bddatarescisao = NULL;
               bddescricaomotres = '';

               /* Verifica se a rescis?o ? no m?s seguinte e se tem o par?metro de FGTS m?s anterior, para n?o buscar o FGTS do m?s */
               IF (SUBSTRING(waaaamm FROM 5 FOR 2) = '01') THEN
                  waaaamm = CAST((CAST((SUBSTRING(waaaamm FROM 1 FOR 4)) AS INTEGER) - 1) AS VARCHAR(4))||'12';
               ELSE
                  BEGIN
                    IF (CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) <= 10) THEN
                       waaaamm = SUBSTRING(waaaamm FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));
                    ELSE
                       waaaamm = SUBSTRING(waaaamm FROM 1 FOR 4)||CAST((CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2));
                  END

               IF (waaaamm = bdreffn AND UPPER(wcalcfgtsmesant) = 'TRUE') THEN
                  BEGIN
                    bdbfgtsmespost = bdbfgts;
                    bdfgtsmespost = bdfgts;

                    bdbfgts = 0;
                    bdbfgts13 = 0;
                    bdbfgtsfefol = 0;
                    bdfgts = 0;
                    bdvfgts13 = 0;
                    bdvfgtsfefol = 0;
                  END
             END


          IF (bddatarescisao IS NOT NULL) THEN
             BEGIN
               wsqlauxdat = 'select x.bdbfgtsmesant,x.bdfgtsmesant, x.bdbfgtsmes, x.bdfgtsmes, x.bdsaldo, x.bdfgts40, x.bdfgts10, x.bdtotal, x.bdfgtsind, x.bdpercmulta40, x.bdpercmulta10 from VRHF_EMP_VAL_GRRF('||bdcodemp||','||bdcodcol||','||bdreffn||','||bdreffn||',0) x';
               EXECUTE STATEMENT wsqlauxdat INTO
                 : bdbfgtsmesant,
                 : bdfgtsmesant,
                 : bdbfgtsmes,
                 : bdfgtsmes,
                 : bdsaldo,
                 : bdfgts40,
                 : bdfgts10,
                 : bdtotalgrrf,
                 : bdfgtsind,
                 : bdpercmulta40,
                 : bdpercmulta10;

               IF (bdtotalgrrf <> 0) THEN
                  BDTEMGRRF = 1;
             END
        END

     SUSPEND;
   END


 -- A PARTIR DAQUI RETORNA OS DADOS DOS AUT?NOMOS (PARTICIPANTES)

 bdcodsintrab = NULL;
 bdcodplafuc = NULL;
 bdhorasmensaiscol = 220;
 bdfgtsind = 0;
 bddatagrrf = NULL;
 bdcodcontti = 0;

 IF (prcodemp IS NULL) THEN
    wcodemp = 'null';
 ELSE
    BEGIN
      SELECT BDRESULT FROM strtran(UPPER(:prcodemp), 'COLCON.', 'FN.') INTO :wcodemp;
      wcodemp = ''''||wcodemp||'''';
    END
--    wcodemp = ''''||'fn.'||substring(prcodemp from 8)||'''';

 IF (prcodaut IS NULL) THEN
    wcodaut = 'null';
 ELSE
    BEGIN
      SELECT BDRESULT FROM strtran(UPPER(:prcodaut), 'COLCON.', 'FN.') INTO :wcodaut;
      wcodaut = ''''||wcodaut||'''';
    END
--    wcodaut = ''''||'fn.'||substring(prcodaut from 8)||'''';

  IF ((prcodtpcc IS NULL) OR (prcodtpcc = '')) THEN
     wcodtpcc = 'null';
  ELSE
     BEGIN
       SELECT BDRESULT FROM strtran(UPPER(:prcodtpcc), 'COLCON.', 'SERV.') INTO :wcodtpcc;
       wcodtpcc = ''''||wcodtpcc||'''';
     END

 wsql = ' select '||
/*01*/    ' 1,'||
/*02*/    ' T.BDCODEMP Codigo_Empresa,'||
/*03*/    ' T.BDCODCOL Codigo_Colaborador,'||
/*04*/    ' EMP.BDNOMEMP Nome_Empresa,'||
/*05*/    ' EMP.BDENDEMP Endereco_Empresa,'||
/*06*/    ' EMP.BDNUMEMP Numero_Empresa,'||
/*07*/    ' EMP.BDBAIEMP Bairro_Empresa,'||
/*08*/    ' EMP.BDCEPEMP Cep_Empresa,'||
--/*09*/    ' EMP.BDCNPJEMP Cnpj_Empresa,'||
--/*10*/    ' EMP.BDNOMCID Cidade_Empresa,'||
--/*11*/    ' EMP.BDSIGLAUF UF_Empresa,'||
/*09*/    ' tEMP.BDCNPJEMP Cnpj_Empresa,'||
/*10*/       'cidEMP.BDNOMCID Cidade_Empresa,'||
/*11*/       'ufEMP.BDSIGLAUF UF_Empresa,'||
/*12*/    ' EMP.BDCOMPLEMP Compl_Empresa ,'||
--/*13*/    ' col.BDNOMCOL Nome_Colaborador,'||
/*14*/    ' s.BDDATASERV Admissao_Colaborador,'||
--/*15*/    ' COL.bdpercratcol Rat_Apo_Col ,'||
--/*16*/    ' CBO.BDDESCCBOTSIN Funcao_Colaborador,'||
--/*17*/    ' COL.BDCPFCOL Cpf_Colaborador ,'||
--/*18*/    ' COL.BDPISCOL Pis_Colaborador ,'||
/*19*/    ' tenq.bdcodenqfed,'||
/*20*/    ' gps.bdsimplesgps,'||
--/*21*/    ' COL.bdctpscol CTPS_Col,'||
--/*22*/    ' COL.bdcodcbo CBO_Col,'||
/*23*/    ' s.BDCODCENTRO Codigo_Plano_CC ,'||
/*24*/    ' s.BDCODTPCC Codigo_CC        ,'||
/*25*/    ' t.bdreffn, '||
/*26*/    'T.BDCODVER Codigo_Verba,'||
/*27*/    'T.BDDESCVER Descricao_Verba,'||
/*28*/    'T.BDREFV Referencia_Verba,'||
/*29*/    'case when (t.BDTIPOCODVER in (0, 2)) then t.BDVALV else 0 end Proventos_Folha ,'||
/*30*/    'case when (t.BDTIPOCODVER in (0, 2)) then 0 else t.BDVALV end Descontos_Folha,'||
/*31*/    's.BDVALORSERV,'||
/*32*/    'coalesce(t.BDBINSSCALC,t.BDBINSS),'||
/*33*/    'coalesce(t.bdbircalc,t.BDBIRRF),'||
/*34*/    't.BDBRAIS,'||
/*35*/    't.BDDESCREDVER,'||
/*36*/    't.bdirrf,'||
--/*37*/    'col.BDGRUPOCLA,'||
/*38*/    'cc.bdnomcta,'||
/*39*/    't.BDPISVER,'||
/*40*/    't.bdclaver,'||
/*41*/    'DESCFED.BDDESCENQFED,'||
--/*42*/    'col.bdcodcla, '||
/*43*/    't.bdordemver, '||
/*44*/    't.bdordemtipocodver, '||
/*45*/    't.bdtipocodver, '||
/*46*/    't.bdtiporefver, '||
/*47*/    't.bdrefhoremp, '||
          'cs.BDBINSSCALC - cs.BDBASEINSS, '||
          'cs.BDDATAPAGSERV, '||
          'gps.BDCCATVCONCOM, '||
          'cs.BDVALORINSS, '||
          '0 BDINSS13FN, '||
          '0 BDBINSSAPFN, '||
          '0 BDINSSAPFN, '||
          '0 BDBINSS13APFN, '||
          '0 BDINSS13APFN '||
    ' from vrhf_sp_calc_autonomo ('||wcodemp||','||wcodaut||','||wrefaux||', null,'||prpuxafiliais||','||prfiliais||','||wcodtpcc||') T';

 wsql = wsql||' left outer join vrh_base_tservterc s on (t.bdreffn = s.bdcodserv and t.bdcodemp = s.bdcodemp and t.bdcodcol = s.bdcodter)';
 wsql = wsql||' left outer join vrhf_base_calc_terc cs on (t.bdreffn = cs.bdcodserv and t.bdcodemp = cs.bdcodemp and t.bdcodcol = cs.bdcodter)';
-- wsql = wsql||' left outer join SP_CONSULTAEMPRESAS('||wrefaux||', T.bdcodemp ,  null ) emp on  (T.bdcodemp = emp.bdcodemp)';
 wsql = wsql||' join vw_tempresas_ref emp on (emp.bdcodemp = t.bdcodemp)';
 wsql = wsql||' join tempresas temp on (temp.bdcodemp = t.bdcodemp)';
 wsql = wsql||' left outer join tcidade cidemp on (cidemp.bdcodcid = emp.bdcodcid)';
 wsql = wsql||' left outer join tuf ufemp on (cidemp.bdcoduf = ufemp.bdcoduf)';

-- wsql = wsql||' left outer join vrh_sp_cad_terc(null,null, '||wrefaux||', 1,1,1,0,0,0,0,1) col on  (T.BDCODCOL = col.BDCODCOL)';
 wsql = wsql||' left outer join vw_tenqfed TENQ on (TENQ.bdcodemp = t.bdcodemp)';
 wsql = wsql||' left outer join TCADENQFED DESCFED on (TENQ.BDCODENQFED = DESCFED.BDCODENQFED)';
-- wsql = wsql||' left outer join VW_VRHF_BASE_TEMPGPS gps on (gps.bdcodemp = t.bdcodemp)';
 wsql = wsql||' left outer join (select BDCODEMP, BDSIMPLESGPS, BDCCATVCONCOM, max(BDREFEMP) BEREFEMP from (select * from VRHF_BASE_TEMPGPS where BDCODEMP = 1920) where BDREFEMP <= '||:prrefini||' group by BDCODEMP, BDSIMPLESGPS, BDCCATVCONCOM) gps on (gps.BDCODEMP = t.BDCODEMP) ';
-- wsql = wsql||' left outer join VRH_FUNCOES_TFUC colfunc on  (col.BDCODPLAFUC = colfunc.BDCODPLAFUC and col.BDCODTFUC = colfunc.BDCODTFUC)';
 wsql = wsql||' left outer join centros_tpcc cc on (cc.bdcodcentro = s.bdcodcentro and cc.bdcodtpcc = s.bdcodtpcc)';
-- wsql = wsql||' left outer join VRH_BASE_CBO_TSIN CBO on (col.bdcodcbo = cbo.bdcodcbo and col.bdcodcbotsin = cbo.bdcodcbotsin)';
-- wsql = wsql||' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = t.BDCODVER) ';

 wtemaut = 0;

 wsqlauxdat = 'select first 1 COLCON.BDCODTER from VRHF_BASE_CALC_TERC COLCON ';
 wsqlauxdat = wsqlauxdat||' join vrh_base_tservterc X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODTER = COLCON.BDCODTER and X.BDCODSERV = COLCON.BDCODSERV) ';
 wsqlauxdat = wsqlauxdat||' where X.BDREFSERV between '||prrefini||' and '||prreffim;
 IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsqlauxdat = wsqlauxdat||' and '||prcodemp;
 IF (prcodaut IS NOT NULL AND prcodaut <> '') THEN
    wsqlauxdat = wsqlauxdat||' and '||prcodaut;

 EXECUTE STATEMENT wsqlauxdat INTO :wtemaut;

 IF (prtipocol <> 1 AND wtemaut <> 0 AND wtemaut IS NOT NULL) THEN
-- if (prcodaut is null) then
    BEGIN
      BDREFAUXV = 0;
      BDBINSSFEFOL = 0;
      BDVINSSFEFOL = 0;
      BDBFGTSFEFOL = 0;
      BDVFGTSFEFOL = 0;

      bdbINSS13 = 0;
      bdbFGTS13 = 0;
      bdbIRRF13 = 0;
      BDBFGTS = 0;
      BDFGTS = 0;
      BDVFGTS13 = 0;
      bdreffn = CAST(wrefaux AS INTEGER);
      bddatarescisao = NULL;
      bddescricaomotres = '';
      bdbsalfam = 0;
      bdbfgtsmesant = 0;
      bdfgtsmesant = 0;
      bdbfgtsmes = 0;
      bdfgtsmes = 0;
      bdsaldo = 0;
      bdfgts40 = 0;
      bdfgts10 = 0;
      bdtotalgrrf = 0;
      BDTEMGRRF = 0;
      BDCODTFUC = 0;
      BDTIPOMOV = 0;
      BDPERCMULTA40 = 0;
      BDPERCMULTA10 = 0;

      FOR EXECUTE STATEMENT wsql INTO
      /*01*/ : bdtipo_col ,
      /*02*/ : bdcodemp ,
      /*03*/ : bdcodcol ,
      /*04*/ : bdnomemp ,
      /*05*/ : bdendemp ,
      /*06*/ : bdnumemp ,
      /*07*/ : bdbaiemp ,
      /*08*/ : bdcepemp ,
      /*09*/ : bdcnpjemp ,
      /*10*/ : bdnomcid ,
      /*11*/ : bdsiglauf ,
      /*12*/ : bdcomplemp ,
--      /*13*/ : bdnomcol ,
      /*14*/ : bddataadmcol ,
--      /*15*/ : bdpercratcol ,
--      /*16*/ : bddesctfuc ,
--      /*17*/ : bdcpfcol ,
--      /*18*/ : bdpiscol ,
      /*19*/ : bdcodenqfed ,
      /*20*/ : bdsimplesgps ,
--      /*21*/ : bdctpscol ,
--      /*22*/ : bdcodcbo ,
      /*23*/ : bdcodcentro ,
      /*24*/ : bdcodtpcc ,
      /*25*/ : bdcodserv,
      /*26*/ : BDCODVER,
      /*27*/ : BDDESCVER,
      /*28*/ : BDREFV,
      /*29*/ : BDPROVENTO,
      /*30*/ : BDDESCONTO,
      /*31*/ : BDSALBASE,
      /*32*/ : BDBINSS,
      /*33*/ : BDBIRRF,
      /*34*/ : BDBRAIS,
      /*35*/ : bddescredver,
      /*36*/ : bdirrf,
--      /*37*/ : BDGRUPOCLA,
      /*38*/ : BDDESCCC,
      /*39*/ : bdpisver,
      /*40*/ : bdclaver,
      /*41*/ : BDDESCENQFED,
--      /*42*/ : bdcodcla,
      /*43*/ : bdordemver,
      /*44*/ : bdordemtipocodver,
      /*45*/ : bdtipocodver,
      /*46*/ : bdtiporefver,
      /*47*/ : bdrefhoremp,
             : BDVALMVINSSTER,
             : BDDATAPGTO,
             : BDCCATVCONCOM,
             : BDINSSFN,
             : BDINSS13FN,
             : BDBINSSAPFN,
             : BDINSSAPFN,
             : BDBINSS13APFN,
             : BDINSS13APFN
      DO
        BEGIN

          wsqlauxdat = 'select first 1 COL.BDNOMCOL,COL.BDPERCRATCOL,COL.BDCPFCOL,COL.BDPISCOL,COL.BDCTPSCOL,COL.BDCODCBO,COL.BDGRUPOCLA,COL.BDCODCLA,CBO.BDDESCCBOTSIN '||
                       'from VRH_SP_CAD_TERC(''colcon.bdcodter = '||bdcodcol||''', null, 201606, 1, 1, 1, 0, 0, 0, 0, 1) COL '||
                       'left outer join VRH_BASE_CBO_TSIN CBO on (COL.BDCODCBO = CBO.BDCODCBO and COL.BDCODCBOTSIN = CBO.BDCODCBOTSIN)';

          EXECUTE STATEMENT wsqlauxdat INTO :bdnomcol, :bdpercratcol, :bdcpfcol, :bdpiscol, :bdctpscol, :bdcodcbo, :bdgrupocla, :bdcodcla, :bddesctfuc;

          bdmvinsster = 0;
          SELECT SUM(BDVALORINSS) FROM VRHF_BASE_CALC_TERC WHERE BDCODEMP = :bdcodemp AND BDCODTER = :BDCODCOL AND BDCODSERV < :bdcodserv AND
             BDREFINSSSERV >= :prrefini AND BDREFINSSSERV <= :prreffim INTO :bdmvinsster;
          bdmvinsster = COALESCE(bdmvinsster, 0);
          
      -- { 17413 Marcelo B. M. 25/05/2017 In?cio }
          bdbaseinssmv = 0; 
          SELECT SUM(BDBASEINSS) FROM VRHF_BASE_CALC_TERC WHERE BDCODEMP = :bdcodemp AND BDCODTER = :BDCODCOL AND BDCODSERV < :bdcodserv AND
             BDREFINSSSERV >= :prrefini AND BDREFINSSSERV <= :prreffim INTO :bdbaseinssmv;
          bdbaseinssmv = COALESCE(bdbaseinssmv, 0);

          bdbaseirrfmv = 0;
          SELECT SUM(BDBASEIR) FROM VRHF_BASE_CALC_TERC WHERE BDCODEMP = :bdcodemp AND BDCODTER = :BDCODCOL AND BDCODSERV < :bdcodserv AND
             BDREFINSSSERV >= :prrefini AND BDREFINSSSERV <= :prreffim INTO :bdbaseirrfmv;
          bdbaseirrfmv = COALESCE(bdbaseirrfmv, 0);

          bdvalorinssmv = 0;
          SELECT SUM(BDVALORINSS) FROM VRHF_BASE_CALC_TERC WHERE BDCODEMP = :bdcodemp AND BDCODTER = :BDCODCOL AND BDCODSERV < :bdcodserv AND
             BDREFINSSSERV >= :prrefini AND BDREFINSSSERV <= :prreffim INTO :bdvalorinssmv;
          bdvalorinssmv = COALESCE(bdvalorinssmv, 0);

          bdvalorirrfmv = 0;
          SELECT SUM(BDVALORIR) FROM VRHF_BASE_CALC_TERC WHERE BDCODEMP = :bdcodemp AND BDCODTER = :BDCODCOL AND BDCODSERV < :bdcodserv AND
             BDREFINSSSERV >= :prrefini AND BDREFINSSSERV <= :prreffim INTO :bdvalorirrfmv;
          bdvalorirrfmv = COALESCE(bdvalorirrfmv, 0);
          -- { 17413 Marcelo B. M. 25/05/2017 Fim }
          
          SUSPEND;
        END
    END

 EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_VERBAS_FOLHA) */
ALTER PROCEDURE VRHF_SP_VERBAS_FOLHA(PREMPRESA VARCHAR(30000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMPRESSAO INTEGER,
PRTIPOFOLHA INTEGER,
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRAGRUPARSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDESCTFUC VARCHAR(40),
BDDATAADMCOL DATE,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDLOGRSINTRAB VARCHAR(15),
BDENDSINTRAB VARCHAR(40),
BDBAISINTRAB VARCHAR(20),
BDNROSINTRAB INTEGER,
BDCOMPLSINTRAB VARCHAR(20),
BDNOMCIDSINTRAB VARCHAR(40),
BDSIGLAUFSINTRAB VARCHAR(2),
BDCODVER INTEGER,
BDREFVER INTEGER,
BDDESCVER VARCHAR(40),
BDREFV NUMERIC(15,6),
BDVALV NUMERIC(15,6))
 AS
DECLARE VARIABLE WFIELDVERREF VARCHAR(30);
DECLARE VARIABLE WORDERBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(10000);
BEGIN
      IF (prreferencia IS NOT NULL) THEN
         EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, prultimodia);
    
      wsql = 'select ';
      wsql = wsql || 'temp.bdcodemp, ';
      wsql = wsql || 'temp.bdnomemp,  ';
      wsql = wsql || 'vw_col_ref_atual.bdcodcol, ';
      wsql = wsql || 'vw_col.bdnomcol, ';
      wsql = wsql || 'tfuc.bddesctfuc, ';
      wsql = wsql || 'vw_col.bddataadmcol, ';
      wsql = wsql || 'vw_col.bdctpscol, ';
      wsql = wsql || 'vw_col.bdseriectpscol, ';
      wsql = wsql || 'vw_col.bddseriectpscol, ';
      wsql = wsql || 'vw_col.bdpiscol, ';
      wsql = wsql || 'col_calcdia.bdsalbasecol, ';
      wsql = wsql || 'tsintrab.bdcodsintrab, ';
      wsql = wsql || 'tsintrab.bddescsintrab, ';
      wsql = wsql || 'tsintrab.bdlogrsintrab, ';
      wsql = wsql || 'tsintrab.bdendsintrab, ';
      wsql = wsql || 'tsintrab.bdbaisintrab, ';
      wsql = wsql || 'tsintrab.bdnrosintrab, ';
      wsql = wsql || 'tsintrab.bdcomplsintrab, ';
      wsql = wsql || 'tcidsintrab.bdnomcid, ';
      wsql = wsql || 'tufsintrab.bdsiglauf, ';
      wsql = wsql || 'tverbas.bddescver, ';


      --folha normal
      IF (prtipofolha = 0) THEN
         BEGIN
           wsql = wsql || 'tfolhanormal.bdcodver, ';
           wsql = wsql || 'tfolhanormal.bdref, ';
           wsql = wsql || 'tfolhanormal.bdrefv, ';
           wsql = wsql || 'tfolhanormal.bdvalv ';
         END
      ELSE
      --adiantamento sal?rio
      IF (prtipofolha = 1) THEN
         BEGIN
           wsql = wsql || 'tfolhaad.bdcodver, ';
           wsql = wsql || 'tfolhaad.bdrefad, ';
           wsql = wsql || 'tfolhaad.bdrefv, ';
           wsql = wsql || 'tfolhaad.bdvalv ';
         END
      ELSE
      --adiantamento 13 sal
      IF (prtipofolha = 2) THEN
         BEGIN
           wsql = wsql || 'ta13sal.bdcodver, ';
           wsql = wsql || 'ta13sal.bdrefa13, ';
           wsql = wsql || 'ta13sal.bdrefva13, ';
           wsql = wsql || 'ta13sal.bdvala13 ';
         END
      --13 salario
      IF (prtipofolha = 3) THEN
         BEGIN
           wsql = wsql || 't13sal.bdcodver, ';
           wsql = wsql || 't13sal.bdref, ';
           wsql = wsql || 't13sal.bdrefv, ';
           wsql = wsql || 't13sal.bdvalv ';
         END
      ELSE
      --complemento 13 sal
      IF (prtipofolha = 4) THEN
         BEGIN
           wsql = wsql || 'tc13sal.bdcodver, ';
           wsql = wsql || 'tc13sal.bdrefc13, ';
           wsql = wsql || 'tc13sal.bdrefvc13, ';
           wsql = wsql || 'tc13sal.bdvalvc13 ';
         END
      ELSE
      --Ferias
      /*if (prtipofolha = 5) then
         begin
         end
      else
      --PLR
      if (prtipofolha = 6) then
         begin
         end
      else*/
      --Folha complementar
      IF (prtipofolha = 7) THEN
         BEGIN
           wsql = wsql || 'tfolhacomp.bdcodver, ';
           wsql = wsql || 'tfolhacomp.bdref, ';
           wsql = wsql || 'tfolhacomp.bdrefv, ';
           wsql = wsql || 'tfolhacomp.bdvalv ';
         END
    
      wsql = wsql || 'from VW_COLABORADORES_REF_ATUAL vw_col_ref_atual ';
      wsql = wSql || 'left outer join SP_CONSULTAEMPRESAS('||prReferencia||', 0,  NULL) temp on (temp.bdCodemp =  vw_col_ref_atual.bdcodemp) ';
      wsql = wsql || 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = vw_col_ref_atual.bdcodemp and
                                                                  vw_col.bdcodcol = vw_col_ref_atual.bdcodcol) ';
      wsql = wsql || 'left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = vw_col_ref_atual.BDCODEMP and
                                                                       COL_DIAVINC.BDCODCOL = vw_col_ref_atual.BDCODCOL) ';

      wsql = wsql || 'left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = COL_DIAVINC.bdcodplafuc and tfuc.bdcodtfuc = COL_DIAVINC.bdcodtfuc) ';
    
      wsql = wsql || 'left outer join vw_tcolcon_calcdia col_calcdia on (col_calcdia.BDCODEMP = vw_col_ref_atual.BDCODEMP and
                                                                       col_calcdia.BDCODCOL = vw_col_ref_atual.BDCODCOL) ';
      wsql = wsql || 'left outer join vrh_base_tsindtrab tsintrab on (tsintrab.bdcodsintrab =  vw_col_ref_atual.bdcodsintrab) ';
      wsql = wsql || 'left outer join tcidade tcidsintrab on (tcidsintrab.bdcodcid = tsintrab.bdcodcid) ';
      wsql = wsql || 'left outer join tuf tufsintrab on (tufsintrab.bdcoduf = tcidsintrab.bdcoduf) ';

      --folha normal
      IF (prtipofolha = 0) THEN
         BEGIN
           wsql = wsql || 'left outer join SP_vrhf_folhanormal tfolhanormal on (tfolhanormal.bdcodemp = vw_col_ref_atual.bdcodemp and tfolhanormal.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = tfolhanormal.bdcodver) ';
         END
      ELSE
      --adiantamento sal?rio
      IF (prtipofolha = 1) THEN
         BEGIN
           wsql = wsql || 'left outer join vw_vrhf_adiantamento_sal on (tfolhaad.bdcodemp = vw_col_ref_atual.bdcodemp and tfolhaad.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = tfolhaad.bdcodver) ';
         END
      ELSE
      --adiantamento 13 sal
      IF (prtipofolha = 2) THEN
         BEGIN
           wsql = wsql || 'left outer join vw_vrhf_a13sal ta13sal on (ta13sal.bdcodemp = vw_col_ref_atual.bdcodemp and ta13sal.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = ta13sal.bdcodver) ';
         END
      --13 salario
      IF (prtipofolha = 3) THEN
         BEGIN
           wsql = wsql || 'left outer join vw_vrhf_13sal t13sal on (t13sal.bdcodemp = vw_col_ref_atual.bdcodemp and t13sal.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = t13sal.bdcodver) ';
         END
      ELSE
      --complemento 13 sal
      IF (prtipofolha = 4) THEN
         BEGIN
           wsql = wsql || 'left outer join vw_vrhf_c13sal tc13sal on (tc13sal.bdcodemp = vw_col_ref_atual.bdcodemp and tc13sal.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = tc13sal.bdcodver) ';
         END
      ELSE
      --Ferias
      /*if (prtipofolha = 5) then
         begin
         end
      else
      --PLR
      if (prtipofolha = 6) then
         begin
         end*/
      --Folha complementar
      IF (prtipofolha = 7) THEN
         BEGIN
           wsql = wsql || 'left outer join SP_VRHF_FOLHACOMPLEMENTAR tfolhacomp on (tfolhacomp.bdcodemp = vw_col_ref_atual.bdcodemp and tfolhacomp.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS tverbas on (tverbas.bdcodver = tfolhacomp.bdcodver) ';
         END

       wwhere = '';

      IF (prempresa <> '') THEN
         wwhere = wwhere||prempresa||' ';
    
      IF (prcolaborador <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||prcolaborador||' ';
         END

      IF (prfuncao > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'tfuc.bdCODTFUC = '||prfuncao||' ';
         END
    
      IF (prSindicato > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'vw_col_ref_atual.bdCODSINTRAB = '||prsindicato||' ';
         END
    
      IF (prclasse > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'vw_col_ref_atual.bdCODCLA = '||prClasse||' ';
         END

      --folha normal
      IF (prtipofolha = 0) THEN
         BEGIN
            wfieldverref = 'tfolhanormal.bdREF';
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'tfolhanormal.bdREF >= '||prrefini||' and '||'tfolhanormal.bdREF <= '||prreffin||' ';
         END
      ELSE
      --adiantamento sal?rio
      IF (prtipofolha = 1) THEN
         BEGIN
            wfieldverref = 'tfolhaad.BDREFA13';
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'tfolhaad.BDREFA13 >= '||prrefini||' and '||'tfolhaad.BDREFAD <= '||prreffin||' ';
         END
      ELSE
      --adiantamento 13 sal
      IF (prtipofolha = 2) THEN
         BEGIN
            wfieldverref = 'ta13sal.BDREFA13';
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'ta13sal.BDREFA13 >= '||prrefini||' and '||'ta13sal.BDREFA13 <= '||prreffin||' ';
         END
      --13 salario
      IF (prtipofolha = 3) THEN
         BEGIN
            wfieldverref = 't13sal.BDREF';
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'t13sal.BDREF >= '||prrefini||' and '||'t13sal.BDREF <= '||prreffin||' ';
         END
      ELSE
      --complemento 13 sal
      IF (prtipofolha = 4) THEN
         BEGIN
           wfieldverref = 'tc13sal.BDREFC13';
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

           wwhere = wwhere||'tc13sal.BDREFC13 >= '||prrefini||' and '||'tc13sal.BDREFC13 <= '||prreffin||' ';
          END
      ELSE
      /*--Ferias
      if (prtipofolha = 5) then
         begin
         end
      else
      --PLR
      if (prtipofolha = 6) then
         begin
         end*/
      --Folha complementar
      IF (prtipofolha = 7) THEN
         BEGIN
           wfieldverref = 'tfolhacomp.BDREF';
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'tfolhacomp.BDREF >= '||prrefini||' and '||'tfolhacomp.BDREF <= '||prreffin||' ';
         END
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;


      worderby = '';
      IF (prordemimpressao IS NOT NULL) THEN
         BEGIN
            worderby = 'order by ';
            IF (prordemimpressao = 0) THEN
               BEGIN
                 IF (pragruparsindicato = 1) THEN
                    worderby = wOrderBy||'temp.bdcodemp,'||wfieldverref||',tsintrab.bdcodsintrab,'||'tverbas.bdcodver,vw_col_ref_atual.bdcodcol ';
                 ELSE
                    worderby = wOrderBy||'temp.bdcodemp,'||wfieldverref||','||'tverbas.bdcodver,vw_col_ref_atual.bdcodcol ';
               END
            ELSE
               BEGIN
                 IF (pragruparsindicato = 1) THEN
                    worderby = wOrderBy||'temp.bdcodemp,'||wfieldverref||',tsintrab.bdcodsintrab,'||'tverbas.bdcodver,vw_col.bdnomcol ';
                 ELSE
                    worderby = wOrderBy||'temp.bdcodemp,'||wfieldverref||','||'tverbas.bdcodver,vw_col.bdnomcol ';
               END
         END
      wsql = wsql||wwhere||worderby;

      FOR EXECUTE STATEMENT wsql
      INTO
         :bdcodemp,
         :bdnomemp,
         :bdcodcol,
         :bdnomcol,
         :bddesctfuc,
         :bddataadmcol,
         :bdctpscol,
         :bdseriectpscol,
         :bddseriectpscol,
         :bdpiscol,
         :bdsalbasecol,
         :bdcodsintrab,
         :bddescsintrab,
         :bdlogrsintrab,
         :bdendsintrab,
         :bdbaisintrab,
         :bdnrosintrab,
         :bdcomplsintrab,
         :bdnomcidsintrab,
         :bdsiglaufsintrab,
         :bddescver,
         :bdcodver,
         :bdrefver,
         :bdrefv,
         :bdvalv DO
       BEGIN
         SUSPEND;
       END
END
^

/* Alter (VRHF_SP_VERBAS_PREV_RESC) */
ALTER PROCEDURE VRHF_SP_VERBAS_PREV_RESC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER)
 RETURNS(BDCODPLAFUC INTEGER,
BDCODSINTRAB INTEGER,
BDCODCLA INTEGER,
BDDESCENQFED VARCHAR(10),
BDTEMGRRF INTEGER,
BDBSALFAM NUMERIC(18,6),
BDDATARESCISAO DATE,
BDDESCRICAOMOTRES VARCHAR(300),
BDTIPOMOV INTEGER,
BDTIPO_COL INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDCNPJEMP VARCHAR(18),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCOMPLEMP DM_BDCOMPENDERECO,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDPERCRATCOL NUMERIC(18,6),
BDDESCTFUC VARCHAR(80),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCODENQFED INTEGER,
BDSIMPLESGPS INTEGER,
BDCTPSCOL DM_BDCTPS,
BDCODCBO INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREFFN INTEGER,
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(80),
BDREFV NUMERIC(18,6),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDSALBASE NUMERIC(18,6),
BDBINSS NUMERIC(18,6),
BDBFGTS NUMERIC(18,6),
BDFGTS NUMERIC(18,6),
BDBIRRF NUMERIC(18,6),
BDBRAIS NUMERIC(18,6),
BDDESCREDVER VARCHAR(80),
BDIRRF NUMERIC(18,6),
BDGRUPOCLA INTEGER,
BDBINSS13 NUMERIC(18,6),
BDBFGTS13 NUMERIC(18,6),
BDBIRRF13 NUMERIC(18,6),
BDVFGTS13 NUMERIC(18,6),
BDBINSSFEFOL NUMERIC(18,6),
BDVINSSFEFOL NUMERIC(18,6),
BDBFGTSFEFOL NUMERIC(18,6),
BDVFGTSFEFOL NUMERIC(18,6),
BDDESCCC VARCHAR(80),
BDPISVER VARCHAR(5),
BDCLAVER VARCHAR(20),
BDBFGTSMESANT NUMERIC(18,6),
BDFGTSMESANT NUMERIC(18,6),
BDBFGTSMES NUMERIC(18,6),
BDFGTSMES NUMERIC(18,6),
BDSALDO NUMERIC(18,6),
BDFGTS40 NUMERIC(18,6),
BDFGTS10 NUMERIC(18,6),
BDTOTALGRRF NUMERIC(18,6),
BDORDEMVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDTIPOCODVER INTEGER,
BDTIPOREFVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATAPGTO DATE,
BDBFGTSMESPOST NUMERIC(18,6),
BDFGTSMESPOST NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDINSSFNPR NUMERIC(18,6),
BDINSS13FNPR NUMERIC(18,6),
BDCCATVCONCOM DM_BOOLEAN,
BDREFAUXV NUMERIC(18,6),
BDFGTSIND NUMERIC(18,6),
BDDATAGRRF DATE,
BDPERCMULTA40 NUMERIC(15,2),
BDPERCMULTA10 NUMERIC(15,2))
 AS
declare variable WSQLAUXDAT varchar(300);
declare variable WAAAAMM varchar(6);
declare variable WULDIAMES varchar(15);
declare variable WSQL varchar(32700);
declare variable WREFAUX varchar(10);
declare variable WCODEMP varchar(3000);
declare variable WCODCOL varchar(3000);
declare variable WREFINI varchar(10);
declare variable WREFFIM varchar(10);
declare variable WREF integer;
declare variable WCALCFGTSMESANT DM_BOOLEAN;
BEGIN
    IF (prreffim IS NOT NULL) THEN
        BEGIN
            EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
            wRef = prreffim;
        END
    ELSE 
        BEGIN
            IF (prrefini IS NOT NULL) THEN
                BEGIN
                    EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);
                    wRef = prrefini;
                END
            ELSE
                BEGIN
                    wRef = 201112;
                END
        END

    IF (prcodemp IS NULL) THEN
        wcodemp = 'null';
    ELSE
        wcodemp = ''''||prcodemp||'''';

    IF (prcodcol IS NULL) THEN
        wcodcol = 'null';
    ELSE
        wcodcol = ''''||prcodcol||'''';

    IF (prrefini IS NULL) THEN
        wrefini = ' null ';
    ELSE
        wrefini = ''||prrefini;

    IF (prreffim IS NULL) THEN
        wreffim = ' null ';
    ELSE
        wreffim = ''||prreffim;

    IF (prreffim IS NOT NULL) THEN
        BEGIN
        wrefaux = wreffim;
        END
    ELSE 
        BEGIN
            IF (prrefini IS NOT NULL) THEN
                BEGIN
                    wrefaux = wrefini;
                END
            ELSE
                BEGIN
                    wrefaux = 'null';
                END
        END

    wsql = '';
    IF (wrefaux <> 'null') THEN
        wsql = 'select cast(ultdia as varchar(2)) from ULTIMO_DIA_MES('||SUBSTRING(wrefaux FROM 5 FOR 2)||','||SUBSTRING(wrefaux FROM 1 FOR 4)||')';

    IF (wsql <> '') THEN
        BEGIN
            EXECUTE STATEMENT wsql INTO wuldiames;
            wuldiames = SUBSTRING(wrefaux FROM 5 FOR 2)||'/'||wuldiames||'/'||SUBSTRING(wrefaux FROM 1 FOR 4);
            wuldiames = ''''||wuldiames||'''';
        END

    wsql = 'select '||
           '0 Tipo_Col, res.BDCODEMP Codigo_Empresa,res.BDCODCOL Codigo_Colaborador,TEMP.BDCODMATRIZ, EMP.BDNOMEMP Nome_Empresa,EMP.BDENDEMP Endereco_Empresa,'||
           'EMP.BDNUMEMP Numero_Empresa,EMP.BDBAIEMP Bairro_Empresa,EMP.BDCEPEMP Cep_Empresa,tEMP.BDCNPJEMP Cnpj_Empresa,cid.BDNOMCID Cidade_Empresa,uf.BDSIGLAUF UF_Empresa,'||
           'EMP.BDCOMPLEMP Compl_Empresa ,COL.BDDATAADMCOL Admissao_Colaborador, colconfgts.bdpercratcol Rat_Apo_Col ,colfunc.BDDESCTFUC Funcao_Colaborador,'||
           'colcondoc.BDCPFCOL Cpf_Colaborador ,DOCREF.BDPISCOL Pis_Colaborador ,tenq.bdcodenqfed,DOCREF.bdctpscol CTPS_Col,COLFUNC.bdcodcbo CBO_Col,'||
           'cccol.BDCODCENTRO Codigo_Plano_CC ,cccol.BDCODTPCC Codigo_CC ,'||wref||' Referencia,COLCON.BDCODVER Codigo_Verba,ver.BDDESCVER Descricao_Verba,colcon.BDREFVFN_MAX Referencia_Verba,'||
           'case when (RVA.BDTIPOCODVER in (0, 2)) then COLCON.BDVALVFN else 0 end Proventos_Folha, case when (RVA.BDTIPOCODVER in (0, 2)) then 0 else COLCON.BDVALVFN end Descontos_Folha,'||
           'foln.BDSALBASE,foln.BDBINSS,foln.BDBFGTS,foln.BDFGTS,foln.BDBIRRF,foln.BDBRAIS,ver.BDDESCREDVER,foln.BDIRRF,classe.bdgrupocla,foln.BDBINSS13,foln.BDBFGTS13,foln.BDBIRRF13,'||
           'cc.bdnomcta,rva.bdpisver,ver.BDCLAVER,foln.BDFGTS13,foln.BDBINSSFEFOL,foln.BDINSSFEFOL,foln.BDBFGTSFEFOL,foln.BDFGTSFEFOL,res.bddatarescisaoprev,pres.bddescpres,'||
           'pres.bdtipomov,foln.BDBSALFAM,DESCFED.BDDESCENQFED,colconvinc.bdcodcla,colvinc.BDCODSINTRAB,colvincdia.bdcodplafuc,VER.bdordemver,RVA.BDORDEMTIPOCODVER,'||
           'RVA.BDTIPOCODVER,RVA.BDTIPOREFVER,empref.bdrefhoremp,res.BDCALCFGTSMESANTPREV BDCALCFGTSMESANT, res.BDDATAPAGRESCISAOPREV, '||
           'FOLN.BDBINSSAPFNPR, FOLN.BDINSSAPFNPR, FOLN.BDBINSS13APFNPR, FOLN.BDINSS13APFNPR, FOLN.BDINSS, FOLN.BDINSS13, colcon.BDREFAUXVFN_MAX, '||
           'res.BDDATAPAGGRFCPREV ';

    wsql = wsql||
           'from ('||
           'select colcon.* from vrh_emp_trescisao_previa colcon where COLCON.BDREFRESCISAOPREV = '||wref;

    IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

    IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

    wsql = wsql||
           ') res '||
           'left outer join SP_VRH_CC_DATA(RES.bdcodemp,RES.bdcodcol,cast(' || wuldiames ||' as date)) cccol ' ||
           '                               on (cccol.bdcodemp = RES.bdcodemp and cccol.bdcodcol = RES.bdcodcol)'||
           'left outer join VRH_EMP_TCOLCON col on (col.bdcodemp = res.bdcodemp and col.bdcodcol = res.bdcodcol) '||
           'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = RES.BDCODEMP and COLCAD.BDCODCOL = RES.BDCODCOL) '||
           'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = RES.BDCODEMP and DOCREF.BDCODCOL = RES.BDCODCOL) '||
           'left outer join vw_vrhf_emp_tcolcon_fgtsgps colconfgts on (colconfgts.bdcodemp = res.bdcodemp and colconfgts.bdcodcol = res.bdcodcol) '||
           'left outer join vw_vrh_emp_tcolcon_vinc colconvinc on (colconvinc.bdcodemp = res.bdcodemp and colconvinc.bdcodcol = res.bdcodcol) '||
           'left outer join vw_vrh_emp_tcol_vinc colvinc on (colvinc.bdcodemp = res.bdcodemp and colvinc.bdcodcol = res.bdcodcol) '||
           'left outer join vw_vrh_emp_tcol_vincdia colvincdia on (colvincdia.bdcodemp = res.bdcodemp and colvincdia.bdcodcol = res.bdcodcol) '||
           'left outer join vrh_emp_tcolcon_doc colcondoc on (colcondoc.bdcodemp = res.bdcodemp and colcondoc.bdcodcol = res.bdcodcol) '||
           'left outer join vrh_emp_tcol_doc coldoc on (coldoc.bdcodemp = res.bdcodemp and coldoc.bdcodcol = res.bdcodcol) '||
           'left outer join VWRH_UNION_FNPR_FTPR_MES colcon on (colcon.bdcodemp = res.bdcodemp and colcon.bdcodcol = res.bdcodcol) '||
           'left outer join VWRH_UNION_FNPR_FTPR_MES_BASES FOLN on (FOLN.BDCODEMP = res.BDCODEMP and FOLN.BDCODCOL = res.BDCODCOL) '||
           'left outer join vrh_base_tclasse classe on (classe.bdcodcla = colconvinc.bdcodcla) '||
           'left outer join CENTROS_TPCC cc on (cc.bdcodcentro = cccol.BDCODCENTRO and cc.bdcodtpcc = cccol.bdcodtpcc) '||
           'left outer join VW_VERBAS_REF_ATUAL RVA on (RVA.BDCODVER = colcon.BDCODVER) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = colcon.BDCODVER) '||
           'left outer join VW_TEMPRESAS_REF emp on (emp.bdcodemp = res.bdcodemp) '||
           'left outer join tempresas temp on (temp.bdcodemp = res.bdcodemp) '||
           'left outer join VW_VRHF_BASE_TEMPCALC empref on (empref.bdcodemp = res.bdcodemp) '||
           'left outer join VRH_FUNCOES_TFUC colfunc on  (colvincdia.BDCODPLAFUC = colfunc.BDCODPLAFUC and colvincdia.BDCODTFUC = colfunc.BDCODTFUC) '||
           'left outer join vw_tenqfed TENQ on (TENQ.bdcodemp = res.bdcodemp) '||
           'left outer join vrh_base_tprepresc pres on (pres.bdcodpres = res.bdcodpres) '||
           'left outer join TCADENQFED DESCFED on (TENQ.BDCODENQFED = DESCFED.BDCODENQFED) '||
           'left outer join tcidade cid on (emp.bdcodcid = cid.bdcodcid) '||
           'left outer join tuf uf on (uf.bdcoduf = cid.bdcoduf) '||
           'order by res.BDCODEMP,res.BDCODCOL ';

    wcodemp = 0;
    wcodcol = 0;

    FOR EXECUTE STATEMENT wsql INTO
        /*01*/ : bdtipo_col ,
        /*02*/ : bdcodemp ,
        /*03*/ : bdcodcol ,
               : bdcodmatriz,
        /*04*/ : bdnomemp ,
        /*05*/ : bdendemp ,
        /*06*/ : bdnumemp ,
        /*07*/ : bdbaiemp ,
        /*08*/ : bdcepemp ,
        /*09*/ : bdcnpjemp ,
        /*10*/ : bdnomcid ,
        /*11*/ : bdsiglauf ,
        /*12*/ : bdcomplemp ,
        --/*13*/ : bdnomcol ,
        /*14*/ : bddataadmcol ,
        /*15*/ : bdpercratcol ,
        /*16*/ : bddesctfuc ,
        /*17*/ : bdcpfcol ,

               : bdpiscol ,

        /*18*/ : bdcodenqfed ,
        --/*19*/ : bdsimplesgps ,
        /*20*/ : bdctpscol ,
        /*21*/ : bdcodcbo ,
        /*22*/ : bdcodcentro ,
        /*23*/ : bdcodtpcc ,
        /*24*/ : bdreffn,
        /*25*/ : BDCODVER,
        /*26*/ : BDDESCVER,
        /*27*/ : BDREFV,
        /*28*/ : BDPROVENTO,
        /*29*/ : BDDESCONTO,
        /*30*/ : BDSALBASE,
        /*31*/ : BDBINSS,
        /*32*/ : BDBFGTS,
        /*33*/ : BDFGTS,
        /*34*/ : BDBIRRF,
        /*35*/ : BDBRAIS,
        /*36*/ : bddescredver,
        /*37*/ : bdirrf,
        /*38*/ : bdgrupocla,
        /*39*/ : bdbINSS13,
        /*40*/ : bdbFGTS13,
        /*41*/ : bdbIRRF13,
        /*42*/ : BDDESCCC,
        /*43*/ : bdpisver,
        /*44*/ : bdclaver,
        /*45*/ : BDVFGTS13,
               : BDBINSSFEFOL,
               : BDVINSSFEFOL,
               : BDBFGTSFEFOL,
               : BDVFGTSFEFOL,
        /*46*/ : bddatarescisao,
        /*47*/ : bddescricaomotres,
               : bdtipomov,
        /*48*/ : bdbsalfam,
        /*49*/ : BDDESCENQFED,
        /*50*/ : bdcodcla,
        /*51*/ : BDCODSINTRAB,
        /*52*/ : bdcodplafuc,
               : bdordemver,
               : bdordemtipocodver,
               : bdtipocodver,
               : bdtiporefver,
               : bdrefhoremp,
               : wcalcfgtsmesant,
               : bddatapgto,
               : bdbinssapfn,
               : bdinssapfn,
               : bdbinss13apfn,
               : bdinss13apfn,
               : bdinssfnpr,
               : bdinss13fnpr,
        --       : bdccatvconcom,
               : bdrefauxv,
               : bddatagrrf
    DO
        BEGIN
            bdcodserv = bdreffn;
            bdbfgtsmesant = 0;
            bdfgtsmesant = 0;
            bdbfgtsmes = 0;
            bdfgtsmes = 0;
            bdsaldo = 0;
            bdfgts40 = 0;
            bdfgts10 = 0;
            bdtotalgrrf = 0;
            bdtemgrrf = 0;
            bdbfgtsmespost = 0;
            bdfgtsmespost = 0;
            bdfgtsind = 0;
            bdpercmulta10 = 0;
            bdpercmulta40 = 0;

            if ((wcodemp <> BDCODEMP) or (wcodcol <> BDCODCOL)) then
                begin
                    wsqlauxdat = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||BDREFFN||' order by BDREFCOL DESC ';
                    execute statement wsqlauxdat into :BDNOMCOL;
     
                    if (wcodemp <> BDCODEMP) then
                        begin
                            wsqlauxdat = 'select first 1 BDSIMPLESGPS, BDCCATVCONCOM from VRHF_BASE_TEMPGPS where BDCODEMP = '||BDCODEMP||' and  BDREFEMP <= '||BDREFFN||' order by BDREFEMP DESC ';
                            execute statement wsqlauxdat into :BDSIMPLESGPS, :BDCCATVCONCOM;
                        end

                    wcodemp = BDCODEMP;
                    wcodcol = BDCODCOL;

                    IF (bddatarescisao IS NOT NULL) THEN
                        BEGIN
                            wsqlauxdat = 'select bdaaaamm from aaaamm(cast('||''''||CAST(bddatarescisao AS VARCHAR(10))||''''||' as date))';
     
                            EXECUTE STATEMENT wsqlauxdat INTO waaaamm;
     
                            IF (waaaamm <> bdreffn) THEN
                                BEGIN
                                    bddatarescisao = NULL;
                                    bddescricaomotres = '';
     
                                    /* Verifica se a rescis?o ? no m?s seguinte e se tem o par?metro de FGTS m?s anterior, para n?o buscar o FGTS do m?s */
                                    IF (SUBSTRING(waaaamm FROM 5 FOR 2) = '01') THEN
                                        waaaamm = CAST((CAST((SUBSTRING(waaaamm FROM 1 FOR 4)) AS INTEGER) - 1) AS VARCHAR(4))||'12';
                                    ELSE
                                        BEGIN
                                            IF (CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) <= 10) THEN
                                                waaaamm = SUBSTRING(waaaamm FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));
                                            ELSE
                                                waaaamm = SUBSTRING(waaaamm FROM 1 FOR 4)||CAST((CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));
                                        END
     
                                    IF (waaaamm = bdreffn AND UPPER(wcalcfgtsmesant) = 'TRUE') THEN
                                        BEGIN
                                            bdbfgtsmespost = bdbfgts;
                                            bdfgtsmespost = bdfgts;
                             
                                            bdbfgts = 0;
                                            bdbfgts13 = 0;
                                            bdbfgtsfefol = 0;
                                            bdfgts = 0;
                                            bdvfgts13 = 0;
                                            bdvfgtsfefol = 0;
                                        END
                                END
     
     
                        END
                end

            IF (bddatarescisao IS NOT NULL) THEN
                BEGIN
                    wsqlauxdat = 'select x.bdbfgtsmesant,x.bdfgtsmesant, x.bdbfgtsmes, x.bdfgtsmes, x.bdsaldo, x.bdfgts40, x.bdfgts10, x.bdtotal, x.bdfgtsind, x.bdpercmulta40, x.bdpercmulta10 from VRHF_EMP_VAL_GRRF('||bdcodemp||','||bdcodcol||','||bdreffn||','||bdreffn||',2) x';
                    EXECUTE STATEMENT wsqlauxdat INTO
                    : bdbfgtsmesant,
                    : bdfgtsmesant,
                    : bdbfgtsmes,
                    : bdfgtsmes,
                    : bdsaldo,
                    : bdfgts40,
                    : bdfgts10,
                    : bdtotalgrrf,
                    : bdfgtsind,
                    : bdpercmulta40,
                    : bdpercmulta10;
            
                    IF (bdtotalgrrf <> 0) THEN
                        BDTEMGRRF = 1;
                END

        SUSPEND;
        END

END
^

/* Alter (VRHF_SP_VERBAS_SIM_COL_CALC) */
ALTER PROCEDURE VRHF_SP_VERBAS_SIM_COL_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE wsql VARCHAR(15000);
DECLARE VARIABLE wdataini VARCHAR(8);
DECLARE VARIABLE wdatafim VARCHAR(8);
DECLARE VARIABLE wdtaux VARCHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(NULL, prdataini, prdatafim);

  wdtaux = CAST(prdataini AS VARCHAR(10));
  wdataini = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wdtaux = CAST(prdatafim AS VARCHAR(10));
  wdatafim = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);


  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDCODVER, '||
                'BDANOINI, '||
                'BDMESINI, '||
                'BDDIAINI, '||
                'BDANOFIM, '||
                'BDMESFIM, '||
                'BDDIAFIM, '||
                'BDFORMULAREF, '||
                'BDFORMULAVAL ';
  wsql = wsql||'from VW_VERBAS_SIM_COL_ATUAL ';
  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wsql = wsql||' and '||PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     wsql = wsql||' and '||PRCODCOL;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDANOINI,
    :BDMESINI,
    :BDDIAINI,
    :BDANOFIM,
    :BDMESFIM,
    :BDDIAFIM,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SP_VERBAS_SIM_PRES_CALC) */
ALTER PROCEDURE VRHF_SP_VERBAS_SIM_PRES_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODPRES INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WDATAINI VARCHAR(8);
DECLARE VARIABLE WDATAFIM VARCHAR(8);
DECLARE VARIABLE WDTAUX VARCHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(NULL, prdataini, prdatafim);

  wdtaux = CAST(prdataini AS VARCHAR(10));
  wdataini = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wdtaux = CAST(prdatafim AS VARCHAR(10));
  wdatafim = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);


  wsql = 'select VS.BDCODPRES, '||
                'VS.BDCODVER, '||
                'VS.BDANOINI, '||
                'VS.BDMESINI, '||
                'VS.BDDIAINI, '||
                'VS.BDANOFIM, '||
                'VS.BDMESFIM, '||
                'VS.BDDIAFIM, '||
                'VS.BDFORMULAREF, '||
                'VS.BDFORMULAVAL ';
  wsql = wsql||'from VW_VERBAS_SIM_PRESC_ATUAL VS ';
  wsql = wsql|| 'where ((VS.BDDATAINI >= '||wdataini||' and VS.BDDATAINI <= '||wdatafim||') or '||
                      '(VS.BDDATAFIM >= '||wdataini||' and VS.BDDATAFIM <= '||wdatafim||') or '||
                      '(VS.BDDATAINI <= '||wdataini||' and VS.BDDATAFIM >= '||wdatafim||')) ';

  wsql = wsql||' and (exists (select RESC.BDCODPRES from VRH_EMP_TRESCISAO RESC where VS.BDCODPRES = RESC.BDCODPRES and RESC.BDDATARESCISAO >= '''||prdataini||
             ''' and RESC.BDDATARESCISAO <= '''||prdatafim||'''';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wsql = wsql||' and '||PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     wsql = wsql||' and '||PRCODCOL;

  wsql = wsql||')) ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODPRES,
    :BDCODVER,
    :BDANOINI,
    :BDMESINI,
    :BDDIAINI,
    :BDANOFIM,
    :BDMESFIM,
    :BDDIAFIM,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SPF_BC_PROLAB_COLAB) */
ALTER PROCEDURE VRHF_SPF_BC_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE camposum VARCHAR(50);
DECLARE VARIABLE tabela VARCHAR(100);
DECLARE VARIABLE strtpfolha VARCHAR(100);
DECLARE VARIABLE wsql VARCHAR(5000);
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        camposum   = 'BDBINSSFN';
        strtpfolha   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';

      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          camposum   = 'BDBINSSFC';
          strtpfolha   = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            camposum = 'BDBASEINSS13';
            strtpfolha   = '13';
            tabela   = 'VRHF_EMP_T13SAL FOLHA ';
         END
       ELSE
         BEGIN
            camposum   = 'BDBASEINSSC13';
            strtpfolha   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
         END


  WSql = 'select sum(FOLHA.'||camposum||')';
  wsql = wsql || ' FROM '||:tabela;

  wsql = wsql || ' left outer join vw_colaboradores_ref_atual con on (FOLHA.bdcodemp = CON.bdcodemp and ';
  wsql = wsql ||                                                     ' FOLHA.bdcodcol = CON.bdcodcol)';
  wsql = wsql || ' where CON.bdcontrcol = '||:PRTIPOCADASTRO;--SEGURADOS COLABORADORES - SEGURADOS PROLABORISTAS
  wsql = wsql || ' AND FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF (:prfiltrocol <> NULL) THEN
    wsql = wsql || ' and '||:prfiltrocol;

  FOR EXECUTE STATEMENT wsql
     INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SPF_BC_PROLABORISTAS) */
ALTER PROCEDURE VRHF_SPF_BC_PROLABORISTAS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE ALIQ NUMERIC(15,4);
DECLARE VARIABLE SQL VARCHAR(500);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_BC_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',1)';

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
          SELECT BDEMPEMP FROM vrh_sp_empresas(NULL, :prref) WHERE bdcodemp = :premp
          INTO
            :aliq;

         BDVALOR = ((BDVALOR *ALIQ)/100 );
         SUSPEND;
       END

END
^

/* Alter (VRHF_SPF_BC_RAT) */
ALTER PROCEDURE VRHF_SPF_BC_RAT(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE ALIQFAP NUMERIC(15,4);
DECLARE VARIABLE ALIQ NUMERIC(15,4);
DECLARE VARIABLE ALIQCNAE NUMERIC(15,4);
DECLARE VARIABLE SQL VARCHAR(5000);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_BC_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',0)';

  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
         SELECT cn.bdtaxacnae FROM sp_consultaempresas(:prref,:premp,0) emp
         LEFT OUTER JOIN vw_tcnae_ref cn ON (emp.bdcodcnae = cn.bdcodcnae)
         WHERE bdcodemp = :premp
         INTO
           :aliqcnae;

         IF ((aliqcnae IS NULL) OR (aliqcnae = 0)) THEN
           BEGIN
             SELECT cn.bdtaxacnae FROM sp_consultaempresas(:prref,:premp,0) emp
             LEFT OUTER JOIN vw_tcnae_ref cn ON (emp.bdcodcnae = cn.bdcodcnae)
             WHERE bdcodemp = :premp
             INTO
               :aliqcnae;
           END

         SELECT bdfap FROM vrh_sp_empresas(NULL,:prREF)
         WHERE bdcodemp = :premp
         INTO
           :ALIQFAP;

         aliq = (aliqcnae * aliqfap);

         BDVALOR = ((BDVALOR *ALIQ)/100 );

         SUSPEND;
       END
END
^

/* Alter (VRHF_SPF_BC_SEGURADOS) */
ALTER PROCEDURE VRHF_SPF_BC_SEGURADOS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE aliq NUMERIC(15,4);
DECLARE VARIABLE sql VARCHAR(5000);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_BC_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',0)';

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
          SELECT emp.BDFUNEMP FROM vrh_sp_empresas(NULL, :prref) emp WHERE bdcodemp = :premp
          INTO
            :aliq;
--    :BDEMPEMP,
--    :BDAUTEMP,
--    :BDFUNEMP,
         BDVALOR = ((BDVALOR *ALIQ)/100 );

         SUSPEND;
       END

END
^

/* Alter (VRHF_SPF_BC_TERCEIROS) */
ALTER PROCEDURE VRHF_SPF_BC_TERCEIROS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE aliq NUMERIC(15,4);
DECLARE VARIABLE sql VARCHAR(5000);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_BC_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',0)';

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
         SELECT EMP.bdperterc FROM vrh_sp_empresas(NULL,:prref) emp
         WHERE EMP.bdcodemp = :premp
         INTO
           :aliq;

         BDVALOR = ((BDVALOR *ALIQ)/100 );

         SUSPEND;
       END

END
^

/* Alter (VRHF_SPF_PROLAB_COLAB) */
ALTER PROCEDURE VRHF_SPF_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE camposum VARCHAR(50);
DECLARE VARIABLE tabela VARCHAR(100);
DECLARE VARIABLE strtpfolha VARCHAR(100);
DECLARE VARIABLE wsql VARCHAR(5000);
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        camposum   = 'BDINSSFN';
        strtpfolha   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';

      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          camposum   = 'BDINSSFC';
          strtpfolha   = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            camposum = 'BDVALORINSS13';
            strtpfolha   = '13';
            tabela   = 'VRHF_EMP_T13SAL FOLHA ';
         END
       ELSE
         BEGIN
            camposum   = 'BDVALORINSSC13';
            strtpfolha   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
         END


  WSql = 'select sum(FOLHA.'||camposum||')';
  wsql = wsql || ' FROM '||:tabela;

  wsql = wsql || ' left outer join vw_colaboradores_ref_atual con on (FOLHA.bdcodemp = CON.bdcodemp and ';
  wsql = wsql ||                                                     ' FOLHA.bdcodcol = CON.bdcodcol)';
  wsql = wsql || ' where CON.bdcontrcol = '||:PRTIPOCADASTRO;--SEGURADOS COLABORADORES - SEGURADOS PROLABORISTAS
  wsql = wsql || ' AND FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF (:prfiltrocol IS NOT NULL) THEN
    wsql = wsql || ' and '||:prfiltrocol;

  FOR EXECUTE STATEMENT wsql
     INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SPF_RATAPO) */
ALTER PROCEDURE VRHF_SPF_RATAPO(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE TABELA VARCHAR(100);
DECLARE VARIABLE STRTPFOLHA VARCHAR(50);
DECLARE VARIABLE CAMPOSUM VARCHAR(50);
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WVALCALC NUMERIC(15,6);
DECLARE VARIABLE PERC NUMERIC(15,4);
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        camposum   = 'BDBRATAPOFN + FOLHA.BDBRATAPOFEFN + FOLHA.BDBRATAPO13FN';
        strtpfolha   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';

      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          camposum   = 'BDBRATAPOFC + FOLHA.BDBRATAPOFEFC + FOLHA.BDBRATAPO13FC';
          strtpfolha   = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            camposum = 'BDBRATAPO13';
            strtpfolha   = '13';
            tabela   = 'VRHF_EMP_T13SAL FOLHA ';
         END
       ELSE
         BEGIN
            camposum   = 'BDBRATAPOC13';
            strtpfolha   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
         END


  WSql = 'select FOLHA.BDCODCOL, sum(FOLHA.'||camposum||') BDVALOR';
  wsql = wsql || ' FROM '||:tabela;

  wsql = wsql || ' left outer join vw_colaboradores_ref_atual con on (FOLHA.bdcodemp = CON.bdcodemp and ';
  wsql = wsql ||                                                     ' FOLHA.bdcodcol = CON.bdcodcol)';
  wsql = wsql || ' where CON.bdcontrcol = 0';--SEGURADOS COLABORADORES .... APOSENTADORIA
  wsql = wsql || ' AND FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF ((:prfiltrocol IS NOT NULL) AND (:prfiltrocol <> ''))  THEN
    wsql = wsql || ' and '||:prfiltrocol;

  wsql = wsql || ' group by folha.bdcodcol ';

  wvalcalc = 0;

  FOR EXECUTE STATEMENT wsql
     INTO
        : wcodcol,
        : BDVALOR
     DO
       BEGIN

/*         select col.bdPERCRATCOL from VW_COLABORADORES_REF_ATUAL col
         where col.bdcodcol = :wcodcol and col.bdcodemp = :premp
         into
           :perc;
        if (:bdvalor is not null) then
          wvalcalc = wvalcalc + ((:bdvalor * :perc) /100);   */
       END


  BDVALOR = wvalcalc;

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);

END
^

/* Alter (VRHF_SPF_SALFAM) */
ALTER PROCEDURE VRHF_SPF_SALFAM(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE tabelaclasse VARCHAR(100);
DECLARE VARIABLE tabela VARCHAR(100);
DECLARE VARIABLE strtpfolha VARCHAR(10);
DECLARE VARIABLE wsql VARCHAR(5000);
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        STRTPFOLHA   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';
        tabelaclasse = 'vrhf_emp_tverbafn VFOLHA ';
      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          STRTPFOLHA = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
          tabelaclasse = 'vrhf_emp_tverbafc VFOLHA ';

        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            STRTPFOLHA   = '13';
            tabela       = 'VRHF_EMP_T13SAL FOLHA ';
            tabelaclasse = 'vrhf_emp_tverba13 VFOLHA ';
         END
       ELSE
         BEGIN
            STRTPFOLHA   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
            tabelaclasse = 'vrhf_emp_tverbaC13 VFOLHA ';
         END


  WSql = 'select sum(FOLHA.BDSALFAM'||strtpfolha||')';
  wsql = wsql || ' FROM '||:tabela;
  wsql = wsql || ' left outer join '||:tabelaclasse||' on (FOLHA.bdcodemp = VFOLHA.bdcodemp and ';
  wsql = wsql ||                                          'FOLHA.bdcodcol = VFOLHA.bdcodcol and ';
  wsql = wsql ||                                          'FOLHA.bdref'||strtpfolha||'  = VFOLHA.bdref'||strtpfolha||')';

  wsql = wsql || ' left outer join vrh_base_tverbas ver on (VFOLHA.bdcodver = ver.bdcodver) ';
  wsql = wsql || 'where substring(ver.bdclaver from 1 for 5) = ''9.050''';
  wsql = wsql || ' and FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF (:prfiltrocol <> '') THEN
    wsql = wsql || ' and '||:prfiltrocol;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VRHF_SPF_SALMATERNIDADE) */
ALTER PROCEDURE VRHF_SPF_SALMATERNIDADE(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE tabelaclasse VARCHAR(100);
DECLARE VARIABLE tabela VARCHAR(100);
DECLARE VARIABLE strtpfolha VARCHAR(10);
DECLARE VARIABLE verba VARCHAR(10);
DECLARE VARIABLE wsql VARCHAR(5000);
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        STRTPFOLHA   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';
        tabelaclasse = 'vrhf_emp_tverbafn VFOLHA ';
        verba        = '8.005';
      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          STRTPFOLHA = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
          tabelaclasse = 'vrhf_emp_tverbafc VFOLHA ';
          verba        = '8.005';
        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            STRTPFOLHA   = '13';
            tabela       = 'VRHF_EMP_T13SAL FOLHA ';
            tabelaclasse = 'vrhf_emp_tverba13 VFOLHA ';
            verba        = '5.010';
         END
       ELSE
         BEGIN
            STRTPFOLHA   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
            tabelaclasse = 'vrhf_emp_tverbaC13 VFOLHA ';
            verba        = '6.010';
         END


  WSql = 'select sum(FOLHA.BDSALMATEMP'||strtpfolha||')';
  wsql = wsql || ' FROM '||:tabela;
  wsql = wsql || ' left outer join '||:tabelaclasse||' on (FOLHA.bdcodemp = VFOLHA.bdcodemp and ';
  wsql = wsql ||                                          'FOLHA.bdcodcol = VFOLHA.bdcodcol and ';
  wsql = wsql ||                                          'FOLHA.bdref'||strtpfolha||'  = VFOLHA.bdref'||strtpfolha||')';

  wsql = wsql || ' left outer join vrh_base_tverbas ver on (VFOLHA.bdcodver = ver.bdcodver) ';
  wsql = wsql || 'where substring(ver.bdclaver from 1 for 5) = '||verba;
  wsql = wsql || ' and FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF (:prfiltrocol <> '') THEN
    wsql = wsql || ' and '||:prfiltrocol;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (VSUC_GETDEMONSTRATIVO) */
ALTER PROCEDURE VSUC_GETDEMONSTRATIVO(PRCODEMP VARCHAR(1000),
PRIGNORAZERAMENTO INTEGER,
PRDETALHAFILIAL INTEGER,
PRSALDOANTERIOR INTEGER,
PRCONTABILIZACAO INTEGER,
PRDATAINI DATE,
PRDATAFIN DATE,
PREXPORTACAOECF INTEGER,
PRINDICE INTEGER,
PRCC VARCHAR(2048),
PRDETALHAR_CC INTEGER,
PRLANCNOTCC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDTIPCTA INTEGER,
BDGRUPOCTA INTEGER,
BDRELCTA INTEGER,
BDSALANT NUMERIC(15,2),
BDSALDEB NUMERIC(15,2),
BDSALCRE NUMERIC(15,2),
BDMOVPER NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDSALANT1 NUMERIC(15,2),
BDSALDEB1 NUMERIC(15,2),
BDSALCRE1 NUMERIC(15,2),
BDMOVPER1 NUMERIC(15,2),
BDSALATU1 NUMERIC(15,2),
BDSALANT2 NUMERIC(15,2),
BDSALDEB2 NUMERIC(15,2),
BDSALCRE2 NUMERIC(15,2),
BDMOVPER2 NUMERIC(15,2),
BDSALATU2 NUMERIC(15,2),
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(2048))
 AS
declare variable WSQL varchar(30000);
declare variable WCODMATRIZ integer;
declare variable WDATAINI_ANT_ANT date;
declare variable WDATAFIN_ANT_ANT date;
declare variable WDATAINI_ANT date;
declare variable WDATAFIN_ANT date;
declare variable WDATAINI date;
declare variable WDATAFIN date;
declare variable WCOUNT integer;
declare variable WEMPRESAS varchar(10000);
declare variable WSTR varchar(10000);
declare variable WSQLDEB varchar(5000);
declare variable WSQLCRE varchar(5000);
declare variable WCTALON varchar(40);
declare variable WCODTPLA integer;
declare variable WDEB_ANT_ZER numeric(15,2);
declare variable WCRE_ANT_ZER numeric(15,2);
declare variable WDEB_ANT numeric(15,2);
declare variable WCRE_ANT numeric(15,2);
declare variable WDEB_2_ZER numeric(15,2);
declare variable WCRE_2_ZER numeric(15,2);
declare variable WDEB_2 numeric(15,2);
declare variable WCRE_2 numeric(15,2);
declare variable WDEB_2_ATU numeric(15,2);
declare variable WCRE_2_ATU numeric(15,2);
declare variable WDEB_1_ZER numeric(15,2);
declare variable WCRE_1_ZER numeric(15,2);
declare variable WDEB_1 numeric(15,2);
declare variable WCRE_1 numeric(15,2);
declare variable WDEB_1_ATU numeric(15,2);
declare variable WCRE_1_ATU numeric(15,2);
declare variable WDEB_ZER numeric(15,2);
declare variable WCRE_ZER numeric(15,2);
declare variable WDEB numeric(15,2);
declare variable WCRE numeric(15,2);
declare variable WDEB_ATU numeric(15,2);
declare variable WCRE_ATU numeric(15,2);
declare variable WZERAMENTO_ANT smallint;
declare variable WZERAMENTO_ANT_ANT smallint;
declare variable WCODPLAPADRAOREF smallint;
declare variable WCAMPOSCC varchar(100);
declare variable WANOECF smallint;
BEGIN
--alt 85094 - 20/06/2018 - Carlos Machado - Adicionado tratamento de centro de custo.
  WCAMPOSCC = ' BDCODTPCC, BDCODCENTRO ';
  -- codigo da matriz
  wsql = 'select distinct bdcodmatriz from tempresas ';
  wsql = wsql||'where bdcodmatriz is not null ';
  wsql = wsql||'and bdcodemp in ('||prcodemp||')';
  EXECUTE STATEMENT wsql INTO :wcodmatriz;

  IF ((wcodmatriz IS NULL) OR (wcodmatriz = 0)) THEN
     BEGIN
       EXECUTE STATEMENT 'select first 1 bdcodemp from tempresas where bdcodemp in ('||prcodemp||')' INTO wcodmatriz;
     END

  -- filtro das empresas
  wempresas = 'and (';
  wstr = prcodemp||',';
  WHILE (wstr <> '') DO
    BEGIN
      wcount = POSITION(',', wstr);
      wempresas = wempresas||'(((TLAN.BDCODEMP = '||wcodmatriz||')';
      IF (wcodmatriz <> SUBSTRING(wstr FROM 1 FOR wcount-1)) THEN
         wempresas = wempresas||' and (bdfilial = '||SUBSTRING(wstr FROM 1 FOR wcount-1)||')) or (TLAN.BDCODEMP = '||SUBSTRING(wstr FROM 1 FOR wcount-1)||')) or ';
      ELSE
         wempresas = wempresas||')) or ';
      wstr = SUBSTRING(wstr FROM wcount+1 FOR CHAR_LENGTH(wstr));
    END
  wempresas = SUBSTRING(wempresas FROM 1 FOR CHAR_LENGTH(wempresas)-CHAR_LENGTH(' or '))||')';


  --exception ex_date;
  -- plano padrao
  --alt:11615 - 30/06/2015 - Carrega o codigo do plano referencial da empresa. Pedro
  wsql = 'select first 1 bdcodplapadrao, BDCODPLAPADRAOREF from VW_TEMPRESAS_REF where bdcodemp = '||wcodmatriz;
  EXECUTE STATEMENT wsql INTO :bdcodplapadrao, :wCodPlaPadraoRef;

  --#Alt.:12232 - 13/06/2015 - Carrega o ano da preparaso mais proximo com data informada
  wanoecf = 0;
  IF (prexportacaoecf = 1) THEN
    BEGIN
      wsql = 'select first 1 bdANO from PLANOS_TPLA_ECF ';
      wsql = wsql||'where (bdANO <= substring('''||prdataini||''' from 1 for 4)) and ';
      wsql = wsql||'(bdCODPLAPADRAOREF = '||wcodplapadraoref||') and ';
      wsql = wsql||'(bdCODPLAPADRAO = '||bdcodplapadrao||') order by bdANO desc';
      EXECUTE STATEMENT wsql INTO :wanoecf;
    END

  -- datas dos zeramentos
  wsql = 'select first 2 distinct bddatainizer, bddatafimzer from vsuc_empresas_tencexe ';
  wsql = wsql||'where bddatafimzer < '''||prdataini||''' ';
  wsql = wsql||'and bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by bddatafimzer desc ';
  wcount = 1;
  wzeramento_ant = 0;
  wzeramento_ant_ant = 0;
  FOR EXECUTE STATEMENT wsql INTO :wdataini, wdatafin DO
     BEGIN
       IF (wcount = 1) THEN
          BEGIN
            --alt:13744 - 17/05/2016 - Se tiver selecionado o ano inteiro, estiver selecionando apenas um ano e tiver marcado
            --para mostrar o Saldo Anterior, entao o periodo anterior sera o ano anterior inteiro, independente do zeramento. Pedro
            IF ((prSaldoAnterior = 1) AND (EXTRACT(YEAR FROM prdataini) = EXTRACT(YEAR FROM prdatafin)) AND
                (EXTRACT(DAY FROM prdataini) = 1) AND (EXTRACT(MONTH FROM prdataini) = 1) AND
                (EXTRACT(DAY FROM prdatafin) = 31) AND (EXTRACT(MONTH FROM prdatafin) = 12)) THEN
              BEGIN
                wdataini_ant = addyear(prdataini, -1);
                wdatafin_ant = addyear(prdatafin, -1);
              END
            --alt:13744 - 13/05/2016 - Caso haja algum periodo entre o inicio do periodo e o ultimo zeramento,
            --pega esse periodo como periodo anterior, senao, utiliza o periodo do zeramento como periodo anterior. Pedro
            ELSE IF ((wdatafin +1) = prdataini) THEN
              BEGIN
                wdataini_ant = wdataini;
                wdatafin_ant = wdatafin;
              END
            ELSE
              BEGIN
                wdataini_ant = (wdatafin +1);
                wdatafin_ant = (prdataini -1);
              END
          END
       ELSE
         --alt:13744 - 17/05/2016 - Se tiver selecionado o ano inteiro, estiver selecionando apenas um ano e tiver marcado
         --para mostrar o Saldo Anterior, entao o periodo anterior sera o ano anterior inteiro, independente do zeramento. Pedro
         IF ((prSaldoAnterior = 1) AND (EXTRACT(YEAR FROM prdataini) = EXTRACT(YEAR FROM prdatafin)) AND
             (EXTRACT(DAY FROM prdataini) = 1) AND (EXTRACT(MONTH FROM prdataini) = 1) AND
             (EXTRACT(DAY FROM prdatafin) = 31) AND (EXTRACT(MONTH FROM prdatafin) = 12)) THEN
           BEGIN
             wdataini_ant_ant = addyear(prdataini, -2);
             wdatafin_ant_ant = addyear(prdatafin, -2);
           END
         ELSE --alt:14760 - 14/06/2016 - Correcao na estrutura. Pedro
           BEGIN
             wdataini_ant_ant = wdataini;
             wdatafin_ant_ant = wdatafin;
           END
       wcount = wcount + 1;
     END
  -- caso nao ha algumas das datas anteriores, pegar a data de inicio das atividades
  IF ((wdataini_ant IS NULL) OR (wdatafin_ant IS NULL) OR (wdataini_ant_ant IS NULL) OR (wdatafin_ant_ant IS NULL)) THEN
     BEGIN
       wsql = 'select min(bddatainiativemp) from tempresas ';
       wsql = wsql||'where bddatainiativemp is not null ';
       wsql = wsql||'and bdcodemp in ('||prcodemp||') ';
       EXECUTE STATEMENT wsql INTO :wdataini;
     END
  -- data do periodo anterior
  IF ((wdataini_ant IS NULL) OR (wdatafin_ant IS NULL)) THEN
     BEGIN
       wdataini_ant = wdataini;
       wdatafin_ant = prdataini -1;
     END
  -- data do periodo anterior ao anterior
  IF ((wdataini_ant_ant IS NULL) OR (wdatafin_ant_ant IS NULL)) THEN
     BEGIN
       wdatafin_ant_ant = wdataini_ant-1;
       IF (wdataini < wdatafin_ant_ant) THEN
          wdataini_ant_ant = wdataini;
       ELSE
          wdataini_ant_ant = wdatafin_ant_ant-1;
     END     
  -- data atual
  wdataini = prdataini;
  wdatafin = prdatafin;

  -- limpar tabela temporaria
  EXECUTE STATEMENT 'delete from VSUC_EMPRESAS_DEMONSTRATIVO';

  -- calculo dos debitos e creditos nos periodos selecionados
  wsqldeb = '';
  -- saldo anterior a todos os periodos
  wsqldeb = wsqldeb||'sum(case when (bddata < '''||wdataini_ant_ant||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitoantzer, ';
  wsqldeb = wsqldeb||'sum(case when (bddata < '''||wdataini_ant_ant||''' and bdtipolan <> 10) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitoant, ';
  -- periodo anterior ao anterior
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini_ant_ant||''' and '''||wdatafin_ant_ant||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito2zer, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini_ant_ant||''' and '''||wdatafin_ant_ant||''') and (bdtipolan <> 10)) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito2, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata < '''||wdataini_ant_ant||''') or ((bddata between '''||wdataini_ant_ant||''' and '''||wdatafin_ant_ant||''') and (bdtipolan <> 10))) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito2atu, ';
  -- periodo anterior
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini_ant||''' and '''||wdatafin_ant||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito1zer, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini_ant||''' and '''||wdatafin_ant||''') and (bdtipolan <> 10)) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito1, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata < '''||wdataini_ant||''') or ((bddata between '''||wdataini_ant||''' and '''||wdatafin_ant||''') and (bdtipolan <> 10))) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito1atu, ';
  -- periodo atual
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini||''' and '''||wdatafin||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitozer, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini||''' and '''||wdatafin||''') and (bdtipolan <> 10)) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata < '''||wdataini||''') or ((bddata between '''||wdataini||''' and '''||wdatafin||''') and (bdtipolan <> 10))) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitoatu ';
  --exception ex_date;

  --alt:6178 - 11/11/2015 - Adicionada validacao, se tiver informado um codigo de indice, entao substituira onde possui o campo "BDVALOR" pelo proprio campo mais o valor do indice na data do lancamento. Pedro
  IF (prIndice > 0) THEN
    wsqldeb = REPLACE(wsqldeb, 'TLAN.bdvalor', 'TLAN.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prIndice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),'||
                                                             '(select first 1 BDVALIND from TINDVAL where BDCODIND = '||prIndice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))');
  IF (prdetalhar_cc = 1) THEN
     begin
      wsqldeb = REPLACE(wsqldeb, 'TLAN.bdvalor', 'iif(BDCODTPCC is null, tlan.bdvalor,tlcc.bdvalor)');
     end

  wsqlcre = '';
  -- saldo anterior a todos os periodos
  wsqlcre = wsqlcre||'       0 as bdcreditoantzer, ';
  wsqlcre = wsqlcre||'       0 as bdcreditoant, ';
  -- periodo anterior ao anterior
  wsqlcre = wsqlcre||'       0 as bdcredito2zer, ';
  wsqlcre = wsqlcre||'       0 as bdcredito2, ';
  wsqlcre = wsqlcre||'       0 as bdcredito2atu, ';
  -- periodo anterior
  wsqlcre = wsqlcre||'       0 as bdcredito1zer, ';
  wsqlcre = wsqlcre||'       0 as bdcredito1, ';
  wsqlcre = wsqlcre||'       0 as bdcredito1atu, ';
  -- periodo atual
  wsqlcre = wsqlcre||'       0 as bdcreditozer, ';
  wsqlcre = wsqlcre||'       0 as bdcredito, ';
  wsqlcre = wsqlcre||'       0 as bdcreditoatu ';


  -- povoando tabela temporaria
  wsql = 'insert into VSUC_EMPRESAS_DEMONSTRATIVO (';
  wsql = wsql||'bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla, ';
  wsql = wsql||wcamposcc||', ';
  wsql = wsql||'bddebitoantzer, bdcreditoantzer, ';
  wsql = wsql||'bddebitoant,    bdcreditoant, ';
  wsql = wsql||'bddebito2zer,   bdcredito2zer, ';
  wsql = wsql||'bddebito2,      bdcredito2, ';
  wsql = wsql||'bddebito2atu,   bdcredito2atu, ';
  wsql = wsql||'bddebito1zer,   bdcredito1zer, ';
  wsql = wsql||'bddebito1,      bdcredito1, ';
  wsql = wsql||'bddebito1atu,   bdcredito1atu, ';
  wsql = wsql||'bddebitozer,    bdcreditozer, ';
  wsql = wsql||'bddebito,       bdcredito, ';
  wsql = wsql||'bddebitoatu,    bdcreditoatu) ';
  wsql = wsql||'select bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla, ';
  IF ((PRDETALHAR_CC != 1)) THEN
     wsql = wsql||'0, 0, ';
  ELSE
     wsql = wsql||' COALESCE(BDCODTPCC,0), COALESCE(BDCODCENTRO,0), ';
  wsql = wsql||'       sum(bddebitoantzer) as bddebitoantzer, ';
  wsql = wsql||'       sum(bdcreditoantzer) as bdcreditoantzer, ';
  wsql = wsql||'       sum(bddebitoant) as bddebitoant, ';
  wsql = wsql||'       sum(bdcreditoant) as bdcreditoant, ';
  wsql = wsql||'       sum(bddebito2zer) as bddebito2zer, ';
  wsql = wsql||'       sum(bdcredito2zer) as bdcredito2zer, ';
  wsql = wsql||'       sum(bddebito2) as bddebito2, ';
  wsql = wsql||'       sum(bdcredito2) as bdcredito2, ';
  wsql = wsql||'       sum(bddebito2atu) as bddebito2atu, ';
  wsql = wsql||'       sum(bdcredito2atu) as bdcredito2atu, ';
  wsql = wsql||'       sum(bddebito1zer) as bddebito1zer, ';
  wsql = wsql||'       sum(bdcredito1zer) as bdcredito1zer, ';
  wsql = wsql||'       sum(bddebito1) as bddebito1, ';
  wsql = wsql||'       sum(bdcredito1) as bdcredito1, ';
  wsql = wsql||'       sum(bddebito1atu) as bddebito1atu, ';
  wsql = wsql||'       sum(bdcredito1atu) as bdcredito1atu, ';
  wsql = wsql||'       sum(bddebitozer) as bddebitozer, ';
  wsql = wsql||'       sum(bdcreditozer) as bdcreditozer, ';
  wsql = wsql||'       sum(bddebito) as bddebito, ';
  wsql = wsql||'       sum(bdcredito) as bdcredito, ';
  wsql = wsql||'       sum(bddebitoatu) as bddebitoatu, ';
  wsql = wsql||'       sum(bdcreditoatu) as bdcreditoatu ';
  wsql = wsql||'from (';
  IF (prdetalhar_cc = 1) THEN
     wsql = wsql||'select '||wcamposcc||', TLAN.bdcodemp, bdfilial, bdtipolancfilial, bddebito as bdcodtpla, ';
  ELSE
     wsql = wsql||'select TLAN.bdcodemp, bdfilial, bdtipolancfilial, bddebito as bdcodtpla, ';
  wsql = wsql||wsqldeb||','||wsqlcre;
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  IF (prdetalhar_cc = 1) THEN
    BEGIN
      if ((prlancnotcc = 1) or (prdetalhar_cc = 0)) then
         wsql = wsql||'LEFT OUTER';
      ELSE
         wsql = wsql||'INNER';
      wsql = wsql||' join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and BDDEBCRE = 0)';
    END
  wsql = wsql||'where (bddata <= '''||wdatafin||''') ';
  wsql = wsql||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and (bddebito is not null) ';
  wsql = wsql||wempresas;
  wsql = wsql||'Group By TLAN.BDCODEMP, bdfilial, bdtipolancfilial, bdcodtpla ';
  IF (prdetalhar_cc = 1) THEN
    wsql = wsql||', '||wcamposcc||' ';
  wsql = wsql||'union ';
  IF (prdetalhar_cc = 1) THEN
     wsql = wsql||'select '||wcamposcc||', TLAN.bdcodemp, bdfilial, bdtipolancfilial, bdcredito as bdcodtpla, ';
  ELSE
     wsql = wsql||'select TLAN.bdcodemp, bdfilial, bdtipolancfilial, bdcredito as bdcodtpla, ';
  wsql = wsql||wsqlcre||','||wsqldeb;
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  IF (prdetalhar_cc = 1) THEN
    BEGIN
      if ((prlancnotcc = 1) or (prdetalhar_cc = 0)) then
         wsql = wsql||'LEFT OUTER';
      ELSE
         wsql = wsql||'INNER';
      wsql = wsql||' join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and BDDEBCRE = 1) ';
    END   
  wsql = wsql||'where (bddata <= '''||wdatafin||''') ';
  wsql = wsql||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and (bdcredito is not null) ';
  wsql = wsql||wempresas;
  wsql = wsql||'Group By bdcodemp, bdfilial, bdtipolancfilial, BDCODTPLA ';
  IF (prdetalhar_cc = 1) THEN
    wsql = wsql||', '||wcamposcc||' ';
  wsql = wsql||') as tlan ';
  IF (PRDETALHAR_CC = 1) THEN
    BEGIN
      IF (NOT ((prcc IS NULL) OR (prcc = ''))) THEN
        BEGIN
          wsql = wsql||' where bdcodtpcc in ('||prcc||') ';
          if (prlancnotcc = 1) THEN
             wsql = wsql||' or bdcodtpcc is null ';
        END
      ELSE IF(prlancnotcc = 0) THEN
         wsql = wsql||' where bdcodtpcc is not null ';
      wsql = wsql||' group by bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla, bdcodtpcc, BDCODCENTRO ';
    END
  ELSE
     wsql = wsql||'group by bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla ';
  wsql = wsql||'order by bdcodemp, bdcodtpla ';
  EXECUTE STATEMENT wsql;

  -- inserir contas titulos e totalizando-as
  FOR SELECT bdcodtpla, bdctalon FROM planos_tpla
      WHERE bdcodplapadrao = :bdcodplapadrao
      AND bdtipcta IN (0, 2) --alt:14249 - 06/05/2016 - nao estava totalizando as contas consolidadoras. Pedro
      INTO :wcodtpla, :wctalon DO
      BEGIN
        wsql = 'insert into VSUC_EMPRESAS_DEMONSTRATIVO (bdcodemp, bdtipolancfilial, bdcodtpla, ';   
        wsql = wsql||        wcamposcc||', ';
        wsql = wsql||'       bddebitoantzer, bdcreditoantzer, ';
        wsql = wsql||'       bddebitoant,    bdcreditoant, ';
        wsql = wsql||'       bddebito2zer,   bdcredito2zer, ';
        wsql = wsql||'       bddebito2,      bdcredito2, ';
        wsql = wsql||'       bddebito2atu,   bdcredito2atu, ';
        wsql = wsql||'       bddebito1zer,   bdcredito1zer, ';
        wsql = wsql||'       bddebito1,      bdcredito1, ';
        wsql = wsql||'       bddebito1atu,   bdcredito1atu, ';
        wsql = wsql||'       bddebitozer,    bdcreditozer, ';
        wsql = wsql||'       bddebito,       bdcredito, ';
        wsql = wsql||'       bddebitoatu,    bdcreditoatu) ';
        wsql = wsql||'select temp.bdcodemp, 0 as bdtipolancfilial, '||wcodtpla||' as bdcodtpla, ';  
        wsql = wsql||'       COALESCE(BDCODTPCC,0), COALESCE(BDCODCENTRO,0), ';
        wsql = wsql||'       sum(bddebitoantzer) as bddebitoantzer, ';
        wsql = wsql||'       sum(bdcreditoantzer) as bdcreditoantzer, ';
        wsql = wsql||'       sum(bddebitoant) as bddebitoant, ';
        wsql = wsql||'       sum(bdcreditoant) as bdcreditoant, ';
        wsql = wsql||'       sum(bddebito2zer) as bddebito2zer, ';
        wsql = wsql||'       sum(bdcredito2zer) as bdcredito2zer, ';
        wsql = wsql||'       sum(bddebito2) as bddebito2, ';
        wsql = wsql||'       sum(bdcredito2) as bdcredito2, ';
        wsql = wsql||'       sum(bddebito2atu) as bddebito2atu, ';
        wsql = wsql||'       sum(bdcredito2atu) as bdcredito2atu, ';
        wsql = wsql||'       sum(bddebito1zer) as bddebito1zer, ';
        wsql = wsql||'       sum(bdcredito1zer) as bdcredito1zer, ';
        wsql = wsql||'       sum(bddebito1) as bddebito1, ';
        wsql = wsql||'       sum(bdcredito1) as bdcredito1, ';
        wsql = wsql||'       sum(bddebito1atu) as bddebito1atu, ';
        wsql = wsql||'       sum(bdcredito1atu) as bdcredito1atu, ';
        wsql = wsql||'       sum(bddebitozer) as bddebitozer, ';
        wsql = wsql||'       sum(bdcreditozer) as bdcreditozer, ';
        wsql = wsql||'       sum(bddebito) as bddebito, ';
        wsql = wsql||'       sum(bdcredito) as bdcredito, ';
        wsql = wsql||'       sum(bddebitoatu) as bddebitoatu, ';
        wsql = wsql||'       sum(bdcreditoatu) as bdcreditoatu ';
        wsql = wsql||'from vsuc_empresas_demonstrativo temp ';
        wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = '||bdcodplapadrao||' and tpla.bdcodtpla = temp.bdcodtpla) ';
        wsql = wsql||'where substring(tpla.bdctalon from 1 for '||CHAR_LENGTH(wctalon)||') = '''||wctalon||''' ';
        wsql = wsql||'and tpla.bdtipcta = 1 ';
        --wsql = wsql||wempresas;
        wsql = wsql||' group by bdcodemp, '||wcamposcc;
        EXECUTE STATEMENT wsql;
      END

  -- retorno do resultado do demonstrativo
  wsql = '';
  IF (prdetalhafilial = 1) THEN
     BEGIN
       wsql = wsql||'select demo.BDCODEMP, tpla.BDCODTPLA, tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta, tpla.bdtipcta, tpla.bdgrupocta, tpla.bdrelcta, ';
       --alt:11615 - 30/06/2015 - Carrega o grupo referencial se for uma exportacao do Sped ECF. Pedro
       IF (prExportacaoECF = 1) THEN
         wsql = wsql||' coalesce(ecf.BDCODGRUPOCTA, 0) as BDCODGRUPOCTA,';
       ELSE
         wsql = wsql||'0 as BDCODGRUPOCTA,';
       --alt:11615 - Fim
       wsql = wsql||'             BDDEBITOANTZER, BDCREDITOANTZER, BDDEBITOANT, BDCREDITOANT, ';
       wsql = wsql||'             BDDEBITO2ZER,   BDCREDITO2ZER,   BDDEBITO2,   BDCREDITO2,   BDDEBITO2ATU,   BDCREDITO2ATU, ';
       wsql = wsql||'             BDDEBITO1ZER,   BDCREDITO1ZER,   BDDEBITO1,   BDCREDITO1,   BDDEBITO1ATU,   BDCREDITO1ATU, ';
       wsql = wsql||'             BDDEBITOZER,    BDCREDITOZER,    BDDEBITO,    BDCREDITO,    BDDEBITOATU,    BDCREDITOATU, demo.bdcodtpcc, cc.BDNOMCTA as BDNOMTPCC ';
     END
  ELSE
     BEGIN
       wsql = wsql||'select '||wcodmatriz||' as BDCODEMP, tpla.BDCODTPLA, tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta, tpla.bdtipcta, tpla.bdgrupocta, tpla.bdrelcta, ';
       --alt:11615 - 30/06/2015 - Carrega o grupo referencial se for uma exportacao do Sped ECF. Pedro
       IF (prExportacaoECF = 1) THEN
         wsql = wsql||' coalesce(ecf.BDCODGRUPOCTA, 0) as BDCODGRUPOCTA,';
       ELSE
         wsql = wsql||'0 as BDCODGRUPOCTA,';
       --alt:11615 - Fim
       wsql = wsql||'             sum(BDDEBITOANTZER), sum(BDCREDITOANTZER), sum(BDDEBITOANT), sum(BDCREDITOANT), ';
       wsql = wsql||'             sum(BDDEBITO2ZER),   sum(BDCREDITO2ZER),   sum(BDDEBITO2),   sum(BDCREDITO2),   sum(BDDEBITO2ATU),   sum(BDCREDITO2ATU), ';
       wsql = wsql||'             sum(BDDEBITO1ZER),   sum(BDCREDITO1ZER),   sum(BDDEBITO1),   sum(BDCREDITO1),   sum(BDDEBITO1ATU),   sum(BDCREDITO1ATU), ';
       wsql = wsql||'             sum(BDDEBITOZER),    sum(BDCREDITOZER),    sum(BDDEBITO),    sum(BDCREDITO),    sum(BDDEBITOATU),    sum(BDCREDITOATU), demo.bdcodtpcc, cc.BDNOMCTA as BDNOMTPCC ';
     END
  wsql = wsql||'from vsuc_empresas_demonstrativo demo ';
  wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = '||bdcodplapadrao||' and tpla.bdcodtpla = demo.bdcodtpla) ';
  --alt:11615 - 30/06/2015 - Carrega o grupo referencial se for uma exportacao do Sped ECF. Pedro
  IF (prExportacaoECF = 1) THEN
    wSQL = wSQL||'left outer join PLANOS_TPLA_ECF ecf on (ecf.BDCODPLAPADRAO = tpla.BDCODPLAPADRAO and ecf.BDCODTPLA = tpla.BDCODTPLA and ecf.BDCODPLAPADRAOREF = '||wCodPlaPadraoRef||' and ecf.BDANO = '||wanoecf||')';
  --alt:11615 - Fim

  wsql = wsql||'left outer join CENTROS_TPCC cc on (cc.BDCODCENTRO = demo.BDCODCENTRO and cc.bdcodtpcc = demo.bdcodtpcc) ';

  IF (prdetalhafilial = 1) THEN
     wsql = wsql||'order by demo.bdcodemp, tpla.bdctalon ';
  ELSE
     BEGIN
       wsql = wsql||'group by tpla.BDCODTPLA, tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta, tpla.bdtipcta, tpla.bdgrupocta, tpla.bdrelcta, BDCODGRUPOCTA, bdcodtpcc, BDNOMTPCC ';
       wsql = wsql||'order by tpla.bdctalon ';
     END


  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdcodtpla, : bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdgrupocta, :bdrelcta, :wCodPlaPadraoRef,
           :wdeb_ant_zer, :wcre_ant_zer,
           :wdeb_ant,     :wcre_ant,
           :wdeb_2_zer,   :wcre_2_zer,
           :wdeb_2,       :wcre_2,
           :wdeb_2_atu,   :wcre_2_atu,
           :wdeb_1_zer,   :wcre_1_zer,
           :wdeb_1,       :wcre_1,
           :wdeb_1_atu,   :wcre_1_atu,
           :wdeb_zer,     :wcre_zer,
           :wdeb,         :wcre,
           :wdeb_atu,     :wcre_atu,
           :bdcodtpcc,    :bdnomtpcc DO
      BEGIN
        IF (bdgrupocta IN (1,2,3)) THEN
           BEGIN
             /*******************************************************************************************************************************
             Contas do Passivo, Patrimonio Liquido e Receitas sao da natureza Credora, portando, devem ser calculadas com "Credito - Debito".
             *******************************************************************************************************************************/

             --alt:14249 - 29/04/2016 - nao deve ignorar o zeramento para as contas do Ativo, Passivo e PL, pois eles compoem o saldo destes grupos. Pedro
             --alt:11615 - 30/06/2015 - Verifica o grupo da conta preparada no Sped ECF, o grupo 04 devera ignorar o zeramento. Pedro
             IF (((prignorazeramento = 1) OR (wCodPlaPadraoRef = 4)) AND NOT (bdgrupocta IN (0,1,2))) THEN
                BEGIN
                  bdsalant2 = wcre_ant_zer - wdeb_ant_zer;
                  bdsaldeb2 = wdeb_2;
                  bdsalcre2 = wcre_2;
                  bdmovper2 = wcre_2 - wdeb_2;
                  bdsalatu2 = bdsalant2 + bdmovper2;

                  bdsalant1 = bdsalant2 + (wcre_2_zer - wdeb_2_zer);
                  bdsaldeb1 = wdeb_1;
                  bdsalcre1 = wcre_1;
                  bdmovper1 = wcre_1 - wdeb_1;
                  bdsalatu1 = bdsalant1 + bdmovper1;

                  bdsalant = bdsalant1 + (wcre_1_zer - wdeb_1_zer);
                  bdsaldeb = wdeb;
                  bdsalcre = wcre;
                  bdmovper = wcre - wdeb;
                  bdsalatu = bdsalant + bdmovper;
                END
             ELSE
                BEGIN
                  bdsalant2 = wcre_ant_zer - wdeb_ant_zer;
                  bdsaldeb2 = wdeb_2_zer;
                  bdsalcre2 = wcre_2_zer;
                  bdmovper2 = wcre_2_zer - wdeb_2_zer;
                  bdsalatu2 = bdsalant2 + bdmovper2;

                  bdsalant1 = bdsalatu2;
                  bdsaldeb1 = wdeb_1_zer;
                  bdsalcre1 = wcre_1_zer;
                  bdmovper1 = wcre_1_zer - wdeb_1_zer;
                  bdsalatu1 = bdsalant1 + bdmovper1;

                  bdsalant = bdsalatu1;
                  bdsaldeb = wdeb_zer;
                  bdsalcre = wcre_zer;
                  bdmovper = wcre_zer - wdeb_zer;
                  bdsalatu = bdsalant + bdmovper;
                END
           END
        ELSE
           BEGIN
             /*******************************************************************************************************************************
             Contas do Ativo, Depesas e Outros sao da natureza Devedora, portando, devem ser calculadas com "Debito - Credito".
             *******************************************************************************************************************************/

             --alt:14249 - 29/04/2016 - Nao deve ignorar o zeramento para as contas do Ativo, Passivo e PL, pois eles compoem o saldo destes grupos. Pedro
             --alt:11615 - 30/06/2015 - Verifica o grupo da conta preparada no Sped ECF, o grupo 04 devera ignorar o zeramento. Pedro
             IF (((prignorazeramento = 1) OR (wCodPlaPadraoRef = 4)) AND NOT (bdgrupocta IN (0,1,2))) THEN
                BEGIN
                  bdsalant2 = wdeb_ant_zer - wcre_ant_zer;
                  bdsaldeb2 = wdeb_2;
                  bdsalcre2 = wcre_2;
                  bdmovper2 = wdeb_2 - wcre_2;
                  bdsalatu2 = bdsalant2 + bdmovper2;

                  bdsalant1 = bdsalant2 + (wdeb_2_zer - wcre_2_zer);
                  bdsaldeb1 = wdeb_1;
                  bdsalcre1 = wcre_1;
                  bdmovper1 = wdeb_1 - wcre_1;
                  bdsalatu1 = bdsalant1 + bdmovper1;

                  bdsalant = bdsalant1 + (wdeb_1_zer - wcre_1_zer);
                  bdsaldeb = wdeb;
                  bdsalcre = wcre;
                  bdmovper = wdeb - wcre;
                  bdsalatu = bdsalant + bdmovper;
                END
             ELSE
                BEGIN
                  bdsalant2 = wdeb_ant_zer - wcre_ant_zer;
                  bdsaldeb2 = wdeb_2_zer;
                  bdsalcre2 = wcre_2_zer;
                  bdmovper2 = wdeb_2_zer - wcre_2_zer;
                  bdsalatu2 = bdsalant2 + bdmovper2;

                  bdsalant1 = bdsalatu2;
                  bdsaldeb1 = wdeb_1_zer;
                  bdsalcre1 = wcre_1_zer;
                  bdmovper1 = wdeb_1_zer - wcre_1_zer;
                  bdsalatu1 = bdsalant1 + bdmovper1;

                  bdsalant = bdsalatu1;
                  bdsaldeb = wdeb_zer;
                  bdsalcre = wcre_zer;
                  bdmovper = wdeb_zer - wcre_zer;
                  bdsalatu = bdsalant + bdmovper;
                END
           END

        SUSPEND;
      END
END
^

/* Alter (VSUC_LANCAMENTOS_AGRUPADOS) */
ALTER PROCEDURE VSUC_LANCAMENTOS_AGRUPADOS(PRCODEMP VARCHAR(1024),
PRTIPOLAN VARCHAR(100),
PRCHAVEONLINE VARCHAR(120),
PRDATA DATE,
PRCONTABILIZACAO INTEGER,
PRDEBITO INTEGER,
PRCREDITO INTEGER,
PRCOMPL SMALLINT = null,
PRCODTPCC VARCHAR(1024) = null)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDLOTE VARCHAR(10),
BDDATA DATE,
BDDEBITO INTEGER,
BDCONCD VARCHAR(5),
BDCREDITO INTEGER,
BDCONCC VARCHAR(5),
BDVALOR NUMERIC(15,2),
BDDATALAN DATE,
BDHORALAN TIME,
BDDATALANALT DATE,
BDHORALANALT TIME,
BDCODUSU INTEGER,
BDCODUSUALTERACAO INTEGER,
BDCODTPHI INTEGER,
BDNOMEHIST VARCHAR(100),
BDCOMPL VARCHAR(200),
BDDCTO VARCHAR(15),
BDCODTERCEIROD INTEGER,
BDCODTERCEIROC INTEGER,
BDTIPLAN VARCHAR(100),
BDTRANSFERIDO INTEGER,
BDGRUPO INTEGER,
BDTOTLAN INTEGER,
BDAGRUPADOR INTEGER,
BDTIPOLAN INTEGER,
BDCHAVEONLINE VARCHAR(120),
BDCODTPCC INTEGER,
BDTRANSACAO INTEGER,
BDTRANFECHADA VARCHAR(5),
BDCONCILIACAOPENDENTE INTEGER,
BDOBSERVACAODEB TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
BDOBSERVACAOCRE TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
 AS
declare variable WSQL varchar(10240);
declare variable WSQLAUX varchar(10240);
declare variable WCOUNT integer;
declare variable WDATA date;
declare variable WDATAANT date;
declare variable WDEBITO integer;
declare variable WDEBANT integer;
declare variable WCREDITO integer;
declare variable WCREANT integer;
declare variable WCHAVEONLINE varchar(120);
declare variable WCHAVEONLINEANT varchar(120);
declare variable WVALOR numeric(15,2);
declare variable WTOTAL numeric(15,2);
declare variable WCHAVE integer;
declare variable WCHAVEANT integer;
declare variable WGRUPO integer;
declare variable WGRUPOANT integer;
declare variable WTOTLAN integer;
declare variable WTOTLANANT integer;
declare variable WAGRUPADOR integer;
declare variable WAGRUPADORANT integer;
declare variable WTIPLAN varchar(100);
declare variable WTIPLANANT varchar(100);
declare variable WCOMPL1 varchar(200);
declare variable WCOMPL2 varchar(200);
declare variable WCODEMPANT integer;
declare variable WCODPLAPADRAOANT integer;
declare variable WTIPOLANANT integer;
declare variable WCODHISTANT integer;
BEGIN
  wchaveonlineant = '';
  wdataant = NULL;
  wdebant = 0;
  wcreant = 0;
  wtotal = 0;
  wcount = 0;
--#Alt:22399 - (11/05/2018) - Carlos Machado.
  wcodempant = 0;
  wcodplapadraoant = 0;
  wtipolanant = 0;
  wcodhistant = 0;
  wtiplanant = 0;

  wsql = 'select lan.bdcodemp, lan.bdcodplapadrao, lan.bdtipolan, lan.bdcodhist, lan.bddata, lan.bddebito, lan.bdcredito, lan.bdchaveonline, tip.bddescricao bdTIPLAN, ';
  wsql = wsql||'min(lan.bdchave), count(lan.bdchave), case when count(lan.bdchave) > 1 then 1 else 0 end as bdagrupador, '; --alt:11759 - 01/02/2016 - S? deve aparecer o bot?o para agrupar nos lan?amentos agrupados, antes mostrava em todos da Folha. Pedro
  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
     BEGIN
       wsql = wsql||'sum(lan.bdvalor), null as bdcodtpcc ';
       wsql = wsql||'from VSUC_EMPRESAS_TLAN lan ';
     END
  ELSE
     BEGIN
       wsql = wsql||'sum(tlcc.BDVALOR), tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  --left join HIST_TPHI hist on ((hist.bdcodhist = lan.bdcodhist) and (hist.bdcodtphi = lan.bdcodtphi))
  wsql = wsql||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wsql = wsql||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wsql = wsql||'WHERE lan.BDCODEMP in ('||prcodemp||') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and ((lan.bdtipolan in ('||prtipolan||')) and (lan.bdchaveonline is not null)) ';
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
     wsql = wsql||' and tlcc.bdcodtpcc in ('||prcodtpcc||')';

  wsql = wsql||'group by lan.bdcodemp, lan.bdcodplapadrao, lan.bdtipolan, lan.bdcodhist, lan.bddata, lan.bddebito, lan.bdcredito, lan.bdchaveonline, tip.bddescricao ';
  wsql = wsql||'order by lan.bdchaveonline, lan.bddata ';
  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodplapadrao, :bdtipolan, :bdcodhist, :wdata, :wdebito, :wcredito, :wchaveonline, :bdtiplan, :wgrupo, :wtotlan, :wagrupador, :wvalor, :bdcodtpcc DO
      BEGIN
-- alt:#6537 - gilberto - 29/08/2013
--        if ((wchaveonlineant <> wchaveonline) or (wdataant <> wdata)) then
--        if ((wchaveonlineant <> wchaveonline) or (wdataant <> wdata) or (coalesce(wdebant, 0) <> coalesce(wdebito, 0)) or (coalesce(wcreant, 0) <> coalesce(wcredito, 0))) then
           BEGIN
             bdchave = wchaveant;
             bddata = wdataant;
             bdgrupo = wgrupoant;
             bdtotlan = wtotlanant;
             bdagrupador = wagrupadorant;
             bdchaveonline = wchaveonlineant;
             IF (wcount >= 2) THEN
                BEGIN
                  IF (wtotal < 0) THEN
                     BEGIN
                       bddebito = wdebant;
                       bdcredito = wcreant;
                       bdvalor = wtotal * -1;
                     END
                  ELSE
                     BEGIN
                       bddebito = wcreant;
                       bdcredito = wdebant;
                       bdvalor = wtotal;
                     END
                END
             ELSE
                BEGIN
                  bddebito = wdebant;
                  bdcredito = wcreant;
                  bdvalor = wtotal;
                END

             IF (wchaveant IS NOT NULL) THEN
               SUSPEND;
             wtotal = 0;
             wdebant = wdebito;
             wcreant = wcredito;
             wdataant = wdata;
             wcount = 0;
             wtotlanant = 0;

-- alt:#6537 - gilberto - 29/08/2013
--             if (wchaveonlineant = prchaveonline and wdataant = prdata) then
--             if ((wchaveonlineant = prchaveonline) and (wdataant = prdata) and (coalesce(wdebito, 0) = coalesce(prdebito, 0)) and (coalesce(wcredito, 0) = coalesce(prcredito, 0))) then
             IF ((wchaveonline = prchaveonline) AND (wdata = prdata) AND (COALESCE(wdebito, 0) = COALESCE(prdebito, 0)) AND (COALESCE(wcredito, 0) = COALESCE(prcredito, 0))) THEN
--             if ((wchaveonline = prchaveonline) and (wdata = prdata)) then
                BEGIN
                  wsqlaux = 'select lan.bdCHAVE,  lan.bdCODEMP, lan.bdcodplapadrao, lan.bdcodhist, lan.BDLOTE, ';
                  wsqlaux = wsqlaux||'lan.BDDATA, lan.BDDEBITO, lan.BDTIPOLAN,  lan.bdCONCD, lan.BDCREDITO, ';
                  wsqlaux = wsqlaux||'lan.bdCONCC, lan.bddatalan, lan.bdhoralan, lan.bddatalanalt, ';
                  wsqlaux = wsqlaux||'lan.bdhoralanalt, lan.bdcodusu, lan.bdcodusualteracao, lan.BDCODTPHI, ';
                  wsqlaux = wsqlaux||'hist.bdNOME,lan.BDCOMPL,  lan.BDDCTO ,lan.bdcodterceirod, lan.bdcodterceiroc, ';
                  wsqlaux = wsqlaux||'tip.bddescricao bdTIPLAN, ';
                  wsqlaux = wsqlaux||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end bdtransferido , ';
                  wsqlaux = wsqlaux||'null as bdtotlan, 0 as bdagrupador, lan.bdchaveonline, lan.bdtransacao, lan.bdtranfechada, ';
                  --alt:17776 - 09/03/2017 - Adicionadas colunas do status de concilia??o e observa??o, acrescentadas para a central de concilia??es. Pedro
                  wsqlaux = wsqlaux||'lan.bdconciliacaopendente, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
                  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
                     BEGIN
                       wsqlaux = wsqlaux||'lan.bdvalor, null as bdcodtpcc ';
                       wsqlaux = wsqlaux||'from VSUC_EMPRESAS_TLAN lan ';
                     END
                  ELSE
                     BEGIN
                       wsqlaux = wsqlaux||'tlcc.BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
                       wsqlaux = wsqlaux||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bdcodtpcc in ('||prcodtpcc||')) ';
                     END
                  wsqlaux = wsqlaux||'left join HIST_TPHI hist on ((hist.bdcodhist = lan.bdcodhist) and (hist.bdcodtphi = lan.bdcodtphi)) ';
                  wsqlaux = wsqlaux||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
                  wsqlaux = wsqlaux||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
                  --alt:17776 - 09/03/2017 - Adicionadas colunas do status de concilia??o e observa??o, acrescentadas para a central de concilia??es. Pedro
                  wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = lan.BDCODEMP and tObsDeb.BDCHAVE = lan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
                  wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = lan.BDCODEMP and tObsCre.BDCHAVE = lan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
                  wsqlaux = wsqlaux||'WHERE lan.BDCODEMP in ('||prcodemp||') ';
                  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                  IF (prcontabilizacao <> 99) THEN
                    wsqlaux = wsqlaux||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
                  wsqlaux = wsqlaux||'and ((lan.bdtipolan in ('||prtipolan||')) and (lan.bdchaveonline is not null)) ';
                  wsqlaux = wsqlaux||'and lan.bddata = cast('''||prdata||''' as date) ' ;
                  wsqlaux = wsqlaux||'and lan.bdchaveonline = '''||prchaveonline||''' ';
-- alt:#6537 - gilberto - 29/08/2013
                  wsqlaux = wsqlaux||' and ((coalesce(lan.bddebito, 0) = '||COALESCE(wdebito, 0)||') and (coalesce(lan.bdcredito, 0) = '||COALESCE(wcredito, 0)||')) ';

                  wsqlaux = wsqlaux||'order by lan.bdchaveonline, lan.bddata ';
                  FOR EXECUTE STATEMENT wsqlaux
                      INTO :bdchave, :bdcodemp, :bdcodplapadrao, :bdcodhist, :bdlote, :bddata, :bddebito, :bdtipolan, :bdconcd, :bdcredito, :bdconcc,
                           :bddatalan, :bdhoralan, :bddatalanalt, :bdhoralanalt, :bdcodusu, :bdcodusualteracao, :bdcodtphi, :bdnomehist, :bdcompl, :bddcto,
                           :bdcodterceirod, :bdcodterceiroc, :bdtiplan, :bdtransferido, :bdtotlan, :bdagrupador, :bdchaveonline, :bdtransacao, :bdtranfechada,
                           :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :bdcodtpcc DO
                      BEGIN
                        BDGRUPO = :wGrupo; --alt:11759 - 04/02/2016 - Preciso que o grupo seja o mesmo que o do lan?amento agrupado, para poder ordenar corretamente, j? que nem sempre ? agrupada a ChaveOnline inteira. Pedro
                        SUSPEND;
                      END
                END
           END

        IF ((wdebant = wcredito) AND (wcreant = wdebito) AND (wdataant = wdata)) THEN
           BEGIN
             wtotal = wtotal - wvalor;
             wcount = wcount + 1;
           END
        ELSE
           BEGIN
             wtotal = wtotal + wvalor;
             wcount = wcount + 1;
           END
        wtotlanant = wtotlanant + wtotlan;


        wchaveant = wgrupo;
        wdataant = wdata;
        wdebant = wdebito;
        wcreant = wcredito;
        wchaveonlineant = wchaveonline;
        wgrupoant = wgrupo;
        wagrupadorant = wagrupador;
        wcodempant = bdcodemp;
        wcodplapadraoant = bdcodplapadrao;
        wtipolanant = bdtipolan;
        wcodhistant = bdcodhist;
        wtiplanant = bdtiplan;

        BDCODEMP = NULL;
        BDCHAVE = NULL;
        BDCODPLAPADRAO = NULL;
        BDCODHIST = NULL;
        BDLOTE = NULL;
        BDDATA = NULL;
        BDDEBITO = NULL;
        BDCONCD = NULL;
        BDCREDITO = NULL;
        BDCONCC = NULL;
        BDVALOR = NULL;
        BDDATALAN = NULL;
        BDHORALAN = NULL;
        BDDATALANALT = NULL;
        BDHORALANALT = NULL;
        BDCODUSU = NULL;
        BDCODUSUALTERACAO = NULL;
        BDCODTPHI = NULL;
        BDNOMEHIST = NULL;
        BDCOMPL = NULL;
        BDDCTO = NULL;
        BDCODTERCEIROD = NULL;
        BDCODTERCEIROC = NULL;
        BDTIPLAN = NULL;
        BDTRANSFERIDO = NULL;
        BDGRUPO = NULL;
        BDTOTLAN = NULL;
        BDAGRUPADOR = NULL;
        BDTIPOLAN = NULL;
        BDCHAVEONLINE = NULL;
        BDCODTPCC = NULL;
        BDTRANSACAO = NULL;
        BDTRANFECHADA = NULL;
        BDCONCILIACAOPENDENTE = NULL;
        BDOBSERVACAODEB = NULL;
        BDOBSERVACAOCRE = NULL;
      END

  IF (wchaveant IS NOT NULL) THEN
     BEGIN
       bdchave = wchaveant;
       bddata = wdataant;
       bdgrupo = wgrupoant;
       bdtotlan = wtotlanant;
       bdagrupador = wagrupadorant;
       bdchaveonline = wchaveonlineant;
       bdcodemp = wcodempant;
       bdcodplapadrao = wcodplapadraoant;
       bdtipolan = wtipolanant;
       bdcodhist = wcodhistant;
       bdtiplan = wtiplanant;

       IF (wcount >= 2) THEN
          BEGIN
            IF (wtotal < 0) THEN
               BEGIN
                 bddebito = wdebant;
                 bdcredito = wcreant;
                 bdvalor = wtotal * -1;
               END
            ELSE
               BEGIN
                 bddebito = wcreant;
                 bdcredito = wdebant;
                 bdvalor = wtotal;
               END
          END
       ELSE
          BEGIN
            bddebito = wdebant;
            bdcredito = wcreant;
            bdvalor = wtotal;
          END

       IF (wchaveant IS NOT NULL) THEN
          BEGIN
            SUSPEND;
-- alt:#6537 - gilberto - 29/08/2013
--            if (wchaveonlineant = prchaveonline and wdataant = prdata) then
            IF ((wchaveonlineant <> wchaveonline) OR (wdataant <> wdata) OR (COALESCE(wdebant, 0) <> COALESCE(wdebito, 0)) OR (COALESCE(wcreant, 0) <> COALESCE(wcredito, 0))) THEN
               BEGIN
                 wsqlaux = 'select lan.bdCHAVE,  lan.bdCODEMP, lan.bdcodplapadrao, lan.bdcodhist, lan.BDLOTE, ';
                 wsqlaux = wsqlaux||'lan.BDDATA, lan.BDDEBITO, lan.BDTIPOLAN,  lan.bdCONCD, lan.BDCREDITO, ';
                 wsqlaux = wsqlaux||'lan.bdCONCC, lan.bddatalan, lan.bdhoralan, lan.bddatalanalt, ';
                 wsqlaux = wsqlaux||'lan.bdhoralanalt, lan.bdcodusu, lan.bdcodusualteracao, lan.BDCODTPHI, ';
                 wsqlaux = wsqlaux||'hist.bdNOME,lan.BDCOMPL,  lan.BDDCTO ,lan.bdcodterceirod, lan.bdcodterceiroc, ';
                 wsqlaux = wsqlaux||'tip.bddescricao bdTIPLAN, ';
                 wsqlaux = wsqlaux||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end bdtransferido , ';
                 wsqlaux = wsqlaux||'null as bdtotlan, 0 as bdagrupador, lan.bdchaveonline, lan.bdtransacao, lan.bdtranfechada, ';
                 --alt:17776 - 09/03/2017 - Adicionadas colunas do status de concilia??o e observa??o, acrescentadas para a central de concilia??es. Pedro
                 wsqlaux = wsqlaux||'lan.bdconciliacaopendente, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
                 IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
                    BEGIN
                      wsqlaux = wsqlaux||'lan.bdvalor, null as bdcodtpcc ';
                      wsqlaux = wsqlaux||'from VSUC_EMPRESAS_TLAN lan ';
                    END
                 ELSE
                    BEGIN
                      wsqlaux = wsqlaux||'tlcc.BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
                      wsqlaux = wsqlaux||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bdcodtpcc in ('||prcodtpcc||')) ';
                    END
                 wsqlaux = wsqlaux||'left join HIST_TPHI hist on ((hist.bdcodhist = lan.bdcodhist) and (hist.bdcodtphi = lan.bdcodtphi)) ';
                 wsqlaux = wsqlaux||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
                 wsqlaux = wsqlaux||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
                 --alt:17776 - 09/03/2017 - Adicionadas colunas do status de concilia??o e observa??o, acrescentadas para a central de concilia??es. Pedro
                 wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = tlan.BDCODEMP and tObsDeb.BDCHAVE = tlan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
                 wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = tlan.BDCODEMP and tObsCre.BDCHAVE = tlan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
                 wsqlaux = wsqlaux||'WHERE lan.BDCODEMP in ('||prcodemp||') ';
                 --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                 IF (prcontabilizacao <> 99) THEN
                   wsqlaux = wsqlaux||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
                 wsqlaux = wsqlaux||'and ((lan.bdtipolan in ('||prtipolan||')) and (lan.bdchaveonline is not null)) ';
                 wsqlaux = wsqlaux||'and lan.bddata = cast('''||prdata||''' as date) ' ;
                 wsqlaux = wsqlaux||'and lan.bdchaveonline = '''||prchaveonline||''' ';
                 wsqlaux = wsqlaux||'order by lan.bdchaveonline, lan.bddata ';
                 FOR EXECUTE STATEMENT wsqlaux
                     INTO :bdchave, :bdcodemp, :bdcodplapadrao, :bdcodhist, :bdlote, :bddata, :bddebito, :bdtipolan, :bdconcd, :bdcredito, :bdconcc,
                          :bddatalan, :bdhoralan, :bddatalanalt, :bdhoralanalt, :bdcodusu, :bdcodusualteracao, :bdcodtphi, :bdnomehist, :bdcompl, :bddcto,
                          :bdcodterceirod, :bdcodterceiroc, :bdtiplan, :bdtransferido, :bdtotlan, :bdagrupador, :bdchaveonline, :bdtransacao, :bdtranfechada,
                          :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :bdcodtpcc DO
                     BEGIN
                        BDGRUPO = :wGrupo; --alt:11759 - 04/02/2016 - Preciso que o grupo seja o mesmo que o do lan?amento agrupado, para poder ordenar corretamente, j? que nem sempre ? agrupada a ChaveOnline inteira. Pedro
                        SUSPEND;
                      END
               END
          END
     END
END
^

/* Alter (VSUC_LANCAMENTOS_EF_AGRUPADOS) */
ALTER PROCEDURE VSUC_LANCAMENTOS_EF_AGRUPADOS(PRCODEMP VARCHAR(1024),
PRTIPOLAN VARCHAR(100),
PRCONTABILIZACAO INTEGER,
PRDATA DATE,
PRTRANSACAO INTEGER,
PRCODTPCC VARCHAR(1024) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDLOTE VARCHAR(10),
BDDATA DATE,
BDDEBITO INTEGER,
BDCONCD VARCHAR(5),
BDCREDITO INTEGER,
BDCONCC VARCHAR(5),
BDVALOR NUMERIC(15,2),
BDDATALAN DATE,
BDHORALAN TIME,
BDDATALANALT DATE,
BDHORALANALT TIME,
BDCODUSU INTEGER,
BDCODUSUALTERACAO INTEGER,
BDCODTPHI INTEGER,
BDNOMEHIST VARCHAR(100),
BDCOMPL VARCHAR(200),
BDDCTO VARCHAR(15),
BDCODTERCEIROD INTEGER,
BDCODTERCEIROC INTEGER,
BDTIPLAN VARCHAR(100),
BDTRANSFERIDO INTEGER,
BDGRUPO INTEGER,
BDTOTLAN INTEGER,
BDAGRUPADOR INTEGER,
BDTIPOLAN INTEGER,
BDCHAVEONLINE VARCHAR(120),
BDCODTPCC INTEGER,
BDTRANSACAO INTEGER,
BDTRANFECHADA VARCHAR(5),
BDCONCILIACAOPENDENTE INTEGER,
BDOBSERVACAODEB TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
BDOBSERVACAOCRE TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WTRANSANT INTEGER;
BEGIN
  wsql = 'select * from (';
  wsql = wsql||'select lan.bdcodemp, lan.bdcodplapadrao, lan.bdcodhist, lan.bddata, lan.BDTRANSACAO, lan.bdtipolan, tip.bddescricao as bdTIPLAN, ';
  wSQL = wSQL||'max(lan.BDDEBITO) as BDDEBITO, max(lan.BDCREDITO) as BDCREDITO, max(lan.BDCODTPHI) as BDCODTPHI, ';
  wsql = wsql||'min(lan.BDCHAVE) as BDCHAVE, count(lan.bdchave) as BDCOUNT, 1 as bagrupador, ';

  wSQL = wSQL||'max(lan.BDLOTE) as BDLOTE, null as BDCONCD, null as BDCONCC, null as BDDATALAN, null as BDHORALAN, null as BDDATALANALT, ';
  wSQL = wSQL||'null as BDHORALANALT, null as BDCODUSU, null as BDCODUSUALTERACAO, null as BDNOMEHIST, max(lan.BDCOMPL) as BDCOMPL, ';
  wSQL = wSQL||'max(lan.BDDCTO) as BDDCTO, max(lan.BDCODTERCEIROD) as BDCODTERCEIROD, max(lan.BDCODTERCEIROC) as BDCODTERCEIROC, null as BDTRANFECHADA, null as BDTRANSFERIDO, ';
  wSQL = wSQL||'null as BDCONCILIACAOPENDENTE, null as BDOBSERVACAODEB, null as BDOBSERVACAOCRE, ';

  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
     BEGIN
       wsql = wsql||'avg(lan.bdvalor) as BDVALOR, null as bdcodtpcc ';
       wsql = wsql||'from VSUC_EMPRESAS_TLAN lan ';
     END
  ELSE
     BEGIN
       wsql = wsql||'avg(tlcc.BDVALOR) as BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wsql = wsql||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wsql = wsql||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wsql = wsql||'WHERE (lan.bdtipolan in ('||prtipolan||')) ';
  
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
     wsql = wsql||' and tlcc.bdcodtpcc in ('||prcodtpcc||')';

  --1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

  wsql = wsql||'and ((lan.BDDEBITO is null) or (lan.BDCREDITO is null)) ';
  wsql = wsql||'and (lan.BDTRANFECHADA = ''TRUE'') ';
  wsql = wsql||'and (lan.BDCODEMP in ('||prcodemp||')) ';
  wsql = wsql||'group by lan.bdcodemp, lan.bdcodplapadrao, lan.bdtipolan, lan.bdcodhist, lan.bddata, lan.BDTRANSACAO, tip.bddescricao ';
  wsql = wsql||'having (count(lan.bdchave) = 2) and (sum(case when BDDEBITO is null then 0 else BDVALOR end) = sum(case when BDCREDITO is null then 0 else BDVALOR end))';
  
  wsql = wsql||' union '; /**********************************************************************************************************************************************/

  wSQL = wSQL||'select lan.bdcodemp, lan.bdcodplapadrao, lan.bdcodhist, lan.bddata, lan.BDTRANSACAO, lan.bdtipolan, tip.bddescricao as bdTIPLAN, ';
  wSQL = wSQL||'lan.BDDEBITO, lan.BDCREDITO, lan.BDCODTPHI, ';
  wsql = wsql||'lan.bdchave, 1 as BDCOUNT, 0 as bagrupador, ';

  wSQL = wSQL||'BDLOTE, BDCONCD, BDCONCC, BDDATALAN, BDHORALAN, BDDATALANALT, BDHORALANALT, BDCODUSU, BDCODUSUALTERACAO, ';
  wSQL = wSQL||'null as BDNOMEHIST, BDCOMPL, BDDCTO, BDCODTERCEIROD, BDCODTERCEIROC, BDTRANFECHADA, ';
  wSQL = wSQL||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end BDTRANSFERIDO, ';
  wSQL = wSQL||'lan.BDCONCILIACAOPENDENTE, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
     BEGIN
       wSQL = wSQL||'lan.bdvalor, null as bdcodtpcc ';
       wSQL = wSQL||'from VSUC_EMPRESAS_TLAN lan ';
     END
  ELSE
     BEGIN
       wSQL = wSQL||'tlcc.BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wSQL = wSQL||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wSQL = wSQL||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wSQL = wSQL||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wSQL = wSQL||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = lan.BDCODEMP and tObsDeb.BDCHAVE = lan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
  wSQL = wSQL||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = lan.BDCODEMP and tObsCre.BDCHAVE = lan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
  wSQL = wSQL||'where (lan.bdtipolan in ('||prtipolan||')) ';
  
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
     wsql = wsql||' and tlcc.bdcodtpcc in ('||prcodtpcc||')';

  --1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and (lan.BDCODEMP in ('||prcodemp||')) ';


  wsql = wsql||') order by BDTRANSACAO, BDDATA, BAGRUPADOR DESC ';
  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodplapadrao, :bdcodhist, :bddata, :bdtransacao, :bdtipolan, :bdtiplan,
                                  :bddebito, :bdcredito, :bdcodtphi,
                                  :bdchave, :bdtotlan, :bdagrupador,
                                  :BDLOTE, :BDCONCD, :BDCONCC, :BDDATALAN, :BDHORALAN, :BDDATALANALT, :BDHORALANALT, :BDCODUSU, :BDCODUSUALTERACAO,
                                  :BDNOMEHIST, :BDCOMPL, :BDDCTO, :BDCODTERCEIROD, :BDCODTERCEIROC, :BDTRANFECHADA, :BDTRANSFERIDO,
                                  :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :bdcodtpcc DO
    BEGIN
      BDGRUPO = BDTRANSACAO;

      IF ((BDAGRUPADOR = 1) OR (BDTRANSACAO IS NULL) OR (BDTRANSACAO <> wTransAnt) OR ((BDTRANSACAO = prTRANSACAO) AND (BDDATA = prDATA))) THEN
        SUSPEND;

      wTransAnt = BDTRANSACAO;
    END
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_LISTA_TLAN_CONC_CLIFOR for: VSUC_NRO_NOTA_COMPL */
ALTER PROCEDURE VSUC_SP_LISTA_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCLIFOR SMALLINT,
PRLANCONC SMALLINT,
PRZEROESQ SMALLINT,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_NRO_NOTA_COMPL) */
ALTER PROCEDURE VSUC_NRO_NOTA_COMPL(PRCOMPL VARCHAR(200),
PRZEROESQ SMALLINT)
 RETURNS(NRONF VARCHAR(50))
 AS
DECLARE VARIABLE WCHAR CHAR(1);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  -- retorna os numeros dos documentos de acordo com o parametro de ignorar zeros a esquerda
  wconta = 1;
  --#alt:6773. Carlos Mello(30/09/2013)
  /*nronf = '';
  while (wconta <= strlen(prcompl)) do
    begin
      wchar = substring(prcompl from wconta for 1);
      select pos from pos(:wchar,'0123456789') into :wpos;
      if (wpos <> 0) then
         nronf = nronf||wchar;
      wconta = wconta + 1;
    end*/
  nronf = prcompl; -- Est? vindo o N?mero do documento

  IF ((przeroesq IS NULL) OR (przeroesq = 0)) THEN
     BEGIN
       WHILE (SUBSTRING(nronf FROM 1 FOR 1) = '0') DO
         BEGIN
           nronf = SUBSTRING(nronf FROM 2 FOR strlen(nronf)-1);
         END
     END

  SUSPEND;
END
^

/* Alter (VSUC_RETORNA_CLA_INCORP) */
ALTER PROCEDURE VSUC_RETORNA_CLA_INCORP(PRCODCTA INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODEMPREENDIMENTO INTEGER,
PRUNIDIMOB INTEGER)
 RETURNS(BDCLASSIFICACAO VARCHAR(40))
 AS
DECLARE VARIABLE WUSAEMPREENDIMENTO VARCHAR(5);
DECLARE VARIABLE WUSAUNIDIMOB VARCHAR(5);
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WCLASSIFICACAOORG VARCHAR(40);
DECLARE VARIABLE WCLASSIFICACAOAUX VARCHAR(40);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WPOSCTA INTEGER;
DECLARE VARIABLE WPOSANT INTEGER;
BEGIN
  SELECT BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB, BDCTALON FROM PLANOS_TPLA
  WHERE BDCODPLAPADRAO = :prcodplapadrao AND
        BDCODTPLA = :prcodcta
  INTO :wusaempreendimento, :wusaunidimob, :wclassificacaoorg;

  IF (((wusaempreendimento IS NULL) OR (wusaempreendimento = '') OR (UPPER(wusaempreendimento) = 'FALSE') ) AND
      ((wusaunidimob IS NULL) OR (wusaunidimob = '') OR (UPPER(wusaunidimob) = 'FALSE'))) THEN
      EXIT;

  wclassificacao = '';
  wclassificacaoaux = wclassificacaoorg;
  wpos = 1;
  wposcta = POSITION('.', wclassificacaoorg);
  WHILE (wclassificacao <> wclassificacaoorg) DO
    BEGIN
      wclassificacao = SUBSTRING(wclassificacaoorg FROM 1 FOR wposcta-1);

      SELECT BDCTAEMPREENDIMENTOSIMOB FROM PLANOS_TPLA
      WHERE BDCODPLAPADRAO = :prcodplapadrao AND
            BDCTALON = :wclassificacao
      INTO :wusaempreendimento;

      IF (UPPER(wusaempreendimento) = 'TRUE') THEN
        BREAK;

      wpos = wpos + POSITION('.', wclassificacaoaux);
      wclassificacaoaux = SUBSTRING(wclassificacaoorg FROM wpos FOR strlen(wclassificacaoorg));
      wposant = wposcta;
      wposcta = POSITION(wclassificacaoaux, wclassificacaoorg)-1;

      IF (POSITION('.', wclassificacaoaux) = 0) THEN
        BEGIN
          --Ja percorreu todos os n?veis
          IF (wposant = wpos-1) THEN
            wposcta = strlen(wclassificacaoorg)+1;
          ELSE
          --Falta percorrer um n?vel
          IF (wposcta < wposant) THEN
            wposcta = wpos-1;
          ELSE
            BREAK;
           END
    END

  IF (UPPER(wusaempreendimento) = 'TRUE') THEN
    bdclassificacao = SUBSTRING(wclassificacaoorg FROM 1 FOR wposant)||LPAD(prcodempreendimento, 9, '0')||SUBSTRING(wclassificacaoorg FROM wposcta FOR strlen(wclassificacaoorg));

  IF ((UPPER(wusaunidimob) = 'TRUE') AND (prunidimob > 0) AND (prunidimob IS NOT NULL)) THEN
    BEGIN
      wclassificacaoaux = bdclassificacao;
      WHILE (POSITION('.', wclassificacaoaux) > 0) DO
        BEGIN
          wpos = wpos + POSITION('.', wclassificacaoaux);
          wclassificacaoaux = SUBSTRING(bdclassificacao FROM wpos FOR strlen(bdclassificacao));
          wposant = wpos;
      END

      bdclassificacao = SUBSTRING(bdclassificacao FROM 1 FOR wposant-1)||LPAD(prunidimob, 9, '0');
    END

  SUSPEND;
END
^

/* Alter (VSUC_SP_BALANCO_PATRIMONIAL) */
ALTER PROCEDURE VSUC_SP_BALANCO_PATRIMONIAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSEMCC INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSAL_ANT_DEB NUMERIC(15,2),
BDSAL_ANT_CRE NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDCODEMPFILIAL INTEGER,
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20),
BDPERTENCECONTA INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(4096);
DECLARE VARIABLE WSQLTCC VARCHAR(1024);
DECLARE VARIABLE WSEQCTA VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WCTALONATIVO VARCHAR(40);
DECLARE VARIABLE WCTALONPATLIQ VARCHAR(40);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
DECLARE VARIABLE WCODEMPATUAL INTEGER;
DECLARE VARIABLE WRELCONTA INTEGER;
BEGIN
  -- sql referente as empresas selecionadas
  wsqlemp = 'select bdcodemp, bdcodmatriz, bdcodplapadrao,  bdcodcentros from vw_empresas_ref_atual where bdcodemp in ('||prcodemp||') order by bdcodmatriz,  bdcodemp';
  -- laco das empresas selecionadas
  wdatahora = CURRENT_TIMESTAMP;

  FOR EXECUTE STATEMENT wsqlemp
      INTO :wcodemp, :bdcodmatriz, :wcodplapadrao, :wcodcentros DO
      BEGIN
        -- retorna a primeira conta do ativo
        SELECT FIRST 1 planos_tpla.bdcodtpla, planos_tpla.bdctalon FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
        AND planos_tpla.bdctalon = :prctalonini
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini, :wctalonativo;

        -- retorna a primeira conta do passivo a descoberto
        SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
        AND planos_tpla.bdctalon = :prctalonpas
        ORDER BY planos_tpla.bdctalon ASC INTO :wctalonpatliq;

        -- retorna a ultima conta do resto do plano
        wsql = 'select first 1 planos_tpla.bdcodtpla from planos_tpla ';
        wsql = wsql||'where planos_tpla.bdcodplapadrao = '||wcodplapadrao;
        wsql = wsql||' and substring(planos_tpla.bdctalon from 1 for '||strlen(prctalonfin)||') = '''||prctalonfin||'''';
        wsql = wsql||'order by planos_tpla.bdctalon desc';
        EXECUTE STATEMENT wsql INTO :wcodctafin;

        -- sql responsavel pela limpeza da tabela cache de saldos
--        delete from VSUC_EMPRESAS_TBALANCETE;
        DELETE FROM VSUC_EMPRESAS_TBALANCETE_3 WHERE bdcodemp <> 0;
-- gilberto - 20/03/2015 - ALT:#9178 - alterado para calcular cc com rotina "VSUC_SP_RETORNA_SALDO_CONTAS_XZ"
        IF ((prlistacc IS NULL) OR (TRIM(prlistacc) = '')) THEN
           BEGIN
             FOR SELECT tsal.codemp, tsal.codplapadrao, tsal.conta, tsal.classificacao, tsal.nomeconta, tsal.tipconta,
                        tsal.saldo_anterior, tsal.saldo_ant_deb, tsal.saldo_ant_cre, tsal.saldo_atual, tsal.saldo_deb, tsal.saldo_cre,
                        tref.bdnomemp, temp.bdcnpjemp, tsal.formula, tsal.participante, tsal.GRUPOCONTA, tsal.apecta, tsal.pertenceconta, tsal.relconta
                 FROM VSUC_SP_RETORNA_SALDO_CONTAS_X(:wcodemp, :wcodctaini, :wcodctafin, :prdatini, :prdatfin, :prindice, :prignzer, :bdcodtpcc, :wcodplapadrao,0,
                                                     :prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                 LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.codemp)
                 LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                 WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                        WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                        AND tempresas_ref.bdrefemp <= :prrefemp
                                        ORDER BY tempresas_ref.bdrefemp DESC) --and
                       --((tsal.relconta = 0) or (tsal.relconta is null)) -- RelConta -> 0 - Balan?o Patrimonial | 1 - Demonstra??o de Resultado
                 INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                      :bdsalant, :bdsal_ant_deb, :bdsal_ant_cre, :bdsalatu, :bdsaldo_deb, :bdsaldo_cre,
                      :bdnomemp, :bdcnpjemp, :bdformula, :wparticipante, :bdgrpcta, :bdapecta, :BDPERTENCECONTA, :wrelconta DO
             BEGIN
               -- Sol. #3208 - Bruno Borges 08/05/2012

               --alt:11586 - Precisa retornar zero pra quando vai imprimir sem CC e as linhas de espa?o entre t?tulos. Como Null estava dando problema na ordena??o. Pedro
               bdcodtpcc = 0;

               bdcodempfilial = bdcodemp;

               SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
               IF (wpos <> 0) THEN
                  BEGIN
                    IF (bdcodmatriz IS NULL) THEN
                       bdcodmatriz = bdcodemp;

                    bdcodemp = bdcodmatriz;

                    --bdcodmatriz = bdcodemp;
                    --if (bdcodmatriz is null) then
                    --   bdcodmatriz = bdcodemp;

                    --bdcodemp = bdcodmatriz;
                  END
               -- Fim
               -- sql para verificar se a conta atual e uma titulo geral
               bdsalmov = bdsalatu - bdsalant;

               IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonativo)) = wctalonativo) THEN
                  bdseqcta = 'ATIVO';
               ELSE
                 IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonpatliq)) = wctalonpatliq) THEN
                   bdseqcta = 'PASSIVO A DESCOBERTO';
                 ELSE
                 --alt:7876 - Verifica o grupo da conta para saber se deve exibir ou excluir. (o que tem o "DEL" ? deletado pelo Delphi). Pedro
                 IF ((wrelconta = 0) OR (wrelconta IS NULL)) THEN
                    bdseqcta = 'X';
                 ELSE
                    bdseqcta = 'DEL';

               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                 BEGIN
                   --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                   FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                       --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta, -- alt:#6647 - gilberto - 12/09/2013
                       FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                            :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                       -- Fim
                       INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                       BEGIN
                         IF (prconcatenacodparticipante = 1) THEN
                           BEGIN
                             wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                        -- 100 -> m?ximo de caracteres para nome da conta
                                        -- 003 -> qtd de caracteres " - ";
                             wpos     = ((100 - wpos) - 3);
                             bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                           END

                         bdsalmov = bdsalatu - bdsalant;
                         SUSPEND;
                       END
                 END
               ELSE
                 BEGIN
                   -- gilberto
                   IF ((NOT prconsolidada IS NULL) AND (prconsolidada <> 0)) THEN
                     SUSPEND;
                   ELSE
                     BEGIN
                       SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                       IF ((wfind IS NULL) OR (wfind = 0)) THEN
                         SUSPEND;
                       ELSE
                         IF (bdtipcta = 2) THEN
                           SUSPEND;
                     END
                 END
             END
           END
        ELSE
           BEGIN
             FOR SELECT tsal.bdcodemp, tsal.bdcodplapadrao, tsal.bdconta, tsal.bdclassificacao, tsal.bdnomeconta, tsal.bdtipconta,
                        tsal.bdsaldo_anterior, tsal.bdsaldo_ant_deb, tsal.bdsaldo_ant_cre, tsal.bdsaldo_atual, tsal.bdsaldo_deb, tsal.bdsaldo_cre,
                        tref.bdnomemp, temp.bdcnpjemp, tsal.bdformula, tsal.bdparticipante, tsal.bdGRUPOCONTA, tsal.bdapecta, tsal.bdpertenceconta, tsal.bdrelconta,
                        COALESCE(tsal.bdcodtpcc, 0), tsal.bdnomtpcc, tref.bdcodcentros
                 FROM vsuc_sp_retorna_saldo_contas_xz(:wcodemp, :wcodctaini, :wcodctafin, :prdatini, :prdatfin, :prindice, :prignzer, :prlistacc, :wcodplapadrao,:prsemcc,
                                                      0, :prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                 LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.bdcodemp)
                 LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                 WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                        WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                        AND tempresas_ref.bdrefemp <= :prrefemp
                                        ORDER BY tempresas_ref.bdrefemp DESC) --and
                       --((tsal.relconta = 0) or (tsal.relconta is null)) -- RelConta -> 0 - Balan?o Patrimonial | 1 - Demonstra??o de Resultado
                 INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                      :bdsalant, :bdsal_ant_deb, :bdsal_ant_cre, :bdsalatu, :bdsaldo_deb, :bdsaldo_cre,
                      :bdnomemp, :bdcnpjemp, :bdformula, :wparticipante, :bdgrpcta, :bdapecta, :BDPERTENCECONTA, :wrelconta, :bdcodtpcc, :bdnomtpcc, :bdcodcentros DO
             BEGIN
               -- Sol. #3208 - Bruno Borges 08/05/2012

               bdcodempfilial = bdcodemp;

               SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
               IF (wpos <> 0) THEN
                  BEGIN
                    IF (bdcodmatriz IS NULL) THEN
                       bdcodmatriz = bdcodemp;

                    bdcodemp = bdcodmatriz;

                    --bdcodmatriz = bdcodemp;
                    --if (bdcodmatriz is null) then
                    --   bdcodmatriz = bdcodemp;

                    --bdcodemp = bdcodmatriz;
                  END
               -- Fim
               -- sql para verificar se a conta atual e uma titulo geral
               bdsalmov = bdsalatu - bdsalant;

               IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonativo)) = wctalonativo) THEN
                  bdseqcta = 'ATIVO';
               ELSE
                 IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonpatliq)) = wctalonpatliq) THEN
                   bdseqcta = 'PASSIVO A DESCOBERTO';
                 ELSE
                 --alt:7876 - Verifica o grupo da conta para saber se deve exibir ou excluir. (o que tem o "DEL" ? deletado pelo Delphi). Pedro
                 IF ((wrelconta = 0) OR (wrelconta IS NULL)) THEN
                    bdseqcta = 'X';
                 ELSE
                    bdseqcta = 'DEL';

               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                 BEGIN
                   --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                   FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                       --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta, -- alt:#6647 - gilberto - 12/09/2013
                       FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                            :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                       -- Fim
                       INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                       BEGIN
                         IF (prconcatenacodparticipante = 1) THEN
                           BEGIN
                             wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                        -- 100 -> m?ximo de caracteres para nome da conta
                                        -- 003 -> qtd de caracteres " - ";
                             wpos     = ((100 - wpos) - 3);
                             bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                           END

                         bdsalmov = bdsalatu - bdsalant;
                         SUSPEND;
                       END
                 END
               ELSE
                 BEGIN
                   -- gilberto
                   IF ((NOT prconsolidada IS NULL) AND (prconsolidada <> 0)) THEN
                     SUSPEND;
                   ELSE
                     BEGIN
                       SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                       IF ((wfind IS NULL) OR (wfind = 0)) THEN
                         SUSPEND;
                       ELSE
                         IF (bdtipcta = 2) THEN
                           SUSPEND;
                     END
                 END
             END
           END
      END
END
^

/* Alter (VSUC_SP_CONCILIACAO) */
ALTER PROCEDURE VSUC_SP_CONCILIACAO(PRCODEMP VARCHAR(2000),
PRCODPLAPADRAO INTEGER,
PRTIPOCONCILIACAO INTEGER,
PRCLASSINI TYPE OF COLUMN PLANOS_TPLA.BDCTALON,
PRTERCEIROINI INTEGER,
PRCLASSFIM TYPE OF COLUMN PLANOS_TPLA.BDCTALON,
PRTERCEIROFIM INTEGER,
PRDEBCRE INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRCOMPARANRDOC DM_BOOLEAN,
PRCONSIDERAZERO DM_BOOLEAN,
PRCOMPARADATA DM_BOOLEAN,
PRVALOREXATO DM_BOOLEAN,
PRRECONCILIAR DM_BOOLEAN)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDTIPOLANCFILIAL SMALLINT)
 AS
DECLARE VARIABLE WSQL DM_MAXVARCHAR;
DECLARE VARIABLE WSQLAUX DM_MAXVARCHAR;
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WCONTAANT INTEGER;
DECLARE VARIABLE WTERCEIRO INTEGER;
DECLARE VARIABLE WTERCEIROANT INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WDCTO DM_BDDCTO;
DECLARE VARIABLE WDCTOANT DM_BDDCTO;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WDATAANT DATE;
DECLARE VARIABLE WDEBITO INTEGER;
DECLARE VARIABLE WTERCEIRODEB INTEGER;
DECLARE VARIABLE WCREDITO INTEGER;
DECLARE VARIABLE WTERCEIROCRE INTEGER;
DECLARE VARIABLE WVALOR DECIMAL(15,2);
DECLARE VARIABLE WVALORDEB DECIMAL(15,2);
DECLARE VARIABLE WVALORCRE DECIMAL(15,2);
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
BEGIN
  DELETE FROM LISTA_LANC WHERE BDCODEMP IS NOT NULL;

  wCONTAANT = 0;
  wTERCEIROANT = 0;
  wDCTOANT = '';
  wDATAANT = '01/01/1900';
  wVALORDEB = 0.00;
  wVALORCRE = 0.00;

  --Faz um la?o de todas as contas (entre a classifica??o inicial e final) e todos os participantes (entre o participante inicial e final)
  wSQL = 'select cta.BDCODTPLA, ';
  IF ((prterceiroini IS NOT NULL) AND (prterceiroini > 0) AND (prterceirofim IS NOT NULL) AND (prterceirofim > 0)) THEN
    wSQL = wSQL||'ter.BDCODTER';
  ELSE
    wSQL = wSQL||'null as BDCODTER';
  wSQL = wSQL||' from PLANOS_TPLA cta';
  IF ((prterceiroini IS NOT NULL) AND (prterceiroini > 0) AND (prterceirofim IS NOT NULL) AND (prterceirofim > 0)) THEN
    wSQL = wSQL||' left join TTERCEIRO ter on (cta.BDPARTICIPANTE = 1 and ter.BDCODTER between '||:prTERCEIROINI||' and '||:prTERCEIROFIM||')';
  wSQL = wSQL||' where cta.BDCODPLAPADRAO = '||:prCodPlaPadrao||' and cta.BDCTALON between '''||:prCLASSINI||''' and '''||:prCLASSFIM||'''';
  wSQL = wSQL||' order by cta.BDCTALON, BDCODTER';
  FOR EXECUTE STATEMENT wSQL INTO :wConta, :wTerceiro DO
    BEGIN
      /*************************************************************************************************************************************************
      /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de concilia??o, alterar tamb?m no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
      /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
      /************************************************************************************************************************************************/

      --Se marcado para reconciliar, atualiza os lan?amentos marcando todos como desconciliados no per?odo e conta informados
      IF (UPPER(prRECONCILIAR) = 'TRUE') THEN
        BEGIN
          wSQL = 'update VSUC_EMPRESAS_TLAN set BDCONCD = null, BDCONCC = null, BDTIPOCONC = 0';      --#alt:13456 - adicionado indice nenhum ao tipo de concilia??o. Ana - 28/10/2016
          wSQL = wSQL||' where (BDDATA >= '''||:prDATAINI||''') and (BDDATA <= '''||:prDATAFIM||''')';
          wSQL = wSQL||' and (BDCODEMP in ('||:prCODEMP||') or BDFILIAL in ('||:prCODEMP||'))';
          IF ((wTERCEIRO IS NULL) OR (wTERCEIRO = 0)) THEN
            wSQL = wSQL||' and ((BDDEBITO = '||:wConta||') or (BDCREDITO = '||:wConta||'))';
          ELSE
            wSQL = wSQL||' and (((BDDEBITO = '||:wConta||') and (BDCODTERCEIROD = '||:wTERCEIRO||')) or ((BDCREDITO = '||:wConta||') and (BDCODTERCEIROC = '||:wTERCEIRO||')))';
          wSQL = wSQL||' and ((bdtipoconc >=4) or (bdtipoconc = 0)) ';       --#alt:13456 - Permite reconciliar apenas as concilia??es autom?ticas. Ana - 28/10/2016
          EXECUTE STATEMENT wSQL;
        END
    
      --Faz um select para retornar todos os lan?amentos no per?odo que podem ser conciliados
      --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar n?meros/caracteres depois dos s?mbolos "/", "\" ou "-". Pedro
      wSQL = 'select * from (select BDCODEMP, BDCHAVE, BDDEBITO, BDCODTERCEIROD, BDCREDITO, BDCODTERCEIROC, BDVALOR, BDTIPOLANCFILIAL, BDDATA, ';
      wSQLAux = 'Substring(bddcto from 1 for';
      wSQLAux = wSQLAux||' case when (bddcto containing '''||'/'||''') then position('''||'/'||''', bddcto) -1';
      wSQLAux = wSQLAux||'      when (bddcto containing '''||'\'||''') then position('''||'\'||''', bddcto) -1';
      wSQLAux = wSQLAux||'      when (bddcto containing '''||'-'||''') then position('''||'-'||''', bddcto) -1';
      wSQLAux = wSQLAux||' else char_length(bddcto) end)';
      IF (UPPER(prCONSIDERAZERO) = 'TRUE') THEN
        wSQL = wSQL||wSQLAux||' as BDDCTO';
      ELSE
        wSQL = wSQL||'lpad('||wSQLAux||', 15, ''0'') as BDDCTO';

      wSQL = wSQL||' from VSUC_EMPRESAS_TLAN';
      wSQL = wSQL||' where (BDCONTABILIZACAO +0 in (0,1))';
      wSQL = wSQL||'   and (BDDATA between '''||:prDATAINI||''' and '''||:prDATAFIM||''')';

      IF ((wTERCEIRO IS NULL) OR (wTERCEIRO = 0)) THEN --Se N?O est? fazendo o la?o numa conta de participante
        wSQL = wSQL||'   and (((BDCODEMP in ('||:prCODEMP||')) and (BDTIPOLANCFILIAL in (0,1)) and (BDDEBITO = '||:wConta||') and ((Upper(BDCONCD) = ''FALSE'') or (BDCONCD is null))) or';
      ELSE                                             --Se est? fazendo o la?o numa conta de participante
        wSQL = wSQL||'   and (((BDCODEMP in ('||:prCODEMP||')) and (BDTIPOLANCFILIAL in (0,1)) and (BDDEBITO = '||:wConta||') and (BDCODTERCEIROD = '||:wTERCEIRO||') and ((Upper(BDCONCD) = ''FALSE'') or (BDCONCD is null))) or';

      IF ((wTERCEIRO IS NULL) OR (wTERCEIRO = 0)) THEN --Se N?O est? fazendo o la?o numa conta de participante
        wSQL = wSQL||'        ((BDCODEMP in ('||:prCODEMP||')) and (BDTIPOLANCFILIAL in (0,2)) and (BDCREDITO = '||:wConta||') and ((Upper(BDCONCC) = ''FALSE'') or (BDCONCC is null))))';
      ELSE                                             --Se est? fazendo o la?o numa conta de participante
        wSQL = wSQL||'        ((BDCODEMP in ('||:prCODEMP||')) and (BDTIPOLANCFILIAL in (0,2)) and (BDCREDITO = '||:wConta||') and (BDCODTERCEIROC = '||:wTERCEIRO||') and ((Upper(BDCONCC) = ''FALSE'') or (BDCONCC is null))))';

      /*************************************************************************************************************************************************
      /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de concilia??o, alterar tamb?m no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
      /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
      /************************************************************************************************************************************************/

      --Preciso de um registro vazio no final para poder comitar o ?ltimo registro oficial, sen?o
      --precisaria fazer toda a valida??o do valor e os updates replicados no final da procedure
      wSQL = wSQL||' union all';
      wSQL = wSQL||' select first 1 null as BDCODEMP, null as BDCHAVE, null as BDDEBITO, null as BDCODTERCEIROD, null as BDCREDITO,';
      wSQL = wSQL||' null as BDCODTERCEIROC, null as BDVALOR, null as BDTIPOLANCFILIAL, null as BDDATA, null as BDDCTO';
      wSQL = wSQL||' from VSUC_EMPRESAS_TLAN ) order by case when BDCODEMP is null then 1 else 0 end';

      IF (UPPER(prComparaNrDoc) = 'TRUE') THEN --Se marcou para comparar por n?mero de documento
        wSQL = wSQL||', BDDCTO, BDDATA';
      ELSE                                     --Se n?o marcou para comparar por n?mero de documento
        wSQL = wSQL||', BDDATA, BDVALOR';

      FOR EXECUTE STATEMENT wSQL INTO :wCODEMP, :wCHAVE, :wDEBITO, :wTERCEIRODEB, :wCREDITO, wTERCEIROCRE, :wVALOR, :wTIPOLANCFILIAL, :wDATA, :wDCTO DO
        BEGIN
          IF ((wConta <> COALESCE(wContaANT, 0)) OR ((wCONTA <> wDEBITO) AND (wCONTA <> wCREDITO)) OR                                --Se o la?o passou para a pr?xima conta
              ((COALESCE(wTerceiro, 0) <> COALESCE(wTerceiroANT, 0)) OR ((wTERCEIRO IS NOT NULL) AND                                 --Se o la?o trocou de participante
               (((wCONTA = wDEBITO) AND (wTERCEIRO <> wTERCEIRODEB)) OR ((wCONTA = wCREDITO) AND (wTERCEIRO <> wTERCEIROCRE))) )) OR --Se passou para o pr?ximo participante
              ((UPPER(prValorExato) = 'TRUE') AND (wVALORDEB > 0) AND (wVALORCRE > 0)) OR                                            --Se marcou para validar o valor exato
              ((UPPER(prComparaData) = 'TRUE') AND (wDATA <> wDATAANT)) OR                                                           --Se marcou para validar data
              ((UPPER(prComparaNrDoc) = 'TRUE') AND (COALESCE(wDCTO, '') <> COALESCE(wDCTOANT, ''))) ) THEN                          --Se marcou para validar documento
            BEGIN
              IF ((wVALORDEB = wVALORCRE) AND (wVALORDEB > 0)) THEN
                BEGIN
                  FOR SELECT BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL FROM LISTA_LANC INTO :BDCODEMP, :BDCHAVE, :BDTIPOLANCFILIAL DO
                    BEGIN
                      --Atualiza o lan?amento como conciliado no caso do d?bito
                      wSQL = 'update VSUC_EMPRESAS_TLAN set BDCONCD = '''||'TRUE'||''', ';
                      --#alt:13456 - adicionado indice para o tipo de concilia??o. Ana - 28/10/2016
                      wSQL = wSQL||' bdtipoconc = case';
                      wSQL = wSQL||'   when ((bdconcc is null) or ((SUBSTRING(upper(bdconcc) from 1 for 1)= '''||'F'||''')))then 4 ';
                      wSQL = wSQL||'   when (bdtipoconc = 8)  or (bdtipoconc = 5) then 6 ';
                      wSQL = wSQL||'   when (bdtipoconc = 2)  or (bdtipoconc = 3) then 7';
                      wSQL = wSQL||'   else bdtipoconc ';
                      wSQL = wSQL||' end ';
                      --#alt:13456. fim
                      wSQL = wSQL||' where (BDCHAVE = '||:BDCHAVE||') and (BDCODEMP = '||:BDCODEMP||')';  --#alt:13456 - adicionado indice Conciliado automaticamente d?bito e cr?dito. Ana - 28/10/2016
                      wSQL = wSQL||' and (BDTIPOLANCFILIAL = '||:BDTIPOLANCFILIAL||') and (BDDEBITO = '||:wConta||') and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null))';
                      IF ((wTERCEIRO IS NOT NULL) AND (wTERCEIRO > 0)) THEN
                        wSQL = wSQL||' and (BDCODTERCEIROD = '||:wTERCEIRO||');';
                      EXECUTE STATEMENT wSQL;

                      /*************************************************************************************************************************************************
                      /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de concilia??o, alterar tamb?m no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
                      /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
                      /************************************************************************************************************************************************/

                      --Atualiza o lan?amento como conciliado no caso do cr?dito
                      wSQL = 'update VSUC_EMPRESAS_TLAN set BDCONCC = '''||'TRUE'||''', ';
                      --#alt:13456 - adicionado indice para o tipo de concilia??o. Ana - 28/10/2016
                      wSQL = wSQL||' bdtipoconc = case';
                      wSQL = wSQL||'   when ((bdconcd is null) or ((SUBSTRING(upper(bdconcd) from 1 for 1)= '''||'F'||''')))then 5 ';
                      wSQL = wSQL||'   when (bdtipoconc = 7)  or (bdtipoconc = 4) then 6 ';
                      wSQL = wSQL||'   when (bdtipoconc = 1)  or (bdtipoconc = 3) then 8 ';
                      wSQL = wSQL||'   else bdtipoconc ';
                      wSQL = wSQL||' end ';
                      --#alt:13456. fim
                      wSQL = wSQL||' where (BDCHAVE = '||:BDCHAVE||') and (BDCODEMP = '||:BDCODEMP||')';  --#alt:13456 - adicionado indice Conciliado automaticamente d?bito e cr?dito. Ana - 28/10/2016
                      wSQL = wSQL||' and (BDTIPOLANCFILIAL = '||:BDTIPOLANCFILIAL||') and (BDCREDITO = '||:wConta||') and ((Upper(BDCONCC) = '''||'FALSE'||''') or (BDCONCC is null))';
                      IF ((wTERCEIRO IS NOT NULL) AND (wTERCEIRO > 0)) THEN
                        wSQL = wSQL||' and (BDCODTERCEIROC = '||:wTERCEIRO||');';
                      EXECUTE STATEMENT wSQL;

                      --Retorna o lan?amento na Stored Procedure que posteriormente ser? inserido na tabela 
                      --LISTA_LANC e utilizado para filtrar o lan?amentos que ser?o exibidos na tela de
                      --consulta de lan?amentos como os lan?amentos que foram conciliados por este processo
                      SUSPEND;
                    END
                END

              wVALORDEB = 0;
              wVALORCRE = 0;
              DELETE FROM LISTA_LANC WHERE BDCODEMP IS NOT NULL;
            END

          /*************************************************************************************************************************************************
          /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de concilia??o, alterar tamb?m no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
          /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
          /************************************************************************************************************************************************/

          --Insere na tabela tempor?ria para poder armazenar todas as chaves do "grupo" atual (pode ser um 
          --grupo pelo documento, data, valor, depende da op??o selecioanda). Posteriormente, quando tiver
          --passado por todos os lan?amentos deste grupo, verifica se o valor do d?bito e cr?dito fecharam,
          --caso positivo, marca todos os lan?amentos encontrados nesta lista como conciliados e retorna eles 
          --na Stored Procedure para que a rotina utilize para mostrar quais lan?amentos foram conciliados.
          IF (wCODEMP IS NOT NULL) THEN
            INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wCODEMP, :wCHAVE, :wTIPOLANCFILIAL);

          IF ((wCONTA <> wCONTAANT) OR (COALESCE(wTERCEIRO, 0) <> COALESCE(wTERCEIROANT, 0))) THEN
            BEGIN
              wVALORDEB = 0;
              wVALORCRE = 0;
            END

          IF (wCONTA = wDEBITO) THEN
            wVALORDEB = wVALORDEB + wVALOR;
          IF (wCONTA = wCREDITO) THEN
            wVALORCRE = wVALORCRE + wVALOR;

          wDCTOANT = wDCTO;
          wDATAANT = wDATA;
          wCONTAANT = wCONTA;
          wTERCEIROANT = wTERCEIRO;
        END
    END

  DELETE FROM LISTA_LANC WHERE BDCODEMP IS NOT NULL;
END
^

/* Alter (VSUC_SP_CONCILIACAO_AUTOMATICA) */
ALTER PROCEDURE VSUC_SP_CONCILIACAO_AUTOMATICA(PRCODEMP INTEGER,
PRCODCTA INTEGER,
PRCODCLIFOR INTEGER,
PRCODPLAPADRAO INTEGER,
PRDOCTO VARCHAR(15),
PRCONTABILIZACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDCODPLAPADRAO INTEGER,
BDDEBITO INTEGER,
BDCODTERCEIROD INTEGER,
BDCONCD VARCHAR(5),
BDCREDITO INTEGER,
BDCODTERCEIROC INTEGER,
BDCONCC VARCHAR(5),
BDVALOR NUMERIC(15,2),
BDLOTE VARCHAR(10),
BDCOMPL VARCHAR(200),
BDDCTO VARCHAR(15))
 AS
DECLARE VARIABLE WSQL VARCHAR(2000);
DECLARE VARIABLE WSQLAUX VARCHAR(2000);
DECLARE VARIABLE WVALORD NUMERIC(15,2);
DECLARE VARIABLE WVALORC NUMERIC(15,2);
DECLARE VARIABLE WCONCC VARCHAR(5);
DECLARE VARIABLE WCONCD VARCHAR(5);
BEGIN
  bdcodemp       = prcodemp;
  bdcodplapadrao = prcodplapadrao;
  wvalord = 0;
  wvalorc = 0;

  --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar n?meros/caracteres depois dos s?mbolos "/", "\" ou "-". Pedro
  prDOCTO = UPPER(SUBSTRING(prDOCTO FROM 1 FOR
                            CASE WHEN (prDOCTO CONTAINING '/') THEN POSITION('/', prDOCTO) -1
                                 WHEN (prDOCTO CONTAINING '\') THEN POSITION('\', prDOCTO) -1
                                 WHEN (prDOCTO CONTAINING '-') THEN POSITION('-', prDOCTO) -1
                            ELSE CHAR_LENGTH(prDOCTO) END));

  -- Soma os valores a d?bitos
  wsql = '';
  /*Carlos Mello(09/05/2013) - Solicita??o.: 5660.
  Foi utilizado o -0.005 para funcionar corretamente o arredondamento, pois n?o quero que arredonde pra cima e nem pra baixo.
  Ex.: 1.999 ficaria 2.00 -> Mas na realidade quero 1.99, ou seja, 1.999 - 0.005 = 1.994 com o arredondamento fica 1.99
       1.994 ficaria 1.99 -> No arredondademto vai ficar 1.994 - 0.005 = 1.989 com arredondamento fica 1.99*/
  --wsql = wsql||'select Round(SUM(tlan.bdvalor),2) ';
  wsql = wsql||'select cast(SUM(tlan.bdvalor) - 0.005 as numeric(15,2)) ';
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  wsql = wsql||'where ';
  wsql = wsql||'(tlan.bdcodemp in ('||:prcodemp||')) and ';
  wsql = wsql||'(tlan.bdcodplapadrao = '||:prcodplapadrao||') and ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'(tlan.bdcontabilizacao in (0,'||:prcontabilizacao||')) and ';
  wsql = wsql||'(bddebito = '||:prcodcta||') and ';
  wsql = wsql||'((tlan.bdconcd is null) or (UPPER(tlan.bdconcd) = '''||'FALSE'||''')) and ';
  --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar n?meros/caracteres depois dos s?mbolos "/", "\" ou "-". Pedro
  --wsql = wsql||'(UPPER(tlan.bddcto) = UPPER('''||:prdocto||''')) and ';
  wsql = wsql||'(Upper(Substring(bddcto from 1 for';
  wsql = wsql||' case when (bddcto containing '''||'/'||''') then position('''||'/'||''', bddcto) -1';
  wsql = wsql||'      when (bddcto containing '''||'\'||''') then position('''||'\'||''', bddcto) -1';
  wsql = wsql||'      when (bddcto containing '''||'-'||''') then position('''||'-'||''', bddcto) -1';
  wsql = wsql||' else char_length(bddcto) end)) = '''||:prDocto||''') and ';
  IF ((prcodclifor = 0) OR (prcodclifor IS NULL)) THEN
    wsql = wsql||'((tlan.bdcodterceirod = 0) or (tlan.bdcodterceirod is null))';
  ELSE
    wsql = wsql||'(tlan.bdcodterceirod = '||:prcodclifor||')';
  EXECUTE STATEMENT wsql INTO :wvalord;

  -- Soma os valores a cr?ditos
  wsql = '';
  --Carlos Mello(09/05/2013) - Solicita??o.: 5660.
  --wsql = wsql||'select Round(SUM(tlan.bdvalor),2) ';
  wsql = wsql||'select cast(SUM(tlan.bdvalor) - 0.005 as numeric(15,2)) ';
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  wsql = wsql||'where ';
  wsql = wsql||'(tlan.bdcodemp in ('||:prcodemp||')) and ';
  wsql = wsql||'(tlan.bdcodplapadrao = '||:prcodplapadrao||') and ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'(tlan.bdcontabilizacao in (0,'||:prcontabilizacao||')) and ';
  wsql = wsql||'(bdcredito = '||:prcodcta||') and ';
  wsql = wsql||'((tlan.bdconcc is null) or (UPPER(tlan.bdconcc) = '''||'FALSE'||''')) and ';
  --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar n?meros/caracteres depois dos s?mbolos "/", "\" ou "-". Pedro
  --wsql = wsql||'(UPPER(tlan.bddcto) = UPPER('''||:prdocto||''')) and ';
  wsql = wsql||'(Upper(Substring(bddcto from 1 for';
  wsql = wsql||' case when (bddcto containing '''||'/'||''') then position('''||'/'||''', bddcto) -1';
  wsql = wsql||'      when (bddcto containing '''||'\'||''') then position('''||'\'||''', bddcto) -1';
  wsql = wsql||'      when (bddcto containing '''||'-'||''') then position('''||'-'||''', bddcto) -1';
  wsql = wsql||' else char_length(bddcto) end)) = '''||:prDocto||''') and ';
  IF ((prcodclifor = 0) OR (prcodclifor IS NULL) ) THEN
    wsql = wsql||'((tlan.bdcodterceiroc = 0) or (tlan.bdcodterceiroc is null))';
  ELSE
    wsql = wsql||'(tlan.bdcodterceiroc = '||:prcodclifor||')';
  EXECUTE STATEMENT wsql INTO :wvalorc;

  /*************************************************************************************************************************************************
  /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de concilia??o, alterar tamb?m no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
  /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
  /************************************************************************************************************************************************/

  -- Verifica se os valores a debito e a credito s?o iguais para gerar a concilia??o
  IF (((wvalord > 0) OR (wvalorc > 0)) AND
      ((wvalord - wvalorc) = 0)) THEN
    BEGIN
      wsql = '';
      wsql = wsql||'select tlan.bdchave, tlan.bddebito, tlan.bdcodterceirod, Upper(tlan.bdconcd) bdconcd, ';
      --Carlos Mello(09/05/2013) - Solicita??o.: 5660.
      --wsql = wsql||'tlan.bdcredito, tlan.bdcodterceiroc, Upper(tlan.bdconcc) bdconcc, Round(tlan.bdvalor,2), ';
      wsql = wsql||'tlan.bdcredito, tlan.bdcodterceiroc, Upper(tlan.bdconcc) bdconcc,  cast(tlan.bdvalor - 0.005 as numeric(15,2)), ';
      wsql = wsql||'tlan.bdlote, tlan.bdcompl, tlan.bddcto ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tlan.bdcodemp in ('||:prcodemp||')) and ';
      wsql = wsql||'(tlan.bdcodplapadrao = '||:prcodplapadrao||') and ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql = wsql||'(tlan.bdcontabilizacao in (0,'||:prcontabilizacao||')) and ';
      wsql = wsql||'((tlan.bddebito = '||:prcodcta||') or (tlan.bdcredito = '||:prcodcta||')) and ';
      wsql = wsql||'(((tlan.bdconcd is null) or (UPPER(tlan.bdconcd) = '''||'FALSE'||''')) or ';
      wsql = wsql||' ((tlan.bdconcc is null) or (UPPER(tlan.bdconcc) = '''||'FALSE'||'''))) and ';
      --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar n?meros/caracteres depois dos s?mbolos "/", "\" ou "-". Pedro
      --wsql = wsql||'(UPPER(tlan.bddcto) = UPPER('''||:prdocto||''')) and ';
      wsql = wsql||'(Upper(Substring(bddcto from 1 for';
      wsql = wsql||' case when (bddcto containing '''||'/'||''') then position('''||'/'||''', bddcto) -1';
      wsql = wsql||'      when (bddcto containing '''||'\'||''') then position('''||'\'||''', bddcto) -1';
      wsql = wsql||'      when (bddcto containing '''||'-'||''') then position('''||'-'||''', bddcto) -1';
      wsql = wsql||' else char_length(bddcto) end)) = '''||:prDocto||''') and ';
      --#alt:16587 - Adicionado controle para o participante, estava conciliando quando o documento era igual mas os participantes diferentes. Ana - 16/12/2016
      IF ((prcodclifor = 0) OR (prcodclifor IS NULL)) THEN
        wsql = wsql||'(((tlan.bdcodterceirod = 0) or (tlan.bdcodterceirod is null)) or ((tlan.bdcodterceiroc = 0) or (tlan.bdcodterceiroc is null)))';
      ELSE
        wsql = wsql||'((tlan.bdcodterceirod = '||:prcodclifor||') or (tlan.bdcodterceiroc = '||:prcodclifor||'))';
      wsql = wsql||'order by tlan.bdvalor';

      /*************************************************************************************************************************************************
      /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de concilia??o, alterar tamb?m no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
      /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
      /************************************************************************************************************************************************/

      -- Altera e retorna os lan?amentos conciliados
      FOR EXECUTE STATEMENT wsql
          INTO :bdchave,:bddebito,:bdcodterceirod,:bdconcd,:bdcredito,:bdcodterceiroc,:bdconcc,
               :bdvalor,:bdlote,:bdcompl,:bddcto DO
          BEGIN
            IF ((bddebito = prcodcta) AND
                ((bdconcd IS NULL) OR (bdconcd = 'FALSE')) AND
                (((prcodclifor = 0) OR (prcodclifor IS NULL)) OR (prcodclifor = bdcodterceirod))) THEN -- concilia lan?amentos a debito
              BEGIN
                wsqlaux = 'update vsuc_empresas_tlan tlan set tlan.bdconcd = '''||'True'||''', ';
                --#alt:13456 - Adicionada atribui??o ao indice do tipo de concilia??o. Ana - 28/10/2016
                --alt:14942 - 27/01/2016 - Alterado para j? definir aqui o c?digo do tipo de concilia??o, assim, n?o precisa percorrer novamente a tabela como estava na rotina abaixo. Pedro
                wsqlaux = wsqlaux||'bdtipoconc = case when Upper(BDCONCC) = '''||'TRUE'||''' then 6 else 4 end ';
                wsqlaux = wsqlaux||'where (bdcodemp = '||:prcodemp||')';
                wsqlaux = wsqlaux||'  and (bdcodplapadrao = '||:prcodplapadrao||')';
                --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                IF (prcontabilizacao <> 99) THEN
                  wsqlaux = wsqlaux||' and (tlan.bdcontabilizacao in (0,'||:prcontabilizacao||'))';
                wsqlaux = wsqlaux||' and (tlan.bdchave = '||:bdchave||')';
                EXECUTE STATEMENT wsqlaux;
                bdconcd = 'True';
                SUSPEND;
              END
            ELSE
              IF ((bdcredito = prcodcta) AND
                  ((bdconcc IS NULL) OR (bdconcc = 'FALSE')) AND
                  (((prcodclifor = 0) OR (prcodclifor IS NULL)) OR (prcodclifor = bdcodterceiroc))) THEN -- concilia lan?amentos a credito
                BEGIN
                  wsqlaux = 'update vsuc_empresas_tlan set bdconcc = '''||'TRUE'||''', ';
                  --#alt:13456 - Adicionada atribui??o ao indice do tipo de concilia??o. Ana - 28/10/2016
                  --alt:14942 - 27/01/2016 - Alterado para j? definir aqui o c?digo do tipo de concilia??o, assim, n?o precisa percorrer novamente a tabela como estava na rotina abaixo. Pedro
                  wsqlaux = wsqlaux||'bdtipoconc = case when Upper(BDCONCD) = '''||'TRUE'||''' then 6 else 5 end ';
                  wsqlaux = wsqlaux||'where (bdcodemp = '||:prcodemp||')';
                  wsqlaux = wsqlaux||'  and (bdcodplapadrao = '||:prcodplapadrao||')';
                  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                  IF (prcontabilizacao <> 99) THEN
                    wsqlaux = wsqlaux||' and (bdcontabilizacao in (0,'||:prcontabilizacao||'))';
                  wsqlaux = wsqlaux||' and (bdchave = '||:bdchave||')';
                  EXECUTE STATEMENT wsqlaux;
                  bdconcc = 'True';
                  SUSPEND;
                END

             /*************************************************************************************************************************************************
             /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de concilia??o, alterar tamb?m no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
             /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
             /************************************************************************************************************************************************/

             /*alt:14942 - 27/01/2017 - Rotina desnecess?ria, retirada para melhoria de performance. Pedro
             --#alt:13456 - Adicionada verifica??o se os dois valores foram conciliados, tanto debito quanto cr?dito
             FOR SELECT bdconcc, bdconcd FROM vsuc_empresas_tlan
                 WHERE (bdcodemp = :prcodemp)
                 AND   (bdchave = :bdchave)
                 INTO :wConcc, :wConcd DO
                   BEGIN
                     IF ((SUBSTRING(upper(wConcc) from 1 for 1)= 'T') AND (SUBSTRING(upper(wConcd) from 1 for 1) = 'T')) THEN
                        UPDATE vsuc_empresas_tlan SET bdtipoconc = 6 WHERE (bdchave = :bdchave) AND (bdcodemp = :prcodemp);
                     SUSPEND;
                   END
             --#alt:13456. fim*/
          END
    END
END
^

/* Alter (VSUC_SP_COPIA_PREPARACAO_ECF) */
ALTER PROCEDURE VSUC_SP_COPIA_PREPARACAO_ECF(PRCODPLAPADRAOREF_DE INTEGER,
PRCODPLAPADRAO_DE INTEGER,
PRCODPLAPADRAOREF_PARA INTEGER,
PRCODPLAPADRAO_PARA INTEGER,
PRANO_DE INTEGER,
PRANO_PARA INTEGER,
PROPCAOTROCA INTEGER)
 RETURNS(BDCODPLAPADRAOREF INTEGER,
BDCODTPLAREF INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDANO INTEGER,
BDCODGRUPOCTA INTEGER)
 AS
DECLARE VARIABLE WSQL DM_MAXVARCHAR;
BEGIN
  --alt:11500 - Criada procedure para copiar a prepara??o da ECF. Pedro
  IF (:prOpcaoTroca = 1) THEN
    BEGIN
      wSQL = 'delete from PLANOS_TPLA_ECF where BDCODPLAPADRAO = '||prCodplapadrao_PARA||' and BDCODPLAPADRAOREF = '||prCodplapadraoRef_PARA||' and BDANO = '||prAno_PARA;
      EXECUTE STATEMENT wSQL;
    END

  --alt:14677 - 13/06/2016 - Altera??o para copiar a conta corretamente baseada na classifica??o do plano de contas referencial tamb?m, pois com as altera??es de layout, os c?digos n?o s?o mais os mesmos entre os planos diferentes. Pedro
  --alt:12432 - 20/01/2016 - Inclu?do par?metro prAno_PARA para poder copiar a prepara??o para outro ano base. Pedro
  wSQL = 'select '||:prCodPlaPadraoRef_PARA||' as BDCODPLAPADRAOREF, ECF_PARA.BDCODTPLAREF, '||:prCodPlaPadrao_PARA||' as BDCODPLAPADRAO,';
  wSQL = wSQL||'   PARA.BDCODTPLA, '||:prAno_PARA||', ECF.BDCODGRUPOCTA';
  wSQL = wSQL||'  from PLANOS_TPLA_ECF ECF';
  wSQL = wSQL||' left join PLANOS_TPLA_ECF_PADRAO ECF_DE on (ECF.BDCODPLAPADRAOREF = ECF_DE.BDCODPLAPADRAOREF AND ECF.BDCODTPLAREF = ECF_DE.BDCODTPLAREF)';
  wSQL = wSQL||' left join PLANOS_TPLA_ECF_PADRAO ECF_PARA on (ECF_PARA.BDCODPLAPADRAOREF = '||:prCodPlaPadraoRef_PARA||' and ECF_DE.BDCTALON = ECF_PARA.BDCTALON)';
  wSQL = wSQL||' inner join PLANOS_TPLA DE on (DE.BDCODPLAPADRAO = ECF.BDCODPLAPADRAO and DE.BDCODTPLA = ECF.BDCODTPLA)';
  wSQL = wSQL||'  left join PLANOS_TPLA PARA on (PARA.BDCODPLAPADRAO = '||:prCodPlaPadrao_PARA||' and PARA.BDCTALON = DE.BDCTALON)';
  wSQL = wSQL||' where ECF.BDCODPLAPADRAO = '||:prCodPlaPadrao_DE;
  wSQL = wSQL||'   and ECF.BDCODPLAPADRAOREF = '||:prCodPlaPadraoRef_DE;
  wSQL = wSQL||'   and ECF.BDANO = '||:prAno_DE;
  --wSQL = wSQL||'   and ECF_PARA.BDCODPLAPADRAOREF = '||:prCodPlaPadraoRef_PARA; alt:17229 - 30/03/2017 - Retirado daqui e colocado direto no join do "ECF_PARA", pois se filtrar aqui n?o tr?s as contas que n?o possuem conta referencial preparada. Pedro
  wSQL = wSQL||'   and ((extract(year from ECF_PARA.BDDTINIVALIDADE) <= ECF.BDANO) or (ECF_PARA.BDDTINIVALIDADE is null))';
  wSQL = wSQL||'   and ((extract(year from ECF_PARA.BDDTFIMVALIDADE) >= ECF.BDANO) or (ECF_PARA.BDDTFIMVALIDADE is null))';
  --wSQL = wSQL||'   and DE.BDCTALON = PARA.BDCTALON'; alt:17229 - 30/03/2017 - Retirado daqui e colocado direto no join do "PARA", pois se filtrar aqui n?o tr?s as contas que n?o possuem conta referencial preparada. Pedro
  --alt:17229 - 30/03/2017 - Alterada regra, conta t?tulo pode copiar a prepara??o tendo apenas o grupo referencial, mas contas anal?ticas precisam ter grupo e conta referencial preparadas. Pedro
  --alt:11743 - 21/05/2015 - Alterada regra para copiar bastando o grupo estar preparado, ignorando a conta ref. Pedro
  wSQL = wSQL||'   and (ECF.BDCODGRUPOCTA is not null) and ((ECF.BDCODTPLAREF is not null) or (DE.BDTIPCTA = 0))';

  IF (:prOpcaoTroca = 3) THEN
    BEGIN
      wSQL = wSQL||'       and not exists(select * ';
      wSQL = wSQL||'                      from PLANOS_TPLA_ECF ';
      wSQL = wSQL||'                      where BDCODPLAPADRAO = PARA.BDCODPLAPADRAO';
      wSQL = wSQL||'                        and BDCODTPLA = PARA.BDCODTPLA';
      wSQL = wSQL||'                        and BDCODPLAPADRAOREF = '||:prCodPlaPadraoRef_PARA;
      wSQL = wSQL||'                        and BDANO = '||:prAno_PARA;
      wSQL = wSQL||'                        and ((BDCODGRUPOCTA is not null) or (BDCODTPLAREF is not null)))'; --alt:11743 - 21/05/2015 - Colocado "or" aqui, porque estava substituindo a prepara??o de qualquer conta que n?o tivesse o grupo ou conta ref preparada. Pedro
    END

  FOR EXECUTE STATEMENT wSQL INTO :BDCODPLAPADRAOREF, :BDCODTPLAREF, :BDCODPLAPADRAO, :BDCODTPLA, :BDANO, :BDCODGRUPOCTA DO
  BEGIN
    --#alt:18406 - Adicionada verifica??o para quando n?o ? encontrado nenhuma classifica??o semelhante entre os planos de c?pia. Ana - 24/04/2017
    IF (BDCODTPLA IS NOT NULL) THEN
      UPDATE OR INSERT INTO PLANOS_TPLA_ECF (BDCODPLAPADRAOREF, BDCODTPLAREF, BDCODPLAPADRAO,
                                             BDCODTPLA, BDANO, BDCODGRUPOCTA) VALUES
                                            (:BDCODPLAPADRAOREF, :BDCODTPLAREF, :BDCODPLAPADRAO,
                                             :BDCODTPLA, :BDANO, :BDCODGRUPOCTA)
                                            MATCHING (BDCODPLAPADRAOREF, BDCODPLAPADRAO, BDCODTPLA, BDANO);
    --SUSPEND;
  END
END
^

/* Alter (VSUC_SP_EXPORTA_SPED_I300) */
ALTER PROCEDURE VSUC_SP_EXPORTA_SPED_I300(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDDATA DATE,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDDEBITO NUMERIC(15,2),
BDCREDITO NUMERIC(15,2),
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40))
 AS
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WVALOR INTEGER;
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WCODTPCC INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefemp, NULL, NULL);
  -- retorna as empresas selecionadas
  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
     INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
     BEGIN
       -- verifica se existe centro de custo selecionado
       IF ((prcodtpcc = '') OR (prcodtpcc IS NULL))  THEN
         BEGIN
           wsql = 'Select tlan.bddata,tlan.bddebito,tpla.bdnomcta,tpla.bdctalon,Sum(tlan.bdvalor) ';
           wsql = wsql||'from (Select bddata,bddebito,bdvalor from VSUC_EMPRESAS_TLAN ';
           wsql = wsql||'      where ';
           --  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
           IF (prcontabilizacao <> 99) THEN
             wsql = wsql||'    (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
           wsql = wsql||'      (bddebito is not null) and ';
           wsql = wsql||'      (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
           wsql = wsql||'      (bdcodemp in ('||bdcodemp||'))) tlan ';
           wsql = wsql||'left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = '||bdcodplapadrao||') and (tpla.bdcodtpla = tlan.bddebito)) ';
           wsql = wsql||'group by tlan.bddata,tlan.bddebito,tpla.bdnomcta,tpla.bdctalon';
           FOR EXECUTE STATEMENT wsql  INTO wdata, wconta, wnomcta, wctalon , wvalor  DO
             BEGIN
               bddata = wdata;
               bdcodcta = wconta;
               bdctalon = wctalon;
               bdnomcta = wnomcta;
               bddebito = wvalor;
               bdcredito = 0;
               SUSPEND;
             END

           wsql = 'Select tlan.bddata,tlan.bdcredito,tpla.bdnomcta,tpla.bdctalon,Sum(tlan.bdvalor) ';
           wsql = wsql||'from (Select bddata,bdcredito,bdvalor from VSUC_EMPRESAS_TLAN ';
           wsql = wsql||'      where ';
           --  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
           IF (prcontabilizacao <> 99) THEN
             wsql = wsql||'    (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
           wsql = wsql||'      (bdcredito is not null) and ';
           wsql = wsql||'      (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
           wsql = wsql||'      (bdcodemp in ('||bdcodemp||'))) tlan ';
           wsql = wsql||'left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = '||bdcodplapadrao||') and (tpla.bdcodtpla = tlan.bdcredito)) ';
           wsql = wsql||'group by tlan.bddata,tlan.bdcredito,tpla.bdnomcta,tpla.bdctalon';
           FOR EXECUTE STATEMENT wsql  INTO wdata, wconta, wnomcta, wctalon , wvalor  DO
             BEGIN
               bddata = wdata;
               bdcodcta = wconta;
               bdctalon = wctalon;
               bdnomcta = wnomcta;
               bdcredito = wvalor;
               bddebito = 0;
               SUSPEND;
             END
         END
       ELSE
         BEGIN
           wsql = 'Select tlan.bddata,tlan.bddebito,tpla.bdnomcta,tpla.bdctalon,tlan.bdcodtpcc,Sum(tlan.bdvalor) as bdvalor ';
           wsql = wsql||'from (Select tlan.bddata,tlan.bddebito,tlcc.bdcodtpcc,(case when (tlcc.bdcodtpcc > 0) then tlcc.bdvalor else tlan.bdvalor end) as bdVALOR ';
           wsql = wsql||'      from (Select bdcodemp,bdchave,bddata,bddebito,bdvalor from VSUC_EMPRESAS_TLAN ';
           wsql = wsql||'            where ';
           --  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
           IF (prcontabilizacao <> 99) THEN
             wsql = wsql||'          (bdCONTABILIZACAO in (0,'||prcontabilizacao||')) and ';
           wsql = wsql||'            (bddebito is not null) and ';
           wsql = wsql||'            (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
           wsql = wsql||'            (bdcodemp in ('||bdcodemp||'))) tlan ';
           wsql = wsql||'      left outer join VSUC_EMPRESAS_TLCC tlcc on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bddebcre = 0)) tlan ';
           wsql = wsql||'left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = '||bdcodplapadrao||') and (tpla.bdcodtpla = tlan.bddebito)) ';
           wsql = wsql||'group by tlan.bddata,tlan.bddebito,tpla.bdnomcta,tpla.bdctalon,tlan.bdcodtpcc';
           FOR EXECUTE STATEMENT wsql  INTO wdata,wconta,wnomcta,wctalon,wcodtpcc,wvalor  DO
             BEGIN
               bddata    = wdata;
               bdcodcta  = wconta;
               bdctalon  = wctalon;
               bdnomcta  = wnomcta;
               bdcodtpcc = wcodtpcc;
               bddebito  = wvalor;
               bdcredito = 0;
               SUSPEND;
             END

           wsql = 'Select tlan.bddata,tlan.bdcredito,tpla.bdnomcta,tpla.bdctalon,tlan.bdcodtpcc,Sum(tlan.bdvalor) as bdvalor ';
           wsql = wsql||'from (Select tlan.bddata,tlan.bdcredito,tlcc.bdcodtpcc,(case when (tlcc.bdcodtpcc > 0) then tlcc.bdvalor else tlan.bdvalor end) as bdVALOR ';
           wsql = wsql||'      from (Select bdcodemp,bdchave,bddata,bdcredito,bdvalor from VSUC_EMPRESAS_TLAN ';
           wsql = wsql||'            where ';
           --  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
           IF (prcontabilizacao <> 99) THEN
             wsql = wsql||'          (bdCONTABILIZACAO in (0,'||prcontabilizacao||')) and ';
           wsql = wsql||'            (bdcredito is not null) and ';
           wsql = wsql||'            (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
           wsql = wsql||'            (bdcodemp in ('||bdcodemp||'))) tlan ';
           wsql = wsql||'      left outer join VSUC_EMPRESAS_TLCC tlcc on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bddebcre = 1)) tlan ';
           wsql = wsql||'left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = '||bdcodplapadrao||') and (tpla.bdcodtpla = tlan.bdcredito)) ';
           wsql = wsql||'group by tlan.bddata,tlan.bdcredito,tpla.bdnomcta,tpla.bdctalon,tlan.bdcodtpcc';
           FOR EXECUTE STATEMENT wsql  INTO wdata,wconta,wnomcta,wctalon,wcodtpcc,wvalor  DO
             BEGIN
               bddata    = wdata;
               bdcodcta  = wconta;
               bdctalon  = wctalon;
               bdnomcta  = wnomcta;
               bdcodtpcc = wcodtpcc;
               bddebito  = 0;
               bdcredito = wvalor;
               SUSPEND;
             END
         END
     END
END
^

/* Alter (VSUC_SP_IMPORTAFORMULA) */
ALTER PROCEDURE VSUC_SP_IMPORTAFORMULA(PRCODPLAPADRAO INTEGER,
PRCODFOR INTEGER,
PRNIVELINI INTEGER,
PRNIVELFIM INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40))
 AS
DECLARE VARIABLE WCONTADOR INTEGER;
DECLARE VARIABLE WNIVEL INTEGER;
DECLARE VARIABLE WAPEFOR VARCHAR(20);
DECLARE VARIABLE WNOMFOR VARCHAR(100);
DECLARE VARIABLE WTIPFOR INTEGER;
DECLARE VARIABLE WCLAFOR VARCHAR(40);
DECLARE VARIABLE WCODPFOR VARCHAR(10);
DECLARE VARIABLE WCTALONFIM VARCHAR(40);
DECLARE VARIABLE WTIPOPROXCTA INTEGER;
DECLARE VARIABLE WCADAUTOMATICO VARCHAR(5);
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WGRUPOFOR INTEGER;
BEGIN

  DELETE FROM vsuc_base_tformula_tpfo TFORMULAS WHERE TFORMULAS.bdcodpfor = :prcodfor;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:prctalonfim)) = :prctalonfim
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wctalonfim;

  SELECT TFor.bdcadautomatico FROM VSUC_BASE_TFORMULA TFor WHERE TFor.bdcodpfor = :PRCODFOR INTO :WCADAUTOMATICO;

  FOR SELECT planos_tpla.bdcodtpla, planos_tpla.bdcodtpla, planos_tpla.bdctalon,
             planos_tpla.bdtipcta, planos_tpla.bdnomcta, planos_tpla.bdapecta, planos_tpla.bdgrupocta
      FROM planos_tpla
      WHERE (planos_tpla.bdcodplapadrao = :prcodplapadrao)
      AND (planos_tpla.bdctalon BETWEEN :prctalonini AND :wctalonfim)
      ORDER BY planos_tpla.bdctalon ASC
      INTO :WCODPFOR, :WCODTPLA, :WCLAFOR, :WTIPFOR, :WNOMFOR, :WAPEFOR, :WGRUPOCTA DO
      BEGIN

          wNivel = 0;
          wcontador = 0;

          IF (WGRUPOCTA IN (0,4,5)) THEN
            wGRUPOFOR = 0;
          ELSE
            wGRUPOFOR = 1;

          WHILE (wcontador < strlen(wClafor)) DO
            BEGIN
             IF (SUBSTRING(wClafor FROM wcontador +1 FOR 1) = '.') THEN
                wNivel = wNivel + 1;

             wContador = wContador +1;
            END


          IF ((wNivel >= prnivelini) AND (wNivel <= prnivelfim)) THEN
             BEGIN
               IF (wnivel = prnivelfim) THEN
                 BEGIN
                   INSERT INTO vsuc_base_tformula_tpfo (BDCODPFOR, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDGRUPOFOR)
                                                VALUES(:prcodfor, :wclafor, '1', :wnomfor, :wapefor, 'Conta('||:wcodpfor||')', :wgrupofor);

                 END
               ELSE
                 BEGIN
                   IF (wtipfor = 1) THEN
                      INSERT INTO vsuc_base_tformula_tpfo (BDCODPFOR, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDGRUPOFOR)
                                                 VALUES(:prcodfor, :wclafor, :wtipfor, :wnomfor, :wapefor, 'Conta('||:wcodpfor||')', :wgrupofor);
                   ELSE
                     BEGIN
                        /* Verifica se o plano de formulas que receber? as contas possi cadastro autom?tico */
                        IF (:WCADAUTOMATICO = 'TRUE') THEN
                        BEGIN
                          /* Verifica se a conta ? t?tulo de ultimo n?vel, ou seja, conta t?tulo acima de uma anal?tica */
                          SELECT FIRST 1 TPla.bdtipcta FROM Planos_TPla TPla WHERE TPla.bdctalon LIKE :WCLAFOR||'.%' ORDER BY TPla.bdctalon INTO :WTIPOPROXCTA;
                          IF (WTIPOPROXCTA = 1) THEN
                          BEGIN
                             INSERT INTO vsuc_base_tformula_tpfo (BDCODPFOR, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDCODPLAPADRAO, BDCODTPLA, BDGRUPOFOR)
                                                   VALUES(:prcodfor, :wclafor, :wtipfor, :wnomfor, :wapefor, '', :prcodplapadrao, :wcodtpla, :wgrupofor);
                          END
                          ELSE
                          BEGIN
                            INSERT INTO vsuc_base_tformula_tpfo (BDCODPFOR, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDGRUPOFOR)
                                                     VALUES(:prcodfor, :wclafor, :wtipfor, :wnomfor, :wapefor, '', :wgrupofor);
                          END
                        END
                        ELSE
                        BEGIN
                          INSERT INTO vsuc_base_tformula_tpfo (BDCODPFOR, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDGRUPOFOR)
                                                     VALUES(:prcodfor, :wclafor, :wtipfor, :wnomfor, :wapefor, '', :wgrupofor);
                        END
                     END
                  END
             END

      END


/*
   BDCODPFOR       INTEGER NOT NULL,
    BDCODFOR        INTEGER NOT NULL,
    BDCLAFOR        VARCHAR(20) NOT NULL COLLATE WIN_PTBR,
    BDTIPFOR        INTEGER,
    BDNEGFOR        VARCHAR(5),
    BDSUBLFOR       VARCHAR(5),
    BDNOMFOR        VARCHAR(40) NOT NULL COLLATE WIN_PTBR,
    BDLINSEMVALFOR  VARCHAR(5),
    BDAPEFOR        VARCHAR(20),
    BDDESCFOR       BLOB SUB_TYPE 0 SEGMENT SIZE 80
);


/*  suspend; usar para jogar para parametros de saida*/
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_TENC_EXERCICIO for: VSUC_SP_INSERT_LANC */
ALTER PROCEDURE VSUC_SP_TENC_EXERCICIO(PRCODEMP INTEGER,
PRCONTA VARCHAR(1024),
PRCTACONTRAPARTIDA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRDATALANC DATE,
PRLOTE VARCHAR(10),
PRCOMPLEMENTO VARCHAR(100),
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRCHAVEZERA INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODHIST INTEGER,
PRREFEMP INTEGER,
PRLANCCONTRAPART INTEGER)
 RETURNS(PRCHAVEZERAMENTO INTEGER,
PRZEROUCONTAS INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_INSERT_LANC) */
ALTER PROCEDURE VSUC_SP_INSERT_LANC(PRCHAVE INTEGER,
PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDEBITO INTEGER,
PRCREDITO INTEGER,
PRCODHIST INTEGER,
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRLOTE VARCHAR(10),
PRDATA DATE,
PRVALOR NUMERIC(15,2),
PRCOMPL VARCHAR(100),
PRDATALAN DATE,
PRHORALAN TIME,
PRTIPOLAN SMALLINT,
PRDCTO VARCHAR(5),
PRCONCD VARCHAR(5),
PRCONCC VARCHAR(5),
PRCHAVEZER INTEGER,
PRREFEMP INTEGER)
 AS
BEGIN

  /* a chave ? gravada automaticamente no before insert*/
  INSERT INTO vsuc_empresas_tlan
  (BDCHAVE, BDCODEMP, BDCODPLAPADRAO, BDDEBITO, BDCREDITO, BDCODHIST,
   BDCODTPHI, bdcodusu, BDLOTE, BDDATA, BDVALOR, BDCOMPL, BDDATALAN,
   BDHORALAN, BDTIPOLAN, BDDCTO, BDCONCD, BDCONCC, BDCHAVEZER)
  VALUES
  (:prchave, :prcodemp, :prcodplapadrao, :prdebito, :prcredito, :prcodhist,
   :prcodtphi, :prusuario, :prlote, :prdata, :prvalor, :prcompl, :prdatalan,
   :prhoralan, :prtipolan, :prdcto, :prconcd, :prconcc, :prchavezer);

  SUSPEND;

END
^

/* Alter (VSUC_SP_LISTA_CTA_RAZAO_VIDEO) */
ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO(PRCODEMP VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRDATINI DATE,
PRDATFIM DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRTIPORAZAO INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDNOMCTA VARCHAR(100),
BDCTALON VARCHAR(40),
BDCODPARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(3000);
DECLARE VARIABLE wsql2 VARCHAR(3000);
DECLARE VARIABLE wsqlemp VARCHAR(3000);
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wsaldo_deb NUMERIC(15,2);
DECLARE VARIABLE wsaldo_cre NUMERIC(15,2);
DECLARE VARIABLE wnomcta VARCHAR(100);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wsomavlr NUMERIC(15,2);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wparticipante INTEGER;
DECLARE VARIABLE wcodempaux INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wcodcta INTEGER;
DECLARE VARIABLE wtipocta INTEGER;
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wsomavlraux NUMERIC(15,2);
DECLARE VARIABLE wempprinc INTEGER;
BEGIN
  -- Foi aleterado a rotina para melhorar o desempenho
  /*wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao ';
  wsql = wsql||'from planos_tpla tpla ';
  wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao) ';
  wsql = wsql||'where ';
  wsql = wsql||'tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and ((tpla.bdcodtpla = tlan.bddebito) or (tpla.bdcodtpla = tlan.bdcredito)) ';
  wsql = wsql||'and (tlan.bddata between '''||prdatini||''' and '''||prdatfim||''') ';
  wsql = wsql||'and tpla.bdcodtpla in (select tcta.bdcodtpla from planos_tpla tcta ';
  wsql = wsql||'                       where (tcta.bdcodplapadrao = tlan.bdcodplapadrao) and ';
  wsql = wsql||'                       (tcta.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''') ';
  if (prTipoRazao = 1) then
    begin
      wsql = wsql||' and ((((bdconcd = ''TRUE'') and (not bddebito is null)) and (tpla.bdcodtpla = tlan.bddebito)) ';
      wsql = wsql||' or (((BDCONCC = ''TRUE'') and (not bdcredito is null))) and (tpla.bdcodtpla = tlan.bdcredito)) ';
    end
  else
    if (prTipoRazao = 2) then
      begin
        wsql = wsql||' and ((((bdconcd is null) and (not bddebito is null)) and (tpla.bdcodtpla = tlan.bddebito)) ';
        wsql = wsql||' or (((BDCONCC is null) and (not bdcredito is null))) and (tpla.bdcodtpla = tlan.bdcredito)) ';
      end
  wsql = wsql||'                       order by tcta.bdctalon)';*/
  wdatini = SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 1 FOR 4);

  IF (prctalonini = prctalonfim) THEN
    BEGIN
      wsql = '';
      wsql = 'select tpla.bdcodtpla, tpla.bdnomcta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao from planos_tpla tpla ';
      --#alt:5619 - gilberto - 13/08/2013 ______________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta > 0)) THEN
         wsql = wsql||' inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      ---------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||' where (tpla.bdcodplapadrao = '||prcodplapadrao||') and (tpla.bdctalon between '''||prctalonini||''' and  '''||prctalonfim||''' )';
      FOR EXECUTE STATEMENT wsql INTO :bdcodtpla,:bdnomcta,:bdctalon,:wparticipante,:wcodplapadrao DO
      BEGIN
        -- retorna as empresas selecionadas
        wsqlemp = 'select temp.bdcodemp from tempresas temp ';
        wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
        wsqlemp = wsqlemp||'order by temp.bdcodemp';
        -- executa o sql das empresas
        FOR EXECUTE STATEMENT wsqlemp INTO :wcodemp DO
        BEGIN
          wsomavlr = 0;
          wsql2    = '';
          --#alt:5837
          /*wsql2    = 'Select Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' (bdcodemp = '||wcodemp||') and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' ((bddebito = '||bdcodtpla||') or (bdcredito = '||bdcodtpla||'))';
          if (prTipoRazao = 1) then
            begin
              wsql2 = wsql2||' and ((((Upper(bdconcd) = ''TRUE'') and (not bddebito is null)) and (bddebito = '||bdcodtpla||')) ';
              wsql2 = wsql2||' or   (((Upper(bdconcc)  = ''TRUE'') and (not bdcredito is null)) and (bdcredito = '||bdcodtpla||'))) ';
            end
          else
            if (prTipoRazao = 2) then
              begin
                wsql2 = wsql2||' and (((((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) and (not bddebito is null)) and (bddebito = '||bdcodtpla||')) ';
                wsql2 = wsql2||' or   ((((Upper(bdconcc) = ''FALSE'') or (bdconcc is null)) and (not bdcredito is null)) and (bdcredito = '||bdcodtpla||'))) ';
              end */
          --D?bito
          wsql2    = 'Select bdcodemp,bdfilial,bdtipolancfilial,bddebito, 1 as bdtipcta, Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' ((bdcodemp = '||wcodemp||') or (bdfilial = '||wcodemp||')) and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' (bddebito = '||bdcodtpla||') ';
          --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
          IF (prcontabilizacao <> 99) THEN
            wsql2    = wsql2||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';
          IF (prTipoRazao = 1) THEN
            wsql2 = wsql2||' and (Upper(bdconcd) = ''TRUE'') ';
          ELSE
          IF (prTipoRazao = 2) THEN
            wsql2 = wsql2||' and ((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) ';
          wsql2 = wsql2||'Group By bdcodemp,bdfilial,bdtipolancfilial,bddebito ';

          wsql2 = wsql2||'union all ';
          --Cr?dito
          wsql2    = wsql2||'Select bdcodemp,bdfilial,bdtipolancfilial,bdcredito, 2 as bdtipcta, Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' ((bdcodemp = '||wcodemp||') or (bdfilial = '||wcodemp||')) and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' (bdcredito = '||bdcodtpla||') ';
          --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
          IF (prcontabilizacao <> 99) THEN
            wsql2    = wsql2||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';
          IF (prTipoRazao = 1) THEN
            wsql2 = wsql2||' and (Upper(bdconcc) = ''TRUE'') ';
          ELSE
          IF (prTipoRazao = 2) THEN
            wsql2 = wsql2||' and ((Upper(bdconcc) = ''FALSE'') or (bdconcd is null)) ';
          wsql2 = wsql2||'Group By bdcodemp,bdfilial,bdtipolancfilial,bdcredito ';
          --#alt:5837
          --execute statement wsql2 into :wsomavlr;
          FOR EXECUTE STATEMENT wsql2 INTO :wcodempaux,:wfilial,:wtipolancfilial,:wcodcta,:wtipocta,:wsomavlraux DO
            BEGIN
              SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipocta,:wcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
              IF (wpermite = 1) THEN
                wsomavlr = wsomavlr + wsomavlraux;
            END

          IF (wsomavlr > 0) THEN
            BEGIN
              -- Detalhado por participante
              IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN--#alt:6309
                BEGIN
                  FOR SELECT tctapar.bdnome, tctapar.bdclassificacao, tctapar.bdcodparticipante, tctapar.bdsaldo_deb, tctapar.bdsaldo_cre
                  --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,0,0,0, -- alt:#6647 - gilberto - 12/09/2013
                  FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,0,0,0,0,
                                                       :prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tctapar
                  INTO :wnomcta, :bdctalon, :bdcodparticipante,:wsaldo_deb,:wsaldo_cre  DO
                    BEGIN
                      IF ((wsaldo_deb <> 0) OR (wsaldo_cre <> 0))  THEN
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:bdcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 003 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              bdnomcta = bdcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                            END
                          SUSPEND;
                        END
                    END
                END
--              else
                SUSPEND;
            END
        END
      END
    END
  ELSE
    BEGIN
      wcodempaux = 0;
      wcodcta    = 0;

      wsql = '';
      --#alt:5837
      /*wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'(tlan.bdcodemp in ('||prcodemp||')) and ';
      wsql = wsql||'((tpla.bdcodtpla = tlan.bddebito) or (tpla.bdcodtpla = tlan.bdcredito)) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';*/
/*
      wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) and ';
      wsql = wsql||'(tpla.bdcodtpla = tlan.bddebito) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';
*/
      wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'       tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')) ';
      --#alt:5619 - gilberto - 13/08/2013 _____________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta <> 0)) THEN
         wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      --------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||'where ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';
      wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
         wsql = wsql||' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';
      wsql = wsql||' union all ';
/*
      wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 2 as bdtipolanc ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) and ';
      wsql = wsql||'(tpla.bdcodtpla = tlan.bdcredito) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';
*/
      wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'       tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')) ';
      --#alt:5619 - gilberto - 13/08/2013 _____________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta <> 0)) THEN
         wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      --------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||'where ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';
      wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql = wsql||' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';

      --Retorna a empresa principal
      SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
      IF (wpos = 0) THEN
        wempprinc = prcodemp;
      ELSE
        wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

      FOR EXECUTE STATEMENT wsql
      INTO :bdcodtpla,:bdnomcta,:bdctalon,:wparticipante,:wcodplapadrao,:wcodemp,:wfilial,:wtipolancfilial,:wtipocta DO
      BEGIN
        IF ((wcodemp <> wcodempaux) OR (bdcodtpla <> wcodcta)) THEN
          BEGIN
            -- Detalhado por participante
            IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN
              BEGIN
                FOR SELECT tctapar.bdnome, tctapar.bdclassificacao, tctapar.bdcodparticipante, tctapar.bdsaldo_deb, tctapar.bdsaldo_cre
                    --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla, -- alt:#6647 - gilberto - 12/09/2013
                    FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,
                                                         0,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tctapar
                INTO :wnomcta, :bdctalon, :bdcodparticipante,:wsaldo_deb,:wsaldo_cre  DO
                BEGIN
                  IF ((wsaldo_deb <> 0) OR (wsaldo_cre <> 0))  THEN
                    BEGIN
                      IF (prconcatenacodparticipante = 1) THEN
                        BEGIN
                          wpos     = CHARACTER_LENGTH(:bdcodparticipante);
                                     -- 100 -> m?ximo de caracteres para nome da conta
                                     -- 003 -> qtd de caracteres " - ";
                          wpos     = ((100 - wpos) - 3);
                          bdnomcta = bdcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                        END
                      SUSPEND;
                      wcodempaux = wcodemp;
                      wcodcta    = bdcodtpla;
                    END
                END
              END
            ELSE
              BEGIN
                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipocta,:wempprinc,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  SUSPEND;
                wcodempaux = wcodemp;
                wcodcta    = bdcodtpla;
              END
          END
      END
    END
END
^

/* Alter (VSUC_SP_LISTA_CTA_RAZAO_VIDEO_X) */
ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO_X(PRCODEMP VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRDATINI DATE,
PRDATFIM DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRTIPORAZAO INTEGER,
PRPARTINI INTEGER,
PRPARTFIM INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARCC INTEGER,
PRLCC VARCHAR(1024),
PRLANCAMENTOSEMCC INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDNOMCTA VARCHAR(100),
BDCTALON VARCHAR(40),
BDCODPARTICIPANTE INTEGER,
BDCNPJPART VARCHAR(10))
 AS
DECLARE VARIABLE WSQL VARCHAR(8192);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WCAMPO INTEGER;
DECLARE VARIABLE WPOS_PERNAMATRIZ INTEGER;
DECLARE VARIABLE WPOS_MATRIZ INTEGER;
DECLARE VARIABLE WPOS_FILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WTIPCTA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMETER VARCHAR(100);
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WMULTICTA INTEGER;
DECLARE VARIABLE WCNPJPARTANT VARCHAR(10);
BEGIN
  wsql = 'select first 1 distinct bdcodmatriz ';
  wsql = wsql||'from tempresas ';
  wsql = wsql||'where bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and bdcodmatriz is not null ';
  EXECUTE STATEMENT wsql INTO :wcodmatriz;

  SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wmulticta;

  wsql = '';
  --wsql = wsql||'select distinct tlan.bdcodemp, coalesce(tlan.bdfilial, 0), tlan.bdtipolancfilial, tlan.bdcodtpla, tlan.bdtipcta, ';
  wsql = wsql||'select distinct tlan.bdcodemp, coalesce(tlan.bdfilial, 0), tlan.bdtipolancfilial, tlan.bdcodtpla, ';
  wsql = wsql||'       tpla.bdnomcta, tpla.bdctalon, ';
  --alt:16045 - 24/10/2016 - Se estiver agrupando pelo CNPJ, precisa buscar o c?digo do participante matriz. Pedro
  IF (prAgruparParticipantePorCNPJ = 1) THEN
    wSQL = wSQL||'coalesce(terc.BDCODTER, tlan.BDCODTER), ter.BDNOME, substring(coalesce(terc.BDCGCTER, terAux.BDCGCTER) from 1 for 10) as BDCNPJPART ';
  ELSE IF (prdetalharctaparticipante = 1) THEN
     wsql = wsql||'tlan.BDCODTER, ter.BDNOME, substring(terc.BDCGCTER from 1 for 10) as BDCNPJPART ';
  ELSE
     wsql = wsql||'null as BDCODTER, null as BDNOMETER, null as BDCNPJPART ';
  --alt:16045 - Fim

  wsql = wsql||'from ( ';
  /************************************************** D?bito **************************************************/
  --wsql = wsql||'Select distinct tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bddebito as bdcodtpla, 1 as bdtipcta, ';
  wsql = wsql||'Select distinct tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bddebito as bdcodtpla, ';
  IF (prdetalharctaparticipante = 1) THEN
     wsql = wsql||'       bdcodterceirod as bdcodter ';
  ELSE
     wsql = wsql||'       null as bdcodter ';
  wsql = wsql||'from vsuc_empresas_tlan tlan ';

  --alt:1186 - Feita valida??o para verificar os centros de custos tamb?m conforme as op??es selecionadas. Pedro
  --alt:10547 - Adicionada valida??o dos Centros de Custos. Se ele n?o estiver preenchido, mesmo que venha marcado para utilizar os CC, deve ignorar para n?o causar erro. Pedro
  IF ((PRDETALHARCC = 1) AND (TRIM(prlcc) <> '')) THEN
    BEGIN
      IF (prlancamentosemcc = 0) THEN
        wsql = wsql||'inner join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 0 and tlcc.bdcodtpcc in ('||prlcc||')) ';
      ELSE
        wsql = wsql||'left outer join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 0 and tlcc.bdcodtpcc in ('||prlcc||')) ';
    END
  --alt:1186 - Fim

  IF ((wmulticta IS NOT NULL) AND (wmulticta <> 0)) THEN
     wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tlan.bdcodplapadrao and tsel.bdcodtpla = tlan.bddebito) ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||prcodplapadrao||') ';
  wsql = wsql||'and (tlan.bddebito IS NOT null) ';
  IF (prcontabilizacao <> 99) THEN
     wsql = wsql||'   and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (prTipoRazao = 1) THEN
     wsql = wsql||'  and (Upper(tlan.bdconcd) = '''||'TRUE'||''') ';
  ELSE
  IF (prTipoRazao = 2) THEN
     wsql = wsql||'     and ((Upper(tlan.bdconcd) = '''||'FALSE'||''') or (tlan.bdconcd is null)) ';
  wsql = wsql||'and (tlan.bddata between '''||prdatini||''' and '''||prdatfim||''') ';
  wsql = wsql||'and ((tlan.bdcodemp IN ('||prcodemp||')) ';
  IF ((wcodmatriz = 0) OR (wcodmatriz IS NULL)) THEN
     wsql = wsql||') ';
  ELSE
     wsql = wsql||' or (tlan.bdfilial IN ('||prcodemp||') and tlan.bdcodemp = '||wcodmatriz||')) ';

  wsql = wsql||'union all ';
  /************************************************** Cr?dito **************************************************/
  --wsql = wsql||'Select distinct tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bdcredito as bdcodtpla, 2 as bdtipcta, ';
  wsql = wsql||'Select distinct tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bdcredito as bdcodtpla, ';
  IF (prdetalharctaparticipante = 1) THEN
     wsql = wsql||'       bdcodterceiroc as bdcodter ';
  ELSE
     wsql = wsql||'       null as bdcodter ';
  wsql = wsql||'from vsuc_empresas_tlan tlan ';

  --alt:1186 - Feita valida??o para verificar os centros de custos tamb?m conforme as op??es selecionadas. Pedro
  --alt:10547 - Adicionada valida??o dos Centros de Custos. Se ele n?o estiver preenchido, mesmo que venha marcado para utilizar os CC, deve ignorar para n?o causar erro. Pedro
  IF ((PRDETALHARCC = 1) AND (TRIM(prlcc) <> '')) THEN
    BEGIN
      IF (prlancamentosemcc = 0) THEN
        wsql = wsql||'inner join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 1 and tlcc.bdcodtpcc in ('||prlcc||')) ';
      ELSE
        wsql = wsql||'left outer join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 1 and tlcc.bdcodtpcc in ('||prlcc||')) ';
    END
  --alt:1186 - Fim

  IF ((wmulticta IS NOT NULL) AND (wmulticta <> 0)) THEN
     wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tlan.bdcodplapadrao and tsel.bdcodtpla = tlan.bdcredito) ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||prcodplapadrao||') ';
  wsql = wsql||'and (tlan.bdcredito IS NOT NULL) ';
  IF (prcontabilizacao <> 99) THEN
     wsql = wsql||'   and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (prTipoRazao = 1) THEN
     wsql = wsql||'  and (Upper(tlan.bdconcC) = '''||'TRUE'||''') ';
  ELSE
  IF (prTipoRazao = 2) THEN
     wsql = wsql||'     and ((Upper(tlan.bdconcc) = '''||'FALSE'||''') or (tlan.bdconcc is null)) ';
  wsql = wsql||'and (tlan.bddata between '''||prdatini||''' and '''||prdatfim||''') ';
  wsql = wsql||'and ((tlan.bdcodemp IN ('||prcodemp||')) ';
  IF ((wcodmatriz = 0) OR (wcodmatriz IS NULL)) THEN
     wsql = wsql||') ';
  ELSE
     wsql = wsql||' or (tlan.bdfilial IN ('||prcodemp||') and tlan.bdcodemp = '||wcodmatriz||')) ';
  wsql = wsql||') tlan ';
  wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcodtpla) ';
  IF ((wmulticta IS NOT NULL) AND (wmulticta <> 0)) THEN
     wsql = wsql||') ';
  ELSE
     wsql = wsql||' and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''' )) ';
  --alt:16045 - 24/10/2016 - Quando for para agrupar por CNPJ, faz a busca para retornar sempre o c?digo e CNPJ do participante matriz. Pedro
  IF (prAgruparParticipantePorCNPJ = 1) THEN
    BEGIN
      wSQL = wSQL||'left join TTERCEIRO terAux on (terAux.BDCODTER = tlan.BDCODTER) ';
      wSQL = wSQL||'cross join SP_CONSULTA_TERCEIRO_MATRIZ(null, terAux.BDCGCTER) terc ';
      wSQL = wSQL||'left join VW_TTERCEIRO_SIMPLES ter on (ter.BDCODTER = terc.BDCODTER) ';
      wSQL = wSQL||'where terAux.BDCODTER between '||:prPartIni||' and '||prPartFim||' ';
    END
  --alt:7206 - Alterado para trazer o CNPJ do participante para agrupar conforme novo par?metro. Pedro
  ELSE IF (prDetalharCtaParticipante = 1) THEN
    BEGIN
      --alt:16045 - 24/10/2016 - Alterado para buscar o participante pela View, pois tem um desempenho melhor. Pedro
      --wsql = wsql||'left outer join (select bdcodter, bdnometer from tterceiro_ref order by bdrefemp desc) ter on (ter.bdcodter = tlan.bdcodter) ';
      wSQL = wSQL||'left join VW_TTERCEIRO_SIMPLES ter on (ter.BDCODTER = tlan.BDCODTER) ';
      wsql = wsql||'left outer join TTERCEIRO terc on (terc.BDCODTER = ter.BDCODTER) ';
      wSQL = wSQL||'where ter.BDCODTER between '||:prPartIni||' and '||prPartFim||' ';
      --alt:7206 - Fim
    END
  --alt:7206 - Alterado a ordem, adicionando o CNPJ, pois se os participantes do mesmo CNPJ n?o estiverem em sequ?ncia n?o funciona a rotina abaixo. Pedro
  --wsql = wsql||'order by bdcodtpla, bdcodter ';
  IF (PRAGRUPARPARTICIPANTEPORCNPJ = 0) THEN
    wsql = wsql||'order by tlan.bdcodtpla, tlan.bdcodter ';
  ELSE
    wsql = wsql||'order by bdcodtpla, bdcnpjpart, terc.bdcodter ';

  wcnpjpartant = '';
  FOR EXECUTE STATEMENT wsql
      --alt:7206 - Alterado para trazer o CNPJ do participante para agrupar conforme novo par?metro. Pedro
      --into :wcodemp, :wfilial, :wtipolancfilial, :bdcodtpla, :wtipcta, :bdnomcta, :bdctalon, :bdcodparticipante, :wnometer do
      INTO :wcodemp, :wfilial, :wtipolancfilial, :bdcodtpla, /*:wtipcta,*/ :bdnomcta, :bdctalon, :bdcodparticipante, :wnometer, :BDCNPJPART DO
      BEGIN
        /*wcampo = wtipcta;
        wpos_pernamatriz = position(wcodmatriz, wcodemp);
        wpos_matriz = position(wcodemp,  prcodemp);
        wpos_filial = position(wfilial,  prcodemp);

        if (((wcodmatriz = wcodemp) and (wfilial = 0)) or
            --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
            ((wcodmatriz = wfilial) and (wcampo = wtipolancfilial)) or
            --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
            ((wcodmatriz = wcodemp) and (wfilial <> 0) and (wcampo <> wtipolancfilial) and (wpos_pernamatriz > 0)) or
            --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
            ((prmatrizfilialconsolidado = 1) and (wcodmatriz <> wcodemp) and (wfilial = 0) and (wpos_matriz > 0)) or
            --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
            ((prmatrizfilialconsolidado = 1) and (wcodmatriz = wcodemp) and (wfilial <> 0) and (wcampo = wtipcta) and (wpos_filial > 0))) then*/

           /*select bdpermite from vsuc_sp_permitecalcsaldolancmf(:wtipcta,:wcodmatriz,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
           wpermite = 1;
           IF (wpermite = 1) THEN
           BEGIN*/
             IF ((COALESCE(wcodtpla, 0) <> COALESCE(bdcodtpla, 0)) OR (COALESCE(wcodter, 0) <> COALESCE(bdcodparticipante, 0))) THEN
                BEGIN
                  IF ((prdetalharctaparticipante = 1) AND (bdcodparticipante IS NOT NULL)) THEN
                     BEGIN
                       wctalon = REVERSE(bdctalon);
                       wctalon = SUBSTRING(wctalon FROM POSITION('.', wctalon) FOR CHARACTER_LENGTH(wctalon));
                       bdctalon = REVERSE(wctalon)||LPAD(bdcodparticipante, 8, '0');
                       bdnomcta = SUBSTRING(bdcodparticipante||SUBSTRING(' - '||wnometer FROM 1 FOR (100 - CHARACTER_LENGTH(bdcodparticipante))) FROM 1 FOR 100);
                     END

                  --alt:7206 - Alterado para trazer o CNPJ do participante para agrupar conforme novo par?metro. Pedro
                  IF ((PRAGRUPARPARTICIPANTEPORCNPJ = 0) OR (BDCNPJPART <> wcnpjpartant)) THEN
                    SUSPEND;

                  --alt:7206 - Copia o CNPJ atual para o anterior para poder usar na pr?xima vez que passar pelo suspend. Pedro
                  wcnpjpartant = BDCNPJPART;
                END
           --END
        wcodtpla = bdcodtpla;
        wcodter = bdcodparticipante;
      END
END
^

/* Alter (VSUC_SP_LISTA_TLAN_CONC_CLIFOR) */
ALTER PROCEDURE VSUC_SP_LISTA_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCLIFOR SMALLINT,
PRLANCONC SMALLINT,
PRZEROESQ SMALLINT,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCLASSIFICACAOINI VARCHAR(50);
DECLARE VARIABLE WCLASSIFICACAOFIM VARCHAR(50);
DECLARE VARIABLE WDEBITO INTEGER;
DECLARE VARIABLE WCREDITO INTEGER;
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WSOMALANCS NUMERIC(15,2);
DECLARE VARIABLE WNRONF VARCHAR(200);
DECLARE VARIABLE WCONCILIOU VARCHAR(7);
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WDEBCRE VARCHAR(9);
DECLARE VARIABLE WCAMPOCONC VARCHAR(7);
DECLARE VARIABLE WCAMPOLANCPRINC VARCHAR(7);
DECLARE VARIABLE WVALDEB NUMERIC(15,2);
DECLARE VARIABLE WVALCRE NUMERIC(15,2);
DECLARE VARIABLE WVLRDEBAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRCREAUX INTEGER;
DECLARE VARIABLE WCONTA_PARTICIPANTE INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  conciliacaook = 0;

  -- pega a classifica??o inicial da conta
  SELECT bdctalon FROM planos_tpla WHERE (bdcodplapadrao = :prcodplapadrao) AND (bdcodtpla = :prcontainicial) INTO :wclassificacaoini;

  -- pega a classifica??o final da conta
  SELECT bdctalon FROM planos_tpla WHERE (bdcodplapadrao = :prcodplapadrao) AND (bdcodtpla = :prcontafinal) INTO :wclassificacaofim;

  -- limpa as concilia??es anteriores
  IF (prlanconc = 1) THEN
     BEGIN
       FOR SELECT tlan.bdchave FROM vsuc_empresas_tlan tlan, planos_tpla tpla
           WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
           AND   (tlan.bdcodplapadrao = :prcodplapadrao)
           AND   (tlan.bdcodplapadrao = tpla.bdcodplapadrao)
           AND   ((tlan.bddebito = tpla.bdcodtpla) OR (tlan.bdcredito = tpla.bdcodtpla))
           AND   (tpla.bdctalon BETWEEN :wclassificacaoini AND :wclassificacaofim)
           --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
           AND   (tlan.bdcontabilizacao IN (0,:prcontabilizacao))
           AND   (bdcodemp = :prempresa) INTO :wchave DO
       BEGIN
         UPDATE vsuc_empresas_tlan SET bdconcd = NULL, bdconcc = NULL WHERE (bdchave = :wchave) AND (bdcodemp = :prempresa);
         conciliacaook = conciliacaook + 1;
       END
     
       IF (conciliacaook > 0) THEN
          conciliacaook = 1;
--       suspend;
     END

  -- retorna as contas selecionadas
  FOR SELECT tpla.bdcodtpla, tpla.BDPARTICIPANTE FROM planos_tpla tpla
      WHERE tpla.bdcodplapadrao = :prcodplapadrao
      AND tpla.bdctalon BETWEEN :wclassificacaoini AND :wclassificacaofim
      ORDER BY tpla.bdctalon
      INTO :wconta, :WCONTA_PARTICIPANTE DO
      BEGIN
        -- retorna os numeros dos documentos de acordo com o parametro de ignorar zeros a esquerda
        FOR SELECT DISTINCT (SELECT nronf FROM VSUC_NRO_NOTA_COMPL(tlan.bddcto, :przeroesq)) FROM vsuc_empresas_tlan tlan
            WHERE tlan.bdcodemp = :prempresa
            AND tlan.bdcodplapadrao = :prcodplapadrao
            AND ((tlan.bddebito = :wconta) OR (tlan.bdcredito = :wconta))
            AND ((tlan.bddcto IS NOT NULL) AND (tlan.bddcto <> ''))
            --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
            AND (tlan.bdcontabilizacao IN (0,:prcontabilizacao))
            ORDER BY tlan.bddcto
            INTO :wnronf DO
            BEGIN

              /*for select bdcodter from tterceiro where (BDCODTER in (select distinct BDCODTERCEIROD from vsuc_empresas_tlan
                                                                       where (bddata between :prdatainicial and :prdatafinal)
                                                                             and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                                                                             and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                                                                             and   (bdcodplapadrao = :prcodplapadrao)
                                                                             and   ((bddebito = :wconta) or (bdcredito = :wconta))
                                                                             --#alt:6500 - gilberto - 23/08/2013
                                                                             --and   (bdcodemp = :prempresa)
                                                                             and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                                                                             --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                                                             and (bdcontabilizacao in (0,:prcontabilizacao))
                                                                             --#alt:6773. Carlos Mello(30/09/2013)
                                                                             --and   (bddcto like '%'||:wnronf)
                                                                             and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf))) and
                                                                             (BDCODTERCEIROD is not null or BDCODTERCEIROC is not null) ))
                                                     or
                                                     (BDCODTER in (select distinct BDCODTERCEIROC from vsuc_empresas_tlan
                                                                       where (bddata between :prdatainicial and :prdatafinal)
                                                                             and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                                                                             and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                                                                             and   (bdcodplapadrao = :prcodplapadrao)
                                                                             and   ((bddebito = :wconta) or (bdcredito = :wconta))
                                                                             --#alt:6500 - gilberto - 23/08/2013
                                                                             --and   (bdcodemp = :prempresa)
                                                                             and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                                                                             --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                                                             and (bdcontabilizacao in (0,:prcontabilizacao))
                                                                             --#alt:6773. Carlos Mello(30/09/2013)
                                                                             --and   (bddcto like '%'||:wnronf)
                                                                             and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf))) and
                                                                             (BDCODTERCEIROD is not null or BDCODTERCEIROC is not null) ))
              order by bdcodter into :WCODTER do
                  begin*/

                      -- soma os lan?amentos a debito e a credito

                      -- N?o ? uma conta de Participante. Bruno Borges - 11/11/2013
                      IF (WCONTA_PARTICIPANTE = 0) THEN
                         BEGIN
                           SELECT SUM(COALESCE((CASE WHEN (bddebito = :wconta) THEN bdvalor END), 0)) "bdvaldeb",
                                  SUM(COALESCE((CASE WHEN (bdcredito = :wconta) THEN bdvalor END), 0)) "bdvalcre"
                               FROM vsuc_empresas_tlan
                               WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                               AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                               AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                               AND   (bdcodplapadrao = :prcodplapadrao)
                               AND   ((bddebito = :wconta) OR (bdcredito = :wconta))
                               --#alt:6500 - gilberto - 23/08/2013
                               --and   (bdcodemp = :prempresa)
                               AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                               --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                               AND (bdcontabilizacao IN (0,:prcontabilizacao))
                               --#alt:6773. Carlos Mello(30/09/2013)
                               --and   (bddcto like '%'||:wnronf)
                               AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)))
                               INTO :wvaldeb, :wvalcre;

                               -- verifica se os valores a debito e a credito s?o iguais para gerar a concilia??o
                               IF (((wvaldeb - wvalcre) = 0) AND (wvaldeb > 0) AND (wvalcre > 0)) THEN
                                  BEGIN
                                    -- concilia lan?amentos a debito
                                    UPDATE vsuc_empresas_tlan SET bdconcd = 'TRUE'
                                    WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                    AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                    AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                    AND   (bdcodplapadrao = :prcodplapadrao)
                                    AND   (bddebito = :wconta)
                                    --#alt:6500 - gilberto - 23/08/2013
                                    --and   (bdcodemp = :prempresa)
                                    AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                    --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                    AND   (bdcontabilizacao IN (0,:prcontabilizacao))
                                    --#alt:6773. Carlos Mello(30/09/2013)
                                    --and   (bddcto like '%'||:wnronf);
                                    AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)));
                 
                                    -- concilia lan?amentos a credito
                                    UPDATE vsuc_empresas_tlan SET bdconcc = 'TRUE'
                                    WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                    AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                    AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                    AND   (bdcodplapadrao = :prcodplapadrao)
                                    AND   (bdcredito = :wconta)
                                    --#alt:6500 - gilberto - 23/08/2013
                                    --and   (bdcodemp = :prempresa)
                                    AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                    --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                    AND   (bdcontabilizacao IN (0,:prcontabilizacao))
                                    --#alt:6773. Carlos Mello(30/09/2013)
                                    --and   (bddcto like '%'||:wnronf);
                                    AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)));
                 
                                    -- informa que houve concilia??o
                                    conciliacaook = 1;
                                  END      



                         END
                      ELSE
                         BEGIN

                            FOR SELECT DISTINCT bdcodter FROM tterceiro WHERE (BDCODTER IN (SELECT /*distinct*/ BDCODTERCEIROD FROM vsuc_empresas_tlan
                                                                                            WHERE ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                                                                                  AND   (bdcodplapadrao = :prcodplapadrao)
                                                                                                  AND   ((bddebito = :wconta))
                                                                                                  --#alt:6500 - gilberto - 23/08/2013
                                                                                                  --and   (bdcodemp = :prempresa)
       
                                                                                                  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                                                                                  AND (bdcontabilizacao IN (0,:prcontabilizacao))
                                                                                                  --#alt:6773. Carlos Mello(30/09/2013)
                                                                                                  --and   (bddcto like '%'||:wnronf)
                                                                                                  AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf))) AND
                                                                                                  (BDCODTERCEIROD IS NOT NULL) AND
                                                                                                  (bddata BETWEEN :prdatainicial AND :prdatafinal) AND
                                                                                                  ((bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal) AND (bdcodemp = :prempresa) )) OR (bdcodemp = :prempresa))
                                                                                           )
                                                                              )
                                                                   OR
                                                                   (BDCODTER IN (SELECT /*distinct*/ BDCODTERCEIROC FROM vsuc_empresas_tlan
                                                                                     WHERE ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                                                                           AND   (bdcodplapadrao = :prcodplapadrao)
                                                                                           AND   ((bdcredito = :wconta))
                                                                                           --#alt:6500 - gilberto - 23/08/2013
                                                                                           --and   (bdcodemp = :prempresa)

                                                                                           --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                                                                           AND (bdcontabilizacao IN (0,:prcontabilizacao))
                                                                                           --#alt:6773. Carlos Mello(30/09/2013)
                                                                                           --and   (bddcto like '%'||:wnronf)
                                                                                           AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf))) AND
                                                                                           (BDCODTERCEIROC IS NOT NULL) AND
                                                                                           (bddata BETWEEN :prdatainicial AND :prdatafinal) AND
                                                                                           ((bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal) AND (bdcodemp = :prempresa) )) OR (bdcodemp = :prempresa))
                                                                                )
                                                                   )
                            ORDER BY bdcodter INTO :WCODTER DO     
                                BEGIN

                                   SELECT SUM(COALESCE((CASE WHEN (bddebito = :wconta) THEN bdvalor END), 0)) "bdvaldeb",
                                          SUM(COALESCE((CASE WHEN (bdcredito = :wconta) THEN bdvalor END), 0)) "bdvalcre"
                                       FROM vsuc_empresas_tlan
                                       WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                       AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                       AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                       AND   (bdcodplapadrao = :prcodplapadrao)
                                       AND   ((bddebito = :wconta) OR (bdcredito = :wconta))
                                       --#alt:6500 - gilberto - 23/08/2013
                                       --and   (bdcodemp = :prempresa)
                                       AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                       --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                       AND (bdcontabilizacao IN (0,:prcontabilizacao))
                                       --#alt:6773. Carlos Mello(30/09/2013)
                                       --and   (bddcto like '%'||:wnronf)
                                       AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)))
        
                                       /*********************************************************/
             
                                       AND (BDCODTERCEIROD = :WCODTER OR BDCODTERCEIROC = :WCODTER)
        
                                       /*******************************************************/
             
                                       INTO :wvaldeb, :wvalcre;
        
        
                                       -- verifica se os valores a debito e a credito s?o iguais para gerar a concilia??o
                                       IF (((wvaldeb - wvalcre) = 0) AND (wvaldeb > 0) AND (wvalcre > 0)) THEN
                                          BEGIN
                                            -- concilia lan?amentos a debito
                                            UPDATE vsuc_empresas_tlan SET bdconcd = 'TRUE'
                                            WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                            AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                            AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                            AND   (bdcodplapadrao = :prcodplapadrao)
                                            AND   (bddebito = :wconta)
                                            --#alt:6500 - gilberto - 23/08/2013
                                            --and   (bdcodemp = :prempresa)
                                            AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                            --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                            AND   (bdcontabilizacao IN (0,:prcontabilizacao))
                                            --#alt:6773. Carlos Mello(30/09/2013)
                                            --and   (bddcto like '%'||:wnronf);
                                            AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)))

                                            AND (BDCODTERCEIROD = :WCODTER);
                         


                                            -- concilia lan?amentos a credito
                                            UPDATE vsuc_empresas_tlan SET bdconcc = 'TRUE'
                                            WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                            AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                            AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                            AND   (bdcodplapadrao = :prcodplapadrao)
                                            AND   (bdcredito = :wconta)
                                            --#alt:6500 - gilberto - 23/08/2013
                                            --and   (bdcodemp = :prempresa)
                                            AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                            --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                                            AND   (bdcontabilizacao IN (0,:prcontabilizacao))
                                            --#alt:6773. Carlos Mello(30/09/2013)
                                            --and   (bddcto like '%'||:wnronf);
                                            AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)))

                                            AND (BDCODTERCEIROC = :WCODTER);

                         
                                            -- informa que houve concilia??o
                                            conciliacaook = 1;
                                          END      
                                END
                         END



                      /*
                      -- verifica se os valores a debito e a credito s?o iguais para gerar a concilia??o
                      if (((wvaldeb - wvalcre) = 0) and (wvaldeb > 0) and (wvalcre > 0)) then
                         begin
                           -- concilia lan?amentos a debito
                           update vsuc_empresas_tlan set bdconcd = 'TRUE'
                           where (bddata between :prdatainicial and :prdatafinal)
                           and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                           and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                           and   (bdcodplapadrao = :prcodplapadrao)
                           and   (bddebito = :wconta)
                           --#alt:6500 - gilberto - 23/08/2013
                           --and   (bdcodemp = :prempresa)
                           and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                           --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                           and   (bdcontabilizacao in (0,:prcontabilizacao))
                           --#alt:6773. Carlos Mello(30/09/2013)
                           --and   (bddcto like '%'||:wnronf);
                           and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)));
        
                           -- concilia lan?amentos a credito
                           update vsuc_empresas_tlan set bdconcc = 'TRUE'
                           where (bddata between :prdatainicial and :prdatafinal)
                           and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                           and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                           and   (bdcodplapadrao = :prcodplapadrao)
                           and   (bdcredito = :wconta)
                           --#alt:6500 - gilberto - 23/08/2013
                           --and   (bdcodemp = :prempresa)
                           and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                           --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                           and   (bdcontabilizacao in (0,:prcontabilizacao))
                           --#alt:6773. Carlos Mello(30/09/2013)
                           --and   (bddcto like '%'||:wnronf);
                           and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)));
        
                           -- informa que houve concilia??o
                           conciliacaook = 1;
                         end      
                        */
                  --end
            END
      END
  SUSPEND;

/*
  conciliacaook = 0;

  -- pega a classifica??o inicial da conta
  select bdctalon from planos_tpla where (bdcodplapadrao = :prcodplapadrao) and (bdcodtpla = :prcontainicial) into :wclassificacaoini;

  -- pega a classifica??o final da conta
  select bdctalon from planos_tpla where (bdcodplapadrao = :prcodplapadrao) and (bdcodtpla = :prcontafinal) into :wclassificacaofim;

  -- limpa as concilia??es anteriores
  if (prlanconc = 1) then
     begin
       for select tlan.bdchave from vsuc_empresas_tlan tlan, planos_tpla tpla
           where (bddata Between :prdatainicial and :prdatafinal)
           and   (tlan.bdcodplapadrao = :prcodplapadrao)
           and   (tlan.bdcodplapadrao = tpla.bdcodplapadrao)
           and   ((tlan.bddebito = tpla.bdcodtpla) or (tlan.bdcredito = tpla.bdcodtpla))
           and   (tpla.bdctalon between :wclassificacaoini and :wclassificacaofim)
           --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
           and   (tlan.bdcontabilizacao in (0,:prcontabilizacao))
           and   (bdcodemp = :prempresa) into :wchave do
       begin
         update vsuc_empresas_tlan set bdconcd = null, bdconcc = null where (bdchave = :wchave) and (bdcodemp = :prempresa);
         conciliacaook = conciliacaook + 1;
       end
     
       if (conciliacaook > 0) then
          conciliacaook = 1;
--       suspend;
     end

  -- retorna as contas selecionadas
  for select tpla.bdcodtpla from planos_tpla tpla
      where tpla.bdcodplapadrao = :prcodplapadrao
      and tpla.bdctalon between :wclassificacaoini and :wclassificacaofim
      order by tpla.bdctalon
      into :wconta do
      begin
        -- retorna os numeros dos documentos de acordo com o parametro de ignorar zeros a esquerda
        for select distinct (select nronf from VSUC_NRO_NOTA_COMPL(tlan.bddcto, :przeroesq)) from vsuc_empresas_tlan tlan
            where tlan.bdcodemp = :prempresa
            and tlan.bdcodplapadrao = :prcodplapadrao
            and ((tlan.bddebito = :wconta) or (tlan.bdcredito = :wconta))
            and ((tlan.bddcto is not null) and (tlan.bddcto <> ''))
            --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
            and (tlan.bdcontabilizacao in (0,:prcontabilizacao))
            order by tlan.bddcto
            into :wnronf do
            begin
              -- soma os lan?amentos a debito e a credito
              select sum(coalesce((case when (bddebito = :wconta) then bdvalor end), 0)) "bdvaldeb",
                     sum(coalesce((case when (bdcredito = :wconta) then bdvalor end), 0)) "bdvalcre"
                  from vsuc_empresas_tlan
                  where (bddata between :prdatainicial and :prdatafinal)
                  and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                  and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                  and   (bdcodplapadrao = :prcodplapadrao)
                  and   ((bddebito = :wconta) or (bdcredito = :wconta))
                  --#alt:6500 - gilberto - 23/08/2013
                  --and   (bdcodemp = :prempresa)
                  and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                  and (bdcontabilizacao in (0,:prcontabilizacao))
                  --#alt:6773. Carlos Mello(30/09/2013)
                  --and   (bddcto like '%'||:wnronf)
                  and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)))
                  into :wvaldeb, :wvalcre;
              -- verifica se os valores a debito e a credito s?o iguais para gerar a concilia??o
              if (((wvaldeb - wvalcre) = 0) and (wvaldeb > 0) and (wvalcre > 0)) then
                 begin
                   -- concilia lan?amentos a debito
                   update vsuc_empresas_tlan set bdconcd = 'TRUE'
                   where (bddata between :prdatainicial and :prdatafinal)
                   and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                   and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                   and   (bdcodplapadrao = :prcodplapadrao)
                   and   (bddebito = :wconta)
                   --#alt:6500 - gilberto - 23/08/2013
                   --and   (bdcodemp = :prempresa)
                   and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                   --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                   and   (bdcontabilizacao in (0,:prcontabilizacao))
                   --#alt:6773. Carlos Mello(30/09/2013)
                   --and   (bddcto like '%'||:wnronf);
                   and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)));

                   -- concilia lan?amentos a credito
                   update vsuc_empresas_tlan set bdconcc = 'TRUE'
                   where (bddata between :prdatainicial and :prdatafinal)
                   and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                   and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                   and   (bdcodplapadrao = :prcodplapadrao)
                   and   (bdcredito = :wconta)
                   --#alt:6500 - gilberto - 23/08/2013
                   --and   (bdcodemp = :prempresa)
                   and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                   --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
                   and   (bdcontabilizacao in (0,:prcontabilizacao))
                   --#alt:6773. Carlos Mello(30/09/2013)
                   --and   (bddcto like '%'||:wnronf);
                   and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)));

                   -- informa que houve concilia??o
                   conciliacaook = 1;
                 end
            end
      end
  suspend;
 */
END
^

/* Alter (VSUC_SP_MOVIMENTO_MENSAL) */
ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRCC VARCHAR(5000),
PRANOINICIAL INTEGER,
PRANOFINAL INTEGER,
PRREFEMP INTEGER,
PRPARTICIPANTE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDDEB01 NUMERIC(15,2),
BDDEB02 NUMERIC(15,2),
BDDEB03 NUMERIC(15,2),
BDDEB04 NUMERIC(15,2),
BDDEB05 NUMERIC(15,2),
BDDEB06 NUMERIC(15,2),
BDDEB07 NUMERIC(15,2),
BDDEB08 NUMERIC(15,2),
BDDEB09 NUMERIC(15,2),
BDDEB10 NUMERIC(15,2),
BDDEB11 NUMERIC(15,2),
BDDEB12 NUMERIC(15,2),
BDCRE01 NUMERIC(15,2),
BDCRE02 NUMERIC(15,2),
BDCRE03 NUMERIC(15,2),
BDCRE04 NUMERIC(15,2),
BDCRE05 NUMERIC(15,2),
BDCRE06 NUMERIC(15,2),
BDCRE07 NUMERIC(15,2),
BDCRE08 NUMERIC(15,2),
BDCRE09 NUMERIC(15,2),
BDCRE10 NUMERIC(15,2),
BDCRE11 NUMERIC(15,2),
BDCRE12 NUMERIC(15,2),
BDMOV01 NUMERIC(15,2),
BDMOV02 NUMERIC(15,2),
BDMOV03 NUMERIC(15,2),
BDMOV04 NUMERIC(15,2),
BDMOV05 NUMERIC(15,2),
BDMOV06 NUMERIC(15,2),
BDMOV07 NUMERIC(15,2),
BDMOV08 NUMERIC(15,2),
BDMOV09 NUMERIC(15,2),
BDMOV10 NUMERIC(15,2),
BDMOV11 NUMERIC(15,2),
BDMOV12 NUMERIC(15,2),
BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2),
BDSALTOTDEB NUMERIC(15,2),
BDSALTOTCRE NUMERIC(15,2),
BDSALTOTMOV NUMERIC(15,2),
BDSALTOTATU NUMERIC(15,2),
BDANO INTEGER,
BDGRPCTA INTEGER,
BDDEBANT NUMERIC(15,2),
BDCREANT NUMERIC(15,2),
BDMOVANT NUMERIC(15,2),
BDSALANT NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WBDSALTOTDEB NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTCRE NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTMOV NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTATU NUMERIC(15,2);
DECLARE VARIABLE WBDDEBANT NUMERIC(15,2);
DECLARE VARIABLE WBDCREANT NUMERIC(15,2);
DECLARE VARIABLE WBDSALANT NUMERIC(15,2);
DECLARE VARIABLE WBDDEB01 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB02 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB03 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB04 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB05 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB06 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB07 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB08 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB09 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB10 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB11 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB12 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE01 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE02 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE03 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE04 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE05 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE06 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE07 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE08 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE09 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE10 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE11 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE12 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV01 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV02 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV03 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV04 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV05 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV06 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV07 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV08 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV09 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV10 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV11 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV12 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL01 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL02 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL03 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL04 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL05 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL06 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL07 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL08 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL09 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL10 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL11 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL12 NUMERIC(15,2);
BEGIN
  wcount = 0;
  WHILE (wcount <= pranofinal - pranoinicial) DO
    BEGIN
      BDANO = :pranoinicial + :wcount;
      --Precisa zerar o valores para n?o interferir nos valores dos pr?ximos anos
      bdsaltotdeb = 0;
      bdsaltotcre = 0;
      bdsaltotmov = 0;
      bdsaltotatu = 0;
      bddebant    = 0;
      bdcreant    = 0;
      bdmovant    = 0;
      bdsalant    = 0;

      bddeb01 = 0;
      bddeb02 = 0;
      bddeb03 = 0;
      bddeb04 = 0;
      bddeb05 = 0;
      bddeb06 = 0;
      bddeb07 = 0;
      bddeb08 = 0;
      bddeb09 = 0;
      bddeb10 = 0;
      bddeb11 = 0;
      bddeb12 = 0;

      bdcre01 = 0;
      bdcre02 = 0;
      bdcre03 = 0;
      bdcre04 = 0;
      bdcre05 = 0;
      bdcre06 = 0;
      bdcre07 = 0;
      bdcre08 = 0;
      bdcre09 = 0;
      bdcre10 = 0;
      bdcre11 = 0;
      bdcre12 = 0;

      --alt:9515 - Adicionado campo do movimento. Pedro
      bdmov01 = 0;
      bdmov02 = 0;
      bdmov03 = 0;
      bdmov04 = 0;
      bdmov05 = 0;
      bdmov06 = 0;
      bdmov07 = 0;
      bdmov08 = 0;
      bdmov09 = 0;
      bdmov10 = 0;
      bdmov11 = 0;
      bdmov12 = 0;

      bdsal01 = 0;
      bdsal02 = 0;
      bdsal03 = 0;
      bdsal04 = 0;
      bdsal05 = 0;
      bdsal06 = 0;
      bdsal07 = 0;
      bdsal08 = 0;
      bdsal09 = 0;
      bdsal10 = 0;
      bdsal11 = 0;
      bdsal12 = 0;

      wsql = 'select bdcodemp from tempresas where bdcodemp in ('||prcodemp||')';
      FOR EXECUTE STATEMENT wsql INTO :wcodemp DO
          BEGIN
            SELECT bdano, bdgrpcta, bdsaltotdeb, bdsaltotcre, bdsaltotmov, bdsaltotatu, bddebant, bdcreant, bdsalant,
                   bddeb01, bddeb02, bddeb03, bddeb04, bddeb05, bddeb06, bddeb07, bddeb08, bddeb09, bddeb10, bddeb11, bddeb12,
                   bdcre01, bdcre02, bdcre03, bdcre04, bdcre05, bdcre06, bdcre07, bdcre08, bdcre09, bdcre10, bdcre11, bdcre12,
                   bdmov01, bdmov02, bdmov03, bdmov04, bdmov05, bdmov06, bdmov07, bdmov08, bdmov09, bdmov10, bdmov11, bdmov12,
                   bdsal01, bdsal02, bdsal03, bdsal04, bdsal05, bdsal06, bdsal07, bdsal08, bdsal09, bdsal10, bdsal11, bdsal12
            FROM vsuc_sp_retorna_mov_mensal(:wcodemp, :prconta, :prcc, :bdano, :bdano, :prrefemp, :prparticipante, :prignorazeramento,:prcontabilizacao,:prmatrizfilialconsolidado)
            INTO :bdano, :bdgrpcta, :wbdsaltotdeb, :wbdsaltotcre, :wbdsaltotmov, :wbdsaltotatu, :wbddebant, :wbdcreant, :wbdsalant,
                 :wbddeb01, :wbddeb02, :wbddeb03, :wbddeb04, :wbddeb05, :wbddeb06, :wbddeb07, :wbddeb08, :wbddeb09, :wbddeb10, :wbddeb11, :wbddeb12,
                 :wbdcre01, :wbdcre02, :wbdcre03, :wbdcre04, :wbdcre05, :wbdcre06, :wbdcre07, :wbdcre08, :wbdcre09, :wbdcre10, :wbdcre11, :wbdcre12,
                 :wbdmov01, :wbdmov02, :wbdmov03, :wbdmov04, :wbdmov05, :wbdmov06, :wbdmov07, :wbdmov08, :wbdmov09, :wbdmov10, :wbdmov11, :wbdmov12,
                 :wbdsal01, :wbdsal02, :wbdsal03, :wbdsal04, :wbdsal05, :wbdsal06, :wbdsal07, :wbdsal08, :wbdsal09, :wbdsal10, :wbdsal11, :wbdsal12;

            bdsaltotdeb = COALESCE(bdsaltotdeb, 0) + COALESCE(wbdsaltotdeb, 0);
            bdsaltotcre = COALESCE(bdsaltotcre, 0) + COALESCE(wbdsaltotcre, 0);
            bdsaltotatu = COALESCE(bdsaltotatu, 0) + COALESCE(wbdsaltotatu, 0);
            bdsaltotmov = COALESCE(bdsaltotmov, 0) + COALESCE(wbdsaltotmov, 0);
            bddebant    = COALESCE(bddebant, 0) + COALESCE(wbddebant, 0);
            bdcreant    = COALESCE(bdcreant, 0) + COALESCE(wbdcreant, 0);
            bdsalant    = COALESCE(bdsalant, 0) + COALESCE(wbdsalant, 0);

            bddeb01 = COALESCE(bddeb01, 0) + COALESCE(wbddeb01, 0);
            bddeb02 = COALESCE(bddeb02, 0) + COALESCE(wbddeb02, 0);
            bddeb03 = COALESCE(bddeb03, 0) + COALESCE(wbddeb03, 0);
            bddeb04 = COALESCE(bddeb04, 0) + COALESCE(wbddeb04, 0);
            bddeb05 = COALESCE(bddeb05, 0) + COALESCE(wbddeb05, 0);
            bddeb06 = COALESCE(bddeb06, 0) + COALESCE(wbddeb06, 0);
            bddeb07 = COALESCE(bddeb07, 0) + COALESCE(wbddeb07, 0);
            bddeb08 = COALESCE(bddeb08, 0) + COALESCE(wbddeb08, 0);
            bddeb09 = COALESCE(bddeb09, 0) + COALESCE(wbddeb09, 0);
            bddeb10 = COALESCE(bddeb10, 0) + COALESCE(wbddeb10, 0);
            bddeb11 = COALESCE(bddeb11, 0) + COALESCE(wbddeb11, 0);
            bddeb12 = COALESCE(bddeb12, 0) + COALESCE(wbddeb12, 0);

            bdcre01 = COALESCE(bdcre01, 0) + COALESCE(wbdcre01, 0);
            bdcre02 = COALESCE(bdcre02, 0) + COALESCE(wbdcre02, 0);
            bdcre03 = COALESCE(bdcre03, 0) + COALESCE(wbdcre03, 0);
            bdcre04 = COALESCE(bdcre04, 0) + COALESCE(wbdcre04, 0);
            bdcre05 = COALESCE(bdcre05, 0) + COALESCE(wbdcre05, 0);
            bdcre06 = COALESCE(bdcre06, 0) + COALESCE(wbdcre06, 0);
            bdcre07 = COALESCE(bdcre07, 0) + COALESCE(wbdcre07, 0);
            bdcre08 = COALESCE(bdcre08, 0) + COALESCE(wbdcre08, 0);
            bdcre09 = COALESCE(bdcre09, 0) + COALESCE(wbdcre09, 0);
            bdcre10 = COALESCE(bdcre10, 0) + COALESCE(wbdcre10, 0);
            bdcre11 = COALESCE(bdcre11, 0) + COALESCE(wbdcre11, 0);
            bdcre12 = COALESCE(bdcre12, 0) + COALESCE(wbdcre12, 0);

            --alt:9515 - Adicionados campos do movimento. Pedro
            bdmov01 = COALESCE(bdmov01, 0) + COALESCE(wbdmov01, 0);
            bdmov02 = COALESCE(bdmov02, 0) + COALESCE(wbdmov02, 0);
            bdmov03 = COALESCE(bdmov03, 0) + COALESCE(wbdmov03, 0);
            bdmov04 = COALESCE(bdmov04, 0) + COALESCE(wbdmov04, 0);
            bdmov05 = COALESCE(bdmov05, 0) + COALESCE(wbdmov05, 0);
            bdmov06 = COALESCE(bdmov06, 0) + COALESCE(wbdmov06, 0);
            bdmov07 = COALESCE(bdmov07, 0) + COALESCE(wbdmov07, 0);
            bdmov08 = COALESCE(bdmov08, 0) + COALESCE(wbdmov08, 0);
            bdmov09 = COALESCE(bdmov09, 0) + COALESCE(wbdmov09, 0);
            bdmov10 = COALESCE(bdmov10, 0) + COALESCE(wbdmov10, 0);
            bdmov11 = COALESCE(bdmov11, 0) + COALESCE(wbdmov11, 0);
            bdmov12 = COALESCE(bdmov12, 0) + COALESCE(wbdmov12, 0);

            bdsal01 = COALESCE(bdsal01, 0) + COALESCE(wbdsal01, 0);
            bdsal02 = COALESCE(bdsal02, 0) + COALESCE(wbdsal02, 0);
            bdsal03 = COALESCE(bdsal03, 0) + COALESCE(wbdsal03, 0);
            bdsal04 = COALESCE(bdsal04, 0) + COALESCE(wbdsal04, 0);
            bdsal05 = COALESCE(bdsal05, 0) + COALESCE(wbdsal05, 0);
            bdsal06 = COALESCE(bdsal06, 0) + COALESCE(wbdsal06, 0);
            bdsal07 = COALESCE(bdsal07, 0) + COALESCE(wbdsal07, 0);
            bdsal08 = COALESCE(bdsal08, 0) + COALESCE(wbdsal08, 0);
            bdsal09 = COALESCE(bdsal09, 0) + COALESCE(wbdsal09, 0);
            bdsal10 = COALESCE(bdsal10, 0) + COALESCE(wbdsal10, 0);
            bdsal11 = COALESCE(bdsal11, 0) + COALESCE(wbdsal11, 0);
            bdsal12 = COALESCE(bdsal12, 0) + COALESCE(wbdsal12, 0);
          END

      wcount = wcount + 1;
      SUSPEND;
    END
END
^

/* Alter (VSUC_SP_NOMENCLATURA_CTA_PARTIC) */
ALTER PROCEDURE VSUC_SP_NOMENCLATURA_CTA_PARTIC(PRCODTERCEIRO INTEGER,
PRCLASSIFICACAO VARCHAR(40),
PRCONCATENA INTEGER)
 RETURNS(BDNOME VARCHAR(100),
BDCLASSIFICACAO VARCHAR(100))
 AS
DECLARE VARIABLE wnome VARCHAR(100);
DECLARE VARIABLE wsql VARCHAR(2000);
DECLARE VARIABLE wpos INTEGER;
BEGIN
/*
  bdclassificacao = substring(prclassificacao from 1 for (select BDRPOS from RPOS('.',:prclassificacao))) ||
                    (select bdretorno from preenche_esquerda(cast(:prcodterceiro as varchar(8)),8,'0'));
*/
  bdclassificacao = REVERSE(prclassificacao);
  bdclassificacao = SUBSTRING(bdclassificacao FROM POSITION('.', bdclassificacao) FOR strlen(bdclassificacao));
  bdclassificacao = REVERSE(bdclassificacao);
  bdclassificacao = bdclassificacao||LPAD(prcodterceiro, 8, '0');
  -- Busca o nome do participante
  --wsql = 'select tterc.bdnometer from vw_tterceiro_vsuc tterc ';
  --wsql = wsql||'where ';
  --wsql = wsql||'tterc.bdcodter = '||:prcodterceiro;
/*
  wsql = 'select ref.bdnometer ';
  wsql = wsql||' from tterceiro_ref REF';
  wsql = wsql||' where REF.bdcodter = '||:prcodterceiro;
  wsql = wsql||' and REF.bdrefemp = (select max(RF2.bdREFEMP) from TTERCEIRO_REF RF2 where RF2.bdcodter = REF.bdCODTER)';

  --execute statement wsql
*/
  SELECT FIRST 1 bdnometer FROM tterceiro_ref WHERE bdcodter = :prcodterceiro ORDER BY bdrefemp
  INTO :wnome;

  IF (prconcatena = 1) THEN
    BEGIN
      wpos  = CHARACTER_LENGTH(:prcodterceiro);
              -- 100 -> m?ximo de caracteres para nome da conta
              -- 03 -> qtd de caracteres " - ";
      wpos  = ((100 - wpos) - 3);
      wnome = prcodterceiro||' - '||SUBSTRING(wnome FROM 1 FOR wpos);
    END

  bdnome = SUBSTRING(wnome FROM 1 FOR 100);
  SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: SP_RETORNA_SALDO_EMP for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE SP_RETORNA_SALDO_EMP(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_RETORNA_SALDO_MATRIZFILIAL for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: SP_RETORNA_SALDO_MATRIZFILIAL_X for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL_X(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0,
PRCODTERCEIRO INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER,
CHAVELAN INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_LISTA_CTA_RAZAO_VIDEO for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO(PRCODEMP VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRDATINI DATE,
PRDATFIM DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRTIPORAZAO INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDNOMCTA VARCHAR(100),
BDCTALON VARCHAR(40),
BDCODPARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_CRITICA_LANC for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE VSUC_SP_RETORNA_CRITICA_LANC(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRCHAVEINI INTEGER,
PRCHAVEFIM INTEGER,
PRLOTEINI VARCHAR(10),
PRLOTEFIM VARCHAR(10),
PRTRANSINI INTEGER,
PRTRANSFIM INTEGER,
PRCOLUNAS INTEGER,
PRLCC VARCHAR(1024),
PRTOTDIA INTEGER,
PRTOTMES INTEGER,
PRTOTANO INTEGER,
PRTOTLOTE INTEGER,
PRDATAS VARCHAR(1024),
PRLANCSEMTRANS INTEGER,
PRREFEMP INTEGER,
PRCODTIPOLANC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(200),
PREMPRESA INTEGER,
PRNOMEEMPRESA /* DM_BDNOMEMP */ VARCHAR(100),
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDEBCRE INTEGER,
PRVALOR NUMERIC(15,2),
PRVALORRAT NUMERIC(15,2),
PRQUEBRADIA DATE,
PRQUEBRAMES VARCHAR(7),
PRQUEBRARANO VARCHAR(4),
PRQUEBRALOTE VARCHAR(10),
PRSEQUENCIA INTEGER,
PRNOMECC VARCHAR(40),
PRCODEMPFILIAL INTEGER,
PRCONTAB INTEGER,
PRDESCTIPOLANC VARCHAR(100),
BDTRANSACAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_SALDO_CONS_ORCA for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONS_ORCA(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRCODTPCC INTEGER,
PRANO INTEGER,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_SALDO_CONTAS for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRLANCSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDATAHORA VARCHAR(30),
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
CLANOM VARCHAR(140),
TIPCONTA SMALLINT,
SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
FORMULA VARCHAR(200),
PARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_SALDO_CONTAS_X for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_X(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRINDICE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRLANCSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRNIVEISCONTA VARCHAR(50),
PREMPRESAS VARCHAR(2048),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDRE INTEGER = 0,
PRTODOPLANOCONTAS INTEGER = 0)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
CLANOM VARCHAR(140),
TIPCONTA SMALLINT,
SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
FORMULA VARCHAR(200),
PARTICIPANTE INTEGER,
APECTA VARCHAR(20),
PERTENCECONTA INTEGER,
SALDO_ANT_DEB_DRE NUMERIC(15,2),
SALDO_ANT_CRE_DRE NUMERIC(15,2),
SALDO_ANTERIOR_DRE NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_SALDO_ORCA for: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_ORCA(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRINDICE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRDATAHORA VARCHAR(30),
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
TIPCONTA SMALLINT,
BDORCADO INTEGER,
BDREALIZADO NUMERIC(15,2),
FORMULA VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_PERMITECALCSALDOLANCMF) */
ALTER PROCEDURE VSUC_SP_PERMITECALCSALDOLANCMF(PRCAMPO INTEGER,
PRCODEMPMASTER INTEGER,
PRCODEMP INTEGER,
PRFILIAL INTEGER,
PRTIPOLANCFILIAL INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PREMPRESAS VARCHAR(2048))
 RETURNS(BDPERMITE SMALLINT)
 AS
DECLARE VARIABLE wpos_matriz INTEGER;
DECLARE VARIABLE wpos_filial INTEGER;
DECLARE VARIABLE wpos_pernamatriz INTEGER;
BEGIN
  --Carlos Mello - #alt:5837. Foi feito uma altera??o onde ? permitodo lan?ar nas filias mesmo estando na matriz, mas
  --para calcular o saldo precisa seguir algumas regras. Ex: Se estou na matriz, filial, filtros ou qual perna do lan?amento deve calcular
  --OBS.: Caso tenha alguma alter??o nessa regra, favor verficar a rotina "getPermiteCalcSaldoLancMatrizFilial" no fonte uLancamentoDBMGR

  -- BDPERMITE, PRCONSOLIDADO  -> 0 - False | 1 - True
  -- PRCAMPO, PRTIPOLANCFILIAL -> 1 - D?bito | 2 - Cr?dito
  -- PRCONSOLIDADO -> Pelo que observei algumas stored procedure calculam separadamente as empresas e depois somam a matriz com filial, por isso foi criado o par?metro
  bdpermite = 0;
  IF (prfilial IS NULL) THEN
    prfilial = 0;

  --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
  --select Pos from pos(','||:prcodempmaster||',', ','||:prempresas||',') into :wpos_pernamatriz;
  --alt:#6535 - gilberto - 05/09/2013
  wpos_pernamatriz = POSITION(prcodempmaster, prcodemp);

  --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
  --select Pos from pos(','||:prcodemp||',', ','||:prempresas||',') into :wpos_matriz;
  --alt:#6535 - gilberto - 05/09/2013
  wpos_matriz = POSITION(prcodemp,  prempresas);

  --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
  --select Pos from pos(','||:prfilial||',', ','||:prempresas||',') into :wpos_filial;
  --alt:#6535 - gilberto - 05/09/2013
  wpos_filial = POSITION(prfilial,  prempresas);


  IF (((prcodempmaster = prcodemp) AND (prfilial = 0)) OR
      --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
      ((prcodempmaster = prfilial) AND (prcampo = prtipolancfilial)) OR
      --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
      ((prcodempmaster = prcodemp) AND (prfilial <> 0) AND (prcampo <> prtipolancfilial) AND (wpos_pernamatriz > 0)) OR
      --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
      ((prmatrizfilialconsolidado = 1) AND (prcodempmaster <> prcodemp) AND (prfilial = 0) AND (wpos_matriz > 0)) OR
      --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
      ((prmatrizfilialconsolidado = 1) AND (prcodempmaster = prcodemp) AND (prfilial <> 0) AND (prcampo = prtipolancfilial) AND (wpos_filial > 0))) THEN
    bdpermite = 1;
  SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_BALANCETE_MENSAL for: VSUC_SP_RETORNA_BALANCETE */
ALTER PROCEDURE VSUC_SP_BALANCETE_MENSAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDDATINI DATE,
BDDATFIN DATE,
BDAPECTA VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_RETORNA_BALANCETE) */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRORDEM INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDRE INTEGER = 0,
PRTODOPLANOCONTAS INTEGER = 0,
PRDETALHAREMPREENDIMENTO INTEGER = 0,
PRDETALHARUNIDIMOB INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDCODTER INTEGER,
BDAPECTA VARCHAR(20),
BDSALDO_ANTERIOR_DRE NUMERIC(15,2),
BDSALDO_ANT_DEB_DRE NUMERIC(15,2),
BDSALDO_ANT_CRE_DRE NUMERIC(15,2),
BDRAIZCNPJPARTICIPANTE VARCHAR(10),
BDRAIZCLASSIFICACAOCTA VARCHAR(40))
 AS
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WSALDO_ANT_DEB NUMERIC(15,2);
DECLARE VARIABLE WSALDO_DEB NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_CRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ATUAL NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCLANOM VARCHAR(140);
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WGRPCTA SMALLINT;
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
DECLARE VARIABLE WSALDO_ANTERIOR_DRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_DEB_DRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_CRE_DRE NUMERIC(15,2);
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCODTPCCANT INTEGER;
DECLARE VARIABLE WNOMTPCC VARCHAR(40);
DECLARE VARIABLE WTPCCLON VARCHAR(20);
declare variable WCODEMPREENDIMENTO integer;
declare variable WCODUNIDIMOB integer;
declare variable WDESCEMPREENDIMENTO varchar(500);
declare variable WDESCUNIDIMOB varchar(500);
declare variable WCADINCORP integer;
declare variable WRAIZCTASEMEMPREENDIMENTO varchar(40);
declare variable WRAIZCTASEMEMPREENDIMENTOANT varchar(40);
BEGIN
-- select * from VSUC_SP_RETORNA_BALANCETE('13,14', '01/01/2015', '12/31/2015', 0, 19, 35, '', 201204, 0, 0,1, 1, 0,'1,2,3,4') order by bdcodtpcc, bdctalon
  DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
  -- retorna as empresas selecionadas
  wsql = 'select case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  wpos = POSITION(',', :prcodemp);
  IF (wpos <> 0) THEN
     wsql = wsql||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsql = wsql||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsql = wsql||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsql = wsql||'       end bdcodemp, ';
  wsql = wsql||'       temp.bdcodemp bdcodempfilial, ';
  wsql = wsql||'       tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  wdatahora = CURRENT_TIMESTAMP;
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        bdcodter = 0;
        wcadincorp = 0;
        -- delete from vsuc_empresas_tbalancete where bdcodemp <> 0;
        -- verifica se existe centro de custo selecionado
        IF (prcodtpcc = '') THEN
           BEGIN
             bdcodtpcc = 0;
             bdnomtpcc = '';
             bdtpcclon = '';


             --#alt:11436 - Adiconado controle para o parametro de imprimir o plano de contas completo PRTODOPLANOCONTAS. Ana - 15/12/2016
             -- retorna todas as contas do plano de contas sem o centro de custo
             FOR SELECT tsalcta.conta, tsalcta.classificacao, tsalcta.nomeconta, tsalcta.tipconta, tsalcta.GRUPOCONTA,
                        tsalcta.saldo_ant_deb, tsalcta.saldo_ant_cre, tsalcta.saldo_deb,
                        tsalcta.saldo_cre, tsalcta.saldo_atual,
                        tsalcta.saldo_anterior, tsalcta.formula, tsalcta.relconta, tsalcta.clanom, tsalcta.participante, tsalcta.apecta,
                        tsalcta.saldo_ant_deb_dre, tsalcta.saldo_ant_cre_dre, tsalcta.saldo_anterior_dre
                 FROM vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prindice, :prignora_zeramento, 0, :bdcodplapadrao,:prlansemcc,
                                                     :prnaomostracontacomp,:prconsolidada,:prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,:prdre, :prtodoplanocontas) tsalcta
                 INTO :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta, :bdgrpcta,
                      :bdsaldo_ant_deb, :bdsaldo_ant_cre, :bdsaldo_deb, :bdsaldo_cre, :bdsaldo_atual,
                      :bdsaldo_anterior, :bdformula, :bdrelcta, :bdclanom, :wparticipante, :bdapecta,
                      :bdsaldo_ant_deb_dre, :bdsaldo_ant_cre_dre, :bdsaldo_anterior_dre DO
                 BEGIN
                   -- Detalhado por participante
                   IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                     BEGIN
--                       delete from vsuc_empresas_tbalancete_2 tbalan where tbalan.bdcodemp = :bdcodempfilial and tbalan.bddatahora = :wdatahora and tbalan.bdcodtpla = :bdcodcta;
                       --delete from vsuc_empresas_tbalancete_3 tbalan where tbalan.bdcodemp = :bdcodempfilial and tbalan.bdcodtpla = :bdcodcta;


                       FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_deb, tsalctapar.bdsaldo_ant_deb,
                                  tsalctapar.bdsaldo_cre, tsalctapar.bdsaldo_ant_cre, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdmovimento,
                                  tsalctapar.bdcodparticipante, tsalctapar.bdraizcnpjparticipante, tsalctapar.bdraizclassificacaocta
                           --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           --from vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           --                                     :prignora_zeramento,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tsalctapar
                           --alt:9167 - Adicionado par?metro para agrupar participantes por CNPJ. Pedro
                           FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                           INTO :bdnomcta, :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                :wcodparticipante, :bdraizcnpjparticipante, :bdraizclassificacaocta DO
                           BEGIN

                             bdcodter = :wcodparticipante;
                             bdclanom = SUBSTRING(bdctalon FROM 1 FOR strlen(bdctalon)-10)||' '||bdnomcta;
                             SUSPEND;
                           END

                     END
                   ELSE
                     BEGIN
                       --Detalhado por incorporadora
                       if ((prdetalharempreendimento = 1) or (prdetalharunidimob = 1)) then
                         BEGIN
                           wcadincorp = 0;
                           wnomcta = bdnomcta;
                           if (wctalonant is null) then
                             wctalonant = bdctalon;

                           FOR SELECT tsalctaincorp.bdclassificacao, tsalctaincorp.bdsaldo_deb, tsalctaincorp.bdsaldo_ant_deb, tsalctaincorp.bdsaldo_cre, tsalctaincorp.bdsaldo_ant_cre,
                                  tsalctaincorp.bdsaldo_atual, tsalctaincorp.bdsaldo_anterior, tsalctaincorp.bdmovimento, tsalctaincorp.bdcodempreendimento, tsalctaincorp.bdcodunidimob,
                                  tsalctaincorp.bddescempreendimento, tsalctaincorp.bddescunidimob, tsalctaincorp.bdraizclassificacaocta, tsalctaincorp.BDRAIZCTASEMEMPREENDIMENTO
                               FROM VSUC_SP_RETORNA_SALDOS_CTAINCOR(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                    0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :wctalonant, :bdtipcta, :wraizctasemempreendimentoant,
                                                                    :prdetalharempreendimento, :prdetalharunidimob) tsalctaincorp
                               INTO :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                    :wcodempreendimento, :wcodunidimob,:wdescempreendimento, :wdescunidimob, :bdraizclassificacaocta, :WRAIZCTASEMEMPREENDIMENTO DO
                               BEGIN
                                 if ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) then
                                   bdnomcta = bdnomcta||' ('||wdescempreendimento||')';

                                 if (wcodunidimob IS NOT NULL) then
                                   bdnomcta = bdnomcta||' ('||wdescunidimob||')';

                                 if (wraizctasemempreendimento IS NOT NULL) then
                                   wraizctasemempreendimentoant = wraizctasemempreendimento;

                             SUSPEND;

                                 wcadincorp = 1;
                                 bdnomcta = wnomcta;
                           END
                         END

                       bdcodter = 0;
                       bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                       --#Alt:19049
                       bdraizcnpjparticipante = '';
                       --#alt:20415. Ana - 22/09/2017
                       bdraizclassificacaocta = '';

                       --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
                       --#alt:11436 - Adicionada condi??o do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
                       --alt:7847 - Trocada a verifica??o, s? imprime se tiver movimento ou se estiver marcado para imprimir contas sem movimento. Pedro
                       --ALT:8067 - Adicionada exce??o para retornar contas t?tulo, mesmo zeradas, porque quando a anal?tica dela for uma f?rmula elas sempre retornar?o zeradas do banco. Pedro                       
                       IF ((wcadincorp = 0 ) and
                          ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                           (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                           (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                           (PRTODASASCONTAS = 1) OR (BDTIPCTA = 0) OR (bdformula <> '') OR (prtodoplanocontas = 1))) THEN
                           BEGIN
                             SUSPEND;
                           END

                     END

                     if (bdtipcta = 0) then
                       wctalonant = bdctalon;
                 END
           END
        ELSE
           BEGIN
             bdcodter = 0;
             -- retorna a conta longa da conta inicial
             SELECT tpla.bdctalon FROM planos_tpla tpla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :prctaini
             INTO :wctalonant;
             -- inicializa as variaveis
             bdsaldo_ant_cre = 0;
             bdsaldo_ant_deb = 0;
             bdsaldo_cre = 0;
             bdsaldo_deb = 0;
             bdsaldo_anterior = 0;
             bdsaldo_atual = 0;

             --#alt:17388 - Removi o campo bdformula do retorno, pois estava duplicado e atribuia direto pro return deixando o retorno com valor incorreto. Ana - 23/01/2018
             FOR SELECT bdconta, bdclassificacao, bdnomeconta, bdtipconta, BDGRUPOCONTA,
                        bdsaldo_ant_deb, bdsaldo_ant_cre, bdsaldo_deb,
                        bdsaldo_cre, bdsaldo_atual, bdsaldo_anterior,
                        bdformula, bdrelconta, bdclanom, /*bdformula,*/ bdapecta,
                        bdsaldo_ant_deb_dre, bdsaldo_ant_cre_dre, bdsaldo_anterior_dre,
                        bdcodtpcc, bdnomtpcc, bdtpcclon
                        FROM vsuc_sp_retorna_saldo_contas_xz(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prindice, :prignora_zeramento, :prcodtpcc,
                                                            :bdcodplapadrao, :prlansemcc, :prordem, :prnaomostracontacomp, :prconsolidada, :prniveisconta,
                                                            :prcontabilizacao, :prmatrizfilialconsolidado, :prdre) tsalcta
                        INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta,
                             :wsaldo_ant_deb, :wsaldo_ant_cre, :wsaldo_deb,
                             :wsaldo_cre, :wsaldo_atual, :wsaldo_anterior,
                             :wformula, :bdrelcta, :wclanom, /*:bdformula,*/ :bdapecta,
                             :wsaldo_ant_deb_dre, :wsaldo_ant_cre_dre, :wsaldo_anterior_dre,
                             :wcodtpcc, :wnomtpcc, :wtpcclon DO
                      BEGIN
                         --alt:9381 - Quando for nullo troca para zero, sen?o n?o consegue totalizar
                         --corretamente por centro de custo onde for sem centro de custos. Pedro
                         IF (wcodtpcc IS NULL) THEN
                           wcodtpcc = 0;

                         --#Alt:19049
                         bdraizcnpjparticipante = '';
                         --#alt:20416. Ana - 22/09/2017
                         bdraizclassificacaocta = '';

                         --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
                         --#alt:11436 - Adicionada condição do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
                         IF ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                             (BDTIPCTA = 0) OR (bdformula <> '') OR  (prtodoplanocontas = 1)) THEN
                             BEGIN
                               IF ((wctalonant <> wctalon) OR (COALESCE(wcodtpccant, 0) <> COALESCE(wcodtpcc, 0))) THEN
                                  SUSPEND;

                               bdcodcta  = wconta;
                               bdctalon  = wctalon;
                               bdnomcta  = wnomcta;
                               bdtipcta  = wtipcta;
                               bdclanom  = wclanom;
                               bdgrpcta  = wgrpcta;
                               bdformula = wformula;
                               bdcodtpcc = wcodtpcc;
                               bdnomtpcc = wnomtpcc;
                               bdtpcclon = wtpcclon;
 
                               bdsaldo_ant_cre = wsaldo_ant_cre;
                               bdsaldo_ant_deb = wsaldo_ant_deb;
                               bdsaldo_cre = wsaldo_cre;
                               bdsaldo_deb = wsaldo_deb;
                               bdsaldo_anterior = wsaldo_anterior;
                               bdsaldo_atual = wsaldo_atual;

                               --alt:9179 - N?o estava imprimindo o BDMOVIMENTO para os centros de custos. Pedro
                               bdmovimento = bdsaldo_atual - bdsaldo_anterior;
 
                               bdsaldo_ant_cre_dre = wsaldo_ant_cre_dre;
                               bdsaldo_ant_deb_dre = wsaldo_ant_deb_dre;
                               bdsaldo_anterior_dre = wsaldo_anterior_dre;
                             END
                         ELSE
                             BEGIN
                               bdcodcta  = wconta;
                               bdctalon  = wctalon;
                               bdnomcta  = wnomcta;
                               bdtipcta  = wtipcta;
                               bdclanom  = wclanom;
                               bdgrpcta  = wgrpcta;
                               bdformula = wformula;
                               bdcodtpcc = wcodtpcc;
                               bdnomtpcc = wnomtpcc;
                               bdtpcclon = wtpcclon;

                               bdsaldo_ant_cre = bdsaldo_ant_cre + wsaldo_ant_cre;
                               bdsaldo_ant_deb = bdsaldo_ant_deb + wsaldo_ant_deb;
                               bdsaldo_cre = bdsaldo_cre + wsaldo_cre;
                               bdsaldo_deb = bdsaldo_deb + wsaldo_deb;
                               bdsaldo_anterior = bdsaldo_anterior + wsaldo_anterior;
                               bdsaldo_atual = bdsaldo_atual + wsaldo_atual;

                               --alt:9179 - N?o estava imprimindo o BDMOVIMENTO para os centros de custos. Pedro
                               bdmovimento = bdsaldo_atual - bdsaldo_anterior;
 
                               bdsaldo_ant_cre_dre = bdsaldo_ant_cre_dre + wsaldo_ant_cre_dre;
                               bdsaldo_ant_deb_dre = bdsaldo_ant_deb_dre + wsaldo_ant_deb_dre;
                               bdsaldo_anterior_dre = bdsaldo_anterior_dre + wsaldo_anterior_dre;
                            END
                         wctalonant = wctalon;
                         wcodtpccant = wcodtpcc;
                      END

             --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
             --#alt:11436 - Adicionada condição do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
             --alt:9386 - Adicionado esse suspend porque se ele soma centros de custos iguais, o ?ltimo n?o ? impresso. Pedro
             IF ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                 (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                 (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR (BDTIPCTA = 0) OR (bdformula <> '') OR (prtodoplanocontas = 1)) THEN
                   SUSPEND;
             --alt:9386 - Fim

           END

--        delete from vsuc_empresas_tbalancete_2 where bdcodemp <> 0 and bddatahora = :wdatahora;
        DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;

      END
END
^

/* Alter (VSUC_SP_RETORNA_BALANCETE_COMPA) */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE_COMPA(PRCODEMP VARCHAR(2048),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRTIPCOMP INTEGER,
PRQTDCOMP INTEGER,
PRCODTPCC VARCHAR(2048),
PRIGNZER SMALLINT,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCENTROS INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALANT NUMERIC(15,2),
BDSALATU_01 NUMERIC(15,2),
BDSALMOV_01 NUMERIC(15,2),
BDSALATU_02 NUMERIC(15,2),
BDSALMOV_02 NUMERIC(15,2),
BDSALATU_03 NUMERIC(15,2),
BDSALMOV_03 NUMERIC(15,2),
BDSALATU_04 NUMERIC(15,2),
BDSALMOV_04 NUMERIC(15,2),
BDSALATU_05 NUMERIC(15,2),
BDSALMOV_05 NUMERIC(15,2),
BDSALATU_06 NUMERIC(15,2),
BDSALMOV_06 NUMERIC(15,2),
BDSALATU_07 NUMERIC(15,2),
BDSALMOV_07 NUMERIC(15,2),
BDSALATU_08 NUMERIC(15,2),
BDSALMOV_08 NUMERIC(15,2),
BDSALATU_09 NUMERIC(15,2),
BDSALMOV_09 NUMERIC(15,2),
BDSALATU_10 NUMERIC(15,2),
BDSALMOV_10 NUMERIC(15,2),
BDSALATU_11 NUMERIC(15,2),
BDSALMOV_11 NUMERIC(15,2),
BDSALATU_12 NUMERIC(15,2),
BDSALMOV_12 NUMERIC(15,2))
 AS
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCTALONINI VARCHAR(40);
DECLARE VARIABLE WCTALONFIN VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10240);
BEGIN
  wsql = 'select temp.bdcodemp, temp.bdcnpjemp, temp.bdcodmatriz, ';
  wsql = wsql||'tref.bdnomemp, tref.bdcodplapadrao, tref.bdcodcentros ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join tempresas_ref tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and tref.bdrefemp = (select first 1 tempresas_ref.bdrefemp from tempresas_ref ';
  wsql = wsql||                     'where tempresas_ref.bdrefemp <= '||prrefemp;
  wsql = wsql||                     ' and tempresas_ref.bdcodemp = '||prcodemp;
  wsql = wsql||                     ' order by tempresas_ref.bdrefemp desc) ';
  wsql = wsql||'order by temp.bdcodmatriz, temp.bdcodemp';

  FOR EXECUTE STATEMENT wsql 
      INTO :bdcodemp, :bdcnpjemp, :bdcodmatriz, :bdnomemp, :bdcodplapadrao, :bdcodcentros DO
      BEGIN
        DELETE FROM vsuc_empresas_tbalancete;
        -- verifica??o dos centro de custos selecionados
        IF (prcodtpcc <> '') THEN
           BEGIN
             wsql = 'select tpcc.bdcodtpcc, tpcc.bdnomcta from centros_tpcc tpcc ';
             wsql = wsql||'where tpcc.bdcodcentro = '||bdcodcentros;
             wsql = wsql||' and tpcc.bdcodtpcc in ('||prcodtpcc||') ';
             wsql = wsql||'order by tpcc.bdctalon';
           END
        ELSE
        -- o retorno desse sql deve ser "0" para que o la?o passe pelo menos uma vez pelo c?lculo de saldos,
        -- isso deve acontecer quando n?o h? centro de custo selecionado
           BEGIN
             wsql = 'select first 1 distinct(case when (tpcc.bdcodtpcc <> 0) then 0 end) "bdcodtpcc", tpcc.bdnomcta ';
             wsql = wsql||'from centros_tpcc tpcc ';
             wsql = wsql||'where tpcc.bdcodcentro = '||bdcodcentros;
           END

        FOR EXECUTE STATEMENT wsql
            INTO :bdcodtpcc, :bdnomtpcc DO
            BEGIN
              IF (bdcodtpcc = 0) THEN
                 bdnomtpcc = '';

              FOR SELECT tpla.bdcodtpla, tpla.bdctalon, tpla.bdnomcta, tpla.bdtipcta
                  FROM planos_tpla tpla
                  WHERE tpla.bdcodplapadrao = :bdcodplapadrao
                  ORDER BY tpla.bdctalon
                  INTO :bdcodtpla, :bdctalon, :bdnomcta, :bdtipcta DO
                  BEGIN
                    wcount = 1;
                    WHILE (wcount < (prqtdcomp + 1)) DO
                      BEGIN
                        -- mensal
                        IF (prtipcomp = 0) THEN
                           BEGIN
                             wdata_inicial = addmonth(prdatini, wcount);
                             wdata_final   = addmonth(prdatini, wcount+1)-1;
                           END
                        ELSE
                        -- anual
                           BEGIN
                             wdata_inicial = addyear(prdatini, wcount);
                             wdata_final   = addyear(prdatini, wcount+1)-1;
                           END
              
                        IF (wdata_final <= prdatfin) THEN
                           BEGIN
                             -- janeiro
                             IF (wcount = 1) THEN
                                BEGIN
                                  SELECT tsal.SALDO_ANTERIOR, tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalant, bdsalatu_01;
                                END
                             ELSE
                             -- fevereiro
                             IF (wcount = 2) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_02;
                                END
                             ELSE
                             -- mar?o
                             IF (wcount = 3) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_03;
                                END
                             ELSE
                             -- abril
                             IF (wcount = 4) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_04;
                                END
                             ELSE
                             -- maio
                             IF (wcount = 5) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_05;
                                END
                             ELSE
                             -- junho
                             IF (wcount = 6) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_06;
                                END
                             ELSE
                             -- julho
                             IF (wcount = 7) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_07;
                                END
                             ELSE
                             -- agosto
                             IF (wcount = 8) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_08;
                                END
                             ELSE
                             -- setembro
                             IF (wcount = 9) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_09;
                                END
                             ELSE
                             -- outubro
                             IF (wcount = 10) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_10;
                                END
                             ELSE
                             -- novembro
                             IF (wcount = 11) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_11;
                                END
                             ELSE
                             -- dezembro
                             IF (wcount = 12) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_12;
                                END
      
                             SUSPEND;
                             wcount = wcount +1;
                           END
                      END
                  END
            END
      END
END
^

/* Alter (VSUC_SP_RETORNA_BALANCO_PATRI_X) */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRI_X(PRCODEMP VARCHAR(1024),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRINDICE INTEGER,
PRCODPLAPADRAO INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCTASEMMOV INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDSALANT NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDANAVER NUMERIC(15,2),
BDANAHOR NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20))
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODEMPFILIAL INTEGER;
DECLARE VARIABLE WNOMEMP DM_BDNOMEMP;
DECLARE VARIABLE WCNPJEMP VARCHAR(20);
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCTA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA INTEGER;
DECLARE VARIABLE WFORMULA VARCHAR(1024);
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WAPECTA VARCHAR(20);
DECLARE VARIABLE WSALANT NUMERIC(15,2);
DECLARE VARIABLE WSALATU NUMERIC(15,2);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WVALTIT NUMERIC(15,2);
DECLARE VARIABLE WSEQCTA VARCHAR(100);
DECLARE VARIABLE WCONTAANT INTEGER;
DECLARE VARIABLE WTERCEIROANT INTEGER;
DECLARE VARIABLE WEMPRESAANT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(2048);
BEGIN
  -- retorna a primeira conta referente a classificacao
  SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdctalon = :prctalonini
  ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini;
  -- retorna a ultima conta referente a classificacao
  SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdctalon = :prctalonfin
  ORDER BY planos_tpla.bdctalon ASC INTO :wcodctafin;
    
  DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
  wcontaant = 0;
  wterceiroant = 0;
  wempresaant = 0;

  -- laco do calculo dos saldos do plano de contas
  wSQL = 'select bdcodemp, bdcodmatriz, bdcodempfilial, bdnomemp, bdcnpjemp,';
  wSQL = wSQL||'   bdcodplapadrao, bdcodcta, bdctalon, bdnomcta, bdtipcta, bdformula, bdgrpcta, bdapecta,';
  wSQL = wSQL||'   bdsaldo_anterior, bdsaldo_atual, bdcodter';
  wSQL = wSQL||' from vsuc_sp_retorna_balancete('''||:prcodemp||''', '''||:prdatini||''', '''||:prdatfin||''', '||:prignzer||', '||:wcodctaini||', '||:wcodctafin||', '||:prindice||', '''||''||''', ';
  wSQL = wSQL||'                                '||:prrefemp||', 0, 0, '||:prnaomostracontacomp||', '||:prconsolidada||', '||:prdetalharctaparticipante||', 0, ';
  wSQL = wSQL||'                                '||:prconcatenacodparticipante||', '''||:prniveisconta||''', 0, '||:prcontabilizacao||', 0, '||'0)';
  IF (prmatrizfilialconsolidado = 0) THEN
    wSQL = wSQL||' order by BDCODEMPFILIAL, BDCTALON';
  ELSE
    wSQL = wSQL||' order by BDCTALON, BDCODEMPFILIAL';
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp, :wcodmatriz, :wcodempfilial, :wnomemp, :wcnpjemp,
                                  :wcodplapadrao, :wcodcta, :wctalon, :wnomcta, :wtipcta, :wformula, :wgrpcta, :wapecta,
                                  :wsalant, :wsalatu, :wparticipante DO
  BEGIN
    IF ((((prctasemmov = 0) AND ((bdsalatu <> 0) OR (bdsalmov <> 0))) OR (prctasemmov = 1)) AND
        (((wcontaant > 0) AND (wcontaant <> wcodcta)) OR (wterceiroant <> wparticipante)  OR ((prmatrizfilialconsolidado = 0) AND (wempresaant > 0) AND (wempresaant <> wcodempfilial)))) THEN
      BEGIN
        SUSPEND;
        BDCODEMP = 0;
        BDCODMATRIZ = 0;
        BDCODEMPFILIAL = 0;
        BDNOMEMP = '';
        BDCNPJEMP = '';
        BDCODPLAPADRAO = 0;
        BDCODCTA = 0;
        BDCTALON = '';
        BDNOMCTA = '';
        BDTIPCTA = 0;
        BDSEQCTA = '';
        BDSALANT = 0;
        BDSALMOV = 0;
        BDSALATU = 0;
        BDANAVER = 0;
        BDFORMULA = '';
        BDGRPCTA = 0;
        BDAPECTA = '';
      END

    -- Detalhado por participante
    IF ((prdetalharctaparticipante = 1) AND (wparticipante > 0) AND (bdtipcta = 1) AND (prconcatenacodparticipante = 1)) THEN
      BEGIN
        wpos     = CHARACTER_LENGTH(:wparticipante);
                   -- 100 -> m?ximo de caracteres para nome da conta
                   -- 03 -> qtd de caracteres " - ";
        wpos     = ((100 - wpos) - 3);
        bdnomcta = wparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
      END

    BDCODEMP = wcodemp;
    BDNOMEMP = wnomemp;
    BDCNPJEMP = wcnpjemp;
    BDCODPLAPADRAO = wcodplapadrao;
    BDCODCTA = wcodcta;
    BDCTALON = wctalon;
    BDNOMCTA = wnomcta;
    BDTIPCTA = wtipcta;
    BDAPECTA = wapecta;
    BDSEQCTA = wseqcta;
    BDSALANT = COALESCE(BDSALANT, 0) + wSalAnt;
    BDSALATU = COALESCE(BDSALATU, 0) + wSalAtu;
    BDSALMOV = BDSALATU - BDSALANT;
    BDFORMULA = wformula;
    BDGRPCTA = wgrpcta;

    IF (prmatrizfilialconsolidado = 1) THEN
      BEGIN
        BDCODMATRIZ =  wcodemp;
        BDCODEMPFILIAL = wcodemp;
      END
    ELSE
      BEGIN
        BDCODMATRIZ =  wcodmatriz;
        BDCODEMPFILIAL = wcodempfilial;
      END

    -- sql para verificar se a conta atual ? uma titulo geral
    IF ((POSITION('.', bdctalon) = 0) OR ((prmatrizfilialconsolidado = 0) AND (wempresaant > 0) AND (wempresaant <> wcodempfilial))) THEN
      BEGIN
        wseqcta = bdnomcta;
        IF (bdsalatu IS NULL) THEN
          wvaltit = 0;
        ELSE
          wvaltit = bdsalatu;
      END
    bdseqcta = wseqcta;

    -- c?lculo do percentual da analise vertical
    IF (wvaltit = 0) THEN
      bdanaver = 0;
    ELSE
      bdanaver = (bdsalatu * 100) / wvaltit;

    wcontaant = bdcodcta;
    wterceiroant = wparticipante;
    wempresaant = bdcodempfilial;
  END

  IF ((((prctasemmov = 0) AND ((bdsalatu <> 0) OR (bdsalmov <> 0))) OR (prctasemmov = 1)) AND
     --#alt:16143 - Removida a verifica??o das contas pois quando selecionava apenas uma conta n?o estava sendo mostrada. Ana - 06/02/2017
     --(((wcontaant > 0) and (wcontaant <> wcodcta)) or (wterceiroant <> wparticipante) or ((prmatrizfilialconsolidado = 0) and (wempresaant > 0) and (wempresaant <> wcodempfilial)))) then
       ((wcontaant > 0) OR (wterceiroant <> wparticipante) OR ((prmatrizfilialconsolidado = 0) AND (wempresaant > 0) AND (wempresaant <> wcodempfilial)))) THEN
    SUSPEND;
END
^

/* Alter (VSUC_SP_RETORNA_BALANCO_PATRIMO) */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRIMO(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRCTASEMMOV INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDANAVER NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20))
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(4096);
DECLARE VARIABLE WLENGTH INTEGER;
DECLARE VARIABLE WVALTIT NUMERIC(15,2);
DECLARE VARIABLE WSQLTCC VARCHAR(1024);
DECLARE VARIABLE WSEQCTA VARCHAR(100);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
BEGIN
  wsqlemp = 'select case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos <> 0) THEN
     wsqlemp = wsqlemp||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsqlemp = wsqlemp||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsqlemp = wsqlemp||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsqlemp = wsqlemp||'       end bdcodemp, ';
  wsqlemp = wsqlemp||'       temp.bdcodemp bdcodempfilial, ';
  wsqlemp = wsqlemp||'       tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';

  wdatahora = CURRENT_TIMESTAMP;

  FOR EXECUTE STATEMENT wsqlemp
--      into :wcodemp, :bdcodmatriz, :wcodplapadrao, :wcodcentros do
      INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        IF (bdcodmatriz IS NULL) THEN
           bdcodmatriz = 0;
        -- retorna a primeira conta referente a classificacao
        SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :bdcodplapadrao
        AND planos_tpla.bdctalon = :prctalonini
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini;
        -- retorna a ultima conta referente a classificacao
        SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :bdcodplapadrao
        AND planos_tpla.bdctalon = :prctalonfin
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctafin;
        -- sql responsavel pela limpeza da tabela cache de saldos
        --delete from VSUC_EMPRESAS_TBALANCETE_2; Fabiano: 23/05/2012 N?o pode apagar tudo porque tem outros usu?rios que est?o comitando dados. S? posso apagar o que ? meu.
--        delete from vsuc_empresas_tbalancete_2 where bdcodemp <> 0 and bddatahora = :wdatahora;
        DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
        -- verificacao dos centro de custos selecionados
        IF ((TRIM(prlistacc) <> '') AND (wcodcentros IS NOT NULL)) THEN
           BEGIN
             wsqltcc = 'select tpcc.bdcodtpcc, tpcc.bdnomcta from centros_tpcc tpcc ';
             wsqltcc = wsqltcc||'where tpcc.bdcodcentro = '||wcodcentros;
             wsqltcc = wsqltcc||' and tpcc.bdcodtpcc in ('||prlistacc||')';
           END
        ELSE
        -- o retorno desse sql deve ser 0 para que o laco passe pelo menos uma vez pelo calculo de saldos,
        -- isso deve acontecer quando nao ha centro de custo selecionado
           BEGIN
             wsqltcc = 'select case when (temp.bdcodemp <> 0) then 0 end, tref.bdnomemp ';
             wsqltcc = wsqltcc||'from tempresas temp ';
             wsqltcc = wsqltcc||'inner join tempresas_ref tref on (tref.bdcodemp = temp.bdcodemp) ';
             --Pegava sempre a mesma empresa
             --wsqltcc = wsqltcc||'where temp.bdcodemp = '||bdcodemp;
             wsqltcc = wsqltcc||'where temp.bdcodemp = '||bdcodempfilial;
             wsqltcc = wsqltcc||' and tref.bdrefemp = (select first 1 tempresas_ref.bdrefemp from tempresas_ref ';
             wsqltcc = wsqltcc||                      'where tempresas_ref.bdcodemp = temp.bdcodemp ';
             wsqltcc = wsqltcc||                      'and tempresas_ref.bdrefemp <= '||prrefemp;
             wsqltcc = wsqltcc||                      ' order by tempresas_ref.bdrefemp desc) ';
           END
        -- laco dos centro de custos
        IF (NOT ((bdcodplapadrao IS NULL) AND (wcodcentros IS NULL))) THEN
        FOR EXECUTE STATEMENT wsqltcc
            INTO :bdcodtpcc, :bdnomtpcc DO
            BEGIN
              -- caso nao ha centro de custo selecionado, o nome do mesmo deve ser em branco
              IF (bdcodtpcc = 0) THEN
                 BEGIN
                   bdnomtpcc = '';
                   bdcodcentros = 0;
                 END
              ELSE
                 bdcodcentros = wcodcentros;
              -- laco do calculo dos saldos do plano de contas
              FOR SELECT tsal.codemp, tsal.codplapadrao, tsal.conta, tsal.classificacao,
                         tsal.nomeconta, tsal.tipconta, tsal.saldo_anterior, tsal.saldo_atual,
                         tref.bdnomemp, temp.bdcnpjemp, tsal.formula, tsal.grupoconta, tsal.participante, tsal.apecta
                  FROM vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :wcodctaini, :wcodctafin, :prdatini, :prindice, :prdatfin, :prignzer, :bdcodtpcc, :bdcodplapadrao,
                                                      0,:prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                  LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.codemp)
                  LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                  WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                         WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                         AND tempresas_ref.bdrefemp <= :prrefemp
                                         ORDER BY tempresas_ref.bdrefemp DESC)
                  INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                       :bdsalant, :bdsalatu, :bdnomemp, :bdcnpjemp, :bdformula, :BDGRPCTA,  :wparticipante, :bdapecta DO
              BEGIN
                -- Detalhado por participante
                IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                  BEGIN
                    --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                    FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                        --from vsuc_sp_retorna_saldos_cta_part(:bdcodemp,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,-- alt:#6647 - gilberto - 12/09/2013
                        FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodemp,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                             :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                        INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 03 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                            END

                          -- se a conta for "patrimonio liquido"
                          IF (bdctalon = prctalonpas) THEN
                            BEGIN
                              wseqcta = bdnomcta;
                              IF (bdsalatu IS NULL) THEN
                                wvaltit = 0;
                              ELSE
                                wvaltit = bdsalatu;
                            END
                          bdsalmov = bdsalatu - bdsalant;
                          bdseqcta = wseqcta;
                          -- c?lculo do percentual da analise vertical
                          IF (wvaltit = 0) THEN
                            bdanaver = 0;
                          ELSE
                            bdanaver = (bdsalatu * 100) / wvaltit;

                          SUSPEND;
                        END
                  END
                ELSE
                  BEGIN
                    -- sql para verificar se a conta atual ? uma titulo geral
                    SELECT FIRST 1 tpos.pos FROM pos('.', :bdctalon) tpos INTO :wlength;
                    IF (wlength IS NULL) THEN
                      wlength = 0;
                    -- se a conta for uma "titulo geral" ou "patrimonio liquido"
                    IF ((wlength = 0) OR (bdctalon = prctalonpas)) THEN
                      BEGIN
                        wseqcta = bdnomcta;
                        IF (bdsalatu IS NULL) THEN
                          wvaltit = 0;
                        ELSE
                          wvaltit = bdsalatu;
                      END
                    bdsalmov = bdsalatu - bdsalant;
                    bdseqcta = wseqcta;
                    -- caculo do percentual da analise vertical
                    IF (wvaltit = 0) THEN
                      bdanaver = 0;
                    ELSE
                      bdanaver = (bdsalatu * 100) / wvaltit;

                --alt:7847 - Algu?m, talvez o Gilberto havia comentado esta parte que s? d? o suspend se a conta tiver movimento ou for para imprimir contas sem movimento.
                --Estou descomentando essa parte e comentando a que foi adicionada para imprimir sempre as contas consolidadas, pois pelo que vimos, atualmente n?o faz sentido. Pedro
                IF ((prctasemmov = 0) AND ((bdsalatu <> 0) OR (bdsalmov <> 0)) OR (prctasemmov = 1)) THEN
                   SUSPEND;
--                     gilberto
/*                    if ((not prconsolidada is null) and (prconsolidada <> 0)) then
                      suspend;
                    else
                      begin
                        select bdresult from vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) into :wfind;
                        if ((wfind is null) or (wfind = 0)) then
                          suspend;
                        else
                          if (bdtipcta = 2) then
                            suspend;
                      end*/
                  END
              END
            END
      END
END
^

/* Alter (VSUC_SP_RETORNA_CADASTRO_BEM) */
ALTER PROCEDURE VSUC_SP_RETORNA_CADASTRO_BEM(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMOSTRARDEPRECIADOS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODBEM INTEGER,
BDDATATAXADEPRECIACAO DATE,
BDMESESDEPRECIADOS INTEGER,
BDDEPRECIACAOPERIODO NUMERIC(15,2),
BDDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
BDVALORRESIDUALCONTABIL NUMERIC(15,2),
BDVALORRESIDUALCONTABILMOEDA NUMERIC(15,2))
 AS
DECLARE VARIABLE WCTAINI VARCHAR(40);
DECLARE VARIABLE WCTAFIN VARCHAR(40);
BEGIN
  /* conta inicial */
  SELECT FIRST 1 tpla.bdctalon FROM planos_tpla tpla
  WHERE tpla.bdcodplapadrao = :prcodplapadrao
  AND tpla.bdcodtpla = :prctaini
  INTO :wctaini;
  /* conta final */
  SELECT FIRST 1 tpla.bdctalon FROM planos_tpla tpla
  WHERE tpla.bdcodplapadrao = :prcodplapadrao
  AND tpla.bdcodtpla = :prctafin
  INTO :wctafin;

  /* filtro */
  FOR SELECT tbem.bdcodemp, tbem.bdcodbem FROM empresas_tbem tbem
      LEFT OUTER JOIN planos_tpla tpla ON (tpla.bdcodplapadrao = tbem.bdcodplapadrao AND tpla.bdcodtpla = tbem.bdcodtpla)
      WHERE tbem.bdcodemp = :prcodemp
      --alt:13685 - 08/04/2016 - Implementa??o para mostrar bens totalmente depreciados. Pedro
      AND (((:PRMOSTRARDEPRECIADOS = 0) AND (tbem.bddatoriaquibem BETWEEN :prdatini AND :prdatfin)) OR ((:prmostrardepreciados = 1) AND (tbem.bddatoriaquibem <= :prdatfin)))
      AND tpla.bdctalon BETWEEN :wctaini AND :wctafin
      INTO :bdcodemp, :bdcodbem DO
      BEGIN
        SELECT tcalc.prdatataxadepreciacao,
               tcalc.prmesesdepreciados,
               tcalc.prdepreciacaoperiodo, tcalc.prdepreciacaoacumuladaatual,
               tcalc.prvalorresidualcontabil, tcalc.prvalorresidualcontabilmoeda
        FROM sp_cons_calc_dep(:bdcodemp, :bdcodbem, :prdatini, :prdatfin,0,:prcontabilizacao) tcalc
        WHERE (tcalc.PRMESESDEPRECIAR = 0) OR (:prmostrardepreciados = 0) --alt:13685 - 08/04/2016 - Implementa??o para mostrar bens totalmente depreciados. Pedro
        INTO :bddatataxadepreciacao, :bdmesesdepreciados, :bddepreciacaoperiodo,
             :bddepreciacaoacumuladaatual, :bdvalorresidualcontabil, :bdvalorresidualcontabilmoeda;
        SUSPEND;
      END
END
^

/* Alter (VSUC_SP_RETORNA_COMPARATIVO) */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO(PREMPRESAS VARCHAR(1024),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRINDICE INTEGER,
PRTIPCOMP INTEGER,
PRCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDFORMULA VARCHAR(1024))
 AS
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WFIND INTEGER;
DECLARE VARIABLE WCLASSINI VARCHAR(50);
DECLARE VARIABLE WCLASSFIN VARCHAR(50);
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WSQLUPDATE VARCHAR(10240);
DECLARE VARIABLE WSQLTPCC VARCHAR(10240);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCTA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WNOMTPCC VARCHAR(40);
DECLARE VARIABLE WSALATU NUMERIC(15,2);
DECLARE VARIABLE WMOVIMENTO NUMERIC(15,2);
DECLARE VARIABLE WSALDORELATORIO NUMERIC(15,2);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WSQLCONTAS VARCHAR(10240);
DECLARE VARIABLE WSQLMESES VARCHAR(10240);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
BEGIN
  wdatahora = CURRENT_TIMESTAMP;
  --delete from vsuc_empresas_comparativo;

  wsql = 'select first 1 bdcodplapadrao from vw_empresas_ref_atual  ';
  wsql = wsql||'where bdcodemp in ('||prempresas||') ';
  EXECUTE STATEMENT wsql INTO :wcodplapadrao;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prctaini
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prctafin
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas anal?ticas
  SELECT BDRPOS FROM RPOS(',1,',','||:prniveisconta||',') INTO :wimpanalitica;

  wsql = 'select bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp, bdcodplapadrao ';
  wsql = wsql||'from vw_empresas_ref_atual ';
  wsql = wsql||'where bdcodemp in ('||prempresas||') ';

  wcount    = 0;
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao DO
      BEGIN
        -- giovanni... insere somente as contas com lancamentos

        wsqlcontas = '';
        wsqlcontas = wsqlcontas||' select distinct CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta, CONTAS.bdgrupocta, CONTAS.bdnomcta, CONTAS.bdformula, ';
        --alt:7211 - Alterado de wcodemp para prempresas para passar a empresa matriz e suas filiais, caso sejam informadas. Pedro
        --wsqlcontas = wsqlcontas||' CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS('||wcodemp||', '||wcodplapadrao||','''||prdatini||''','''||prdatfin||''','''||wclassini||''','''||wclassfin||''',0,0,0,3,0) CONTAS ';
        wsqlcontas = wsqlcontas||' CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS('''||prempresas||''', '||wcodplapadrao||','''||prdatini||''','''||prdatfin||''','''||wclassini||''','''||wclassfin||''',0,0,0,3,0) CONTAS ';
        wsqlcontas = wsqlcontas||' order by BDCTALON';


        FOR EXECUTE STATEMENT wsqlcontas
            INTO :wcodcta, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wformula, :wparticipante DO
          BEGIN
            -- Filtro pelo n?vel da conta
            SELECT contar_char FROM contar_char(:wctalon,'.') INTO :wnivelconta;
            wnivelconta = wnivelconta + 1;
            SELECT BDRPOS FROM RPOS(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',') INTO :windice;
            IF ((prniveisconta = '9999') OR           -- N?o tem filtro
                (wnivelconta = 1) OR                  -- O primeiro n?vel sempre imprime
                ((windice > 0) AND (:wtipcta = 0)) OR -- O n?vel da conta foi selecionado no filtro e ? t?tulo
                ((windice > 0) AND (wimpanalitica > 0) AND (:wtipcta = 1))) THEN -- ? do n?vel selecionado, anal?tica e foi selecionado para imprimir as contas anal?ticas
              BEGIN
                -- Tratamento para detalhar participante
                IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (wtipcta = 1)) THEN
                  BEGIN
                    FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdcodparticipante
                        --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfin,:wcodcta,:prignzer,0,1,0, -- alt:#6647 - gilberto - 12/09/2013
                        FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfin,:wcodcta,:prindice,:prignzer,0,1,0,
                                                             :prempresas,:prcontabilizacao,:prmatrizfilialconsolidado) tsalctapar
                        INTO :wnomcta, :wctalon, :wcodparticipante DO
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 03 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              wnomcta = wcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                            END

                          INSERT INTO vsuc_empresas_comparativo (bddatahora, bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp, bdcodplapadrao, bdcodcta,
                                                                 bdctalon, bdtipcta, bdgrpcta, bdnomcta, bdformula)
                          VALUES(:wdatahora, :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao, :wcodcta, :wctalon, :wtipcta, :wgrpcta ,:wnomcta, :wformula);
                        END
                  END
                ELSE
                  BEGIN
                    INSERT INTO vsuc_empresas_comparativo (bddatahora, bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp,
                                                           bdcodplapadrao, bdcodcta, bdctalon, bdtipcta, bdgrpcta, bdnomcta, bdformula)
                    VALUES (:wdatahora, :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao, :wcodcta, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wformula);
                  END
              END
          END
      END

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdatini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatfin FROM 1 FOR 4)||SUBSTRING(prdatfin FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdatini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = CAST(SUBSTRING(prdatfin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdatini FROM 1 FOR 4) AS INTEGER);
       IF (wtotal = 0) THEN
          wtotal = 1;
       ELSE
          wTotal = wTotal +1;
     END

  wcount = 0;
  WHILE (wcount < wtotal) DO
    BEGIN
      -- mensal ________________________________________________________
      IF (prtipcomp = 0) THEN
         BEGIN
           wdata_inicial = addmonth(prdatini, wcount);
           wdata_final   = addmonth(prdatini, wcount+1)-1;
         END
      ELSE
      -- anual _________________________________________________________
         BEGIN
           wdata_inicial = addyear(prdatini, wcount);
           wdata_final   = addyear(prdatini, wcount+1)-1;
         END

      IF (wdata_final <= prdatfin) THEN
         BEGIN
           wsqlmeses = '';
           wsqlmeses = wsqlmeses|| ' select bdcodemp, bdnomemp, bdcnpjemp, bdcodmatriz, bdcodplapadrao, bdcodcta, bdctalon, bdnomcta, bdtipcta, bdgrpcta, bdcodtpcc, bdnomtpcc, ';
           wsqlmeses = wsqlmeses|| ' bdsaldo_atual, bdmovimento ';
           wsqlmeses = wsqlmeses|| ' from vsuc_sp_retorna_balancete(''' || :prempresas || ''', ''' || :wdata_inicial || ''', ''';
           wsqlmeses = wsqlmeses|| :wdata_final || ''', ' || :prignzer || ', ' || :prctaini || ', ' || :prctafin || ', '||:prindice||', ''' ||  :prcc || ''' , ' || :prrefemp || ', ';
           wsqlmeses = wsqlmeses|| :prlansemcc || ', 0, 0, 0,'|| :prdetalharctaparticipante || ',0, '''|| :prniveisconta ||''',0,'||:prcontabilizacao||','||:prmatrizfilialconsolidado||')';

/*
           if (prtiposaldo = 2) then
              wsqlmeses = wsqlmeses|| ' where bdsaldo_atual <> 0';
           else
              wsqlmeses = wsqlmeses|| ' where bdmovimento <> 0';*/
           ----
           FOR EXECUTE STATEMENT wsqlmeses
               INTO :wcodemp, :wnomemp, :wcnpjemp, :wcodmatriz, :wcodplapadrao,
                    :wcodcta, :wctalon, :wnomcta, :wtipcta, :wgrpcta, :wcodtpcc, :wnomtpcc,
                    :wsalatu, :wmovimento DO
           BEGIN
             --alt:7333 - Retirado o filtro, pois agora deve trazer tano o saldo quanto o movimento. Pedro
             /*if (prtiposaldo = 2) then
                wSaldoRelatorio = wsalatu;
             else
                wSaldoRelatorio = wmovimento;*/

             --alt:7333 - Adicionados campos do movimento. Pedro
             wsqlupdate = 'update vsuc_empresas_comparativo set ';
             IF (wcount = 0) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO01 = coalesce(BDSALDO01, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO01 = coalesce(BDMOVIMENTO01, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 1) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO02 = coalesce(BDSALDO02, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO02 = coalesce(BDMOVIMENTO02, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 2) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO03 = coalesce(BDSALDO03, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO03 = coalesce(BDMOVIMENTO03, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 3) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO04 = coalesce(BDSALDO04, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO04 = coalesce(BDMOVIMENTO04, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 4) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO05 = coalesce(BDSALDO05, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO05 = coalesce(BDMOVIMENTO05, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 5) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO06 = coalesce(BDSALDO06, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO06 = coalesce(BDMOVIMENTO06, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 6) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO07 = coalesce(BDSALDO07, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO07 = coalesce(BDMOVIMENTO07, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 7) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO08 = coalesce(BDSALDO08, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO08 = coalesce(BDMOVIMENTO08, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 8) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO09 = coalesce(BDSALDO09, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO09 = coalesce(BDMOVIMENTO09, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 9) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO10 = coalesce(BDSALDO10, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO10 = coalesce(BDMOVIMENTO10, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 10) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO11 = coalesce(BDSALDO11, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO11 = coalesce(BDMOVIMENTO11, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 11) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO12 = coalesce(BDSALDO12, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO12 = coalesce(BDMOVIMENTO12, 0) + '||COALESCE(wMovimento, 0);
                END
             wSqlUpdate = wSqlUpdate||' where bdcodemp = '||wcodemp;
             wSqlUpdate = wSqlUpdate||' and bddatahora = '''||wdatahora||'''';
             wSqlUpdate = wSqlUpdate||' and bdcodcta = '||wcodcta;
             wSqlUpdate = wSqlUpdate||' and bdctalon = '''||wctalon||'''';
             IF (TRIM(prcc) <> '') THEN
                wSqlUpdate = wSqlUpdate||' and bdcodtpcc = '||wcodtpcc;

             EXECUTE STATEMENT wSqlUpdate;
           END
         END
      wcount = wcount + 1;
    END

  -- implementado para que se possa agrupar todas as filiais somando os saldos
  IF (PRAGRUPAEMPRESAFILIAIS = 1) THEN
     BEGIN
       wsql = 'select first 1 bdcodemp, bdcodmatriz, bdcnpjemp, bdnomemp, bdcodplapadrao ';
       wsql = wsql||'from vw_empresas_ref_atual ';
       wsql = wsql||'where bdcodemp in ('||prempresas||') ';
       EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodmatriz, :bdcnpjemp, :bdnomemp, :bdcodplapadrao;

       --alt:7333 - Adicionados campos do movimento. Pedro
       FOR SELECT DISTINCT  tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA, tcomp.BDTIPCTA, tcomp.BDGRPCTA, COALESCE(tcomp.BDCODTPCC, 0), tcomp.BDNOMTPCC, tcomp.bdformula,
                  SUM(COALESCE(tcomp.BDSALDO01, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO01, 0)), SUM(COALESCE(tcomp.BDSALDO02, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO02, 0)),
                  SUM(COALESCE(tcomp.BDSALDO03, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO03, 0)), SUM(COALESCE(tcomp.BDSALDO04, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO04, 0)),
                  SUM(COALESCE(tcomp.BDSALDO05, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO05, 0)), SUM(COALESCE(tcomp.BDSALDO06, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO06, 0)),
                  SUM(COALESCE(tcomp.BDSALDO07, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO07, 0)), SUM(COALESCE(tcomp.BDSALDO08, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO08, 0)),
                  SUM(COALESCE(tcomp.BDSALDO09, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO09, 0)), SUM(COALESCE(tcomp.BDSALDO10, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO10, 0)),
                  SUM(COALESCE(tcomp.BDSALDO11, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO11, 0)), SUM(COALESCE(tcomp.BDSALDO12, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO12, 0))
           FROM vsuc_empresas_comparativo tcomp
           WHERE  (bddatahora = :wdatahora)
           GROUP BY tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA, tcomp.BDTIPCTA, tcomp.BDGRPCTA, tcomp.BDCODTPCC, tcomp.BDNOMTPCC, tcomp.bdformula
           ORDER BY tcomp.bdctalon, tcomp.bdcodtpcc
           --alt:7333 - Adicionados campos do movimento. Pedro
           INTO :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :bdformula,
                :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02,
                :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
                :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06,
                :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
                :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10,
                :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
           BEGIN
             BDQTDCOMP = wtotal;
             --alt:7333 - Adicionados campos do movimento. Pedro
             IF ((BDSALDO01 <> 0 OR BDSALDO02 <> 0 OR BDSALDO03 <> 0 OR BDSALDO04 <> 0 OR
                  BDSALDO05 <> 0 OR BDSALDO06 <> 0 OR BDSALDO07 <> 0 OR BDSALDO08 <> 0 OR
                  BDSALDO09 <> 0 OR BDSALDO10 <> 0 OR BDSALDO11 <> 0 OR BDSALDO12 <> 0) OR
                 (BDMOVIMENTO01 <> 0 OR BDMOVIMENTO02 <> 0 OR BDMOVIMENTO03 <> 0 OR BDMOVIMENTO04 <> 0 OR
                  BDMOVIMENTO05 <> 0 OR BDMOVIMENTO06 <> 0 OR BDMOVIMENTO07 <> 0 OR BDMOVIMENTO08 <> 0 OR
                  BDMOVIMENTO09 <> 0 OR BDMOVIMENTO10 <> 0 OR BDMOVIMENTO11 <> 0 OR BDMOVIMENTO12 <> 0) OR
                 (BDTIPCTA = 0) OR (BDFORMULA <> '')) THEN
                 SUSPEND;
           END
     END
  ELSE
  --alt:7333 - Adicionados campos do movimento. Pedro
  FOR SELECT tcomp.BDCODEMP, tcomp.BDCODMATRIZ, tcomp.BDNOMEMP, tcomp.BDCNPJEMP,
             tcomp.bdcodplapadrao, tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA,
             tcomp.BDTIPCTA, tcomp.BDGRPCTA, COALESCE(tcomp.BDCODTPCC, 0), tcomp.BDNOMTPCC,
             tcomp.BDSALDO01, tcomp.BDMOVIMENTO01, tcomp.BDSALDO02, tcomp.BDMOVIMENTO02,
             tcomp.BDSALDO03, tcomp.BDMOVIMENTO03, tcomp.BDSALDO04, tcomp.BDMOVIMENTO04,
             tcomp.BDSALDO05, tcomp.BDMOVIMENTO05, tcomp.BDSALDO06, tcomp.BDMOVIMENTO06,
             tcomp.BDSALDO07, tcomp.BDMOVIMENTO07, tcomp.BDSALDO08, tcomp.BDMOVIMENTO08,
             tcomp.BDSALDO09, tcomp.BDMOVIMENTO09, tcomp.BDSALDO10, tcomp.BDMOVIMENTO10,
             tcomp.BDSALDO11, tcomp.BDMOVIMENTO11, tcomp.BDSALDO12, tcomp.BDMOVIMENTO12, tcomp.bdformula
      FROM vsuc_empresas_comparativo tcomp
      WHERE  (bddatahora = :wdatahora)
      --alt:7333 - Adicionados campos do movimento. Pedro
      ORDER BY tcomp.bdcodemp, tcomp.bdcodmatriz, tcomp.bdctalon, tcomp.bdcodtpcc
      INTO :BDCODEMP, :bdcodmatriz, :BDNOMEMP, :BDCNPJEMP, :bdcodplapadrao,
           :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC,
           :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02,
           :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
           :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06,
           :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
           :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10,
           :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12, :bdformula DO
      BEGIN
        BDQTDCOMP = wtotal;
        SUSPEND;
      END

  --N?o utiliza mais o "vsuc_empresas_tbalancete", mas sim o "vsuc_empresas_tbalancete_2"
  --delete from vsuc_empresas_tbalancete;
  DELETE FROM vsuc_empresas_comparativo WHERE bdcodemp <> 0 AND bddatahora = :wdatahora;
END
^

/* Alter (VSUC_SP_RETORNA_COMPARATIVO_X) */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO_X(PRCODEMP VARCHAR(255),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATAINI DATE,
PRDATAFIN DATE,
PRINDICE INTEGER,
PRCTASEMMOV INTEGER,
PRIMPRIMIRCOLUNASEXTRAS INTEGER,
PRTIPCOMP INTEGER,
PRCODTPCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRCTACONSOLIDADA INTEGER,
PRFORMACALC INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP VARCHAR(100),
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDFORMULA VARCHAR(1024),
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDMEDIASALDO NUMERIC(15,2),
BDTOTALSALDO NUMERIC(15,2),
BDMEDIAMOVIMENTO NUMERIC(15,2),
BDTOTALMOVIMENTO NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(24000);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  --#alt:20462. Criada nova SP para melhorar o desempenho. A antiga permanecer? para caso houver lentid?es ou erros futuros. Ana - 08/05/2018
  IF (PRFORMACALC = 1) THEN
   BEGIN
     FOR SELECT BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA, BDCODEMPFILIAL,
                BDSALDO01, BDMOVIMENTO01, BDSALDO02, BDMOVIMENTO02, BDSALDO03, BDMOVIMENTO03, BDSALDO04, BDMOVIMENTO04,
                BDSALDO05, BDMOVIMENTO05, BDSALDO06, BDMOVIMENTO06, BDSALDO07, BDMOVIMENTO07, BDSALDO08, BDMOVIMENTO08,
                BDSALDO09, BDMOVIMENTO09, BDSALDO10, BDMOVIMENTO10, BDSALDO11, BDMOVIMENTO11, BDSALDO12, BDMOVIMENTO12,
                BDQTDCOMP
         FROM VSUC_SP_RETORNA_COMPARATIVO_Y(:prcodemp, :prctaini, :prctafin, :prdataini, :prdatafin, :prindice, :prctasemmov, :prtipcomp, :prcodtpcc, :prtiposaldo, :prrefemp, :prignzer,
                                            :prlansemcc, :pragrupaempresafiliais, :prdetalharctaparticipante, :prniveisconta, :prcontabilizacao, :prmatrizfilialconsolidado,
                                            :prctaconsolidada)

      INTO
      :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
      :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
      :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
      :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12,
      :BDQTDCOMP DO
        SUSPEND;

   END
  ELSE
  BEGIN
      -- Caso seja para agrupar as empresas eu busco o c?digo, nome e CNPJ separadamente
      IF (pragrupaempresafiliais = 1) THEN
        BEGIN
          wpos = POSITION(',', :prcodemp);
          IF (wpos <> 0) THEN
            wcodemp = COALESCE(CAST(SUBSTRING(prcodemp FROM 1 FOR (wpos -1)) AS INTEGER),0);
          ELSE
            wcodemp = COALESCE(CAST(:prcodemp AS INTEGER),0);
    
          SELECT emp.bdcodemp,emp.bdcnpjemp,ref.bdnomemp  FROM tempresas emp
          INNER JOIN vw_empresas_ref_atual ref ON (ref.bdcodemp = emp.bdcodemp)
          WHERE (emp.bdcodemp = :wcodemp) INTO :wcodemp, :wcnpjemp, :wnomemp;
        END
    
      -- mensal ____________________________________________________________________
      IF (prtipcomp = 0) THEN
         BEGIN
           wtotal = 0;
           wdata_inicial = prdataini;
           WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafin FROM 1 FOR 4)||SUBSTRING(prdatafin FROM 6 FOR 2) AS INTEGER)) DO
             BEGIN
               wtotal = wtotal + 1;
               wdata_inicial = addmonth(prdataini, wtotal);
             END
         END
      ELSE
      -- anual _____________________________________________________________________
         BEGIN
           wtotal = CAST(SUBSTRING(prdatafin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER);
           IF (wtotal = 0) THEN
              wtotal = 1;
           ELSE
              wTotal = wTotal +1;
         END
    
      wcount = 0;
      WHILE (wcount < wtotal) DO
        BEGIN
          -- mensal ________________________________________________________
          IF (prtipcomp = 0) THEN
             BEGIN
               wdata_inicial = addmonth(prdataini, wcount);
               wdata_final   = addmonth(prdataini, wcount + 1) - 1;
             END
          ELSE
          -- anual _________________________________________________________
             BEGIN
               wdata_inicial = addyear(prdataini, wcount);
               wdata_final   = addyear(prdataini, wcount + 1) - 1;
             END
    
          IF (wsql IS NULL) THEN
             BEGIN
               IF (pragrupaempresafiliais = 1) THEN
                 wsql = 'Select null as BDCODEMP, BDCODPLAPADRAO, BDCODCTA, null as BDCODMATRIZ, null as BDNOMEMP, null as BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,null as BDCODEMPFILIAL,';
               ELSE
                 wsql = 'Select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
    
               wsql = wsql||' sum(coalesce(BDSALDO01, 0)) as BDSALDO01, sum(coalesce(BDMOVIMENTO01, 0)) as BDMOVIMENTO01, sum(coalesce(BDSALDO02, 0)) as BDSALDO02, sum(coalesce(BDMOVIMENTO02, 0)) as BDMOVIMENTO02,';
               wsql = wsql||' sum(coalesce(BDSALDO03, 0)) as BDSALDO03, sum(coalesce(BDMOVIMENTO03, 0)) as BDMOVIMENTO03, sum(coalesce(BDSALDO04, 0)) as BDSALDO04, sum(coalesce(BDMOVIMENTO04, 0)) as BDMOVIMENTO04,';
               wsql = wsql||' sum(coalesce(BDSALDO05, 0)) as BDSALDO05, sum(coalesce(BDMOVIMENTO05, 0)) as BDMOVIMENTO05, sum(coalesce(BDSALDO06, 0)) as BDSALDO06, sum(coalesce(BDMOVIMENTO06, 0)) as BDMOVIMENTO06,';
               wsql = wsql||' sum(coalesce(BDSALDO07, 0)) as BDSALDO07, sum(coalesce(BDMOVIMENTO07, 0)) as BDMOVIMENTO07, sum(coalesce(BDSALDO08, 0)) as BDSALDO08, sum(coalesce(BDMOVIMENTO08, 0)) as BDMOVIMENTO08,';
               wsql = wsql||' sum(coalesce(BDSALDO09, 0)) as BDSALDO09, sum(coalesce(BDMOVIMENTO09, 0)) as BDMOVIMENTO09, sum(coalesce(BDSALDO10, 0)) as BDSALDO10, sum(coalesce(BDMOVIMENTO10, 0)) as BDMOVIMENTO10,';
               wsql = wsql||' sum(coalesce(BDSALDO11, 0)) as BDSALDO11, sum(coalesce(BDMOVIMENTO11, 0)) as BDMOVIMENTO11, sum(coalesce(BDSALDO12, 0)) as BDSALDO12, sum(coalesce(BDMOVIMENTO12, 0)) as BDMOVIMENTO12';
               wsql = wsql||' from (';
             END
          ELSE
             wsql = wsql||' union all ';
    
          IF (wcount = 0) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' bdsaldo_atual as BDSALDO01, bdmovimento as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
          ELSE
          IF (wcount = 1) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, bdsaldo_atual as BDSALDO02, bdmovimento as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE  
           IF (wcount = 2) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' bdsaldo_atual as BDSALDO03, bdmovimento as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 3) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, bdsaldo_atual as BDSALDO04, bdmovimento as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 4) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' bdsaldo_atual as BDSALDO05, bdmovimento as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 5) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, bdsaldo_atual as BDSALDO06, bdmovimento as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 6) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' bdsaldo_atual as BDSALDO07, bdmovimento as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 7) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, bdsaldo_atual as BDSALDO08, bdmovimento as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 8) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' bdsaldo_atual as BDSALDO09, bdmovimento as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 9) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, bdsaldo_atual as BDSALDO10, bdmovimento as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 10) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' bdsaldo_atual as BDSALDO11, bdmovimento as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 11) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, bdsaldo_atual as BDSALDO12, bdmovimento as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
    
          wcount = wcount + 1;
        END
    
      wsql = wsql||' ) group by BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDNOMEMP, BDCODMATRIZ, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA, BDCODEMPFILIAL';
    
      FOR EXECUTE STATEMENT wsql INTO
          :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
          :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
          :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
          :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
        BEGIN
          IF (pragrupaempresafiliais = 1) THEN
            BEGIN
              bdcodemp       = wcodemp;
              bdcnpjemp      = wcnpjemp;
              bdnomemp       = wnomemp;
              bdcodempfilial = bdcodemp;
            END
    
          BDQTDCOMP = wtotal;
    
          IF ((PRFORMACALC = 0) AND (PRIMPRIMIRCOLUNASEXTRAS = 1)) THEN
             BEGIN
               BDTOTALSALDO = (COALESCE(BDSALDO01, 0) + COALESCE(BDSALDO02, 0) + COALESCE(BDSALDO03, 0) + COALESCE(BDSALDO04, 0) + COALESCE(BDSALDO05, 0) + COALESCE(BDSALDO06, 0) +
                               COALESCE(BDSALDO07, 0) + COALESCE(BDSALDO08, 0) + COALESCE(BDSALDO09, 0) + COALESCE(BDSALDO10, 0) + COALESCE(BDSALDO11, 0) + COALESCE(BDSALDO12, 0));
               BDMEDIASALDO = BDTOTALSALDO / wtotal;
    
               BDTOTALMOVIMENTO = (COALESCE(BDMOVIMENTO01, 0) + COALESCE(BDMOVIMENTO02, 0) + COALESCE(BDMOVIMENTO03, 0) + COALESCE(BDMOVIMENTO04, 0) +
                                   COALESCE(BDMOVIMENTO05, 0) + COALESCE(BDMOVIMENTO06, 0) + COALESCE(BDMOVIMENTO07, 0) + COALESCE(BDMOVIMENTO08, 0) +
                                   COALESCE(BDMOVIMENTO09, 0) + COALESCE(BDMOVIMENTO10, 0) + COALESCE(BDMOVIMENTO11, 0) + COALESCE(BDMOVIMENTO12, 0));
               BDMEDIAMOVIMENTO = BDTOTALMOVIMENTO / wtotal;
             END
    
          SUSPEND;
        END
  END
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_COMPARATIVO_X for: VSUC_SP_RETORNA_COMPARATIVO_Y */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO_X(PRCODEMP VARCHAR(255),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATAINI DATE,
PRDATAFIN DATE,
PRINDICE INTEGER,
PRCTASEMMOV INTEGER,
PRIMPRIMIRCOLUNASEXTRAS INTEGER,
PRTIPCOMP INTEGER,
PRCODTPCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRCTACONSOLIDADA INTEGER,
PRFORMACALC INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP VARCHAR(100),
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDFORMULA VARCHAR(1024),
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDMEDIASALDO NUMERIC(15,2),
BDTOTALSALDO NUMERIC(15,2),
BDMEDIAMOVIMENTO NUMERIC(15,2),
BDTOTALMOVIMENTO NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_RETORNA_COMPARATIVO_Y) */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO_Y(PRCODEMP VARCHAR(255),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATAINI DATE,
PRDATAFIN DATE,
PRINDICE INTEGER,
PRCTASEMMOV INTEGER,
PRTIPCOMP INTEGER,
PRCODTPCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRCTACONSOLIDADA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP VARCHAR(100),
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDFORMULA VARCHAR(1024),
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDMEDIASALDO NUMERIC(15,2),
BDTOTALSALDO NUMERIC(15,2),
BDMEDIAMOVIMENTO NUMERIC(15,2),
BDTOTALMOVIMENTO NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(24000);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WCOUNTSQL INTEGER;
DECLARE VARIABLE WNUMEROSALDO VARCHAR(3);
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  -- Caso seja para agrupar as empresas eu busco o c?digo, nome e CNPJ separadamente
  IF (pragrupaempresafiliais = 1) THEN
    BEGIN
      wpos = POSITION(',', :prcodemp);
      IF (wpos <> 0) THEN
        wcodemp = COALESCE(CAST(SUBSTRING(prcodemp FROM 1 FOR (wpos -1)) AS INTEGER),0);
      ELSE
        wcodemp = COALESCE(CAST(:prcodemp AS INTEGER),0);

      SELECT emp.bdcodemp,emp.bdcnpjemp,ref.bdnomemp  FROM tempresas emp
      INNER JOIN vw_empresas_ref_atual ref ON (ref.bdcodemp = emp.bdcodemp)
      WHERE (emp.bdcodemp = :wcodemp) INTO :wcodemp, :wcnpjemp, :wnomemp;
    END

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafin FROM 1 FOR 4)||SUBSTRING(prdatafin FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = CAST(SUBSTRING(prdatafin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER);
       IF (wtotal = 0) THEN
          wtotal = 1;
       ELSE
          wTotal = wTotal +1;
     END

  wcount = 0;
  WHILE (wcount < wtotal) DO
    BEGIN
      -- mensal ________________________________________________________
      IF (prtipcomp = 0) THEN
        BEGIN
          wdata_inicial = addmonth(prdataini, wcount);
          wdata_final   = addmonth(prdataini, wcount + 1) - 1;
        END
      ELSE
      -- anual _________________________________________________________
        BEGIN
          wdata_inicial = addyear(prdataini, wcount);
          wdata_final   = addyear(prdataini, wcount + 1) - 1;
        END


      IF (pragrupaempresafiliais = 1) THEN
        wsql = 'Select null as BDCODEMP, BDCODPLAPADRAO, BDCODCTA, null as BDCODMATRIZ, null as BDNOMEMP, null as BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,null as BDCODEMPFILIAL ';
      ELSE
        wsql = 'Select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL ';

      wCountSQL = 1;
      --sempre deve executar 12 vezes por causa dos campos
      WHILE (wCountSQL <= 12) DO
        BEGIN
          IF (wCountSQL <= 9) THEN
            wNumeroSaldo = '0'||wCountSQL;
          ELSE
            wNumeroSaldo = wCountSQL;

          IF (wCountSQL = (wcount + 1)) THEN
            wsql = wsql||' ,bdsaldo_atual as BDSALDO'||wNumeroSaldo||', bdmovimento as BDMOVIMENTO'||wNumeroSaldo||' ';
          ELSE
            wsql = wsql||' ,null as BDSALDO'||wNumeroSaldo||', null as BDMOVIMENTO'||wNumeroSaldo||' ';

          wCountSQL = wCountSQL + 1;
        END

      wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
      wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
      wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
           
      IF (prCtaSemMov = 0) THEN
        BEGIN
          IF (prTipoSaldo = 0) THEN
            wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
          ELSE
          IF (prTipoSaldo = 1) THEN
            wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
          ELSE
          IF (prTipoSaldo = 2) THEN
            wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
        END

      wcount = wcount + 1;

      FOR EXECUTE STATEMENT wsql INTO
        :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
        :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
        :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
        :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
      BEGIN
        IF (pragrupaempresafiliais = 1) THEN
          BEGIN
            bdcodemp       = wcodemp;
            bdcnpjemp      = wcnpjemp;
            bdnomemp       = wnomemp;
            bdcodempfilial = bdcodemp;
          END
    
        BDQTDCOMP = wtotal;
    
        SUSPEND;
      END
    END
END
^

/* Alter (VSUC_SP_RETORNA_CONTAS_I157) */
ALTER PROCEDURE VSUC_SP_RETORNA_CONTAS_I157(PRCODPLAPADRAO INTEGER,
PRCODPLAPADRAOI157 INTEGER)
 RETURNS(BDCODTPLAI157 INTEGER,
BDCTALONI157 VARCHAR(40),
BDNOMCTAI157 VARCHAR(100),
BDTIPCTA INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDCODTER INTEGER,
BDNOMETER VARCHAR(100))
 AS
DECLARE VARIABLE WSQL DM_MAXVARCHAR;
BEGIN
  wSQL =        ' select CTAI157.BDCODTPLAI157, CTAI157.BDCTALON as BDCTALONI157, CTAI157.BDNOMCTA as BDNOMCTAI157, CTAI157.BDTIPCTA,';
  wSQL = wSQL|| '        CTA.BDCODTPLA, CTA.BDCTALON as BDCTALON, CTA.BDNOMCTA, CTAVINC.BDCODTER, ';
  wSQL = wSQL|| '        (select first 1 BDNOMETER ';
  wSQL = wSQL|| '        from TTERCEIRO_REF PART ';
  wSQL = wSQL|| '        where PART.BDCODTER = CTAVINC.BDCODTER ';
  wSQL = wSQL|| '        order by BDREFEMP desc) as BDNOMETER ';
  wSQL = wSQL|| ' from PLANOS_TPLA_ECD_I157 CTAI157 ';
  wSQL = wSQL|| ' left join PLANOS_TPLA_I157 CTAVINC on (CTAI157.BDCODPLAPADRAO = CTAVINC.BDCODPLAPADRAOECD and';
  wSQL = wSQL|| '                                        CTAI157.BDCODTPLAI157 = CTAVINC.BDCODTPLAI157 and ';
  wSQL = wSQL|| '                                        CTAI157.BDCODPLAPADRAOI157 = CTAVINC.BDCODPLAPADRAOI157)';
  wSQL = wSQL|| ' left join PLANOS_TPLA CTA on (CTAVINC.BDCODPLAPADRAO = CTA.BDCODPLAPADRAO and CTAVINC.BDCODTPLA = CTA.BDCODTPLA) ';
  --wSQL = wSQL|| ' left join TTERCEIRO_REF PART on (CTAVINC.BDCODTER = PART.BDCODTER) ';  --#alt:18661. Ana - 10/05/2017
  wSQL = wSQL|| ' where CTAI157.BDCODPLAPADRAO = ' || PRCODPLAPADRAO;
  IF (PRCODPLAPADRAOI157 > 0) THEN
    wSQL = wSQL|| ' and CTAI157.BDCODPLAPADRAOI157 = ' || PRCODPLAPADRAOI157;

  FOR EXECUTE STATEMENT wSQL INTO :BDCODTPLAI157, :BDCTALONI157, :BDNOMCTAI157, :BDTIPCTA, :BDCODTPLA, :BDCTALON, :BDNOMCTA, :BDCODTER, :BDNOMETER DO
  BEGIN
    SUSPEND;
  END
  /*
  FOR EXECUTE STATEMENT wSQL INTO :BDCODTPLAI157, :BDCTALONI157, :BDNOMCTAI157, :BDTIPCTA, :BDCODTPLA, :BDCTALON, :BDNOMCTA, :BDCODTER, :BDNOMETER DO
  BEGIN
    IF ((BDCODTPLA IS NOT NULL) AND (PRTIPO = 1)) THEN
      BEGIN
        IF (BDCODTER IS NULL) THEN
            wcodter = 0;
        ELSE
            wcodter = bdcodter;

        --#alt:18661 - Adicionei essa verifica??o para n?o ter que executar sempre a consulta, quando for a mesma conta e participante, para aumentar o desempenho. Ana - 10/05/2017
        IF ((WCODTERAUX = wcodter) AND (WCODTPLAAUX = BDCODTPLA)) THEN
          SUSPEND; 
        ELSE
          BEGIN
            wSQLAux = 'select BDSAL'||wmessaldo||' from VSUC_SP_MOVIMENTO_MENSAL('''||PRCODEMP||''', '||BDCODTPLA||', '''', ';
            wSQLAux = wSQLAux||wdatfin||', '||wdatfin||', '||PRREF||','||wcodter||', 1, '||prContabilizacao||', 0)';
            FOR EXECUTE STATEMENT wSQLAux INTO :BDSALANT DO
              SUSPEND;
          END

        WCODTERAUX   = wcodter;
        WCODTPLAAUX  = BDCODTPLA;
      END
    ELSE
      BEGIN
        BDSALANT = 0;
        WCODTPLAAUX  = BDCODTPLA;
        SUSPEND;
      END
  END        */

END
^

/* Alter (VSUC_SP_RETORNA_CONTAS_USADAS) */
ALTER PROCEDURE VSUC_SP_RETORNA_CONTAS_USADAS(PREMPRESAS VARCHAR(1024),
PRCODPLAPADRAO INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRTITULOS INTEGER,
PRORCAMENTO INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRTIPOCONCILIACAO INTEGER,
PRTODASASCONTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDTIPCTA SMALLINT,
BDRELCTA INTEGER,
BDINVERTESINAL VARCHAR(5),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140),
BDFORMULA VARCHAR(200),
BDCONDICAO VARCHAR(100),
BDCONCILIAAUTOMATICA VARCHAR(5),
BDGRUPOCTA INTEGER,
BDPARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WANOINI INTEGER;
DECLARE VARIABLE WANOFIM INTEGER;
BEGIN
 /* Criado giovanni */

  --bdcodemp = prempresas;  alt:7211 - Alterado de wcodemp para prempresas para passar a empresa matriz e suas filiais, caso sejam informadas. Pedro
  wsql = 'select first 1 case when (bdcodmatriz is not null) then bdcodmatriz else bdcodemp end ';
  wsql = wsql||' from tempresas where bdcodemp in ('||prempresas||')';
  EXECUTE STATEMENT wsql INTO :bdcodemp;

  /* adiciona contas a debito */
  wanoini = EXTRACT(YEAR FROM prdataini);
  wanofim = EXTRACT(YEAR FROM prdatafim);

  IF ((prtodasascontas IS NOT NULL) AND (prtodasascontas <> 0)) THEN
    BEGIN
      wsql = '';
      wSql = ' select tpla.BDCODTPLA, tpla.BDCODPLAPADRAO, tpla.bdctalon, tpla.bdnomcta,  tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA,  tpla.BDINVERTESINAL, tpla.BDFILTROGER, ';
      wsql = wsql||' tpla.BDCLANOM,  tpla.BDFORMULA,  tpla.BDCONDICAO,  tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
      wsql = wsql||' from planos_tpla tpla ';
      wsql = wsql||' where tpla.BDCODPLAPADRAO = ' || prcodplapadrao ;

      FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdcodplapadrao, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                            :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
        BEGIN
          SUSPEND;
        END

      EXIT;
    END

  IF (prorcamento <> 1) THEN
     BEGIN
       wsql = 'select tlan.BDDEBITO , ';
       wsql = wsql||' tpla.BDCODPLAPADRAO, tpla.bdctalon, tpla.bdnomcta, ';
       wsql = wsql||' tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA, ';
       wsql = wsql||' tpla.BDINVERTESINAL, tpla.BDFILTROGER, tpla.BDCLANOM, ';
       wsql = wsql||' tpla.BDFORMULA,  tpla.BDCONDICAO, ';
       wsql = wsql||' tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
       wsql = wsql||'from (select x.BDDEBITO, x.bdcodplapadrao, x.bdcodemp';
       wsql = wsql||'      from vsuc_empresas_tlan x ';

       --alt:7211 - Alterado de "bdcodemp = prempresas" para bdcodemp in (prempresas) para selecionar a empresa matriz e suas filiais, caso sejam informadas. Pedro
       --wsql = wsql||'      where x.bddebito is not null and x.bdcodemp = '||prempresas||' and x.bdcodplapadrao = '||prcodplapadrao;
       wsql = wsql||'      where x.bddebito is not null and x.bdcodemp in ('||prempresas||') and x.bdcodplapadrao = '||prcodplapadrao;
       IF (PRDATAINI IS NOT NULL) THEN
          wsql = wsql||'   and (x.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
       -- Filtro do lan?amento conciliado
       /* 0 - Normal | 1 - Conciliados | 2 - N?o conciliados | 3 - Todos */
       IF (prtipoconciliacao = 1) THEN
         wsql = wsql||'    and (Upper(bdconcd) = ''TRUE'') ';
       ELSE
         IF (prtipoconciliacao = 2) THEN
           wsql = wsql||'  and ((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) ';
       -- Fim filtro do lan?amento conciliado
       wsql = wsql||'      group by x.BDDEBITO, x.bdcodplapadrao, x.bdcodemp) tlan ';

       wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.bddebito) ';

       IF (prclassificacao_inicial IS NOT NULL) THEN
          wsql = wsql||'where (tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';
       IF (prnaomostracontacomp = 1) THEN
          wsql = wsql||' and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = ' || '''FALSE''' || ')) ';

       FOR EXECUTE STATEMENT wsql INTO  :bdcodtpla, :bdcodplapadrao, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                                   :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
          BEGIN
            SUSPEND;
          END
     
       /* adiciona contas a credito */

       wsql = 'select tlan.BDCREDITO , ';
       wsql = wsql||' tpla.BDCODPLAPADRAO, tpla.bdctalon, tpla.bdnomcta, ';
       wsql = wsql||' tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA, ';
       wsql = wsql||' tpla.BDINVERTESINAL, tpla.BDFILTROGER, tpla.BDCLANOM, ';
       wsql = wsql||' tpla.BDFORMULA,  tpla.BDCONDICAO, ';
       wsql = wsql||' tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
       wsql = wsql||'from (select x.BDCREDITO, x.bdcodplapadrao, x.bdcodemp ';
       wsql = wsql||'      from vsuc_empresas_tlan x ';

       --alt:7211 - Alterado de "bdcodemp = prempresas" para bdcodemp in (prempresas) para selecionar a empresa matriz e suas filiais, caso sejam informadas. Pedro
       --wsql = wsql||'      where x.bdCREDITO is not null and x.bdcodemp = '||prempresas||' and x.bdcodplapadrao = '||prcodplapadrao;
       wsql = wsql||'      where x.bdCREDITO is not null and x.bdcodemp in ('||prempresas||') and x.bdcodplapadrao = '||prcodplapadrao;
       IF (PRDATAINI IS NOT NULL) THEN
          wsql = wsql||'   and (x.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
       -- Filtro do lan?amento conciliado
       /* 0 - Normal | 1 - Conciliados | 2 - N?o conciliados | 3 - Todos */
       IF (prtipoconciliacao = 1) THEN
         wsql = wsql||'    and (Upper(bdconcc) = ''TRUE'') ';
       ELSE
         IF (prtipoconciliacao = 2) THEN
           wsql = wsql||'  and ((Upper(bdconcc) = ''FALSE'') or (bdconcc is null)) ';
       -- Fim filtro do lan?amento conciliado
       wsql = wsql||'      group by x.BDCREDITO, x.bdcodplapadrao, x.bdcodemp) tlan ';

       wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.bdcredito) ';

       IF (prclassificacao_inicial IS NOT NULL) THEN
          wsql = wsql||'where (tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';

     
       FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdcodplapadrao, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                                   :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
          BEGIN
            SUSPEND;
          END
     END
 
   IF (prorcamento = 1) THEN
      BEGIN
        wSql = ' select distinct tlan.BDCODTPLA , ';
        wsql = wsql||'tpla.BDCODPLAPADRAO, tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA,  tpla.BDINVERTESINAL, tpla.BDFILTROGER, tpla.BDCLANOM, tpla.BDFORMULA,  tpla.BDCONDICAO, ';
        wsql = wsql||'tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
        wsql = wsql||'from VSUC_EMPRESAS_TORC tlan ';
        wsql = wsql||'inner join planos_tpla tpla on tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.BDCODTPLA';

        --alt:7211 - Alterado de "bdcodemp = prempresas" para bdcodemp in (prempresas) para selecionar a empresa matriz e suas filiais, caso sejam informadas. Pedro
        --wsql = wsql||' where tlan.bdcodemp = ' || prEmpresas || ' AND  tlan.BDCODTPLA IS NOT NULL ';
        wsql = wsql||' where tlan.bdcodemp in ('||prempresas||') AND  tlan.BDCODTPLA IS NOT NULL ';
        wsql = wsql||' and tpla.BDCODPLAPADRAO = ' || prcodplapadrao ;
        IF (PRDATAINI IS NOT NULL) THEN
           wsql = wsql || ' and (tlan.bdano between '||wanoini||' and '||wanofim||') ';
        IF (prclassificacao_inicial IS NOT NULL) THEN
           wsql = wsql||' and (tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';
  
        FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdcodplapadrao, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                                :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
          BEGIN
            SUSPEND;
          END
      END
 
   /* adiciona contas titulo */
   IF (prtitulos = 0) THEN
      BEGIN
        wSql = ' select tpla.BDCODTPLA , ';
        wsql = wsql||'tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA, tpla.BDINVERTESINAL, tpla.BDFILTROGER, tpla.BDCLANOM, tpla.BDFORMULA,  tpla.BDCONDICAO, ';
        wsql = wsql||'tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
        wsql = wsql||'from planos_tpla tpla ';
--        wsql = wsql||' where tpla.BDCODPLAPADRAO = ' || prcodplapadrao || ' AND tpla.BDTIPCTA in (0,2) ';-- gilberto - 17/05/2011 - incluido as contas consolidadas
--        wsql = wsql||' where tpla.BDCODPLAPADRAO = ' || prcodplapadrao || ' AND ((tpla.BDTIPCTA in (0,2)) or ((tpla.BDTIPCTA = 1) AND (TPLA.bdformula IS NOT NULL))) ';--
        wsql = wsql||' where tpla.BDCODPLAPADRAO = '||prcodplapadrao||' AND ((tpla.BDTIPCTA in (0,2)) or ((tpla.BDTIPCTA = 1) AND (TPLA.bdformula <> ''''))) ';-- GIOVANNI - 27/04/2012 - incluido as com formulas
        IF (prnaomostracontacomp = 1) THEN
            wsql = wsql||' and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = ' || '''FALSE''' || ')) ';

        IF ((prclassificacao_inicial IS NOT NULL) AND (prclassificacao_final IS NOT NULL)) THEN
           wsql = wsql||' and (tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';


        FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                                :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
          BEGIN
            SUSPEND;
          END
      END
END
^

/* Alter (VSUC_SP_RETORNA_CONTR_PATRIMON) */
ALTER PROCEDURE VSUC_SP_RETORNA_CONTR_PATRIMON(PRCODEMP VARCHAR(2048),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRMODELO INTEGER,
PRTIPO INTEGER,
PRCODPLAPADRAO INTEGER,
PRREFEMP INTEGER,
PRMOSTRADEPRECIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRDETALHARTAXADEP INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMTPLA VARCHAR(100),
BDCODFOR INTEGER,
BDNOMFOR VARCHAR(100),
BDCODCC INTEGER,
BDCTALONCC VARCHAR(20),
BDNOMCC VARCHAR(40),
BDVALORCORRIGIDOANTERIOR NUMERIC(15,2),
BDCORRECAOPERIODO NUMERIC(15,2),
BDVALORCORRIGIDOATUAL NUMERIC(15,2),
BDDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
BDDEPRECIACAOPERIODO NUMERIC(15,2),
BDDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
BDDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
BDDEPRECIACAOACUMULADAATUALMOE NUMERIC(15,6),
BDCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
BDVALORRESIDUALCONTABIL NUMERIC(15,2),
BDVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
BDTOTALMESESDEPRECIACAO INTEGER,
BDMESESDEPRECIADOS INTEGER,
BDMESESDEPRECIAR INTEGER,
BDTAXADEPRECIACAOANUAL NUMERIC(6,6),
BDDATATAXADEPRECIACAO DATE,
BDREFERENCIA VARCHAR(7),
BDNATBEM VARCHAR(20),
BDESPECIE VARCHAR(20),
BDDATAAQUISICAO DATE,
BDVALORMOEDA NUMERIC(15,6),
BDVALORAQUISICAOMOEDA NUMERIC(15,6),
BDVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
BDVALORAQUISICAOORIGINAL NUMERIC(15,2),
BDVALORBAIXA NUMERIC(15,2),
BDSOMARDEPRECIACAO INTEGER,
BDCODORIGBEM INTEGER,
BDTIPOBEM INTEGER,
BDCLACOD VARCHAR(10),
BDULTIMOAGREGADO INTEGER)
 AS
DECLARE VARIABLE WCTALONINI VARCHAR(40);
DECLARE VARIABLE WCTALONFIN VARCHAR(40);
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODBEM INTEGER;
DECLARE VARIABLE WNOMBEM VARCHAR(200);
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMTPLA VARCHAR(100);
DECLARE VARIABLE WCODFOR INTEGER;
DECLARE VARIABLE WNOMFOR VARCHAR(100);
DECLARE VARIABLE WCODCC INTEGER;
DECLARE VARIABLE WCCLON VARCHAR(20);
DECLARE VARIABLE WNOMCC VARCHAR(40);
DECLARE VARIABLE WDATE DATE;
DECLARE VARIABLE WDATAUX VARCHAR(7);
DECLARE VARIABLE WVALORAQUISICAO NUMERIC(15,2);
DECLARE VARIABLE WCORRECAOPERIODO NUMERIC(15,2);
DECLARE VARIABLE WVALORCORRIGIDOATUAL NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,2);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,2);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,2);
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WTAXADEPRECIACAOANUAL NUMERIC(6,6);
DECLARE VARIABLE WDATATAXADEPRECIACAO DATE;
DECLARE VARIABLE WDATINI DATE;
DECLARE VARIABLE WDATFIN DATE;
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WNATBEM INTEGER;
DECLARE VARIABLE WESPECIE VARCHAR(20);
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODAUX INTEGER;
BEGIN
  WCODAUX = 0;

  SELECT FIRST 1 TPLA.BDCTALON
  FROM PLANOS_TPLA TPLA
  WHERE TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO AND
        ((TPLA.BDCODTPLA = :PRCTAINI) OR (:PRCTAINI IS NULL))
  ORDER BY BDCTALON ASC
  INTO :WCTALONINI;

  SELECT FIRST 1 TPLA.BDCTALON
  FROM PLANOS_TPLA TPLA
  WHERE TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO AND
        ((TPLA.BDCODTPLA = :PRCTAFIN) OR (:PRCTAFIN IS NULL))
  ORDER BY BDCTALON DESC
  INTO :WCTALONFIN;

  -- retorna as empresas selecionadas
  WSQL = 'select case when (bdcodmatriz is null) then bdcodemp ';
  SELECT POS
  FROM POS(',', :PRCODEMP)
  INTO :WPOS;
  IF (WPOS = 0) THEN
    SELECT POS
    FROM POS('=', :PRCODEMP)
    INTO :WPOS;
  IF (WPOS <> 0) THEN
    WSQL = WSQL || '            when (bdcodmatriz is not null) then bdcodmatriz ';
  ELSE
  BEGIN
    WSQL = WSQL || '          when ((bdcodmatriz is not null) and (bdcodemp not in (' || PRCODEMP || '))) then bdcodmatriz ';
    WSQL = WSQL || '          when (bdcodemp in (' || PRCODEMP || ')) then bdcodemp ';
  END
  WSQL = WSQL || '       end bdcodemp, ';
  WSQL = WSQL || '       bdcodemp bdcodempfilial, ';
  WSQL = WSQL || '       bdcodmatriz, bdnomemp ';
  --  wsql = wsql||'from tempresas temp ';
  WSQL = WSQL || 'from vw_empresas_ref_atual ';
  --  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  SELECT POS
  FROM POS('=', :PRCODEMP)
  INTO :WPOS;
  IF (WPOS <> 0) THEN
    WSQL = WSQL || 'where ' || PRCODEMP;
  ELSE
    WSQL = WSQL || 'where bdcodemp in (' || PRCODEMP || ') ';
  WSQL = WSQL || ' order by bdcodmatriz asc, bdcodemp asc ';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT WSQL
          INTO :BDCODEMP, :BDCODEMPFILIAL, :BDCODMATRIZ, :BDNOMEMP
  DO
  BEGIN

    IF (PRMODELO IN (0, 1, 3)) THEN
    BEGIN
      /*
       wsql = 'select temp.bdcodemp, tbem.bdcodbem, tbem.bdnombem, tpla.bdcodtpla, ';
       wsql = wsql||' tpla.bdctalon,  tpla.bdnomcta, tfor.bdcodter, tfor.bdnometer, ';
       wsql = wsql||' tbem.bddatoriaquibem, tcc.bdcodtpcc, tcc.bdctalon, tcc.bdnomcta, ';
       wsql = wsql||' tbem.bdnatbem, tbem.BDDATORIAQUIBEM, tbem.bdidbem ';
       wsql = wsql||'from empresas_tbem tbem ';
       wsql = wsql||'inner join tempresas temp on (temp.bdcodemp = tbem.bdcodemp) ';
       wsql = wsql||'left outer join planos_tpla tpla on (tpla.bdcodplapadrao = tbem.bdcodplapadrao and tpla.bdcodtpla = tbem.bdcodtpla) ';
       wsql = wsql||'left outer join tterceiro_ref tfor on (tfor.bdcodter = tbem.bdcodter and tfor.bdrefemp = (select first 1 tfr.bdrefemp from tterceiro_ref tfr ';
       wsql = wsql||                                                                                          'where tfr.bdcodter = tfor.bdcodter ';
       wsql = wsql||                                                                                          'and tfr.bdrefemp <= '||prrefemp;
       wsql = wsql||                                                                                         ' order by tfr.bdrefemp desc)) ';
       wsql = wsql||'left outer join centros_tpcc tcc on (tcc.bdcodcentro = tbem.bdcodcentro and tcc.bdcodtpcc = tbem.bdcodtpcc) ';
       wsql = wsql||'where tbem.bdcodemp = '||prcodemp;
       wsql = wsql||'and tbem.bdcodplapadrao = '||prcodplapadrao;
       if (prtipo <> 0) then
          wsql = wsql||' and tbem.BDDATORIAQUIBEM between '''||prdatini||''' and '''||prdatfin||''' ';
       wsql = wsql||' and (tpla.bdctalon between '''||wctalonini||''' and '''||wctalonfin||''') ';
       wsql = wsql||'order by tpla.bdcodtpla';

       for execute statement wsql*/

      --#alt:17098 - Adicionado os campos bdcodorigbem, bdtipobem e bdultimoagregado para os par?metros de sa?da. Ana - 09/05/2017
      --#alt:15304 - Adicionado novo campo no select BDVALAQUIBEM. Ana - 26/08/2016
      FOR SELECT TEMP.BDCODEMP, TBEM.BDCODBEM, TBEM.BDNOMBEM, TPLA.BDCODTPLA, TPLA.BDCTALON, TPLA.BDNOMCTA,
                 TFOR.BDCODTER, TFOR.BDNOMETER, TBEM.BDDATORIAQUIBEM, TCC.BDCODTPCC, TCC.BDCTALON, TCC.BDNOMCTA,
                 TBEM.BDNATBEM, TBEM.BDDATORIAQUIBEM, TBEM.BDIDPATRBEM, TBEM.BDVALAQUIBEM, TBEM.BDCODORIGBEM,
                 TBEM.BDTIPOBEM,
                 (SELECT MAX(BEM2.BDCODBEM)
                  FROM EMPRESAS_TBEM BEM2
                  WHERE BEM2.BDCODORIGBEM = TBEM.BDCODORIGBEM) AS BDULTIMOAGREGADO
          FROM EMPRESAS_TBEM TBEM
          INNER JOIN TEMPRESAS TEMP ON (TEMP.BDCODEMP = TBEM.BDCODEMP)
          LEFT OUTER JOIN PLANOS_TPLA TPLA ON (TPLA.BDCODPLAPADRAO = TBEM.BDCODPLAPADRAO AND TPLA.BDCODTPLA = TBEM.BDCODTPLA)
          LEFT OUTER JOIN TTERCEIRO_REF TFOR ON (TFOR.BDCODTER = TBEM.BDCODTER AND TFOR.BDREFEMP = (SELECT FIRST 1 TFR.BDREFEMP
                                                                                                    FROM TTERCEIRO_REF TFR
                                                                                                    WHERE TFR.BDCODTER = TFOR.BDCODTER AND
                                                                                                          TFR.BDREFEMP <= :PRREFEMP
                                                                                                    ORDER BY TFR.BDREFEMP DESC))
          LEFT OUTER JOIN CENTROS_TPCC TCC ON (TCC.BDCODCENTRO = TBEM.BDCODCENTRO AND TCC.BDCODTPCC = TBEM.BDCODTPCC)
          WHERE TBEM.BDCODEMP = :BDCODEMPFILIAL AND
                TBEM.BDCODPLAPADRAO = :PRCODPLAPADRAO AND
                (TPLA.BDCTALON BETWEEN :WCTALONINI AND :WCTALONFIN)
          ORDER BY TPLA.BDCODTPLA
          INTO :WCODEMP, :WCODBEM, :WNOMBEM, :WCODTPLA, :WCTALON, :WNOMTPLA, :WCODFOR, :WNOMFOR, :WDATA, :WCODCC,
               :WCCLON, :WNOMCC, :WNATBEM, :WDATAAQUISICAO, :WESPECIE, :WVALORAQUISICAO, :BDCODORIGBEM, :BDTIPOBEM,
               :BDULTIMOAGREGADO
      DO
      BEGIN
        IF ((((WDATAAQUISICAO >= PRDATINI) AND
            (WDATAAQUISICAO <= PRDATFIN)) AND
            (PRTIPO <> 0)) OR ((WDATAAQUISICAO <= PRDATFIN) AND
            ((PRTIPO = 0) OR (PRTIPO = 2)))) THEN
        BEGIN
          FOR SELECT PRVALORCORRIGIDOANTERIOR, PRVALORCORRIGIDOANTERIORMOEDA, PRCORRECAOPERIODO, PRVALORCORRIGIDOATUAL,
                     PRDEPRECIACAOACUMULADAANTERIOR, PRDEPRECIACAOPERIODO, PRDEPRECIACAOPERIODOMOEDA,
                     PRDEPRECIACAOACUMULADAATUAL, PRDEPRECIACAOACUMULADAATUALMOED, PRCORRECAOMONETARIADEPRECIACAO,
                     PRVALORRESIDUALCONTABIL, PRVALORRESIDUALCONTABILMOEDA, PRTOTALMESESDEPRECIACAO, PRMESESDEPRECIADOS,
                     PRMESESDEPRECIAR, PRTAXADEPRECIACAOANUAL, PRDATATAXADEPRECIACAO, PRVALORBAIXA, PRDATABAIXA,
                     PRDEPRECIACAOBAIXAMOEDA, PRVALORMOEDA, PRVALORAQUISICAOMOEDA, PRVALORAQUISICAOORIGINAL,
                     PRSOMARDEPRECIACAO
              FROM SP_CONS_CALC_DEP(:WCODEMP, :WCODBEM, :PRDATINI, :PRDATFIN, :PRTIPO, :PRCONTABILIZACAO, :PRDETALHARTAXADEP)
              INTO :BDVALORCORRIGIDOANTERIOR, :BDVALORCORRIGIDOANTERIORMOEDA, :BDCORRECAOPERIODO,
                   :BDVALORCORRIGIDOATUAL, :BDDEPRECIACAOACUMULADAANTERIOR, :BDDEPRECIACAOPERIODO,
                   :BDDEPRECIACAOPERIODOMOEDA, :BDDEPRECIACAOACUMULADAATUAL, :BDDEPRECIACAOACUMULADAATUALMOE,
                   :BDCORRECAOMONETARIADEPRECIACAO, :BDVALORRESIDUALCONTABIL, :BDVALORRESIDUALCONTABILMOEDA,
                   :BDTOTALMESESDEPRECIACAO, :BDMESESDEPRECIADOS, :BDMESESDEPRECIAR, :BDTAXADEPRECIACAOANUAL,
                   :BDDATATAXADEPRECIACAO, :WVALORBAIXA, :WDATABAIXA, :WDEPRECIACAOBAIXAMOEDA, BDVALORMOEDA,
                   BDVALORAQUISICAOMOEDA, BDVALORAQUISICAOORIGINAL, BDSOMARDEPRECIACAO
          DO
          BEGIN
            BDCODEMP = WCODEMP;
            BDCODBEM = WCODBEM;
            BDNOMBEM = WNOMBEM;
            BDCODTPLA = WCODTPLA;
            BDCTALON = WCTALON;
            --#alt:17098. Ana - 09/05/2017
            IF (BDCODORIGBEM > 0) THEN
              IF (BDCODBEM < 10) THEN 
                BDCLACOD = CAST(BDCODORIGBEM AS VARCHAR(10)) || '.0' || CAST(BDCODBEM AS VARCHAR(10));
              ELSE
                BDCLACOD = CAST(BDCODORIGBEM AS VARCHAR(10)) || '.'  || CAST(BDCODBEM AS VARCHAR(10));
            ELSE
              BDCLACOD = CAST(BDCODBEM AS VARCHAR(10));
            BDNOMTPLA = WNOMTPLA;
            BDCODFOR = WCODFOR;
            BDNOMFOR = WNOMFOR;
            BDCODCC = WCODCC;
            BDCTALONCC = WCCLON;
            BDNOMCC = WNOMCC;
            BDVALORBAIXA = WVALORBAIXA;

            IF (BDCODCC IS NULL) THEN
              BDCODCC = 0;

            IF (WNATBEM = 0) THEN
              BDNATBEM = 'Bem original';
            ELSE
            IF (WNATBEM = 1) THEN
              BDNATBEM = 'Aquisi??o parcial';
            ELSE
            IF (WNATBEM = 2) THEN
              BDNATBEM = 'Reavalia??o';
            ELSE
            IF (WNATBEM = 3) THEN
              BDNATBEM = 'Transfer?ncia';
            BDESPECIE = WESPECIE;
            BDDATAAQUISICAO = WDATAAQUISICAO;
            BDESPECIE = WESPECIE;

            --                        if ((prtipo = 2) and ((wvalorbaixa is not null) and (wvalorbaixa > 0))) then
            --                           begin
            --                             bdvalorcorrigidoanterior = wvalorbaixa;
            --                             bdvalorcorrigidoatual = wdepreciacaobaixamoeda;
            --                           end

            --                        suspend;

            IF (BDDEPRECIACAOPERIODO > 0) THEN
            BEGIN

              IF (PRTIPO = 2) THEN
              BEGIN
                IF ((WVALORBAIXA IS NOT NULL) AND
                    (WVALORBAIXA > 0)) THEN
                BEGIN
                  IF ((WDATABAIXA >= PRDATINI) AND
                      (WDATABAIXA <= PRDATFIN)) THEN
                  BEGIN
                    BDVALORCORRIGIDOANTERIOR = WVALORBAIXA;
                    BDVALORCORRIGIDOATUAL = WVALORBAIXA;

                    --#alt:85169. Esta sendo impresso o campo BDVALORAQUISICAOORIGINAL quando o tipo ? o 2, n?o sei quando foi alterado o campo no relat?rio. Ana - 20/06/2018
                    BDVALORAQUISICAOORIGINAL = WVALORBAIXA;
                    BDVALORCORRIGIDOANTERIORMOEDA = (WVALORBAIXA * BDVALORMOEDA);

                    IF (BDCODMATRIZ > 0) THEN
                      BDCODEMP = BDCODMATRIZ;
                    SUSPEND;
                  END
                END
              END
              ELSE
              BEGIN
                IF (BDTOTALMESESDEPRECIACAO > 0) THEN
                BEGIN
                  IF (BDCODMATRIZ > 0) THEN
                    BDCODEMP = BDCODMATRIZ;

                  SUSPEND;
                END
              END
            END
            ELSE
            BEGIN
              -- somente quando no relatorio esta para sair bens que nao tiveram depreciacao
              IF ((BDMESESDEPRECIADOS = 0) OR (PRMOSTRADEPRECIADOS = 1)) THEN
              BEGIN
                IF (BDCODMATRIZ > 0) THEN
                  BDCODEMP = BDCODMATRIZ;

                -- #alt:15304 - Quando o bem n?o tem deprecia??o cadastrada n?o temos como saber se ? do fiscal ou societ?rio. Nesse caso o bem deve aparecer para os dois modelos de contabiliza??o. Ana - 26/08/2016
                IF ((BDVALORAQUISICAOORIGINAL = 0) AND
                    (BDVALORRESIDUALCONTABIL = 0)) THEN
                BEGIN
                  BDVALORAQUISICAOORIGINAL = WVALORAQUISICAO;
                  BDVALORRESIDUALCONTABIL = WVALORAQUISICAO;
                END

                --#alt:17098 - Quando era o relat?rio de rela??o de baixas estava mostrando os bens mesmo sem baixas.  Ana - 09/05/2017
                IF (((PRTIPO = 2) AND ((WVALORBAIXA IS NOT NULL) AND (WVALORBAIXA > 0)) AND ((WDATABAIXA >= PRDATINI) AND (WDATABAIXA <= PRDATFIN))) OR
                   (PRTIPO <> 2)) THEN
                  SUSPEND;
              END
            END

          END
        END
      END
    END
    ELSE
    BEGIN
      /*
       wsql = 'select temp.bdcodemp, tbem.bdcodbem, tbem.bdnombem, tpla.bdcodtpla, ';
       wsql = wsql||' tpla.bdctalon,  tpla.bdnomcta, tfor.bdcodter, tfor.bdnometer, ';
       wsql = wsql||' tbem.bddatoriaquibem, tcc.bdcodtpcc, tcc.bdctalon, tcc.bdnomcta, ';
       wsql = wsql||' tbem.bdnatbem, tbem.bdidbem ';
       wsql = wsql||'from empresas_tbem tbem ';
       wsql = wsql||'inner join tempresas temp on (temp.bdcodemp = tbem.bdcodemp) ';
       wsql = wsql||'left outer join planos_tpla tpla on (tpla.bdcodplapadrao = tbem.bdcodplapadrao and tpla.bdcodtpla = tbem.bdcodtpla) ';
       wsql = wsql||'left outer join tterceiro_ref tfor on (tfor.bdcodter = tbem.bdcodter and tfor.bdrefemp = (select first 1 tfr.bdrefemp from tterceiro_ref tfr ';
       wsql = wsql||                                                                                          'where tfr.bdcodter = tfor.bdcodter ';
       wsql = wsql||                                                                                          'and tfr.bdrefemp <= '||prrefemp;
       wsql = wsql||                                                                                         ' order by tfr.bdrefemp desc)) ';
       wsql = wsql||'left outer join centros_tpcc tcc on (tcc.bdcodcentro = tbem.bdcodcentro and tcc.bdcodtpcc = tbem.bdcodtpcc) ';
       wsql = wsql||'where tbem.bdcodemp = '||prcodemp||' ';
       wsql = wsql||'and tbem.bdcodplapadrao = '||prcodplapadrao;
--               and substring(cast(tbem.bddataquibem as varchar(10)) from 1 for 7) = :wdataux
       if (prtipo <> 0) then
          wsql = wsql||' and tbem.BDDATORIAQUIBEM between '''||prdatini||''' and '''||prdatfin||''' ';
       wsql = wsql||' and (tpla.bdctalon between '''||wctalonini||''' and '''||wctalonfin||''') ';
       wsql = wsql||'order by tpla.bdcodtpla';
       for execute statement wsql*/

      --#alt:17098 - Adicionado os campos bdcodorigbem, bdtipobem e bdultimoagregado para os par?metros de sa?da. Ana - 09/05/2017
      --#alt:15304 - Adicionado novo campo no select BDVALAQUIBEM. Ana - 26/08/2016
      FOR SELECT TEMP.BDCODEMP, TBEM.BDCODBEM, TBEM.BDNOMBEM, TPLA.BDCODTPLA, TPLA.BDCTALON, TPLA.BDNOMCTA,
                 TFOR.BDCODTER, TFOR.BDNOMETER, TBEM.BDDATORIAQUIBEM, TCC.BDCODTPCC, TCC.BDCTALON, TCC.BDNOMCTA,
                 TBEM.BDNATBEM, TBEM.BDIDPATRBEM, TBEM.BDDATORIAQUIBEM, TBEM.BDVALAQUIBEM, TBEM.BDCODORIGBEM,
                 TBEM.BDTIPOBEM,
                 (SELECT MAX(BEM2.BDCODBEM)
                  FROM EMPRESAS_TBEM BEM2
                  WHERE BEM2.BDCODORIGBEM = TBEM.BDCODORIGBEM) AS BDULTIMOAGREGADO
          FROM EMPRESAS_TBEM TBEM
          INNER JOIN TEMPRESAS TEMP ON (TEMP.BDCODEMP = TBEM.BDCODEMP)
          LEFT OUTER JOIN PLANOS_TPLA TPLA ON (TPLA.BDCODPLAPADRAO = TBEM.BDCODPLAPADRAO AND TPLA.BDCODTPLA = TBEM.BDCODTPLA)
          LEFT OUTER JOIN TTERCEIRO_REF TFOR ON (TFOR.BDCODTER = TBEM.BDCODTER AND TFOR.BDREFEMP = (SELECT FIRST 1 TFR.BDREFEMP
                                                                                                    FROM TTERCEIRO_REF TFR
                                                                                                    WHERE TFR.BDCODTER = TFOR.BDCODTER AND
                                                                                                          TFR.BDREFEMP <= :PRREFEMP
                                                                                                    ORDER BY TFR.BDREFEMP DESC))
          LEFT OUTER JOIN CENTROS_TPCC TCC ON (TCC.BDCODCENTRO = TBEM.BDCODCENTRO AND TCC.BDCODTPCC = TBEM.BDCODTPCC)
          WHERE TBEM.BDCODEMP = :BDCODEMPFILIAL AND
                TBEM.BDCODPLAPADRAO = :PRCODPLAPADRAO AND
                (TPLA.BDCTALON BETWEEN :WCTALONINI AND :WCTALONFIN)
          ORDER BY TPLA.BDCODTPLA
          INTO :WCODEMP, :WCODBEM, :WNOMBEM, :WCODTPLA, :WCTALON, :WNOMTPLA, :WCODFOR, :WNOMFOR, :WDATA, :WCODCC,
               :WCCLON, :WNOMCC, :WNATBEM, :WESPECIE, :WDATAAQUISICAO, :WVALORAQUISICAO, :BDCODORIGBEM, :BDTIPOBEM,
               :BDULTIMOAGREGADO
      DO
      BEGIN
        --             if ((((wdataaquisicao >= prdatini) and (wdataaquisicao <= prdatfin)) and (prtipo <> 0)) or ((prtipo = 0) or (prTipo = 2))) then
        IF ((((WDATAAQUISICAO >= PRDATINI) AND
            (WDATAAQUISICAO <= PRDATFIN)) AND
            (PRTIPO <> 0)) OR ((WDATAAQUISICAO <= PRDATFIN) AND
            ((PRTIPO = 0) OR (PRTIPO = 2)))) THEN
        BEGIN
          WDATE = PRDATINI;
          WDATAUX = SUBSTRING(CAST(WDATE AS VARCHAR(10)) FROM 1 FOR 7);

          WHILE (WDATE < PRDATFIN) DO
          BEGIN
            WDATINI = CAST(WDATAUX || '-01' AS DATE);
            WDATFIN = ADDMONTH(WDATINI, 1) - 1;

            BDVALORCORRIGIDOANTERIOR = 0;
            BDVALORCORRIGIDOANTERIORMOEDA = 0;
            BDCORRECAOPERIODO = 0;
            BDVALORCORRIGIDOATUAL = 0;
            BDDEPRECIACAOACUMULADAANTERIOR = 0;
            BDDEPRECIACAOPERIODO = 0;
            BDDEPRECIACAOPERIODOMOEDA = 0;
            BDDEPRECIACAOACUMULADAATUAL = 0;
            BDDEPRECIACAOACUMULADAATUALMOE = 0;
            BDCORRECAOMONETARIADEPRECIACAO = 0;
            BDVALORRESIDUALCONTABIL = 0;
            BDVALORRESIDUALCONTABILMOEDA = 0;
            BDTOTALMESESDEPRECIACAO = 0;
            BDMESESDEPRECIADOS = 0;
            BDMESESDEPRECIAR = 0;
            BDTAXADEPRECIACAOANUAL = 0;
            --#ALT:17098 - Adicionei o valor da baixa, pois ele verificava este valor mas n?o retornava da procedure. Ana - 19/05/2017
            SELECT PRVALORCORRIGIDOANTERIOR, PRVALORCORRIGIDOANTERIORMOEDA, PRCORRECAOPERIODO, PRVALORCORRIGIDOATUAL,
                   PRDEPRECIACAOACUMULADAANTERIOR, PRDEPRECIACAOPERIODO, PRDEPRECIACAOPERIODOMOEDA,
                   PRDEPRECIACAOACUMULADAATUAL, PRDEPRECIACAOACUMULADAATUALMOED, PRCORRECAOMONETARIADEPRECIACAO,
                   PRVALORRESIDUALCONTABIL, PRVALORRESIDUALCONTABILMOEDA, PRTOTALMESESDEPRECIACAO, PRMESESDEPRECIADOS,
                   PRMESESDEPRECIAR, PRTAXADEPRECIACAOANUAL, PRDATATAXADEPRECIACAO, PRVALORMOEDA, PRVALORAQUISICAOMOEDA,
                   PRVALORAQUISICAOORIGINAL, PRSOMARDEPRECIACAO, PRVALORBAIXA
            FROM SP_CONS_CALC_DEP(:WCODEMP, :WCODBEM, :WDATINI, :WDATFIN, :PRTIPO, :PRCONTABILIZACAO, :PRDETALHARTAXADEP)
            INTO :BDVALORCORRIGIDOANTERIOR, :BDVALORCORRIGIDOANTERIORMOEDA, :BDCORRECAOPERIODO, :BDVALORCORRIGIDOATUAL,
                 :BDDEPRECIACAOACUMULADAANTERIOR, :BDDEPRECIACAOPERIODO, :BDDEPRECIACAOPERIODOMOEDA,
                 :BDDEPRECIACAOACUMULADAATUAL, :BDDEPRECIACAOACUMULADAATUALMOE, :BDCORRECAOMONETARIADEPRECIACAO,
                 :BDVALORRESIDUALCONTABIL, :BDVALORRESIDUALCONTABILMOEDA, :BDTOTALMESESDEPRECIACAO, :BDMESESDEPRECIADOS,
                 :BDMESESDEPRECIAR, :BDTAXADEPRECIACAOANUAL, :BDDATATAXADEPRECIACAO, :BDVALORMOEDA,
                 BDVALORAQUISICAOMOEDA, BDVALORAQUISICAOORIGINAL, BDSOMARDEPRECIACAO, WVALORBAIXA;

            BDCODEMP = WCODEMP;
            BDCODBEM = WCODBEM;
            BDNOMBEM = WNOMBEM;
            BDCODTPLA = WCODTPLA;
            BDCTALON = WCTALON;
            --#alt:17098. Ana - 09/05/2017
            IF (BDCODORIGBEM > 0) THEN
              IF (BDCODBEM < 10) THEN 
                BDCLACOD = CAST(BDCODORIGBEM AS VARCHAR(10)) || '.0' || CAST(BDCODBEM AS VARCHAR(10));
              ELSE
                BDCLACOD = CAST(BDCODORIGBEM AS VARCHAR(10)) || '.'  || CAST(BDCODBEM AS VARCHAR(10));
            ELSE
              BDCLACOD = CAST(BDCODBEM AS VARCHAR(10));
            BDNOMTPLA = WNOMTPLA;
            BDCODFOR = WCODFOR;
            BDNOMFOR = WNOMFOR;
            BDCODCC = WCODCC;
            BDCTALONCC = WCCLON;
            BDNOMCC = WNOMCC;
            BDREFERENCIA = WDATAUX;

            IF (BDCODCC IS NULL) THEN
              BDCODCC = 0;

            IF (WNATBEM = 0) THEN
              BDNATBEM = 'Bem original';
            ELSE
            IF (WNATBEM = 1) THEN
              BDNATBEM = 'Aquisi??o parcial';
            ELSE
            IF (WNATBEM = 2) THEN
              BDNATBEM = 'Reavalia??o';
            ELSE
            IF (WNATBEM = 3) THEN
              BDNATBEM = 'Transfer?ncia';
            BDESPECIE = WESPECIE;
            BDDATAAQUISICAO = WDATA;
            BDESPECIE = WESPECIE;

            --                      if ((prtipo = 2) and ((wvalorbaixa is not null) and (wvalorbaixa > 0))) then
            --                         begin
            --                           bdvalorcorrigidoanterior = wvalorbaixa;
            --                           bdvalorcorrigidoatual = wdepreciacaobaixamoeda;
            --                         end
            --                      else

            IF (BDDEPRECIACAOPERIODO > 0) THEN
            BEGIN

              IF ((BDVALORCORRIGIDOANTERIOR IS NOT NULL) OR (BDVALORCORRIGIDOATUAL IS NOT NULL) OR (BDDEPRECIACAOACUMULADAATUAL IS NOT NULL) OR (BDDEPRECIACAOPERIODO IS NOT NULL)) THEN
              BEGIN
                IF (PRTIPO = 2) THEN
                BEGIN
                  IF ((WVALORBAIXA IS NOT NULL) AND
                      (WVALORBAIXA > 0)) THEN
                  BEGIN
                    IF (BDCODMATRIZ > 0) THEN
                      BDCODEMP = BDCODMATRIZ;

                    SUSPEND;
                  END
                END
                ELSE
                BEGIN
                  IF (BDCODMATRIZ > 0) THEN
                    BDCODEMP = BDCODMATRIZ;

                  SUSPEND;
                END
              END
            END
            ELSE -- somente quando no relatorio esta para sair bens que nao tiveram depreciacao
            IF ((BDMESESDEPRECIADOS = 0) OR (PRMOSTRADEPRECIADOS = 1)) THEN
            BEGIN
              IF (BDCODMATRIZ > 0) THEN
                BDCODEMP = BDCODMATRIZ;

              -- #alt:15304 - Quando o bem n?o tem deprecia??o cadastrada n?o temos como saber se ? do fiscal ou societ?rio. Nesse caso o bem deve aparecer para os dois modelos de contabiliza??o. Ana - 26/08/2016
              IF ((BDVALORAQUISICAOORIGINAL = 0) AND
                  (BDVALORRESIDUALCONTABIL = 0)) THEN
              BEGIN
                BDVALORAQUISICAOORIGINAL = WVALORAQUISICAO;
                BDVALORRESIDUALCONTABIL = WVALORAQUISICAO;
              END

              --#alt:19813 - Nesta op??o n?o traz a data da baixa ent?o n?o precisa ser verificado o per?odo. Ana - 24/08/2017
              --#alt:17098 - Quando era o relat?rio de rela??o de baixas estava mostrando os bens mesmo sem baixas.  Ana - 09/05/2017
              IF (((PRTIPO = 2) AND ((WVALORBAIXA IS NOT NULL) AND (WVALORBAIXA > 0)) /*AND ((WDATABAIXA >= PRDATINI) AND (WDATABAIXA <= PRDATFIN))*/) OR
                  (PRTIPO <> 2)) THEN
                SUSPEND;
            END

            WDATE = ADDMONTH(WDATE, 1);
            WDATAUX = SUBSTRING(CAST(WDATE AS VARCHAR(10)) FROM 1 FOR 7);
          END
        END
      END
    END
  END
END
^

/* Alter (VSUC_SP_RETORNA_CRITICA_LANC) */
ALTER PROCEDURE VSUC_SP_RETORNA_CRITICA_LANC(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRCHAVEINI INTEGER,
PRCHAVEFIM INTEGER,
PRLOTEINI VARCHAR(10),
PRLOTEFIM VARCHAR(10),
PRTRANSINI INTEGER,
PRTRANSFIM INTEGER,
PRCOLUNAS INTEGER,
PRLCC VARCHAR(1024),
PRTOTDIA INTEGER,
PRTOTMES INTEGER,
PRTOTANO INTEGER,
PRTOTLOTE INTEGER,
PRDATAS VARCHAR(1024),
PRLANCSEMTRANS INTEGER,
PRREFEMP INTEGER,
PRCODTIPOLANC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(200),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDEBCRE INTEGER,
PRVALOR NUMERIC(15,2),
PRVALORRAT NUMERIC(15,2),
PRQUEBRADIA DATE,
PRQUEBRAMES VARCHAR(7),
PRQUEBRARANO VARCHAR(4),
PRQUEBRALOTE VARCHAR(10),
PRSEQUENCIA INTEGER,
PRNOMECC VARCHAR(40),
PRCODEMPFILIAL INTEGER,
PRCONTAB INTEGER,
PRDESCTIPOLANC VARCHAR(100),
BDTRANSACAO INTEGER)
 AS
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(3096);
DECLARE VARIABLE WCHAVECC INTEGER;
DECLARE VARIABLE WCOMCC INTEGER;
DECLARE VARIABLE WVALORCCDEB NUMERIC(15,2);
DECLARE VARIABLE WVALORCCCRE NUMERIC(15,2);
DECLARE VARIABLE WVALORCCGERAL NUMERIC(15,2);
DECLARE VARIABLE WGUARDAVALORRAT NUMERIC(15,2);
DECLARE VARIABLE WGUARDAPRVALOR NUMERIC(15,2);
DECLARE VARIABLE WGUARDACHAVE INTEGER;
DECLARE VARIABLE WGUARDAEMPRESARAT INTEGER;
DECLARE VARIABLE WGUARDAEMPANT INTEGER;
DECLARE VARIABLE WGUARDACONTADEBCC INTEGER;
DECLARE VARIABLE WGUARDACONTACRECC INTEGER;
DECLARE VARIABLE WGUARDADEBCRE INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITED INTEGER;
DECLARE VARIABLE WPERMITEC INTEGER;
DECLARE VARIABLE WEMPPRINC INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WTRANSACAO INTEGER;
BEGIN
  wdatini = SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 1 FOR 4);

  --alt: 6183 - Adicionado filtro por tipo de lan?amento. Pedro
  SELECT BDDESCRICAO FROM TIPOS_LANCAMENTOS_PADRAO WHERE BDCODTIPO = :prCodTipoLanc INTO :prDescTipoLanc;

  --Retorna a empresa principal
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos = 0) THEN
    wempprinc = prcodemp;
  ELSE
    wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  wsql = 'select tlan.BDCHAVE, tlan.BDDATA, tlan.BDCREDITO, tlan.BDDEBITO, tlan.BDCOMPL, thist.bdnome, tlan.bdlote, tlan.bddcto, tlan.bdvalor, temp.bdcodmatriz , ';
  wsql = wsql||' tlan.bdcodemp, temp.bdnomemp, temp.bdcnpjemp, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bdcontabilizacao, tlan.BDTRANSACAO ';

  IF (prlcc = '') THEN
     wsql = wsql||' , null bdx, null bdy, null bdz, null bdc  from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||' , tlcc.BDVALOR, tlcc.bdcodtpcc, tlcc.bddebcre , tpcc.bdnomcta';
       wsql = wsql||' from vsuc_empresas_tlan tlan ';
       wsql = wsql||' left outer join vsuc_empresas_tlcc tlcc on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
       wsql = wsql||' left outer join CENTROS_TPCC tpcc on (tlcc.bdcodcentro = tpcc.bdcodcentro and tlcc.bdcodtpcc = tpcc.bdcodtpcc) ';
     END

  wsql = wsql||' inner join vw_empresas_ref_atual temp on (temp.bdcodemp = tlan.bdcodemp) ';
  wsql = wsql||' left outer join hist_tphi thist on (thist.bdcodhist = tlan.bdcodhist and thist.bdcodtphi = tlan.bdcodtphi) ';
  wsql = wsql||' where ';

  --alt:6183 - Adicionado o filtro por tipo de lan?amento. Pedro
  IF ((NOT prCodTipoLanc IS NULL) AND (prDescTipoLanc <> '')) THEN
     wSQL = wSQL||' BDTIPOLAN = '||prCodTipoLanc||' and ';

  --#alt:5837.
  --wsql = wsql||'(tlan.bdcodemp in ('||trim(prcodemp)||')) and ';
  wsql = wsql||'((tlan.bdcodemp in ('||TRIM(prcodemp)||')) or (tlan.bdfilial in ('||TRIM(prcodemp)||'))) and ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'(tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) and ';

  IF ((prloteini <> '') AND (prlotefim <> '')) THEN
     wsql = wsql||'(tlan.bdlote between '''||prloteini||''' and '''||prlotefim||''') and ';
  ELSE
  IF (prloteini <> '') THEN
     wsql = wsql||'(tlan.bdlote = '''||prloteini||''') and ';
  ELSE
  IF (prlotefim <> '') THEN
     wsql = wsql||'(tlan.bdlote = '''||prlotefim||''') and ';

  IF ((TRIM(prchaveini) IS NOT NULL) AND (TRIM(prchavefim) IS NOT NULL)) THEN
     wsql = wsql||'(tlan.bdchave between '||prchaveini||' and '||prchavefim||') and ';
  ELSE
  IF (TRIM(prchaveini) IS NOT  NULL) THEN
     wsql = wsql||'(tlan.bdchave >= '||prchaveini||') and ';
  ELSE
  IF (prchavefim IS NOT NULL) THEN
     wsql = wsql||'(tlan.bdchave <= '||prchavefim||') and ';

  --alt:8070 - Filtro pela transa??o inicial e final e imprimir lan?amentos sem transa??o. Pedro
  IF ((TRIM(prtransini) IS NOT NULL) AND (TRIM(prtransfim) IS NOT NULL)) THEN
     BEGIN
       wsql = wsql||'((tlan.bdtransacao between '||prtransini||' and '||prtransfim||') ';

       IF (prlancsemtrans = 0) THEN
          wsql = wsql||') and ';
       ELSE
          wsql = wsql||' or (tlan.bdtransacao is null)) and ';
     END
  ELSE
  IF (TRIM(prtransini) IS NOT  NULL) THEN
     BEGIN
       wsql = wsql||'((tlan.bdtransacao >= '||prtransini||') ';

       IF (prlancsemtrans = 0) THEN
          wsql = wsql||') and ';
       ELSE
          wsql = wsql||' or (tlan.bdtransacao is null)) and ';
     END
  ELSE
  IF (prtransfim IS NOT NULL) THEN
     BEGIN
       wsql = wsql||'((tlan.bdtransacao <= '||prtransfim||') ';

       IF (prlancsemtrans = 0) THEN
          wsql = wsql||') and ';
       ELSE
          wsql = wsql||' or (tlan.bdtransacao is null)) and ';
     END
  ELSE
  IF (prlancsemtrans = 0) THEN
     wsql = wsql||'(tlan.bdtransacao is not null) and';
  --alt:8070 - Fim

  IF (prdatas IS NULL) THEN
     wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
  ELSE
     -- Somente datas com diferencas...
     wsql = wsql||'(tlan.bddata in ('||TRIM(prdatas)||')) ';

  --#alt:16410 - Adicionado filtro por status da transa??o. Ana - 05/05/2017
  IF (prstatustransacao = 1) THEN
    wsql = wsql||'and (upper(BDTRANFECHADA) = ''FALSE'') ';
  ELSE IF (prstatustransacao = 2) THEN
    wsql = wsql||'and (upper(BDTRANFECHADA) = ''TRUE'')';
  --#alt:16410. fim

  wsql = wsql||'order by tlan.bddata, tlan.bdchave, temp.bdcodemp';

  wvalorccdeb = 0;
  wvalorcccre = 0;
  /* laco dos lancamentos diario _____________________________________________*/
  FOR EXECUTE STATEMENT wsql
      INTO :prchave, :prdata,
           :prcodigo_credito, :prcodigo_debito, :prcomplemento, :prhistorico, :prlote, :prdcto,
           :wvalor , :prcodmatriz, :prempresa, :prnomeempresa, :prcnpjemp, :wfilial, :wtipolancfilial, :prcontab, :BDTRANSACAO,
           :prvalorrat, :prcodtpcc, :prdebcre, :prnomecc DO
      BEGIN
        prcodempfilial = prempresa;
        IF (prcodmatriz IS NULL) THEN
           prcodmatriz = prempresa;
        prempresa = prcodmatriz;

        SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prcodempfilial,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermited;
        SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wempprinc,:prcodempfilial,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermitec;

        /* se trocou de chave verifica se tem que lancar valor sem centro de custo */
        IF ((wcomcc = 1) AND (:prchave <> wchavecc)) THEN
          BEGIN
            wguardaprvalor = wValor;
            wguardavalorrat = prvalorrat;
            wguardachave = prchave;
            wguardaempant = prempresa;
            wguardadebcre = prdebcre;


            IF ((wvalorccdeb = 0) AND (wguardacontadebcc > 0) AND (wpermited = 1)) THEN
              BEGIN
                prnomecc = 'Sem centro de custo';
                prvalor = wvalorccgeral;
                wvalorccdeb = 0;
                wcomcc = 0;
                prvalorrat = wvalorccgeral;
                prvalor_debito = wvalorccgeral;
                prvalor_credito = NULL;
                prsequencia = 1;
                prcodtpcc = NULL;
                prdebcre = NULL;

                prempresa = wguardaempresarat;
                prchave   = wchavecc;
                IF ((wfilial > 0) AND (wtipolancfilial = 1)) THEN
                  prcodempfilial = wfilial;
                SUSPEND;
              END

            IF ((wvalorcccre = 0) AND (wguardacontacrecc > 0) AND (wpermitec = 1)) THEN
              BEGIN
                prnomecc = 'Sem centro de custo';
                prvalor = wvalorccgeral;
                wvalorcccre = 0;
                wcomcc = 0;
                prvalorrat = wvalorccgeral;
                prvalor_debito = NULL;
                prvalor_credito = wvalorccgeral;
                prsequencia = 1;
                prcodtpcc = NULL;
                prdebcre = NULL;

                prempresa = wguardaempresarat;
                prchave   = wchavecc;
                IF ((wfilial > 0) AND (wtipolancfilial = 2)) THEN
                  prcodempfilial = wfilial;
                SUSPEND;
              END

            wvalorccdeb = 0;
            wvalorcccre = 0;

            prempresa = wguardaempant;
            prvalor = wguardaprvalor;
            prvalorrat = wguardavalorrat;
            prchave = wguardachave;
            prdebcre = wguardadebcre;
          END

        IF ((prcodigo_debito > 0) AND (wpermited = 1)) THEN
           prvalor_debito = :wvalor;
        ELSE
          BEGIN
            prvalor_debito  = NULL;
            prcodigo_debito = NULL;
          END

        IF ((prcodigo_credito > 0) AND (wpermitec = 1)) THEN
           prvalor_credito = :wvalor;
        ELSE
          BEGIN
            prvalor_credito  = NULL;
            prcodigo_credito = NULL;
          END

        --#alt:5837.
        --if (prcolunas = 1) then
        --  prvalor_credito = :wvalor;

        prvalor = :wvalor;

        IF (prtotdia = 1) THEN
           prquebradia = :prdata;
        IF (prtotmes = 1) THEN
           prquebrames = SUBSTRING(CAST(:prdata AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(:prdata AS VARCHAR(10)) FROM 1 FOR 4);
        IF (prtotano = 1) THEN
           prquebrarano = SUBSTRING(CAST(:prdata AS VARCHAR(10)) FROM 1 FOR 4);

        IF (prtotlote = 1) THEN
          BEGIN
            IF (:prlote <> '' ) THEN
               prquebralote = :prlote;
            ELSE
               prquebralote = '  ';
          END

        IF (:prvalorrat > 0) THEN
          BEGIN
            /* faz um lacamento somente com seus dados gerais, sem valores.... */
            IF ((wvalorccdeb = 0) AND (wvalorcccre = 0)) THEN
              BEGIN
                wguardacontadebcc = prcodigo_debito;
                wguardacontacrecc = prcodigo_credito;
                wguardaempresarat = :prempresa;
                wvalorccgeral = :prvalor;
                wcomcc        = 1;
                wchavecc      = :prchave;
                wguardavalorrat = :prvalorrat;
                prvalor = NULL;
                prvalor_debito = NULL;
                prvalor_credito = NULL;
                prvalorrat = NULL;
                prsequencia = NULL;
                SUSPEND;
                prvalorrat = wguardavalorrat;
              END

            prvalor = wvalorccgeral;
            prsequencia = 2;

            IF ((prdebcre = 0) AND (wpermited = 1)) THEN
               BEGIN
                 wvalorccdeb = wvalorccdeb + :prvalorrat;
                 prvalor = NULL;
                 prvalor_debito = :prvalorrat;
                 prvalor_credito = NULL;
               END
            ELSE
            IF (wpermitec = 1) THEN
               BEGIN
                 wvalorcccre = wvalorcccre + :prvalorrat;
                 prvalor_debito = NULL;
                 prvalor_credito = :prvalorrat;
                 prvalor = NULL;
               END
           END
        ELSE
           BEGIN
             /* nao precisa controlar cc */
             wcomcc    = 0;
           END
        SUSPEND;
      END

  /* se chegou no fim e o ultimo lancamento era de cc */
  IF (wcomcc = 1)  THEN
    BEGIN
      IF ((wvalorccdeb = 0) AND (wguardacontadebcc > 0) AND (wpermited = 1))  THEN
        BEGIN
          prnomecc = 'Sem centro de custo';
          prvalor = wvalorccgeral;
          wvalorccdeb = 0;
          wcomcc = 0;
          prvalorrat = wvalorccgeral;
          prvalor_debito = wvalorccgeral;
          prvalor_credito = NULL;
          prsequencia = 1;
          prcodtpcc = NULL;
          prdebcre = NULL;

          prempresa = wguardaempresarat;
          prchave   = wchavecc;
          IF ((wfilial > 0) AND (wtipolancfilial = 1)) THEN
            prcodempfilial = wfilial;
          SUSPEND;
        END

      IF ((wvalorcccre = 0) AND (wguardacontacrecc > 0) AND (wpermitec = 1))  THEN
        BEGIN
          prnomecc = 'Sem centro de custo';
          prvalor = wvalorccgeral;
          wvalorcccre = 0;
          wcomcc = 0;
          prvalorrat = wvalorccgeral;
          prvalor_debito = NULL;
          prvalor_credito = wvalorccgeral;
          prsequencia = 1;
          prcodtpcc = NULL;
          prdebcre = NULL;

          prempresa = wguardaempresarat;
          prchave   = wchavecc;
          IF ((wfilial > 0) AND (wtipolancfilial = 2)) THEN
            prcodempfilial = wfilial;
          SUSPEND;
        END

      prsequencia = NULL;
      wvalorccdeb = 0;
      wvalorcccre = 0;
    END
END
^

/* Alter (VSUC_SP_RETORNA_DIARIO) */
ALTER PROCEDURE VSUC_SP_RETORNA_DIARIO(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRMODELO INTEGER,
PRFILIAIS VARCHAR(1024),
PRLCC VARCHAR(1024),
PRDETALHARCTAPARTICIPANTE INTEGER,
PRREFEMP INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRCLASSI_CREDITO VARCHAR(40),
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRCLASSI_DEBITO VARCHAR(40),
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(400),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDETALHE VARCHAR(130),
PREMPRESAFILIAL INTEGER,
PRCHAVEONLINE VARCHAR(120),
PRTRANSACAO INTEGER)
 AS
declare variable WVALOR numeric(15,2);
declare variable WCTALONC varchar(40);
declare variable WNOMCTAC varchar(100);
declare variable WPARTICIPANTEC integer;
declare variable WCODTERCEIROC integer;
declare variable WDATINI varchar(10);
declare variable WDATFIN varchar(10);
declare variable WSQL varchar(8192);
declare variable WCTALOND varchar(40);
declare variable WNOMCTAD varchar(100);
declare variable WPARTICIPANTED integer;
declare variable WCODTERCEIROD integer;
declare variable WPOS integer;
declare variable WTIPLAN integer;
declare variable WFILIAL integer;
declare variable WTIPOLANCFILIAL integer;
declare variable WPERMITE integer;       
--#alt:84365 - Carlos Machado - 04/06/2018 - Alterado para suportar mais filiais.
declare variable WEMPRESAS varchar(2000);
declare variable WCODIGOAUX integer;
declare variable WCLASSIAUX varchar(40);
declare variable WVLRAUX numeric(15,2);
declare variable WIMPPERNA integer;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefemp, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 1 FOR 4);

  wsql = '';
  wsql = wsql||'select tlan.BDCHAVE, tlan.BDDATA, ';
  wsql = wsql||'tlan.BDCREDITO, tlan.bdcodterceiroc, tplac.bdctalon, tplac.bdnomcta, tplac.bdparticipante, ';
  wsql = wsql||'tlan.BDDEBITO, tlan.bdcodterceirod, tplad.bdctalon, tplad.bdnomcta, tplad.bdparticipante, ';
  wsql = wsql||'tlan.BDCOMPL, thist.bdnome, tlan.bdcodemp, temp.bdnomemp, ';
  wsql = wsql||'temp.bdcnpjemp, tlan.bdlote, tlan.bddcto, temp.bdcodmatriz, tlan.bdtipolan, tlan.bdchaveonline, ';
  wsql = wsql||'tlan.bdfilial, tlan.bdtipolancfilial, tlan.bdtransacao, ';
  IF (prlcc = '') THEN
     wsql = wsql||'tlan.BDVALOR, tlan.bdchave from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wsql = wsql||'left outer join hist_tphi thist on (thist.bdcodhist = tlan.bdcodhist and thist.bdcodtphi = tlan.bdcodtphi) ';
  wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
  wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
  wsql = wsql||'join vw_empresas_ref_atual temp on (temp.bdcodemp = tlan.bdcodemp) ';
  wsql = wsql||'where ';
  IF (prfiliais <> '') THEN
     wsql = wsql||'((tlan.bdcodemp in ('||TRIM(prfiliais)||')) or (tlan.bdfilial in ('||TRIM(prfiliais)||'))) and ';
  ELSE
     wsql = wsql||'((tlan.bdcodemp = '||prcodemp||') or (tlan.bdfilial = '||prcodemp||')) and ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'(tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
  IF (prlcc <> '') THEN
     wsql = wsql||'(tlcc.bdcodtpcc in ('||TRIM(prlcc)||')) and ';
  wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
  IF (pragrupar = '') THEN
     wsql = wsql||'order by tlan.bddata, temp.bdcodemp';
  ELSE
     BEGIN
       wsql = wsql||'and tlan.bdtipolan not in ('||pragrupar||') ';
       wsql = wsql||'union all ';
       wsql = wsql||'select tlan.BDCHAVE, ';
       wsql = wsql||'       tlan.bddata, ';
       wsql = wsql||'       tlan.BDCREDITO, tlan.bdcodterceiroc, tplac.bdctalon, ';
       wsql = wsql||'       tplac.bdnomcta, tplac.bdparticipante, tlan.BDDEBITO, tlan.bdcodterceirod, tplad.bdctalon, ';
       wsql = wsql||'       tplad.bdnomcta, tplad.bdparticipante, tlan.BDCOMPL, tlan.bdnomehist, tlan.bdcodemp, ';
       wsql = wsql||'       tref.bdnomemp, temp.bdcnpjemp, tlan.bdlote, tlan.bddcto, temp.bdcodmatriz, ';
       wsql = wsql||'       tlan.bdtipolan, tlan.bdchaveonline, null as bdfilial, null as bdtipolancfilial, ';
       wsql = wsql||'       tlan.bdtransacao, tlan.BDVALOR, tlan.bdcodtpcc from tempresas temp ';
       wsql = wsql||'inner join vsuc_lancamentos_agrupados(';
       IF (prfiliais <> '') THEN
          wsql = wsql||''''||prfiliais||''''; --alt:11820 - 01/06/2015 - Adicionadas aspas para poder passar uma string com v?rias filiais. Pedro
       ELSE
          wsql = wsql||prcodemp;
       wsql = wsql||', '''||pragrupar||''', null, null,'||prcontabilizacao||', null, null, 1, ';
       IF (prlcc IS NULL OR prlcc = '') THEN
          wsql = wsql||' null) ';
       ELSE
          wsql = wsql||TRIM(prlcc)||') ';
       wsql = wsql||' tlan on (tlan.bdcodemp = temp.bdcodemp) ';
       wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
       wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
       wsql = wsql||'left outer join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) where ';
       IF (prfiliais <> '') THEN
          wsql = wsql||'(tlan.bdcodemp in ('||TRIM(prfiliais)||')) and ';
       ELSE
          wsql = wsql||'(tlan.bdcodemp = '||prcodemp||') and ';
       -- A rotina vsuc_lancamentos_agrupados n?o tem o campo bdcontabilizacao e a contabiliza??o ? tratado l? dentro
       --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
       --if (prcontabilizacao <> 99) then
       --  wsql = wsql||'(tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
       wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';

       /*wsql = wsql||'select min(tlan.BDCHAVE) as BDCHAVE, ';
       --wsql = wsql||'       cast(addmonth(cast(substring(tlan.bddata from 1 for 4)||'||'''-'''||'||substring(tlan.bddata from 6 for 2)||'||'''-01'''||' as date), 1)-1 as date) as bdDATA, ';
       wsql = wsql||'       tlan.bddata, ';
       wsql = wsql||'       tlan.BDCREDITO, null as bdcodterceiroc, tplac.bdctalon, ';
       wsql = wsql||'       tplac.bdnomcta, tplac.bdparticipante, tlan.BDDEBITO, null as bdcodterceirod, tplad.bdctalon, ';
       wsql = wsql||'       tplad.bdnomcta, tplad.bdparticipante, null as BDCOMPL, thist.bdnome, tlan.bdcodemp, ';
       wsql = wsql||'       tref.bdnomemp, temp.bdcnpjemp, null as bdlote, null as bddcto, ';
       wsql = wsql||'       temp.bdcodmatriz, ';
       if (prlcc = '') then
          wsql = wsql||'sum(tlan.BDVALOR), null as bdchave from vsuc_empresas_tlan tlan ';
       else
          begin
            wsql = wsql||'sum(tlcc.BDVALOR), tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
            wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
          end
       wsql = wsql||'left outer join hist_tphi thist on (thist.bdcodhist = tlan.bdcodhist and thist.bdcodtphi = tlan.bdcodtphi) ';
       wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
       wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
       wsql = wsql||'join tempresas temp on (temp.bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'left outer join tempresas_ref tref on (tref.bdcodemp = temp.bdcodemp) where ';
       if (prfiliais <> '') then
          wsql = wsql||'(tlan.bdcodemp in ('||trim(prfiliais)||')) and ';
       else
          wsql = wsql||'(tlan.bdcodemp = '||prcodemp||') and ';
       if (prlcc <> '') then
          wsql = wsql||'(tlcc.bdcodtpcc in ('||trim(prlcc)||')) and ';
       wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
       wsql = wsql||'and tref.bdrefemp = (select first 1 tempresas_ref.bdrefemp from tempresas_ref ';
       wsql = wsql||                     'where tempresas_ref.bdcodemp = temp.bdcodemp ';
       wsql = wsql||                     'and tempresas_ref.bdrefemp <= '||prrefemp;
       wsql = wsql||                     ' order by tempresas_ref.bdrefemp)';
       wsql = wsql||'and tlan.bdtipolan in ('||pragrupar||') ';
       --wsql = wsql||'group by (addmonth(cast(substring(tlan.bddata from 1 for 4)||'||'''-'''||'||substring(tlan.bddata from 6 for 2)||'||'''-01'''||' as date), 1)-1), ';
       wsql = wsql||'group by tlan.bddata, ';
       wsql = wsql||'         tlan.BDCREDITO, tplac.bdctalon, ';
       wsql = wsql||'         tplac.bdnomcta, tplac.bdparticipante, tlan.BDDEBITO, tplad.bdctalon, ';
       wsql = wsql||'         tplad.bdnomcta, tplad.bdparticipante, thist.bdnome, tlan.bdcodemp, ';
       wsql = wsql||'         tref.bdnomemp, temp.bdcnpjemp, temp.bdcodmatriz ';
       if (prlcc <> '') then
          wsql = wsql||',tlcc.bdcodtpcc ';  */
     END

  /* laco dos lancamentos diario _____________________________________________*/
  prempresa = prcodemp;
  wempresas = prcodemp;
  IF (prfiliais <> '') THEN
    wempresas = prfiliais;

  FOR EXECUTE STATEMENT wsql
      INTO :prchave, :prdata,
           :prcodigo_credito, :wcodterceiroc, :wctalonc, :wnomctac, :wparticipantec,
           :prcodigo_debito, :wcodterceirod, :wctalond, :wnomctad, :wparticipanted,
           :prcomplemento, :prhistorico, :prempresafilial,
           :prnomeempresa, :prcnpjemp, :prlote, :prdcto, :prcodmatriz, :wtiplan, :prchaveonline,
           :wfilial, :wtipolancfilial, :prtransacao, :wvalor, :prcodtpcc DO
      BEGIN
        -- Cr?dito
        prclassi_credito = wctalonc;
        IF ((wparticipantec = 1) AND (prdetalharctaparticipante = 1) AND (wcodterceiroc > 0)) THEN
          SELECT bdclassificacao, bdnome FROM vsuc_sp_nomenclatura_cta_partic(:wcodterceiroc,:wctalonc,0) INTO :prclassi_credito,:wnomctac;
        -- D?bito
        prclassi_debito  = wctalond;
        IF ((wparticipanted = 1) AND (prdetalharctaparticipante = 1) AND (wcodterceirod > 0)) THEN
          SELECT bdclassificacao, bdnome FROM vsuc_sp_nomenclatura_cta_partic(:wcodterceirod,:wctalond,0) INTO :prclassi_debito,:wnomctad;

        IF (prlcc = '') THEN
           prcodtpcc = 0;

        IF (prhistorico IS NOT NULL) THEN
          BEGIN
            SELECT pos FROM pos('*', :prhistorico) INTO :wpos;
              IF ((wpos > 0) AND (wtiplan NOT IN (100,200,300,400))) THEN
                 prhistorico = prcomplemento;
              ELSE
                prhistorico = prhistorico || ' ' || prcomplemento;
          END
        ELSE
          prhistorico = prcomplemento;

        /* diario modelo detalhado ___________________________________________*/
        IF (prmodelo = 1) THEN
           BEGIN
             --prhistorico = prcomplemento;
             /* lancamento a credito _________________________________________*/
             IF ((NOT prcodigo_credito IS NULL) OR (prcodigo_credito <> 0))  THEN
                BEGIN
                  SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:prempresafilial,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:wempresas) INTO :wpermite;
                  IF (wpermite = 1) THEN
                    BEGIN
                      prvalor_credito = wvalor;
                      prvalor_debito  = NULL;
                      prdetalhe       = prcodigo_credito||' - '||prclassi_credito||' - '||wnomctac;
                      IF ((wfilial > 0) AND (wtipolancfilial = 2)) THEN
                        prempresafilial = wfilial;

                      SUSPEND;-- gilberto - 13/11/2012
                    END
                END

              /* lancamento a debito _________________________________________*/
             IF ((NOT prcodigo_debito IS NULL) OR (prcodigo_debito <> 0))  THEN
                BEGIN
                  SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:prempresafilial,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:wempresas) INTO :wpermite;
                  IF (wpermite = 1) THEN
                    BEGIN
                      prvalor_credito = NULL;
                      prvalor_debito  = wvalor;
                      prdetalhe       = prcodigo_debito||' - '||prclassi_debito||' - '||wnomctad;
                      IF ((wfilial > 0) AND (wtipolancfilial = 1)) THEN
                        prempresafilial = wfilial;

                      SUSPEND;
                    END
                END
           END
        ELSE
           /* diario modelo simplificado _____________________________________*/
           BEGIN
             wcodigoaux = 0;
             wclassiaux = '';
             wvlraux    = 0;
             wimpperna  = 0;

             prvalor_credito = wvalor;
             SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:prempresafilial,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:wempresas) INTO :wpermite;
             IF ((wpermite = 0) OR (prcodigo_credito IS NULL))  THEN
               BEGIN
                 prcodigo_credito = NULL;
                 prclassi_credito = '';
                 prvalor_credito  = NULL;
               END
             IF ((wpermite = 1) AND (wfilial > 0) AND (wtipolancfilial = 2)) THEN
               prempresafilial = wfilial;

             IF ((prdetalharfilial = 1) AND (wfilial > 0) AND (wpermite = 1)) THEN
               BEGIN
                 wcodigoaux = prcodigo_debito;
                 wclassiaux = prclassi_debito;
                 wvlraux    = wvalor;

                 prcodigo_debito = NULL;
                 prclassi_debito = '';
                 prvalor_debito  = NULL;

                 wimpperna = 1;
                 SUSPEND;

                 prcodigo_debito = wcodigoaux;
                 prclassi_debito = wclassiaux;
                 prvalor_debito  = wvlraux;

                 prcodigo_credito = NULL;
                 prclassi_credito = '';
                 prvalor_credito  = NULL;
               END

             --alt:14634 - 27/05/2016 - Se o lan?amento ? um "lan?ar a" cr?dito, deve alterar a filial do lan?amento, pois para o d?bito deve enxergar como um lan?amento comum na matriz. Pedro
             IF (wtipolancfilial = 2) THEN
               BEGIN
                 prempresafilial = prcodemp;
                 wfilial = 0;
               END
             prvalor_debito  = wvalor;
             SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:prempresafilial,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:wempresas) INTO :wpermite;
             IF ((wpermite = 0) OR (prcodigo_debito IS NULL)) THEN
               BEGIN
                 prcodigo_debito = NULL;
                 prclassi_debito = '';
                 prvalor_debito  = NULL;
               END
             IF ((wpermite = 1) AND (wfilial > 0) AND (wtipolancfilial = 1)) THEN
               prempresafilial = wfilial;

             IF ((wpermite = 1) OR (wimpperna = 0))  THEN
               SUSPEND;
           END
      END
END
^

/* Alter (VSUC_SP_RETORNA_MOV_DIARIO) */
ALTER PROCEDURE VSUC_SP_RETORNA_MOV_DIARIO(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(DATA DATE,
DEB NUMERIC(15,2),
CRE NUMERIC(15,2),
SAL NUMERIC(15,2),
DEBANT NUMERIC(15,2),
CREANT NUMERIC(15,2),
SALANT NUMERIC(15,2))
 AS
DECLARE VARIABLE wsalaux NUMERIC(15,2);
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wgrupoconta INTEGER;
DECLARE VARIABLE wsaldodeb NUMERIC(15,2);
DECLARE VARIABLE wsaldocre NUMERIC(15,2);
DECLARE VARIABLE wsql VARCHAR(10240);
DECLARE VARIABLE wtamanho INTEGER;
DECLARE VARIABLE wclassificacao VARCHAR(50);
DECLARE VARIABLE wlstcta VARCHAR(8192);
DECLARE VARIABLE wcodcta INTEGER;
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wdebant NUMERIC(15,2);
DECLARE VARIABLE wcreant NUMERIC(15,2);
DECLARE VARIABLE wsalant NUMERIC(15,2);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wempprinc INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wtipolan INTEGER;
DECLARE VARIABLE wvlr NUMERIC(15,2);
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wdataaux DATE;
DECLARE VARIABLE wdataant DATE;
DECLARE VARIABLE wprimeiroreg INTEGER;
DECLARE VARIABLE wpos_pernamatriz INTEGER;
DECLARE VARIABLE wpos_matriz INTEGER;
DECLARE VARIABLE wpos_filial INTEGER;
DECLARE VARIABLE wcampo INTEGER;
BEGIN

  wsaldocre      = 0;
  wsaldodeb      = 0;
  wtamanho       = 0;
  wclassificacao = '';

  -- retorna informa??es referente a conta selecionada _________________________
  wsql = 'select first 1 bdctalon, bdgrupocta, bdcodplapadrao ';
  wsql = wsql||'from PLANOS_TPLA  ';
  wsql = wsql||'where bdCODPLAPADRAO = (select first 1 tref.bdcodplapadrao ';
  wsql = wsql||'                        from tempresas_ref tref ';
  wsql = wsql||'                        where tref.bdcodemp in ('||prcodemp||')';
  wsql = wsql||'                        and tref.bdrefemp <= '||prrefemp;
  wsql = wsql||'                        order by tref.bdrefemp desc) ';
  wsql = wsql||'and (bdCODTPLA = '||prconta||') ';
  EXECUTE STATEMENT wsql
  INTO :wClassificacao, :wgrupoconta, :wcodplapadrao;
  -- retorna a quantidade de caracteres da conta longa selecionada _____________
  wtamanho = strlen(wclassificacao);
  -- retorno dos c?digos das contas selecionadas _______________________________
  wsql = 'select tpla.bdcodtpla from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||' and substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''' ';
  wsql = wsql||'and ((TPLA.BDTIPCTA = 1) or (TPLA.BDTIPCTA is null)) ';
  wsql = wsql||'order by tpla.bdctalon';

  wlstcta = '';
  FOR EXECUTE STATEMENT wsql INTO :wcodcta DO
     BEGIN
       wlstcta = wlstcta||TRIM(CAST(wcodcta AS VARCHAR(10)))||',';
     END
  wlstcta = SUBSTRING(wlstcta FROM 1 FOR strlen(wlstcta)-1);
  -- formata??o das datas para serem usadas no sql _____________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);
  -- sql para ser executado no la?o ____________________________________________
  --#alt:5837.
  /*wsql = 'SELECT SUM(CASE ';
  wsql = wsql||'             WHEN (tlan.bdcredito in ('||wlstcta||')) THEN ';
  wsql = wsql||'               TLAN.BDVALOR ';
  wsql = wsql||'             ELSE ';
  wsql = wsql||'               0 ';
  wsql = wsql||'           end) AS "SALDEB", ';
  wsql = wsql||'       sum(case ';
  wsql = wsql||'             when (tlan.bddebito in ('||wlstcta||')) then ';
  wsql = wsql||'               TLAN.BDVALOR ';
  wsql = wsql||'             else ';
  wsql = wsql||'               0 ';
  wsql = wsql||'           end) AS "SALCRE", ';
  wsql = wsql||'       tlan.bddata "DATA" ';
  wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
  wsql = wsql||'where (tlan.bdcodemp in ('||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
  wsql = wsql||'and (TLAN.BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
  wsql = wsql||'and ((tlan.bdcredito in ('||wlstcta||')) or (tlan.bddebito in ('||wlstcta||'))) ';
  wsql = wsql||'Group By tlan.bddata ';
  wsql = wsql||'Order by tlan.bddata Asc '; */
  --Retorna a empresa principal
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos = 0) THEN
    wempprinc = prcodemp;
  ELSE
    wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  wsql = 'Select * from (';
  wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,1 as bdtipolanc,tlan.bddata "DATA",';
  wsql = wsql||'SUM(CASE WHEN (tlan.bddebito in ('||wlstcta||')) THEN TLAN.BDVALOR ELSE 0 end) AS "SALDEB" ';
  wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
  wsql = wsql||'and (tlan.bddebito in ('||wlstcta||')) ';
  wsql = wsql||'and (TLAN.BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial in ('||prcodemp||'))) ';
  wsql = wsql||'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,bdtipolanc,tlan.bddata';
  wsql = wsql||' union all ';
  wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,2 as bdtipolanc,tlan.bddata "DATA",';
  wsql = wsql||'SUM(CASE WHEN (tlan.bdcredito in ('||wlstcta||')) THEN TLAN.BDVALOR ELSE 0 end) AS "SALCRE" ';
  wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
  wsql = wsql||'where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
  wsql = wsql||'and (tlan.bdcredito in ('||wlstcta||')) ';
  wsql = wsql||'and (TLAN.BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial in ('||prcodemp||'))) ';
  wsql = wsql||'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,bdtipolanc,tlan.bddata';
  wsql = wsql||') Order by data Asc';

  sal = 0;
  -- verifica se a data atual ? a data inicial, para calcular os saldos anteriores
  FOR EXECUTE STATEMENT 'select bdcodemp from tempresas where bdcodemp in ('||prcodemp||')' INTO :wcodemp DO
      BEGIN
        SELECT SALDO_DEB, SALDO_CRE, Saldo_Atual, Saldo_Ant_Deb, Saldo_Ant_Cre, Saldo_Anterior
        FROM sp_retorna_saldo_emp_x(:wcodemp, :prconta, :PRDATAINI, :PRDATAINI, 0, 0, NULL, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado)
        INTO :wsaldodeb, :wsaldocre, :wsalaux, :wdebant, :wcreant, :wsalant;

        deb = COALESCE(deb, 0) + COALESCE(wsaldodeb, 0);
        cre = COALESCE(cre, 0) + COALESCE(wsaldocre, 0);
--        sal = coalesce(sal, 0) + coalesce(wsalaux, 0);
        sal = COALESCE(sal, 0) + COALESCE(wsalant, 0);
        debant = COALESCE(debant, 0) + COALESCE(wdebant, 0);
        creant = COALESCE(creant, 0) + COALESCE(wcreant, 0);
        salant = COALESCE(salant, 0) + COALESCE(wsalant, 0);
      END
  --#alt:5837.
  wdataant     = NULL;
  wprimeiroreg = 1;
  deb = 0;
  cre = 0;
  --for execute statement wsql into :wsaldocre, :wsaldodeb, :data do
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wtipolan,:wdataaux,:wvlr  DO
    BEGIN
      IF ((wdataant <> wdataaux) AND (wprimeiroreg = 0)) THEN
        BEGIN
          SUSPEND;
          deb = 0;
          cre = 0;
        END
      data = wdataaux;

--      select bdpermite from vsuc_sp_permitecalcsaldolancmf(:wtipolan,:wempprinc,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        --alt:#6524 - implementado rotina "POS" aqui, por quest?o de desempenho, precisa apenas uma vez para as duas verifica??es
        IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
           BEGIN
             wpos_pernamatriz = POSITION(prcodemp, wcodemp);
             wpos_matriz = POSITION(wcodemp,  prcodemp);
             wpos_filial = POSITION(wfilial,  prcodemp);
          END
        wpermite = 0;
        --alt:#6524 - implementado rotina "VSUC_SP_PERMITECALCSALDOLANCMF" diretamente aqui, por quest?o de desempenho
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           wpermite = 1;
        ELSE
           BEGIN
             --#Alt:14975 (30/06/2016) - Foi setado a vari?vel wtipolan para a wcampo e alterado de prcodemp para wempprinc no controle do "Lan?ar a". Com as
             --vari?veis anteriores ocorria erro e n?o iria fazer o controle corretamente.
             --wcampo = wtipolancfilial;
             wcampo = wtipolan;
             IF (((wempprinc = wcodemp) AND (wfilial = 0)) OR
                 --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
                 ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
                 --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                 ((wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                 --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
                 ((prmatrizfilialconsolidado = 1) AND (wempprinc <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                 --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
                 ((prmatrizfilialconsolidado = 1) AND (wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
                wpermite = 1;
           END

      IF (wpermite = 1) THEN
        BEGIN
          IF (wvlr IS NULL) THEN
            wvlr = 0;
          wsaldodeb = wvlr;
          wsaldocre = 0;
          IF (wtipolan = 2) THEN--Cr?dito
            BEGIN
              wsaldodeb = 0;
              wsaldocre = wvlr;
            END
          -- aplica??o da regra contabilista _____________________________________
          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
            wsalaux = sal + (wsaldodeb - wsaldocre);
          ELSE
          IF ((wgrupoconta = 1) OR (wgrupoconta = 2) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
            wsalaux = sal + (wsaldocre - wsaldodeb);
          --wsalaux = sal + (wsaldodeb - wsaldocre);

          deb = deb + wsaldodeb;
          cre = cre + wsaldocre;

          sal = wsalaux;
          --#alt:5837.
          --suspend;
        END
      wdataant     = data;
      wprimeiroreg = 0;
    END
  IF (wdataant IS NOT NULL) THEN
    SUSPEND;
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_MOVIMENTO_MENSAL for: VSUC_SP_RETORNA_MOV_MENSAL */
ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRCC VARCHAR(5000),
PRANOINICIAL INTEGER,
PRANOFINAL INTEGER,
PRREFEMP INTEGER,
PRPARTICIPANTE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDDEB01 NUMERIC(15,2),
BDDEB02 NUMERIC(15,2),
BDDEB03 NUMERIC(15,2),
BDDEB04 NUMERIC(15,2),
BDDEB05 NUMERIC(15,2),
BDDEB06 NUMERIC(15,2),
BDDEB07 NUMERIC(15,2),
BDDEB08 NUMERIC(15,2),
BDDEB09 NUMERIC(15,2),
BDDEB10 NUMERIC(15,2),
BDDEB11 NUMERIC(15,2),
BDDEB12 NUMERIC(15,2),
BDCRE01 NUMERIC(15,2),
BDCRE02 NUMERIC(15,2),
BDCRE03 NUMERIC(15,2),
BDCRE04 NUMERIC(15,2),
BDCRE05 NUMERIC(15,2),
BDCRE06 NUMERIC(15,2),
BDCRE07 NUMERIC(15,2),
BDCRE08 NUMERIC(15,2),
BDCRE09 NUMERIC(15,2),
BDCRE10 NUMERIC(15,2),
BDCRE11 NUMERIC(15,2),
BDCRE12 NUMERIC(15,2),
BDMOV01 NUMERIC(15,2),
BDMOV02 NUMERIC(15,2),
BDMOV03 NUMERIC(15,2),
BDMOV04 NUMERIC(15,2),
BDMOV05 NUMERIC(15,2),
BDMOV06 NUMERIC(15,2),
BDMOV07 NUMERIC(15,2),
BDMOV08 NUMERIC(15,2),
BDMOV09 NUMERIC(15,2),
BDMOV10 NUMERIC(15,2),
BDMOV11 NUMERIC(15,2),
BDMOV12 NUMERIC(15,2),
BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2),
BDSALTOTDEB NUMERIC(15,2),
BDSALTOTCRE NUMERIC(15,2),
BDSALTOTMOV NUMERIC(15,2),
BDSALTOTATU NUMERIC(15,2),
BDANO INTEGER,
BDGRPCTA INTEGER,
BDDEBANT NUMERIC(15,2),
BDCREANT NUMERIC(15,2),
BDMOVANT NUMERIC(15,2),
BDSALANT NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_RETORNA_MOV_MENSAL) */
ALTER PROCEDURE VSUC_SP_RETORNA_MOV_MENSAL(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRCC VARCHAR(5000),
PRANOINICIAL INTEGER,
PRANOFINAL INTEGER,
PRREFEMP INTEGER,
PRPARTICIPANTE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDDEB01 NUMERIC(15,2),
BDDEB02 NUMERIC(15,2),
BDDEB03 NUMERIC(15,2),
BDDEB04 NUMERIC(15,2),
BDDEB05 NUMERIC(15,2),
BDDEB06 NUMERIC(15,2),
BDDEB07 NUMERIC(15,2),
BDDEB08 NUMERIC(15,2),
BDDEB09 NUMERIC(15,2),
BDDEB10 NUMERIC(15,2),
BDDEB11 NUMERIC(15,2),
BDDEB12 NUMERIC(15,2),
BDCRE01 NUMERIC(15,2),
BDCRE02 NUMERIC(15,2),
BDCRE03 NUMERIC(15,2),
BDCRE04 NUMERIC(15,2),
BDCRE05 NUMERIC(15,2),
BDCRE06 NUMERIC(15,2),
BDCRE07 NUMERIC(15,2),
BDCRE08 NUMERIC(15,2),
BDCRE09 NUMERIC(15,2),
BDCRE10 NUMERIC(15,2),
BDCRE11 NUMERIC(15,2),
BDCRE12 NUMERIC(15,2),
BDMOV01 NUMERIC(15,2),
BDMOV02 NUMERIC(15,2),
BDMOV03 NUMERIC(15,2),
BDMOV04 NUMERIC(15,2),
BDMOV05 NUMERIC(15,2),
BDMOV06 NUMERIC(15,2),
BDMOV07 NUMERIC(15,2),
BDMOV08 NUMERIC(15,2),
BDMOV09 NUMERIC(15,2),
BDMOV10 NUMERIC(15,2),
BDMOV11 NUMERIC(15,2),
BDMOV12 NUMERIC(15,2),
BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2),
BDSALTOTDEB NUMERIC(15,2),
BDSALTOTCRE NUMERIC(15,2),
BDSALTOTMOV NUMERIC(15,2),
BDSALTOTATU NUMERIC(15,2),
BDANO INTEGER,
BDDEBANT NUMERIC(15,2),
BDCREANT NUMERIC(15,2),
BDMOVANT NUMERIC(15,2),
BDSALANT NUMERIC(15,2),
BDGRPCTA INTEGER)
 AS
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WANOINICIAL VARCHAR(4);
DECLARE VARIABLE WGRUPOCONTA INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCOUNT1 INTEGER;
DECLARE VARIABLE WTAM INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WDEB NUMERIC(15,2);
DECLARE VARIABLE WCRE NUMERIC(15,2);
DECLARE VARIABLE WREF VARCHAR(6);
DECLARE VARIABLE WSALATU NUMERIC(15,2);
DECLARE VARIABLE WLSTCTA VARCHAR(8192);
DECLARE VARIABLE WCODCTA INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WTIPOLAN INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WPOS_PERNAMATRIZ INTEGER;
DECLARE VARIABLE WPOS_MATRIZ INTEGER;
DECLARE VARIABLE WPOS_FILIAL INTEGER;
DECLARE VARIABLE WCAMPO INTEGER;
BEGIN
  bdsaltotdeb = 0;
  bdsaltotcre = 0;
  bdsaltotmov = 0;
  bdsaltotatu = 0;
  wgrupoconta = 0;
  wcodplapadrao = 0;


  SELECT bdgrupocta, strlen(bdctalon), bdctalon, bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE bdCODPLAPADRAO = (SELECT FIRST 1 tref.bdcodplapadrao
                          FROM tempresas_ref tref
                          WHERE tref.bdcodemp = :prcodemp
                          AND tref.bdrefemp <= :prrefemp
                          ORDER BY tref.bdrefemp DESC)
  AND (bdCODTPLA = :prconta)
  INTO :wgrupoconta, :wtam, :wctalon, wcodplapadrao;

  wcount = 0;
  WHILE (wcount <= pranofinal - pranoinicial) DO
    BEGIN
      BDANO = :pranoinicial + :wcount;

      SELECT CAST(:pranoinicial+:wcount AS VARCHAR(4)) AS C_ANO_INI FROM RDB$DataBase INTO :wAnoinicial;

      wdataini = '01/'||'01/'||:wanoinicial;
      wdatafim = '01/'||'31/'||:wanoinicial;

      --alt:9801 - Alterado para fazer o select mesmo que n?o tenha movimento no ano informado, pois a pedido da solicita??o, deve trazer pelo menos o saldo anterior neste caso. Pedro

      /* Feito select para saber se existe lan?amento no ano atual.
         Se tiver, continua a rotina calculando os saldos mes a mes..
         Caso contr?rio, zera vari?veis e passa para pr?ximo ano.*/
      /*select count(bdChave) from vsuc_empresas_tlan
      where (bdCodEmp = :prcodemp)
-- #alt:6470 - gilberto - 16/08/2013 ___________________________________________
--      and (bdData >= '01/01/'||:wanoinicial)
--      and (bdData <= '12/31/'||:wanoinicial) into :wcount1;
      and substring(bddata from 1 for 4) = :wanoinicial into :wcount1;*/
---------------------------------------------------------------------- #alt:6470
      /*if (wcount1 = 0) then
         begin
            wcount = wcount + 1;

            bddeb01 = 0;
            bddeb02 = 0;
            bddeb03 = 0;
            bddeb04 = 0;
            bddeb05 = 0;
            bddeb06 = 0;
            bddeb07 = 0;
            bddeb08 = 0;
            bddeb09 = 0;
            bddeb10 = 0;
            bddeb11 = 0;
            bddeb12 = 0;

            bdcre01 = 0;
            bdcre02 = 0;
            bdcre03 = 0;
            bdcre04 = 0;
            bdcre05 = 0;
            bdcre06 = 0;
            bdcre07 = 0;
            bdcre08 = 0;
            bdcre09 = 0;
            bdcre10 = 0;
            bdcre11 = 0;
            bdcre12 = 0;

            --alt:9515 - Adicionados campos do movimento. Pedro
            bdmov01 = 0;
            bdmov02 = 0;
            bdmov03 = 0;
            bdmov04 = 0;
            bdmov05 = 0;
            bdmov06 = 0;
            bdmov07 = 0;
            bdmov08 = 0;
            bdmov09 = 0;
            bdmov10 = 0;
            bdmov11 = 0;
            bdmov12 = 0;

            bdsal01 = 0;
            bdsal02 = 0;
            bdsal03 = 0;
            bdsal04 = 0;
            bdsal05 = 0;
            bdsal06 = 0;
            bdsal07 = 0;
            bdsal08 = 0;
            bdsal09 = 0;
            bdsal10 = 0;
            bdsal11 = 0;
            bdsal12 = 0;

            suspend;
         end
      else
         begin*/
      --alt:9801 - Fim
              -- M?s 01
              IF ((prparticipante = 0) OR (prparticipante IS NULL)) THEN
                BEGIN
                  SELECT SALDO_DEB, SALDO_CRE, MOVIMENTO, Saldo_Atual, Saldo_Ant_Deb, Saldo_Ant_Cre, Saldo_Anterior
                  FROM sp_retorna_saldo_emp_x(:prcodemp, :prconta, :wdataini, :wdatafim, 0, :prignorazeramento, :prcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado)
                  INTO :bddeb01, :bdcre01, :bdmov01, bdsal01, bddebant, bdcreant, bdsalant;
                END
              ELSE
                BEGIN
                  SELECT BDSALDO_DEB, BDSALDO_CRE, BDMOVIMENTO, BDSALDO_ATUAL, BDSALDO_ANT_DEB, BDSALDO_ANT_CRE, BDSALDO_ANTERIOR
                  --from VSUC_SP_RETORNA_SALDOS_CTA_PART(:prcodemp,:wcodplapadrao, :wdataini, :wdatafim, :prconta, :prignorazeramento, -- alt:#6647 - gilberto - 12/09/2013
                  FROM vsuc_sp_retorna_saldos_ctaparty(:prcodemp,:wcodplapadrao, :wdataini, :wdatafim, :prconta, 0, :prignorazeramento,
                                                       :prparticipante, NULL, 0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, 1) --alt:13972 - 20/06/2016 - Precisa agrupar por CNPJ, sen?o vir?o 2 registros quando h? "lan?ar a". Pedro
                  INTO :bddeb01, :bdcre01, :bdmov01, bdsal01, bddebant, bdcreant, bdsalant;
                END

              wsalatu = COALESCE(bdsalant, 0);
/*
              bddeb01 = 0;
              bddeb02 = 0;
              bddeb03 = 0;
              bddeb04 = 0;
              bddeb05 = 0;
              bddeb06 = 0;
              bddeb07 = 0;
              bddeb08 = 0;
              bddeb09 = 0;
              bddeb10 = 0;
              bddeb11 = 0;
              bddeb12 = 0;
    
              bdcre01 = 0;
              bdcre02 = 0;
              bdcre03 = 0;
              bdcre04 = 0;
              bdcre05 = 0;
              bdcre06 = 0;
              bdcre07 = 0;
              bdcre08 = 0;
              bdcre09 = 0;
              bdcre10 = 0;
              bdcre11 = 0;
              bdcre12 = 0;
*/
              --alt:9515 - Retirado, pois n?o ser? mais utilizada essa lista de contas.
              --Al?m de tornar o processo muito lento ela excede facilmente o limite de caracteres do wSQL.
              --Com ela, essa rotina demorava 10 segundos na RN, agora leva apenas 1 segundo. Pedro
              /*wsql = '';
              wsql = wsql||'select tpla.bdcodtpla from planos_tpla tpla ';
              wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
              wsql = wsql||' and substring(tpla.BDCTALON FROM 1 FOR '||wtam||') = '''||wctalon||''' ';
              wsql = wsql||'order by tpla.bdctalon';

              wlstcta = '';
              for execute statement wsql into :wcodcta do
                 begin
                   wlstcta = wlstcta||trim(cast(wcodcta as varchar(10)))||',';
                 end
              wlstcta = substring(wlstcta from 1 for strlen(wlstcta)-1);*/
              --alt:9515 - Fim

              wsql = 'Select * from (';
              --#alt:5837
              /*wsql = wsql||'SELECT ';
              if ((prparticipante = 0) or (prparticipante is null)) then
                begin
                  wsql = wsql||'   SUM(CASE WHEN (tlan.bdcredito in ('||wlstcta||')) THEN TLAN.BDVALOR ELSE 0 end) AS SALCRE, ';
                  wsql = wsql||'   SUM(case when (tlan.bddebito in ('||wlstcta||')) then TLAN.BDVALOR else 0 end) AS SALDEB, ';
                end
              else
                begin
                  wsql = wsql||'   SUM(CASE WHEN ((tlan.bdcredito in ('||wlstcta||')) and (tlan.BDCODTERCEIROC = '|| :prparticipante ||')) THEN TLAN.BDVALOR ELSE 0 end) AS SALCRE, ';
                  wsql = wsql||'   SUM(case when ((tlan.bddebito in ('||wlstcta||')) and (tlan.BDCODTERCEIROD = '|| :prparticipante ||')) then TLAN.BDVALOR else 0 end) AS SALDEB, ';
                end
              wsql = wsql||'       (substring(bddata from 1 for 4)||substring(bddata from 6 for 2)) as Referencia ';
              wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
              wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
              wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
              if (prignorazeramento <> 1) then
                 wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
              wsql = wsql||'and (substring(cast(TLAN.BDDATA as varchar(10)) from 1 for 4) = '''||wanoinicial||''') ';
              wsql = wsql||'and ((tlan.bdcredito in ('||wlstcta||')) or (tlan.bddebito in ('||wlstcta||'))) ';
              wsql = wsql||'Group By Referencia ';
              wsql = wsql||'Order by Referencia Asc ';*/

              --D?bito
              wsql = wsql||'SELECT tlan.bdcodemp,bdfilial,bdtipolancfilial, 1 as bdtipolan,(substring(bddata from 1 for 4)||substring(bddata from 6 for 2)) as Referencia, ';

              --alt:9515 - Comentado porque n?o vai mais utilizar a lista de contas e a checagem por este m?todo n?o ? adequada. Mais detalhes acima. Pedro
              /*if ((prparticipante = 0) or (prparticipante is null)) then
                wsql = wsql||'SUM(case when (tlan.bddebito in ('||wlstcta||')) then TLAN.BDVALOR else 0 end) AS SALDEB ';
              else
                wsql = wsql||'SUM(case when ((tlan.bddebito in ('||wlstcta||')) and (tlan.BDCODTERCEIROD = '|| :prparticipante ||')) then TLAN.BDVALOR else 0 end) AS SALDEB ';*/

              --#Alt:14968 (01/07/2016) - Inclu?do a condi??o para buscar o valor da TLCC quando tem centro de custo informado. Carlos Mello
              IF ((prCC IS NOT NULL) AND (prCC <> '')) THEN
                wsql = wsql||'sum(TLCC.BDVALOR) AS SALDEB ';
              ELSE
                wsql = wsql||'sum(TLAN.BDVALOR) AS SALDEB ';
              --alt:9515 - Fim

              wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';

              --alt:13972 - 19/05/2016 - Adicionado filtro por centro de custo. Pedro
              IF ((prCC IS NOT NULL) AND (prCC <> '')) THEN
                wSQL = wSQL||'inner join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 0 and tlcc.BDCODTPCC in ('||prCC||')) ';

              --alt:9515 - Adicionado inner join das contas para poder filtrar pela classifica??o. Pedro
              wsql = wsql||'inner join PLANOS_TPLA TPLA on (TPLA.BDCODTPLA = TLAN.BDDEBITO and TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO) ';
              wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';

              IF (prignorazeramento <> 1) THEN
                 wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';

              --alt:9515 - Retirada a valida??o da lista de contas e adicionada pela classifica??o
              --e a do terceiro que tamb?m era feito na parte do select. Mais detalhes acima. Pedro
              --wsql = wsql||'and (tlan.bddebito in ('||wlstcta||')) ';
              wsql = wsql||'and (substring(TPLA.BDCTALON from 1 for '||wtam||') = '''||wctalon||''') ';

              IF ((prparticipante <> 0) AND (prparticipante IS NOT NULL)) THEN
                wsql = wsql||'and (tlan.BDCODTERCEIROD = '|| :prparticipante ||') ';
              --alt:9515 - Fim

              --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
              IF (prcontabilizacao <> 99) THEN
                wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
              wsql = wsql||'and (substring(cast(TLAN.BDDATA as varchar(10)) from 1 for 4) = '''||wanoinicial||''') ';

              --alt:9515 - Alterado para pegar corretamente os lan?amentos com a regra de "lan?ar a". Pedro
              --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (tlan.bdfilial = '||prcodemp||')) ';
              wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||' and tlan.bdtipolancfilial <> 1) or (tlan.bdfilial = '||prcodemp||' and tlan.bdtipolancfilial = 1)) ';

              wsql = wsql||'Group By tlan.BDCODEMP, BDFILIAL, BDTIPOLANCFILIAL, BDTIPOLAN, REFERENCIA ';
              wsql = wsql||' union all ';

              --Cr?dito
              wsql = wsql||'SELECT tlan.bdcodemp,bdfilial,bdtipolancfilial, 2 as bdtipolan,(substring(bddata from 1 for 4)||substring(bddata from 6 for 2)) as Referencia, ';

              --alt:9515 - Comentado porque n?o vai mais utilizar a lista de contas e a checagem por este m?todo n?o ? adequada. Mais detalhes acima. Pedro
              /*if ((prparticipante = 0) or (prparticipante is null)) then
                wsql = wsql||'SUM(case when (tlan.bdcredito in ('||wlstcta||')) then TLAN.BDVALOR else 0 end) AS SALCRE ';
              else
                wsql = wsql||'SUM(case when ((tlan.bdcredito in ('||wlstcta||')) and (tlan.BDCODTERCEIROC = '|| :prparticipante ||')) then TLAN.BDVALOR else 0 end) AS SALCRE ';*/

              --#Alt:14968 (01/07/2016) - Inclu?do a condi??o para buscar o valor da TLCC quando tem centro de custo informado. Carlos Mello
              IF ((prCC IS NOT NULL) AND (prCC <> '')) THEN
                wsql = wsql||'sum(TLCC.BDVALOR) AS SALCRE ';
              ELSE
                wsql = wsql||'sum(TLAN.BDVALOR) AS SALCRE ';
              --alt:9515 - Fim

              wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';

              --alt:13972 - 19/05/2016 - Adicionado filtro por centro de custo. Pedro
              IF ((prCC IS NOT NULL) AND (prCC <> '')) THEN
                wSQL = wSQL||'inner join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 1 and tlcc.BDCODTPCC in ('||prCC||')) ';

              --alt:9515 - Adicionado inner join das contas para poder filtrar pela classifica??o. Pedro
              wsql = wsql||'inner join PLANOS_TPLA TPLA on (TPLA.BDCODTPLA = TLAN.BDCREDITO and TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO) ';
              wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';
              IF (prignorazeramento <> 1) THEN
                 wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';

              --alt:9515 - Retirada a valida??o da lista de contas e adicionada pela classifica??o
              --e a do terceiro que tamb?m era feito na parte do select. Mais detalhes acima. Pedro
              --wsql = wsql||'and (tlan.bdcredito in ('||wlstcta||')) ';
              wsql = wsql||'and (substring(TPLA.BDCTALON from 1 for '||wtam||') = '''||wctalon||''') ';

              IF ((prparticipante <> 0) AND (prparticipante IS NOT NULL)) THEN
                wsql = wsql||'and (tlan.BDCODTERCEIROC = '|| :prparticipante ||') ';
              --alt:9515 - Fim

              --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
              IF (prcontabilizacao <> 99) THEN
                wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
              wsql = wsql||'and (substring(cast(TLAN.BDDATA as varchar(10)) from 1 for 4) = '''||wanoinicial||''') ';

              --alt:9515 - Alterado para pegar corretamente os lan?amentos com a regra de "lan?ar a". Pedro
              --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (tlan.bdfilial = '||prcodemp||')) ';
              wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||' and tlan.bdtipolancfilial <> 2) or (tlan.bdfilial = '||prcodemp||' and tlan.bdtipolancfilial = 2)) ';

              wsql = wsql||'Group By tlan.BDCODEMP, BDFILIAL, BDTIPOLANCFILIAL, BDTIPOLAN, REFERENCIA ';
              wsql = wsql||') Order by Referencia Asc ';

              FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wtipolan,:wref,:wvlr DO
                BEGIN
--                  select bdpermite from vsuc_sp_permitecalcsaldolancmf(:wtipolan,:prcodemp,      :wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
                  --alt:#6524 - implementado rotina "POS" aqui, por quest?o de desempenho, precisa apenas uma vez para as duas verifica??es
                  IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
                     BEGIN
                       wpos_pernamatriz = POSITION(prcodemp, wcodemp);
                       wpos_matriz = POSITION(wcodemp,  prcodemp);
                       wpos_filial = POSITION(wfilial,  prcodemp);
                    END
                  wpermite = 0;
                  --alt:#6524 - implementado rotina "VSUC_SP_PERMITECALCSALDOLANCMF" diretamente aqui, por quest?o de desempenho
                  --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
                  IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
                     wpermite = 1;
                  ELSE
                     BEGIN
                       --alt:9515 - Alterado porque aqui deve passar o tipo da conta, e n?o do lan?amento na filial, ainda mais que ele vai comparar o wcampo com o wtipolancfilial.
                       --Como o wcampo recebe do wtipolancfilial e o wcampo ? comparado com o wtipolancfilial, abaixo estaria como fazer "wtipolancfilial = wtipolancfilial"
                       --e "wtipolancfilial <> wtipolancfilial". Como essas valida??es n?o funcionavam corretamente, n?o retornava os valores corretos. Pedro
                       --wcampo = wtipolancfilial;
                       wcampo = wtipolan;
                       IF (((prcodemp = wcodemp) AND (wfilial = 0)) OR
                           --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
                           ((prcodemp = wfilial) AND (wcampo = wtipolancfilial)) OR
                           --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                           ((prcodemp = wcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                           --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
                           ((prmatrizfilialconsolidado = 1) AND (prcodemp <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                           --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
                           ((prmatrizfilialconsolidado = 1) AND (prcodemp = wcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
                          wpermite = 1;
                     END

                  IF (wpermite = 1) THEN
                    BEGIN
                      /*if (wdeb is null) then
                         wdeb = 0;
                      if (wcre is null) then
                       wcre = 0;*/
                      IF (wvlr IS NULL) THEN
                        wvlr = 0;
                      wdeb = wvlr;
                      wcre = 0;
                      IF (wtipolan = 2) THEN--Cr?dito
                        BEGIN
                          wdeb = 0;
                          wcre = wvlr;
                        END

                      IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                        wsalatu = COALESCE(wsalatu, 0) + (COALESCE(wdeb, 0) - COALESCE(wcre, 0));
                      ELSE
                      IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                        wsalatu = COALESCE(wsalatu, 0) + (COALESCE(wcre, 0) - COALESCE(wdeb, 0));
-- #alt:6470 - gilberto - 20/08/2013
/*                      if (substring(wref from 5 for 2) = '01') then
                        begin
                          bddeb01 = coalesce(bddeb01, 0) + wdeb;
                          bdcre01 = coalesce(bdcre01, 0) + wcre;
                          bdsal01 = coalesce(bdsal01, 0) + wsalatu;

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          if ((wgrupoconta = 0) or (wgrupoconta = 4) or (wgrupoconta = 5))  then -- ATIVO e DESPESAS
                            bdmov01 = coalesce(bdmov01, 0.00) + (coalesce(wdeb, 0.00) - coalesce(wcre, 0.00));
                          else
                          if ((wgrupoconta = 1) or (wgrupoconta = 3)) then -- PASSIVO e RECEITAS
                            bdmov01 = coalesce(bdmov01, 0.00) + (coalesce(wcre, 0.00) - coalesce(wdeb, 0.00));
                        end
                      else */
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '02') THEN
                        BEGIN
                          bddeb02 = COALESCE(bddeb02, 0) + COALESCE(wdeb, 0);
                          bdcre02 = COALESCE(bdcre02, 0) + COALESCE(wcre, 0);
                          bdsal02 = COALESCE(bdsal02, 0) + COALESCE(wsalatu, 0);

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov02 = COALESCE(bdmov02, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov02 = COALESCE(bdmov02, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '03') THEN
                        BEGIN
                          bddeb03 = COALESCE(bddeb03, 0) + COALESCE(wdeb, 0);
                          bdcre03 = COALESCE(bdcre03, 0) + COALESCE(wcre, 0);
                          bdsal03 = COALESCE(bdsal03, 0) + COALESCE(wsalatu, 0);   

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov03 = COALESCE(bdmov03, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov03 = COALESCE(bdmov03, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '04') THEN
                        BEGIN
                          bddeb04 = COALESCE(bddeb04, 0) + COALESCE(wdeb, 0);
                          bdcre04 = COALESCE(bdcre04, 0) + COALESCE(wcre, 0);
                          bdsal04 = COALESCE(bdsal04, 0) + COALESCE(wsalatu, 0);   

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov04 = COALESCE(bdmov04, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov04 = COALESCE(bdmov04, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '05') THEN
                        BEGIN
                          bddeb05 = COALESCE(bddeb05, 0) + COALESCE(wdeb, 0);
                          bdcre05 = COALESCE(bdcre05, 0) + COALESCE(wcre, 0);
                          bdsal05 = COALESCE(bdsal05, 0) + COALESCE(wsalatu, 0);   

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov05 = COALESCE(bdmov05, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov05 = COALESCE(bdmov05, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '06') THEN
                        BEGIN
                          bddeb06 = COALESCE(bddeb06, 0) + COALESCE(wdeb, 0);
                          bdcre06 = COALESCE(bdcre06, 0) + COALESCE(wcre, 0);
                          bdsal06 = COALESCE(bdsal06, 0) + COALESCE(wsalatu, 0);  

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov06 = COALESCE(bdmov06, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov06 = COALESCE(bdmov06, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '07') THEN
                        BEGIN
                          bddeb07 = COALESCE(bddeb07, 0) + COALESCE(wdeb, 0);
                          bdcre07 = COALESCE(bdcre07, 0) + COALESCE(wcre, 0);
                          bdsal07 = COALESCE(bdsal07, 0) + COALESCE(wsalatu, 0);    

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov07 = COALESCE(bdmov07, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov07 = COALESCE(bdmov07, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '08') THEN
                        BEGIN
                          bddeb08 = COALESCE(bddeb08, 0) + COALESCE(wdeb, 0);
                          bdcre08 = COALESCE(bdcre08, 0) + COALESCE(wcre, 0);
                          bdsal08 = COALESCE(bdsal08, 0) + COALESCE(wsalatu, 0);    

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov08 = COALESCE(bdmov08, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov08 = COALESCE(bdmov08, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '09') THEN
                        BEGIN
                          bddeb09 = COALESCE(bddeb09, 0) + COALESCE(wdeb, 0);
                          bdcre09 = COALESCE(bdcre09, 0) + COALESCE(wcre, 0);
                          bdsal09 = COALESCE(bdsal09, 0) + COALESCE(wsalatu, 0); 

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov09 = COALESCE(bdmov09, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov09 = COALESCE(bdmov09, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '10') THEN
                        BEGIN
                          bddeb10 = COALESCE(bddeb10, 0) + COALESCE(wdeb, 0);
                          bdcre10 = COALESCE(bdcre10, 0) + COALESCE(wcre, 0);
                          bdsal10 = COALESCE(bdsal10, 0) + COALESCE(wsalatu, 0);   

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov10 = COALESCE(bdmov10, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov10 = COALESCE(bdmov10, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '11') THEN
                        BEGIN
                          bddeb11 = COALESCE(bddeb11, 0) + COALESCE(wdeb, 0);
                          bdcre11 = COALESCE(bdcre11, 0) + COALESCE(wcre, 0);
                          bdsal11 = COALESCE(bdsal11, 0) + COALESCE(wsalatu, 0); 

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov11 = COALESCE(bdmov11, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov11 = COALESCE(bdmov11, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '12') THEN
                        BEGIN
                          bddeb12 = COALESCE(bddeb12, 0) + COALESCE(wdeb, 0);
                          bdcre12 = COALESCE(bdcre12, 0) + COALESCE(wcre, 0);
                          bdsal12 = COALESCE(bdsal12, 0) + COALESCE(wsalatu, 0);  

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov12 = COALESCE(bdmov12, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov12 = COALESCE(bdmov12, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                    END
                END

              IF (bdsal02 IS NULL) THEN
                 bdsal02 = COALESCE(bdsal01, 0);
              IF (bdsal03 IS NULL) THEN
                 bdsal03 = COALESCE(bdsal02, 0);
              IF (bdsal04 IS NULL) THEN
                 bdsal04 = COALESCE(bdsal03, 0);
              IF (bdsal05 IS NULL) THEN
                 bdsal05 = COALESCE(bdsal04, 0);
              IF (bdsal06 IS NULL) THEN
                 bdsal06 = COALESCE(bdsal05, 0);
              IF (bdsal07 IS NULL) THEN
                 bdsal07 = COALESCE(bdsal06, 0);
              IF (bdsal08 IS NULL) THEN
                 bdsal08 = COALESCE(bdsal07, 0);
              IF (bdsal09 IS NULL) THEN
                 bdsal09 = COALESCE(bdsal08, 0);
              IF (bdsal10 IS NULL) THEN
                 bdsal10 = COALESCE(bdsal09, 0);
              IF (bdsal11 IS NULL) THEN
                 bdsal11 = COALESCE(bdsal10, 0);
              IF (bdsal12 IS NULL) THEN
                 bdsal12 = COALESCE(bdsal11, 0);

              -- gilberto - 21/08/2013 - #alt:6470 -----------------------------
              -- inserido coalesce pois alguns valores eram nulos prejudicando os meses seguintes
              IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                 BEGIN
--                   wsalatu = wsalatu + (wdeb - wcre);
                   bdsal02 = COALESCE(bdsal01, 0) + COALESCE(bddeb02, 0) - COALESCE(bdcre02, 0);
                   bdsal03 = COALESCE(bdsal02, 0) + COALESCE(bddeb03, 0) - COALESCE(bdcre03, 0);
                   bdsal04 = COALESCE(bdsal03, 0) + COALESCE(bddeb04, 0) - COALESCE(bdcre04, 0);
                   bdsal05 = COALESCE(bdsal04, 0) + COALESCE(bddeb05, 0) - COALESCE(bdcre05, 0);
                   bdsal06 = COALESCE(bdsal05, 0) + COALESCE(bddeb06, 0) - COALESCE(bdcre06, 0);
                   bdsal07 = COALESCE(bdsal06, 0) + COALESCE(bddeb07, 0) - COALESCE(bdcre07, 0);
                   bdsal08 = COALESCE(bdsal07, 0) + COALESCE(bddeb08, 0) - COALESCE(bdcre08, 0);
                   bdsal09 = COALESCE(bdsal08, 0) + COALESCE(bddeb09, 0) - COALESCE(bdcre09, 0);
                   bdsal10 = COALESCE(bdsal09, 0) + COALESCE(bddeb10, 0) - COALESCE(bdcre10, 0);
                   bdsal11 = COALESCE(bdsal10, 0) + COALESCE(bddeb11, 0) - COALESCE(bdcre11, 0);
                   bdsal12 = COALESCE(bdsal11, 0) + COALESCE(bddeb12, 0) - COALESCE(bdcre12, 0);
                 END
              ELSE
              IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                 BEGIN
--                   wsalatu = wsalatu + (wcre - wdeb);
                   bdsal02 = COALESCE(bdsal01, 0) + COALESCE(bdcre02, 0) - COALESCE(bddeb02, 0);
                   bdsal03 = COALESCE(bdsal02, 0) + COALESCE(bdcre03, 0) - COALESCE(bddeb03, 0);
                   bdsal04 = COALESCE(bdsal03, 0) + COALESCE(bdcre04, 0) - COALESCE(bddeb04, 0);
                   bdsal05 = COALESCE(bdsal04, 0) + COALESCE(bdcre05, 0) - COALESCE(bddeb05, 0);
                   bdsal06 = COALESCE(bdsal05, 0) + COALESCE(bdcre06, 0) - COALESCE(bddeb06, 0);
                   bdsal07 = COALESCE(bdsal06, 0) + COALESCE(bdcre07, 0) - COALESCE(bddeb07, 0);
                   bdsal08 = COALESCE(bdsal07, 0) + COALESCE(bdcre08, 0) - COALESCE(bddeb08, 0);
                   bdsal09 = COALESCE(bdsal08, 0) + COALESCE(bdcre09, 0) - COALESCE(bddeb09, 0);
                   bdsal10 = COALESCE(bdsal09, 0) + COALESCE(bdcre10, 0) - COALESCE(bddeb10, 0);
                   bdsal11 = COALESCE(bdsal10, 0) + COALESCE(bdcre11, 0) - COALESCE(bddeb11, 0);
                   bdsal12 = COALESCE(bdsal11, 0) + COALESCE(bdcre12, 0) - COALESCE(bddeb12, 0);
                 END

              bdsaltotdeb = COALESCE(bdsaltotdeb, 0) +
                            COALESCE(bddeb01, 0) +
                            COALESCE(bddeb02, 0) +
                            COALESCE(bddeb03, 0) +
                            COALESCE(bddeb04, 0) +
                            COALESCE(bddeb05, 0) +
                            COALESCE(bddeb06, 0) +
                            COALESCE(bddeb07, 0) +
                            COALESCE(bddeb08, 0) +
                            COALESCE(bddeb09, 0) +
                            COALESCE(bddeb10, 0) +
                            COALESCE(bddeb11, 0) +
                            COALESCE(bddeb12, 0);
        
              bdsaltotcre = COALESCE(bdsaltotcre, 0) +
                            COALESCE(bdcre01, 0) +
                            COALESCE(bdcre02, 0) +
                            COALESCE(bdcre03, 0) +
                            COALESCE(bdcre04, 0) +
                            COALESCE(bdcre05, 0) +
                            COALESCE(bdcre06, 0) +
                            COALESCE(bdcre07, 0) +
                            COALESCE(bdcre08, 0) +
                            COALESCE(bdcre09, 0) +
                            COALESCE(bdcre10, 0) +
                            COALESCE(bdcre11, 0) +
                            COALESCE(bdcre12, 0);
              -------------------------------------------------------- #alt:6470
        
              --alt:9515 - Adicionados campos do movimento. Pedro
              bdsaltotmov = COALESCE(bdsaltotmov, 0) +
                            COALESCE(bdmov01, 0) +
                            COALESCE(bdmov02, 0) +
                            COALESCE(bdmov03, 0) +
                            COALESCE(bdmov04, 0) +
                            COALESCE(bdmov05, 0) +
                            COALESCE(bdmov06, 0) +
                            COALESCE(bdmov07, 0) +
                            COALESCE(bdmov08, 0) +
                            COALESCE(bdmov09, 0) +
                            COALESCE(bdmov10, 0) +
                            COALESCE(bdmov11, 0) +
                            COALESCE(bdmov12, 0);

              bdsaltotatu = bdsal12;
              BDGRPCTA = wgrupoconta;
        
              wcount = wcount +1;
              SUSPEND;
         --end
    END
END
^

/* Alter (VSUC_SP_RETORNA_RAZAO_CONTAS) */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRLCC VARCHAR(1024),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(PRHISTORICO VARCHAR(100),
PRDATA DATE,
PRCHAVE INTEGER,
PRCONTA INTEGER,
PRCONTRA INTEGER,
PRCREDITO NUMERIC(15,2),
PRDEBITO NUMERIC(15,2),
PRCONCILIADO VARCHAR(5),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCC INTEGER,
PRNOME_CONTA VARCHAR(100),
PRCLASS_CONTA VARCHAR(40),
PRCLASS_CONTRA VARCHAR(40),
PRNOME_CONTA_CONTRA VARCHAR(100),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCOMPL VARCHAR(200),
PRCNPJEMP VARCHAR(18),
PRCODMATRIZ INTEGER,
PRGRPCTA INTEGER,
PRCODHIST INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODTPHI INTEGER,
PRPARTICIPANTECONTA INTEGER,
PRPARTICIPANTECONTRA INTEGER,
PRCODTERCEIROCONTA INTEGER,
PRCODTERCEIROCONTRA INTEGER,
PRCODEMPFILIAL INTEGER,
PRTIPOLAN INTEGER,
PRCHAVEONLINE VARCHAR(120))
 AS
DECLARE VARIABLE wcredito INTEGER;
DECLARE VARIABLE wdebito INTEGER;
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wctalonc VARCHAR(40);
DECLARE VARIABLE wctalonaxuc VARCHAR(40);
DECLARE VARIABLE wnomctac VARCHAR(100);
DECLARE VARIABLE wtipctac INTEGER;
DECLARE VARIABLE wcodterceiroc INTEGER;
DECLARE VARIABLE wparticipantec INTEGER;
DECLARE VARIABLE wconcd VARCHAR(5);
DECLARE VARIABLE wconcc VARCHAR(5);
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wsql VARCHAR(11244);
DECLARE VARIABLE wctalond VARCHAR(40);
DECLARE VARIABLE wctalonaxud VARCHAR(40);
DECLARE VARIABLE wnomctad VARCHAR(100);
DECLARE VARIABLE wtipctad INTEGER;
DECLARE VARIABLE wcodterceirod INTEGER;
DECLARE VARIABLE wparticipanted INTEGER;
DECLARE VARIABLE wgrpctac INTEGER;
DECLARE VARIABLE wgrpctad INTEGER;
DECLARE VARIABLE wdebcre INTEGER;
DECLARE VARIABLE wcodempresalan INTEGER;
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wempprinc INTEGER;
DECLARE VARIABLE wselectcta INTEGER;
DECLARE VARIABLE wsubstr VARCHAR(1024);
DECLARE VARIABLE wstr VARCHAR(1024);
DECLARE VARIABLE wpos_pernamatriz INTEGER;
DECLARE VARIABLE wcount INTEGER;
DECLARE VARIABLE wpos_matriz INTEGER;
DECLARE VARIABLE wpos_filial INTEGER;
DECLARE VARIABLE wcampo INTEGER;
BEGIN
  wsql = 'select first 1 case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  wpos = POSITION(',', :prcodemp);
  IF (wpos <> 0) THEN
     wsql = wsql||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsql = wsql||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsql = wsql||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsql = wsql||'       end bdcodemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||')';
  EXECUTE STATEMENT wsql INTO :prempresa;

  wdatini   = SUBSTRING(CAST(prdata_inicial AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
              SUBSTRING(CAST(prdata_inicial AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
              SUBSTRING(CAST(prdata_inicial AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin   = SUBSTRING(CAST(prdata_final AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
              SUBSTRING(CAST(prdata_final AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
              SUBSTRING(CAST(prdata_final AS VARCHAR(10)) FROM 1 FOR 4);

  --Retorna a empresa principal
  wpos = POSITION(',', :prcodemp);
  IF (wpos = 0) THEN
     wempprinc = prcodemp;
  ELSE
     wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  -- D?bito
  wsql = 'select tlan.bdchave, tlan.bddata, tlan.bdcodemp, ';
  wsql = wsql||'tlan.bdcredito, tlan.bdcodterceiroc, tlan.bdconcc, tplac.bdctalon, tplac.bdnomcta, tplac.bdgrupocta, tplac.bdtipcta, tplac.bdparticipante, ';
  wsql = wsql||'tlan.bddebito, tlan.bdcodterceirod, tlan.bdconcd, tplad.bdctalon, tplad.bdnomcta, tplad.bdgrupocta, tplad.bdtipcta, tplad.bdparticipante, ';
  wsql = wsql||'this.bdnome, tlan.bdlote, tlan.bdcompl, tlan.bddcto, this.bdcodhist, tlan.bdcodtphi, tlan.bdcodplapadrao, ';
  wsql = wsql||'temp.bdcnpjemp, temp.bdcodmatriz, temp.bdnomemp, tlan.bdtipolan, tlan.bdchaveonline, tlan.bdfilial, tlan.bdtipolancfilial, ';

  IF (prlcc = '') THEN
     wsql = wsql||'tlan.bdvalor, tlan.bdchave, tlan.bdchave from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.bdvalor, tlcc.bdcodtpcc, tlcc.bddebcre from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
  wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
  wsql = wsql||'left outer join hist_tphi this on (this.bdcodhist = tlan.bdcodhist and this.bdcodtphi = tlan.bdcodtphi) ';
  wsql = wsql||'inner join vw_empresas_ref_atual temp on (temp.bdcodemp = tlan.bdcodemp) ';
  wsql = wsql||'where ';
  --#alt:5619 - gilberto - 13/08/2013 __________________________________________________
  SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wselectcta;
  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
     wsql = wsql||'(tlan.bddebito in (select bdcodtpla from vsuc_select_contas tsel)) ';
  -----------------------------------------------------------------------------#alt:5619
  ELSE
     wsql = wsql||'(tplad.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (prlcc <> '') THEN
     wsql = wsql||'and (tlcc.bdcodtpcc in ('||TRIM(prlcc)||')) ';
  wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
  IF ((prpartini IS NOT NULL) AND (prpartfin IS NOT NULL)) THEN
     wsql = wsql||'and (tlan.bdcodterceirod between '||prpartini||' and '||prpartfin||') ';
  --#alt:5837.
  --wsql = wsql||'and tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial in ('||prcodemp||'))) ';

  FOR EXECUTE STATEMENT wsql
  INTO :prchave, :prdata, :prempresa,
       :wcredito, :wcodterceiroc, :wconcc, :wctalonc, :wnomctac, :wgrpctac, :wtipctac, :wparticipantec,
       :wdebito, :wcodterceirod, :wconcd, :wctalond, :wnomctad, :wgrpctad, :wtipctad, :wparticipanted,
       :prhistorico, :prlote, :prcompl, :prdcto, :prcodhist, :prcodtphi, :prcodplapadrao,
       :prcnpjemp, :prcodmatriz, :prnomeempresa, :prtipolan, :prchaveonline, :wfilial, :wtipolancfilial,
       :wvalor, :prcc, :wdebcre DO
  BEGIN
    prcodempfilial = prempresa;

    wpos = POSITION(',', :prcodemp);
    IF (wpos <> 0) THEN
       BEGIN
         prcodempfilial = prempresa;
         IF (prcodmatriz IS NULL) THEN
            prcodmatriz = prempresa;
         prempresa = prcodmatriz;
       END

    --Foi criado essas vari?veis auxiliares pois quando esta por detalhar participante
    --ele precisa verificar a classifica??o pela conta original
    wctalonaxuc = wctalonc;
    wctalonaxud = wctalond;

    IF (prlcc = '') THEN
       prcc = 0;
    -- D?bito
--    if ((prdetalharctaparticipante = 1) and (wparticipanted = 1) and (wtipctad = 1)) then
--      select bdclassificacao, bdnome from vsuc_sp_nomenclatura_cta_partic(:wcodterceirod,:wctalond,:prconcatenacodparticipante) into :wctalond,:wnomctad;


    --alt:#6524 - implementado rotina "POS" aqui, por quest?o de desempenho, precisa apenas uma vez para as duas verifica??es
--    select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
    IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
       BEGIN
       --alt:#6535 - gilberto - 05/09/2013
         wpos_pernamatriz = POSITION(wempprinc, prcodemp);
         wpos_matriz = POSITION(prempresa, prcodemp);
         wpos_filial = POSITION(wfilial, prcodemp);
      END
    wcampo = 1;

    IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
       wpermite = 1;
    ELSE
    IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
        --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
        ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
        --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
        ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
        --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
        ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
        --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
        ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
       wpermite = 1;
    ELSE
       wpermite = 0;
    -------------------------------------------------------------------alt:#6524
    IF (wpermite = 1) THEN
      BEGIN
        --#alt:5837.
        IF ((wfilial > 0) AND (wtipolancfilial = 1)) THEN
          prcodempfilial = wfilial;
        --Verifica se precisa limpar a conta contra
        --alt:#6524-------------------------------------------------------------
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(2,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        wcampo = 2;
    
        IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           wpermite = 1;
        ELSE
        IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
            --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
            ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
            --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
            ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
            --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
            ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
            --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
            ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
           wpermite = 1;
        ELSE
           wpermite = 0;
        ---------------------------------------------------------------alt:#6524
        IF (prclassificacao_inicial = prclassificacao_final) THEN
          BEGIN
            IF (((prlcc = '') AND (NOT wdebito IS NULL)) OR
                ((prlcc <> '') AND (wdebcre = 0))) THEN
              BEGIN
                IF (wctalonaxud BETWEEN prclassificacao_inicial AND prclassificacao_final) THEN
                  BEGIN
                    prdebito     = wvalor;
                    prcredito    = NULL;
                    prconta      = wdebito;
                    prcontra     = wcredito;
                    prconciliado = wconcd;
                    prgrpcta     = wgrpctad;

                    prnome_conta         = wnomctad;
                    prclass_conta        = wctalond;
                    prparticipanteconta  = wparticipanted;
                    prcodterceiroconta   = wcodterceirod;
                    prclass_contra       = wctalonc;
                    prnome_conta_contra  = wnomctac;
                    prparticipantecontra = wparticipantec;
                    prcodterceirocontra  = wcodterceiroc;
                    --#alt:5837.
                    IF ((wpermite = 0) OR ((prdetalharfilial = 1) AND (wfilial > 0))) THEN
                      BEGIN
                        prcontra             = NULL;
                        prclass_contra       = '';
                        prnome_conta_contra  = '';
                        prparticipantecontra = NULL;
                        prcodterceirocontra  = NULL;
                      END
                    SUSPEND;
                  END
              END
          END
        ELSE
          BEGIN
            IF (((prlcc = '') AND (NOT wdebito IS NULL)) OR
                ((prlcc <> '') AND (wdebcre = 0))) THEN
              BEGIN
                IF (wctalonaxud BETWEEN prclassificacao_inicial AND prclassificacao_final) THEN
                  BEGIN
                    prdebito     = wvalor;
                    prcredito    = NULL;
                    prconta      = wdebito;
                    prcontra     = wcredito;
                    prconciliado = wconcd;
                    prgrpcta     = wgrpctad;

                    prnome_conta         = wnomctad;
                    prclass_conta        = wctalond;
                    prparticipanteconta  = wparticipanted;
                    prcodterceiroconta   = wcodterceirod;
                    prclass_contra       = wctalonc;
                    prnome_conta_contra  = wnomctac;
                    prparticipantecontra = wparticipantec;
                    prcodterceirocontra  = wcodterceiroc;
                    --#alt:5837.
                    IF ((wpermite = 0) OR ((prdetalharfilial = 1) AND (wfilial > 0))) THEN
                      BEGIN
                        prcontra             = NULL;
                        prclass_contra       = '';
                        prnome_conta_contra  = '';
                        prparticipantecontra = NULL;
                        prcodterceirocontra  = NULL;
                      END
                    SUSPEND;
                  END
              END
          END
      END
  END
  -- Cr?dito
  wsql = 'select tlan.bdchave, tlan.bddata, tlan.bdcodemp, ';
  wsql = wsql||'tlan.bdcredito, tlan.bdcodterceiroc, tlan.bdconcc, tplac.bdctalon, tplac.bdnomcta, tplac.bdgrupocta, tplac.bdtipcta, tplac.bdparticipante, ';
  wsql = wsql||'tlan.bddebito, tlan.bdcodterceirod, tlan.bdconcd, tplad.bdctalon, tplad.bdnomcta, tplad.bdgrupocta, tplad.bdtipcta, tplad.bdparticipante, ';
  wsql = wsql||'this.bdnome, tlan.bdlote, tlan.bdcompl, tlan.bddcto, this.bdcodhist, tlan.bdcodtphi, tlan.bdcodplapadrao, ';
  wsql = wsql||'temp.bdcnpjemp, temp.bdcodmatriz, temp.bdnomemp, tlan.bdtipolan, tlan.bdchaveonline, tlan.bdfilial, tlan.bdtipolancfilial, ';
  IF (prlcc = '') THEN
     wsql = wsql||'tlan.bdvalor, tlan.bdchave, tlan.bdchave from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.bdvalor, tlcc.bdcodtpcc, tlcc.bddebcre from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
  wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
  wsql = wsql||'left outer join hist_tphi this on (this.bdcodhist = tlan.bdcodhist and this.bdcodtphi = tlan.bdcodtphi) ';
  wsql = wsql||'inner join vw_empresas_ref_atual temp on (temp.bdcodemp = tlan.bdcodemp) ';
  wsql = wsql||'where ';
  --#alt:5619 - gilberto - 13/08/2013 ______________________________________________
  SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wselectcta;
  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
     wsql = wsql||'(tlan.bdcredito in (select bdcodtpla from vsuc_select_contas)) ';
  -------------------------------------------------------------------------#alt:5619
  ELSE
     wsql = wsql||'(tplac.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (prlcc <> '') THEN
     wsql = wsql||'and (tlcc.bdcodtpcc in ('||TRIM(prlcc)||')) ';
  wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
  IF ((prpartini IS NOT NULL) AND (prpartfin IS NOT NULL)) THEN
     wsql = wsql||'and (tlan.bdcodterceiroc between '||prpartini||' and '||prpartfin||') ';
  --#alt:5837.
  --wsql = wsql||'and tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial in ('||prcodemp||'))) ';


  FOR EXECUTE STATEMENT wsql
  INTO :prchave, :prdata, :prempresa,
       :wcredito, :wcodterceiroc, :wconcc, :wctalonc, :wnomctac, :wgrpctac, :wtipctac, :wparticipantec,
       :wdebito, :wcodterceirod, :wconcd, :wctalond, :wnomctad, :wgrpctad, :wtipctad, :wparticipanted,
       :prhistorico, :prlote, :prcompl, :prdcto, :prcodhist, :prcodtphi, :prcodplapadrao,
       :prcnpjemp, :prcodmatriz, :prnomeempresa, :prtipolan, :prchaveonline, :wfilial, :wtipolancfilial,
       :wvalor, :prcc, :wdebcre DO
  BEGIN
    prcodempfilial = prempresa;

    wpos = POSITION(',', :prcodemp);
    IF (wpos <> 0) THEN
       BEGIN
--         prcodempfilial = prempresa;
         IF (prcodmatriz IS NULL) THEN
            prcodmatriz = prempresa;
         prempresa = prcodmatriz;
       END

    --Foi criado essas vari?veis auxiliares pois quando esta por detalhar participante
    --ele precisa verificar a classifica??o pela conta original
    wctalonaxuc = wctalonc;
    wctalonaxud = wctalond;

    IF (prlcc = '') THEN
       prcc = 0;
    -- Cr?dito
--    if ((prdetalharctaparticipante = 1) and (wparticipantec = 1) and (wtipctac = 1)) then
--       select bdclassificacao, bdnome from vsuc_sp_nomenclatura_cta_partic(:wcodterceiroc,:wctalonc,:prconcatenacodparticipante) into :wctalonc,:wnomctac;


    --alt:#6524 - implementado rotina "POS" aqui, por quest?o de desempenho, precisa apenas uma vez para as duas verifica??es
    --select bdpermite from vsuc_sp_permitecalcsaldolancmf(2,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
    IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
       BEGIN
       --alt:#6535 - gilberto - 05/09/2013
         wpos_pernamatriz = POSITION(wempprinc, prcodemp);
         wpos_matriz = POSITION(prempresa, prcodemp);
         wpos_filial = POSITION(wfilial, prcodemp);
      END
    wcampo = 2;

    IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
       wpermite = 1;
    ELSE
    IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
        --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
        ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
        --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
        ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
        --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
        ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
        --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
        ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
       wpermite = 1;
    ELSE
       wpermite = 0;
    -------------------------------------------------------------------alt:#6524
    IF (wpermite = 1) THEN
      BEGIN
        --#alt:5837.
        IF ((wfilial > 0) AND (wtipolancfilial = 2)) THEN
          prcodempfilial = wfilial;
        --Verifica se precisa limpar a conta contra
        --alt:#6524-------------------------------------------------------------
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        wcampo = 2;
    
        IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           wpermite = 1;
        ELSE
        IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
            --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
            ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
            --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
            ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
            --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
            ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
            --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
            ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
           wpermite = 1;
        ELSE
           wpermite = 0;
        ---------------------------------------------------------------alt:#6524
        IF (prclassificacao_inicial = prclassificacao_final) THEN
          BEGIN
            IF (((prlcc = '') AND (NOT wcredito IS NULL)) OR
                ((prlcc <> '') AND (wdebcre = 1))) THEN
              BEGIN
                IF (wctalonaxuc BETWEEN prclassificacao_inicial AND prclassificacao_final) THEN
                  BEGIN
                    prdebito     = NULL;
                    prcredito    = wvalor;
                    prconta      = wcredito;
                    prcontra     = wdebito;
                    prconciliado = wconcc;
                    prgrpcta     = wgrpctac;

                    prnome_conta         = wnomctac;
                    prclass_conta        = wctalonc;
                    prparticipanteconta  = wparticipantec;
                    prcodterceiroconta   = wcodterceiroc;
                    prclass_contra       = wctalond;
                    prnome_conta_contra  = wnomctad;
                    prparticipantecontra = wparticipanted;
                    prcodterceirocontra  = wcodterceirod;
                    --#alt:5837.
                    IF ((wpermite = 0) OR ((prdetalharfilial = 1) AND (wfilial > 0))) THEN
                      BEGIN
                        prcontra             = NULL;
                        prclass_contra       = '';
                        prnome_conta_contra  = '';
                        prparticipantecontra = NULL;
                        prcodterceirocontra  = NULL;
                      END
                    SUSPEND;
                  END
              END
          END
        ELSE
          BEGIN
            IF (((prlcc = '') AND (NOT wcredito IS NULL)) OR
                ((prlcc <> '') AND (wdebcre = 1))) THEN
              BEGIN
                IF (wctalonaxuc BETWEEN prclassificacao_inicial AND prclassificacao_final) THEN
                  BEGIN
                    prdebito     = NULL;
                    prcredito    = wvalor;
                    prconta      = wcredito;
                    prcontra     = wdebito;
                    prconciliado = wconcc;
                    prgrpcta     = wgrpctac;

                    prnome_conta         = wnomctac;
                    prclass_conta        = wctalonc;
                    prparticipanteconta  = wparticipantec;
                    prcodterceiroconta   = wcodterceiroc;
                    prclass_contra       = wctalond;
                    prnome_conta_contra  = wnomctad;
                    prparticipantecontra = wparticipanted;
                    prcodterceirocontra  = wcodterceirod;
                    --#alt:5837.
                    IF ((wpermite = 0) OR ((prdetalharfilial = 1) AND (wfilial > 0))) THEN
                      BEGIN
                        prcontra             = NULL;
                        prclass_contra       = '';
                        prnome_conta_contra  = '';
                        prparticipantecontra = NULL;
                        prcodterceirocontra  = NULL;
                      END
                    SUSPEND;
                  END
              END
          END
      END
  END
END
^

/* Alter (VSUC_SP_RETORNA_RAZAO_CONTAS_X) */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS_X(PRCODEMP VARCHAR(1024),
PRREFEMP INTEGER,
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRDETALHARCC INTEGER,
PRLCC DM_MAXVARCHAR,
PRLANCAMENTOSEMCC INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRCONTASSEMMOVIMENTO INTEGER,
PRIGNORAZERAMENTO INTEGER = 0)
 RETURNS(PRHISTORICO VARCHAR(100),
PRDATA DATE,
PRCHAVE INTEGER,
PRCONTA INTEGER,
PRCONTRA INTEGER,
PRCREDITO NUMERIC(18,2),
PRDEBITO NUMERIC(18,2),
PRCONCILIADO VARCHAR(5),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCC INTEGER,
PRNOME_CONTA VARCHAR(100),
PRNOME_CONTA_ORIGINAL VARCHAR(100),
PRCLASS_CONTA VARCHAR(40),
PRCLASS_CONTRA VARCHAR(40),
PRNOME_CONTA_CONTRA VARCHAR(100),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCOMPL VARCHAR(200),
PRCNPJEMP VARCHAR(18),
PRCODMATRIZ INTEGER,
PRGRPCTA INTEGER,
PRCODHIST INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODTPHI INTEGER,
PRPARTICIPANTECONTA INTEGER,
PRPARTICIPANTECONTRA INTEGER,
PRCODTERCEIROCONTA INTEGER,
PRCODTERCEIROCONTRA INTEGER,
PRCGC_CONTA VARCHAR(18),
PRCODEMPFILIAL INTEGER,
PRTIPOLANCFILIAL INTEGER,
PRTIPOLAN INTEGER,
PRCHAVEONLINE VARCHAR(120),
PRCODCENTRO INTEGER,
PRTRANSACAO INTEGER,
PRTRANFECHADA DM_BOOLEAN,
PRCONCILIACAOPENDENTE INTEGER,
PRDEBCRE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(30000) CHARACTER SET WIN1252;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WEMPPRINC INTEGER;
DECLARE VARIABLE WSELECTCTA INTEGER;
DECLARE VARIABLE WPOS_PERNAMATRIZ INTEGER;
DECLARE VARIABLE WPOS_MATRIZ INTEGER;
DECLARE VARIABLE WPOS_FILIAL INTEGER;
DECLARE VARIABLE WCAMPO INTEGER;
DECLARE VARIABLE WTIPCTACONTA INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WNOMETER VARCHAR(100) CHARACTER SET WIN1252;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
BEGIN
  wsql = 'select first 1 case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  wpos = POSITION(',', :prcodemp);
  IF (wpos <> 0) THEN
     wsql = wsql||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsql = wsql||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsql = wsql||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsql = wsql||'       end bdcodemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||')';
  --alt:15745 - 14/09/2016 - Corrigida vari?vel onde deve ser gravado o c?digo da empresa matriz. Estava com erro no "lan?ar a" validar com a empresa incorreta. Pedro
  --EXECUTE STATEMENT wsql INTO :prempresa;
  EXECUTE STATEMENT wsql INTO :prcodmatriz;

  --Retorna a empresa principal
  IF (wpos = 0) THEN
     wempprinc = prcodemp;
  ELSE
     wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wselectcta;

  wsql = '';
  wsql = wsql||'select tx.bdchave, tx.bddata, ';
  --#Alt:21066 - Alterado por causa da lentid?o (Carlos Mello)
  --wsql = wsql||'       tx.bdcodemp, emp.bdnomemp, emp.bdcnpjemp, ';
  wsql = wsql||'       tx.bdcodemp, empref.bdnomemp, emp.bdcnpjemp, ';
  wsql = wsql||'       tx.bdcodplapadrao, ';
  wsql = wsql||'       tx.bdlote, tx.bdcompl, tx.bddcto, ';
  wsql = wsql||'       tx.bdfilial, tx.bdtipolancfilial, ';
  wsql = wsql||'       tx.bdtipolan, tx.bdchaveonline, ';
  wsql = wsql||'       tx.bdcodhist, tx.bdcodtphi, this.bdnome,  ';
  wsql = wsql||'       tpla.bdcodtpla as BDCONTA, tx.bdcodter as bdcodter_conta, tx.bdconc as bdconc_conta, tx.bdconciliacaopendente, ';
  wsql = wsql||'       tpla.bdctalon as ctalon_conta, tpla.bdnomcta as bdnomcta_conta, tpla.bdnomcta as bdnomcta_conta_original, tpla.bdgrupocta as bdgrupocta_conta, tpla.bdtipcta as bdtipcta_conta, ';

  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
    wsql = wsql||'case when lista.BDTIPOSELECAO = 1 then tpla.bdparticipante else 0 end as bdparticipante, ';
  ELSE
    wsql = wsql||'tpla.bdparticipante, ';

  wsql = wsql||'       tplaCtr.bdcodtpla as BDCONTRA, tx.bdcodterceiroc as bdcodter_contra, tplaCtr.bdctalon as bdctalon_contra, tplaCtr.bdnomcta as bdnomcta_contra, tplaCtr.bdparticipante as bdparticipante_contra, ';
  wsql = wsql||'       tx.bddebito, tx.bdcredito, tx.debcre, ';
  wsql = wsql||'       tx.bdcodcentro, tx.bdcodtpcc, tx.bdtransacao, tx.BDTRANFECHADA, terc.BDCGCTER, null as BDNOMETER ';

  --alt:13329 - 10/02/2016 - Agora o select ? feito dentro do la?o, pois preciso retornar o nome E o c?digo do participante matriz quando est? sendo agrupado pelo CNPJ. Pedro
  /*IF (prdetalharctaparticipante = 1) THEN
     wsql = wsql||' (select first 1 terc2.bdnometer from tterceiro_ref terc2 where (terc2.bdcodter = tx.bdcodter) order by terc2.bdcodter desc, terc2.bdrefemp desc) as bdnometer ';
  ELSE
     wsql = wsql||' null as bdnometer ';*/

  --alt:13893 - 29/08/2016 - Alterado para poder trazer contas sem movimento. Pedro
  --wsql = wsql||'from ( ';
  wsql = wsql||'from planos_tpla tpla ';
  wsql = wsql||'left outer join (';
  -- debito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  wsql = wsql||'select tlan.bdchave, tlan.bddata, tlan.bdcodemp, tlan.bdcodplapadrao, ';
  wsql = wsql||'       tlan.bdlote, tlan.bdcompl, tlan.bddcto, ';
  wsql = wsql||'       tlan.bdfilial, tlan.bdtipolancfilial,  ';
  wsql = wsql||'       tlan.bdtipolan, tlan.bdchaveonline, ';
  wsql = wsql||'       tlan.bdcodhist, tlan.bdcodtphi, ';
  wsql = wsql||'       tlan.bddebito as bdconta, tlan.bdcodterceirod as bdcodter, tlan.bdconcd as bdconc, tlan.bdconciliacaopendente, ';
  wsql = wsql||'       tlan.bdcredito as bdcontra, tlan.bdcodterceiroc, tlan.bdtransacao, tlan.BDTRANFECHADA, ';

  --alt:1186 - Colocado aqui em cima e adicionada valida??o do novo par?metro, pois precisa o novo par?metro antes do LancamentoSemCC. Pedro
  IF ((prlcc = '') OR (prdetalharcc = 0))  THEN
     BEGIN
       --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
       IF (prindice = 0) THEN
         wsql = wsql||'tlan.bdvalor as bddebito,';
       ELSE
         BEGIN
           wsql = wsql||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
           wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bddebito,';
         END
       --alt:6178 - Fim

       wsql = wsql||'       null as bdcredito, 0 as debcre, ';
       wsql = wsql||'       null as bdcodcentro, null as bdcodtpcc ';
       wsql = wsql||'from vsuc_empresas_tlan tlan ';
     END
  ELSE
  --alt:1186 - Fim
  --alt:7794 - Adicionada a op??o de mostrar lan?amentos sem centro de custo. Pedro
  IF (prlancamentosemcc <> 0) THEN
     BEGIN
       --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
       IF (prindice = 0) THEN
         wsql = wsql||'case when TLCC.BDVALOR is null then TLAN.BDVALOR else TLCC.BDVALOR end as BDDEBITO, ';
       ELSE
         BEGIN
           wsql = wsql||'case when TLCC.BDVALOR is null then TLAN.BDVALOR else TLCC.BDVALOR end';
           wsql = wsql||'          / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
           wsql = wsql||'                     (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bddebito,';
         END
       --alt:6178 - Fim

       wsql = wsql||'       null as bdcredito, 0 as debcre, TLCC.BDCODCENTRO, TLCC.BDCODTPCC ';
       wsql = wsql||'from vsuc_empresas_tlan tlan ';
       --alt:9149 - Adicionado "TLCC.BDDEBCRE = 0" porque se tiver centro de custo no cr?dito e n?o tiver no d?bito, n?o retorna o sem cento de custo do d?bito. Pedro
       wsql = wsql||'left outer join VSUC_EMPRESAS_TLCC TLCC on (TLAN.BDCODEMP = TLCC.BDCODEMP and TLAN.BDCHAVE = TLCC.BDCHAVE and TLCC.BDDEBCRE = 0) ';
     END
  ELSE
  --alt:7794 - Fim
  -- centro de custo a debito --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     BEGIN
       --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
       IF (prindice = 0) THEN
         wsql = wsql||'tlcc.bdvalor as bddebito,';
       ELSE
         BEGIN
           wsql = wsql||'tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
           wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bddebito,';
         END
       --alt:6178 - Fim
       wsql = wsql||'       null as bdcredito, 0 as debcre, ';
       wsql = wsql||'       tlcc.bdcodcentro, tlcc.bdcodtpcc ';
       wsql = wsql||'from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END

  wsql = wsql||'where (tlan.bddata between '''||prdata_inicial||''' and '''||prdata_final||''') ';

  -- contabiliza??o ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (prcontabilizacao <> 99) THEN
     wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  -- filtro de centro de custo a debito ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  --alt:7794 - Adicionada a op??o de mostrar lan?amentos sem centro de custo. Pedro
  IF (prlcc <> '') THEN
     BEGIN
       --alt:1186 - Adicionada essa valida??o para aqui tratar quando n?o for para detalhar por centro de custo mas deve validar os
       --centros de custos selecionados ou sem centro de custos, caso que ocorre no Raz?o em V?deo. Pedro
       IF (prdetalharcc = 0) THEN
         BEGIN
           wsql = wsql||'and (exists (select first 1 * from VSUC_EMPRESAS_TLCC tlcc where tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave ';
           wsql = wsql||'and tlcc.bdcodtpcc in ('||TRIM(prlcc)||') and tlcc.bddebcre = 0) ';
           IF (prlancamentosemcc <> 0) THEN
             wsql = wsql||'or not exists (select first 1 * from VSUC_EMPRESAS_TLCC tlcc where tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 0)) ';
           ELSE
             wsql = wsql||')';
         END
       --alt:1186 - Fim
       ELSE
       IF (prlancamentosemcc <> 0) THEN
          wsql = wsql||'and ((tlcc.bdcodtpcc in ('||TRIM(prlcc)||') and tlcc.bddebcre = 0) or (TLCC.BDCODTPCC is null)) ';
       ELSE
          wsql = wsql||'and (tlcc.bdcodtpcc in ('||TRIM(prlcc)||') and tlcc.bddebcre = 0) ';
     END

  /*if (prlcc <> '') then
     wsql = wsql||'and (tlcc.bdcodtpcc in ('||trim(prlcc)||') and tlcc.bddebcre = 0) '; */
  --alt:7794 - Fim

  -- filtro de participante a debito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  --if ((prpartini is not null) and (prpartfin is not null)) then  --alt:9167 - Adicionada valida??o do par?metro de agrupar participante por CNPJ, pois se for para agrupar, deve validar no select externo. Pedro
  IF ((prpartini IS NOT NULL) AND (prpartfin IS NOT NULL) AND (PRAGRUPARPARTICIPANTEPORCNPJ = 0)) THEN
     --wsql = wsql||'and (tlan.bdcodterceirod between '||prpartini||' and '||prpartfin||') '; Gilberto - 13/01/2015 - ALT:#10519 - deve trazer inclusive quem n?o tem conta de participante
     -- #alt: 11705 (Carlos Mello) wsql = wsql||'and ((tlan.bdcodterceirod between '||prpartini||' and '||prpartfin||') or (tlan.bdcodterceirod is null)) ';
     wsql = wsql||'and ((tlan.bdcodterceirod between '||prpartini||' and '||prpartfin||') or (coalesce(tlan.bdcodterceirod,0) = 0)) ';

  -- ignora zeramento ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (prignorazeramento <> 0) THEN
     wsql = wsql||'and (tlan.bdtipolan <> 10) ';
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial in ('||prcodemp||'))) ';

  wsql = wsql||'union ';
  -- credito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  wsql = wsql||'select tlan.bdchave, tlan.bddata, tlan.bdcodemp, tlan.bdcodplapadrao, ';
  wsql = wsql||'       tlan.bdlote, tlan.bdcompl, tlan.bddcto, ';
  wsql = wsql||'       tlan.bdfilial, tlan.bdtipolancfilial,  ';
  wsql = wsql||'       tlan.bdtipolan, tlan.bdchaveonline, ';
  wsql = wsql||'       tlan.bdcodhist, tlan.bdcodtphi, ';
  wsql = wsql||'       tlan.bdcredito as bdconta, tlan.bdcodterceiroc as bdcodter, tlan.bdconcc as bdconc, tlan.bdconciliacaopendente, ';
  wsql = wsql||'       tlan.bddebito as bdcontra, tlan.bdcodterceirod, tlan.bdtransacao, tlan.BDTRANFECHADA, ';

  --alt:1186 - Colocado aqui em cima e adicionada valida??o do novo par?metro, pois precisa o novo par?metro antes do LancamentoSemCC. Pedro
  IF ((prlcc = '') OR (prdetalharcc = 0))  THEN
     BEGIN
       wsql = wsql||'null as bddebito, ';
       --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
       IF (prindice = 0) THEN
         wsql = wsql||'tlan.bdvalor as bdcredito,';
       ELSE
         BEGIN
           wsql = wsql||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
           wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdcredito,';
         END
       --alt:6178 - Fim

       wsql = wsql||'       1 as debcre, null as bdcodcentro, null as bdcodtpcc ';
       wsql = wsql||'from vsuc_empresas_tlan tlan ';
     END
  ELSE
  --alt:1186 - Fim
  --alt:7794 - Adicionada a op??o de mostrar lan?amentos sem centro de custo. Pedro
  IF (prlancamentosemcc <> 0) THEN
     BEGIN
       wsql = wsql||'null as bddebito, ';
       --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
       IF (prindice = 0) THEN
         wsql = wsql||'case when TLCC.BDVALOR is null then TLAN.BDVALOR else TLCC.BDVALOR end as bdcredito, ';
       ELSE
         BEGIN
           wsql = wsql||'case when TLCC.BDVALOR is null then TLAN.BDVALOR else TLCC.BDVALOR end';
           wsql = wsql||'          / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
           wsql = wsql||'                     (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdcredito,';
         END
       --alt:6178 - Fim

       wsql = wsql||'       1 as debcre, TLCC.BDCODCENTRO, TLCC.BDCODTPCC ';
       wsql = wsql||'from vsuc_empresas_tlan tlan ';
       --alt:9149 - Adicionado "TLCC.BDDEBCRE = 1" porque se tiver centro de custo no d?bito e n?o tiver no cr?dito, n?o retorna o sem cento de custo do cr?dito. Pedro
       wsql = wsql||'left outer join VSUC_EMPRESAS_TLCC TLCC on (TLAN.BDCODEMP = TLCC.BDCODEMP and TLAN.BDCHAVE = TLCC.BDCHAVE and TLCC.BDDEBCRE = 1) ';
     END
  ELSE
  --alt:7794 - Fim
  -- centro de custo a credito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     BEGIN
       wsql = wsql||'null as bddebito, ';
       --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
       IF (prindice = 0) THEN
         wsql = wsql||'tlcc.bdvalor as bdcredito,';
       ELSE
         BEGIN
           wsql = wsql||'tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
           wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdcredito,';
         END
       --alt:6178 - Fim
       wsql = wsql||'       1 as debcre, tlcc.bdcodcentro, tlcc.bdcodtpcc ';
       wsql = wsql||'from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END

  wsql = wsql||'where (tlan.bddata between '''||prdata_inicial||''' and '''||prdata_final||''') ';

  -- contabiliza??o ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (prcontabilizacao <> 99) THEN
     wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  -- filtro de centro de custo a credito ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  --alt:7794 - Adicionada a op??o de mostrar lan?amentos sem centro de custo. Pedro
  IF (prlcc <> '') THEN
     BEGIN
       --alt:1186 - Adicionada essa valida??o para aqui tratar quando n?o for para detalhar por centro de custo mas deve validar os
       --centros de custos selecionados ou sem centro de custos, caso que ocorre no Raz?o em V?deo. Pedro
       IF (prdetalharcc = 0) THEN
         BEGIN
           wsql = wsql||'and (exists (select first 1 * from VSUC_EMPRESAS_TLCC tlcc where tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave ';
           wsql = wsql||'and tlcc.bdcodtpcc in ('||TRIM(prlcc)||') and tlcc.bddebcre = 1) ';
           IF (prlancamentosemcc <> 0) THEN
             wsql = wsql||'or not exists (select first 1 * from VSUC_EMPRESAS_TLCC tlcc where tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 1)) ';
           ELSE
             wsql = wsql||')';
         END
       --alt:1186 - Fim
       ELSE
       IF (prlancamentosemcc <> 0) THEN
          wsql = wsql||'and ((tlcc.bdcodtpcc in ('||TRIM(prlcc)||') and tlcc.bddebcre = 1) or (TLCC.BDCODTPCC is null)) ';
       ELSE
          wsql = wsql||'and (tlcc.bdcodtpcc in ('||TRIM(prlcc)||') and tlcc.bddebcre = 1) ';
     END

  /*if (prlcc <> '') then
     wsql = wsql||'and (tlcc.bdcodtpcc in ('||trim(prlcc)||') and tlcc.bddebcre = 1) ';*/
  --alt:7794 - Fim

  -- filtro de participante a credito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  --if ((prpartini is not null) and (prpartfin is not null)) then  --alt:9167 - Adicionada valida??o do par?metro de agrupar participante por CNPJ, pois se for para agrupar, deve validar no select externo. Pedro
  IF ((prpartini IS NOT NULL) AND (prpartfin IS NOT NULL) AND (PRAGRUPARPARTICIPANTEPORCNPJ = 0)) THEN
--     wsql = wsql||'and (tlan.bdcodterceiroc between '||prpartini||' and '||prpartfin||') '; Gilberto - 13/01/2015 - ALT:#10519 - deve trazer inclusive quem n?o tem conta de participante
     -- #alt: 11705 (Carlos Mello) wsql = wsql||'and ((tlan.bdcodterceiroc between '||prpartini||' and '||prpartfin||') or (tlan.bdcodterceiroc is null)) ';
     wsql = wsql||'and ((tlan.bdcodterceiroc between '||prpartini||' and '||prpartfin||') or (coalesce(tlan.bdcodterceiroc,0) = 0)) ';

  -- ignora zeramento ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (prignorazeramento <> 0) THEN
     wsql = wsql||'and (tlan.bdtipolan <> 10) ';
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial in ('||prcodemp||'))) ';
  wsql = wsql||') tx on (tpla.bdcodplapadrao = tx.bdcodplapadrao and tpla.bdcodtpla = tx.bdconta) ';
  wsql = wsql||'left outer join hist_tphi this on (this.bdcodhist = tx.bdcodhist and this.bdcodtphi = tx.bdcodtphi) ';
  wsql = wsql||'left outer join planos_tpla tplaCtr on (tplaCtr.bdcodplapadrao = tx.bdcodplapadrao and tplaCtr.bdcodtpla = tx.bdcontra) ';

--  IF (prdetalharctaparticipante = 1) THEN
--     wsql = wsql||'left outer join (select bdcodter, bdnometer, bdcgcter from vw_tterceiro) terc on (terc.bdcodter = tx.bdcodter) ';

  --#Alt:21066 - Alterado por causa da lentid?o (Carlos Mello - 29/11/2017)
  --wsql = wsql||'left join vw_empresas_ref_atual emp on (emp.bdcodemp = tx.bdcodemp) ';
  wsql = wsql||'left join TEMPRESAS EMP on (EMP.BDCODEMP = TX.BDCODEMP) ';
  wsql = wsql||'left join ( Select bdCODEMP, bdNOMEMP from TEMPRESAS_REF REF ';
  wsql = wsql||'            where ';
  wsql = wsql||'           (REF.bdCODEMP in ('||prcodemp||')) and ';
  wsql = wsql||'           (REF.bdREFEMP = (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x ';
  wsql = wsql||'                            WHERE x.bdcodemp in ('||prcodemp||') AND ';
  wsql = wsql||'                            X.BDREFEMP <= (SELECT TRIM(rdb$get_context('||'''USER_SESSION'''||','||'''W_ANOMES'''||')) FROM rdb$database) ';
  wsql = wsql||'                            ORDER BY x.bdcodemp DESC, x.bdrefemp DESC)) ';
  wsql = wsql||'          ) EMPREF on (EMPREF.BDCODEMP = TX.BDCODEMP) ';
  --#Alt:21066 - Fim
  wsql = wsql||'left join TTERCEIRO terc on (terc.bdcodter = tx.bdcodter) '; --alt:13329 - 10/02/2016 - Ordenar participante pelo CGC e utilizado no caso de agrupar pelo CNPJ. Pedro

  --alt:9167 - Caso seja para agrupar participante por CNPJ, foi adicionada essa cl?usula where para fazer isso. Pedro
  IF ((prpartini IS NOT NULL) AND (prpartfin IS NOT NULL) AND (PRAGRUPARPARTICIPANTEPORCNPJ = 1)) THEN
  BEGIN
    --alt:13329 - 10/02/2016 - Alterado m?todo de filtragem. Melhoria de desempenho e n?o estava trazendo os outros participantes matriz/filial quando n?o estava no range informado. Pedro
    --wsql = wsql||'where (substring(terc.BDCGCTER from 1 for 10) in (select substring(BDCGCTER from 1 for 10) from VW_TTERCEIRO where bdcodter between '||prpartini||' and '||prpartfin||')) ';
    /*wsql = wsql || ' inner join tterceiro terc on terc.bdcodter = tx.bdcodter ';
    wsql = wsql || 'where ';
    wsql = wsql || 'exists ';
    wsql = wsql || '( ';
    wsql = wsql || '  select bdcodter from tterceiro t3 where t3.bdcodter between '||prpartini||' and '||prpartfin||' and ';
    wsql = wsql || '  substring(terc.BDCGCTER from 1 for 10) ';
    wsql = wsql || '  = ';
    wsql = wsql || '  substring(t3.BDCGCTER from 1 for 10) ';
    wsql = wsql || ') ';*/

    --alt:16679 - 30/05/2017 - Caso o participante inicial seja o mesmo que o final, n?o pode fazer esse filtro do c?digo do participante, implementado na altera??o #16045, sen?o n?o tr?s . Pedro
    IF (prPartIni = prPartFin) THEN
      wsql = wsql||'join TTERCEIRO terAux on (terAux.BDCODTER between '||prPARTINI||' and '||prPARTFIN||' and substring(terc.BDCGCTER from 1 for 10) = substring(terAux.BDCGCTER from 1 for 10)) ';
    --alt:16045 - 20/10/2016 - Adicionado filtro para o c?digo participante relacionando com a tabela apelidada de "terc", pois sem isso, n?o estava filtrando os participantes. Pedro
    ELSE
      wsql = wsql||'join TTERCEIRO terAux on (terc.BDCODTER = terAux.BDCODTER and terAux.BDCODTER between '||prPARTINI||' and '||prPARTFIN||' and substring(terc.BDCGCTER from 1 for 10) = substring(terAux.BDCGCTER from 1 for 10)) ';
    --alt:13329 - Fim
  END
  --alt:9167 - Fim

  -- detalhar contas espec?ficas de participantes ------------------------------------------------------------------------------------------------------------------------------------------------------------------
  wsql = wsql||'left join VSUC_SELECT_CONTAS lista on (tpla.BDCODPLAPADRAO = lista.BDCODPLAPADRAO and tpla.BDCODTPLA = lista.BDCODTPLA) ';

  --alt:13893 - 29/08/2016 - Adicionado filtro para as contas. Pedro
  -- sele??o de contas ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
     wsql = wsql||'where (tpla.BDCODTPLA in (select bdcodtpla from vsuc_select_contas tsel)) ';
  ELSE
    BEGIN
      SELECT FIRST 1 BDCODPLAPADRAO FROM TEMPRESAS_REF WHERE BDCODEMP = :prCodMatriz AND BDREFEMP <= :prRefEmp ORDER BY BDCODEMP DESC, BDREFEMP DESC INTO :wCodPlaPadrao;
      wsql = wsql||'where (tpla.BDCODPLAPADRAO = '||wCodPlaPadrao||' and tpla.BDCTALON between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''' and tpla.BDTIPCTA = 1) ';
    END

  wsql = wsql||'order by bdcodemp, bddata, bdconta, terc.BDCGCTER ';

  FOR EXECUTE STATEMENT wsql
  INTO :prchave, :prdata,
       :prempresa, :prnomeempresa, :prcnpjemp,
       :prcodplapadrao,
       :prlote, :prcompl, :prdcto,
       :wfilial, :prtipolancfilial,
       :prtipolan, :prchaveonline,
       :prcodhist, :prcodtphi, :prhistorico,
       :prconta, :prcodterceiroconta, :prconciliado, :prconciliacaopendente,
       :prclass_conta, :prnome_conta, :prnome_conta_original, :prgrpcta, :wtipctaconta, :prparticipanteconta,
       :prcontra, :prcodterceirocontra, :prclass_contra, :prnome_conta_contra, :prparticipantecontra,
       :prdebito, :prcredito, :prdebcre,
       :prcodcentro, :prcc, :prtransacao, :prtranfechada, :prcgc_conta, :wnometer DO
  BEGIN
    --alt:13329 - 10/02/2016 - Foi trazido para c? o select que buscava o nome do participante, que agora tamb?m tr?s o c?digo dele, mas apenas do "matriz" no caso de estar agrupando pelo CNPJ. Pedro
    IF ((prparticipanteconta = 1) AND (prdetalharctaparticipante = 1) AND (prcodterceiroconta IS NOT NULL)) THEN
      BEGIN
        IF ((prDetalharCtaParticipante = 1) AND (prAgruparParticipantePorCNPJ = 1)) THEN
          SELECT FIRST 1 BDCODTER, BDNOMETER FROM VW_TTERCEIRO WHERE SUBSTRING(BDCGCTER FROM 1 FOR 10) = SUBSTRING(:prcgc_conta FROM 1 FOR 10) ORDER BY BDCGCTER INTO :wcodter, :wnometer;
        ELSE
          SELECT FIRST 1 BDCODTER, BDNOMETER FROM TTERCEIRO_REF WHERE BDCODTER = :prcodterceiroconta ORDER BY BDCODTER DESC, BDREFEMP DESC INTO :wcodter, :wnometer;
      END
    --alt:13329 - Fim

    IF ((prtipolancfilial = 1) AND (prdebito <> 0)) THEN
      prcodempfilial = wfilial;
    ELSE IF ((prtipolancfilial = 2) AND (prcredito <> 0)) THEN
      prcodempfilial = wfilial;
    ELSE
      prcodempfilial = prempresa;

    --alt:15745 - 14/09/2016 - Corrigida vari?vel onde deve ser gravado o c?digo da empresa matriz. Estava com erro no "lan?ar a" validar com a empresa incorreta. Pedro
    /*if (prcodmatriz is null) then
      prcodmatriz = prempresa;
    prempresa = prcodmatriz;*/
    --alt:12505 - Fim

    --Foi criado essas vari?veis auxiliares pois quando esta por detalhar participante
    --ele precisa verificar a classifica??o pela conta original
    --wctalonaxuc = wctalonc;
    --wctalonaxud = wctalond;

    --alt:13972 - 15/06/2016 - N?o pode mais jogar zero aqui, pois agora utiliza o c?digo do centro de custo para detalhar o saldo anterior. Pedro
    --IF (prlcc = '') THEN
    --   prcc = 0;

    IF ((prdetalharctaparticipante = 1) AND (prparticipanteconta = 1) AND (wtipctaconta = 1) AND (prcodterceiroconta IS NOT NULL)) THEN
       BEGIN
         --select bdclassificacao, bdnome from vsuc_sp_nomenclatura_cta_partic(:wcodterceirod,:wctalond,:prconcatenacodparticipante) into :wctalond,:wnomctad;
         prclass_conta = REVERSE(prclass_conta);
         prclass_conta = SUBSTRING(prclass_conta FROM POSITION('.', prclass_conta) FOR strlen(prclass_conta));
         prclass_conta = REVERSE(prclass_conta);
         prclass_conta = prclass_conta||LPAD(wcodter, 9, '0'); --alt:14526 - 27/06/2016 - Alterado de 8 para 9 casas para ficar igual ao Balancete e Cadastro de Participantes. Pedro

         IF (prconcatenacodparticipante = 1) THEN
           BEGIN
             wpos = CHARACTER_LENGTH(:wcodter);
             wpos = ((100 - wpos) - 3);
             wnometer = wcodter||' - '||SUBSTRING(wnometer FROM 1 FOR wpos);
           END
         prnome_conta = SUBSTRING(wnometer FROM 1 FOR 100);
       END


    --alt:#6524 - implementado rotina "POS" aqui, por quest?o de desempenho, precisa apenas uma vez para as duas verifica??es
    --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
    IF (NOT ((prtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
       BEGIN
       --alt:#6535 - gilberto - 05/09/2013
         wpos_pernamatriz = POSITION(wempprinc, prcodemp);
         wpos_matriz = POSITION(prempresa, prcodemp);
         wpos_filial = POSITION(wfilial, prcodemp);
      END
    wcampo = prdebcre + 1;

    IF ((prtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
       wpermite = 1;
    ELSE
    IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
        --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
--      ((wempprinc = wfilial) AND (wcampo = prtipolancfilial)) OR   --#alt:14902 - alterado pois quando estava na matriz e selecionava apenas as filiais ele imprimia apenas a wEmpPrinc. Ana - 17/08/2016
        ((wpos_filial > 0) AND (wcampo = prtipolancfilial)) OR
        --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
        ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> prtipolancfilial) AND (wpos_pernamatriz > 0)) OR
        --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
        ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
        --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
        ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = prtipolancfilial) AND (wpos_filial > 0))) THEN
       wpermite = 1;
    ELSE
       wpermite = 0;
    -------------------------------------------------------------------alt:#6524
    --alt:13893 - 29/08/2016 - Tamb?m deve retornar o registro caso esteja marcado para trazer as contas sem movimento. Pedro
    IF ((wpermite = 1) OR ((prContasSemMovimento = 1) AND (PRCHAVE IS NULL))) THEN
       SUSPEND;
  END
END
^

/* Alter (VSUC_SP_RETORNA_RAZAO_SALDO) */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(1024),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(100),
BDCODCENTRO INTEGER,
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(40),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(40),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER,
BDVLRCONCILIADO NUMERIC(15,2),
BDVLRACONCILIAR NUMERIC(15,2),
BDCHAVEONLINE VARCHAR(120))
 AS
DECLARE VARIABLE wconta INTEGER;
DECLARE VARIABLE wsaldo NUMERIC(15,2);
DECLARE VARIABLE wclass VARCHAR(40);
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wordem INTEGER;
DECLARE VARIABLE wclassini VARCHAR(40);
DECLARE VARIABLE wclassfin VARCHAR(40);
DECLARE VARIABLE wtam INTEGER;
DECLARE VARIABLE wcredito NUMERIC(15,2);
DECLARE VARIABLE wdebito NUMERIC(15,2);
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wsqlsaldo VARCHAR(1024);
DECLARE VARIABLE wsql VARCHAR(10240);
DECLARE VARIABLE wparticipante INTEGER;
DECLARE VARIABLE wclass_ant VARCHAR(40);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wsqlemp VARCHAR(10240);
DECLARE VARIABLE wcodempefilial INTEGER;
DECLARE VARIABLE wcodmatriz INTEGER;
BEGIN
  EXECUTE STATEMENT 'delete from vsuc_empresas_trazao_saldo where bdcodemp is not null';

  wsql = 'insert into VSUC_EMPRESAS_TRAZAO_SALDO (BDCODEMP,BDCODPLAPADRAO,BDCODTPLA,BDCTALON,BDTIPCTA,BDGRPCTA,BDNOMCTA,BDCODCENTRO,BDCODTPCC,BDPARTICIPANTE,BDSALDO,BDTIPOLANCFILIAL,BDFILIAL) ';
  wsql = wsql||'select tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdconta, ';
  wsql = wsql||'tpla.BDCTALON, tpla.BDTIPCTA, tpla.bdgrupocta, tpla.BDNOMCTA, tlan.bdcodcentro, tlan.bdcodtpcc, null as bdcodter, ';
  wsql = wsql||'((select SALDO_ANTERIOR from sp_retorna_saldo_emp(tlan.bdcodemp, tpla.bdcodtpla, '''||prdata_inicial||''', '''||prdata_final||''', 0, tlan.bdcodtpcc, null, '||prrefemp||', '||bdconciliados||','||prcontabilizacao||','||prmatrizfilialconsolidado||',tlan.bdparticipante))),';
  wsql = wsql||'tlan.bdtipolancfilial,tlan.bdfilial ';
  wsql = wsql||'from (select distinct bdcodemp, bdcodplapadrao, bdconta, bdfilial, bdtipolancfilial, bdcodcentro, bdcodtpcc, bdparticipante ';--gilberto - 12/08/2013 - #alt:6159
  wsql = wsql||'from (select distinct tlan.bdcodemp, bdcodplapadrao, bddebito as bdconta, tlan.bdfilial, tlan.bdtipolancfilial, ';
  IF (TRIM(prlcc) = '') THEN
     wsql = wsql||' null as bdcodcentro, null as bdcodtpcc, tlan.bdcodterceirod as bdparticipante from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.bdcodcentro, tlcc.bdcodtpcc, tlan.bdcodterceirod as bdparticipante from vsuc_empresas_tlan tlan ';
       wsql = wsql||' left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 0 and tlcc.bdcodtpcc in ('||prlcc||')) ';
     END
  --Carlos Mello(05/02/2013) - Solicita??o.: 5022. N?o estava calculando o Saldo Anterior corretamente.
  --wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') and bddata between '''||prdata_inicial||''' and '''||prdata_final||''' and bddebito is not null ';
-- GILBERTO - 23/04/2013 - 5504 - N?O CALCULAVA SALDO ANTERIOR DA FILIAL SE A MESMA N?O TIVER MOVIMENTO NO PER?ODO
--  wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') and bddata between '''||substring(prdata_inicial from 1 for 4)||'-01-01'||''' and '''||substring(prdata_final from 1 for 4)||'-12-31'||''' and bddebito is not null ';
  --#alt:5837
  --wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'     where ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial in ('||prcodemp||'))) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'   and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
--  WSQL = WSQL||'     AND bddata <= '''||substring(prdata_final from 1 for 4)||'-12-31'||''' and bddebito is not null ';-- gilberto - 26/07/2013 - 6159
  WSQL = WSQL||'     AND bddata < '''||prdata_inicial||''' and bddebito is not null '; -- gilberto - 26/07/2013 - 6159
  -- gilberto - 28/05/2013 - incluido para considerar participante no calculo de saldo anterior
  IF ((prpartini IS NOT NULL) AND (prpartini <> 0)) THEN
     wsql = wsql||' and (tlan.bdcodterceirod >= '||prpartini||')';
  IF ((prpartfin IS NOT NULL) AND (prpartfin <> 0)) THEN
     wsql = wsql||' and (tlan.bdcodterceirod <= '||prpartfin||')';
  -- __________________________________________________________________________________________
  wsql = wsql||'      union all ';
  wsql = wsql||'      select distinct tlan.bdcodemp, bdcodplapadrao, bdcredito as bdconta, tlan.bdfilial, tlan.bdtipolancfilial, ';
  IF (TRIM(prlcc) = '') THEN
     wsql = wsql||' null as bdcodcentro, null as bdcodtpcc, tlan.bdcodterceiroc as bdparticipante from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.bdcodcentro, tlcc.bdcodtpcc, tlan.bdcodterceirod as bdparticipante from vsuc_empresas_tlan tlan ';
       wsql = wsql||' left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 1 and tlcc.bdcodtpcc in ('||prlcc||')) ';
     END
  --Solicita??o.: 5022.
  --wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') and bddata between '''||prdata_inicial||''' and '''||prdata_final||''' and bdcredito is not null) tlan ';
-- GILBERTO - 23/04/2013 - 5504 - N?O CALCULAVA SALDO ANTERIOR DA FILIAL SE A MESMA N?O TIVER MOVIMENTO NO PER?ODO
--  wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') and bddata between '''||substring(prdata_inicial from 1 for 4)||'-01-01'||''' and '''||substring(prdata_final from 1 for 4)||'-12-31'||''' and bdcredito is not null) tlan ';
  --#alt:5837
  --wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'     where ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial in ('||prcodemp||'))) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'   and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
--  WSQL = WSQL||'     and bddata <= '''||substring(prdata_final from 1 for 4)||'-12-31'||''' and bdcredito is not null';-- gilberto - 26/07/2013 - 6159
  WSQL = WSQL||'     and bddata < '''||prdata_inicial||''' and bdcredito is not null';-- gilberto - 26/07/2013 - 6159
  -- gilberto - 28/05/2013 - incluido para considerar participante no calculo de saldo anterior
  IF ((prpartini IS NOT NULL) AND (prpartini <> 0)) THEN
     wsql = wsql||' and (tlan.bdcodterceiroc >= '||prpartini||')';
  IF ((prpartfin IS NOT NULL) AND (prpartfin <> 0)) THEN
     wsql = wsql||' and (tlan.bdcodterceiroc <= '||prpartfin||')';
  -- __________________________________________________________________________________________
  wsql = wsql||')';--gilberto - 12/08/2013 - #alt:6159
  wsql = wsql||') tlan ';
  wsql = wsql||' inner join planos_tpla tpla on (tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.bdconta and tpla.bdtipcta = 1) ';
  wsql = wsql||'where tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''' ';
  EXECUTE STATEMENT wsql;

--  if (prdetalharctaparticipante = 1) then
     BEGIN
       wsql = 'insert into VSUC_EMPRESAS_TRAZAO_SALDO (BDCODEMP,BDCODPLAPADRAO,BDCODTPLA,BDCTALON,BDTIPCTA,BDGRPCTA,BDNOMCTA,BDCODCENTRO,BDCODTPCC,BDPARTICIPANTE,BDSALDO,BDTIPOLANCFILIAL,BDFILIAL) ';
       wsql = wsql||'select tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdconta, ';
       wsql = wsql||'tpla.BDCTALON, tpla.BDTIPCTA, tpla.bdgrupocta, tpla.BDNOMCTA, null as bdcodcentro, null as bdcodtpcc, tlan.bdcodter, ';
--       wsql = wsql||'(select bdsaldo_anterior from vsuc_sp_retorna_saldos_cta_part(tlan.bdcodemp, tlan.bdcodplapadrao, '''||prdata_inicial||''', '''||prdata_final||''', tlan.bdconta, '; -- alt:#6647 - gilberto - 12/09/2013
       wsql = wsql||'(select bdsaldo_anterior from vsuc_sp_retorna_saldos_ctaparty(tlan.bdcodemp, tlan.bdcodplapadrao, '''||prdata_inicial||''', '''||prdata_final||''', tlan.bdconta,'||:prindice||', ';
       wsql = wsql||'                                                              0, tlan.bdcodter, 0, '||bdconciliados||','''||:prcodemp||''','||:prcontabilizacao||','||:prmatrizfilialconsolidado||')),';
       wsql = wsql||'tlan.bdtipolancfilial,tlan.bdfilial ';
       wsql = wsql||'from (select distinct bdcodemp, bdcodplapadrao, bdconta, bdfilial, bdtipolancfilial, bdcodter ';-- #alt:6430 - gilberto - 20/08/2013
       wsql = wsql||'from (select distinct bdcodemp, bdcodplapadrao, bddebito as bdconta, bdcodterceirod as bdcodter, bdfilial, bdtipolancfilial ';
       wsql = wsql||'      from vsuc_empresas_tlan ';
       --#alt:5837
       --wsql = wsql||'      where bdcodemp in ('||prcodemp||') and ';
       wsql = wsql||'      where ((bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) and ';
       --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
       IF (prcontabilizacao <> 99) THEN
         wsql = wsql||'   (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
       wsql = wsql||'      bddata between '''||SUBSTRING(prdata_inicial FROM 1 FOR 4)||'-01-01'||''' and '''||SUBSTRING(prdata_final FROM 1 FOR 4)||'-12-31'||''' and bddebito is not null and bdcodterceirod is not null ';
       wsql = wsql||'      union all ';
       wsql = wsql||'      select distinct bdcodemp, bdcodplapadrao, bdcredito as bdconta, bdcodterceiroc as bdcodter, bdfilial, bdtipolancfilial ';
       wsql = wsql||'      from vsuc_empresas_tlan ';
       --#alt:5837
       --wsql = wsql||'      where bdcodemp in ('||prcodemp||') and ';
       wsql = wsql||'      where ((bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) and ';
       --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
       IF (prcontabilizacao <> 99) THEN
         wsql = wsql||'    (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
       wsql = wsql||'      bddata between '''||SUBSTRING(prdata_inicial FROM 1 FOR 4)||'-01-01'||''' and '''||SUBSTRING(prdata_final FROM 1 FOR 4)||'-12-31'||''' and bdcredito is not null and bdcodterceiroc is not null)) tlan ';
       wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.bdconta and tpla.bdtipcta = 1) ';
       wsql = wsql||'where tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''' ';
       EXECUTE STATEMENT wsql;
     END

  -- BDCONCILIADOS = 0 TODOS 1 CONCILIADOS 2 NAO CONCILIADOS

  wconta     = 0;
  wsaldo     = 0;
  wordem     = 0;
  bdvlraconciliar = 0;
  bdvlrconciliado = 0;
  wclass_ant = '';

  wsql = '';
  IF (pragrupar <> '') THEN
     wsql = wsql||'select * from (';

  wsql = wsql||'select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta, ';
  wsql = wsql||'TRazao.prcontra, TRazao.prcredito, TRazao.prdebito, ';
  wsql = wsql||'TRazao.prconciliado, TRazao.prempresa, ';
  wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
  wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRAZAO.prlote, TRAZAO.prdcto, TRAZAO.prcompl, TRAZAO.prcnpjemp, ';
  wsql = wsql||'TRAZAO.PRGRPCTA, TRAZAO.PRCODHIST, TRAZAO.PRCODTPHI, TRAZAO.PRCODPLAPADRAO , ';
  wsql = wsql||'(substring((CAST(TRazao.prdata AS VARCHAR(10))) from 6 for 2) || ''/'' || substring((CAST(TRazao.prdata AS VARCHAR(10))) from 1 for 4)) as "BDREF", ';
  wsql = wsql||'TRAZAO.prparticipanteconta, tRAZAO.prcodterceiroconta, tRAZAO.prcodterceirocontra, trazao.PRCODEMPFILIAL, trazao.prcodmatriz, trazao.PRCHAVEONLINE ';

  wsql = wsql||'from vsuc_sp_retorna_razao_contas('''||TRIM(prcodemp)||''','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',''';
--  wsql = wsql||                                   trim(prlcc)||''','||trim(prordempresa)||','||prrefemp||','||prdetalharctacliente||','||prdetalharctafornecedor||','||PRCONCATENACODCLIFOR||',null,null) TRazao ';
  wsql = wsql||                                   TRIM(prlcc)||''',';
  wsql = wsql||TRIM(prordempresa)||',';
  wsql = wsql||prrefemp||',';
  wsql = wsql||prdetalharctaparticipante||',';
  wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
  IF (prpartini IS NOT NULL) THEN
     wsql = wsql||prpartini||',';
  ELSE
     wsql = wsql||'null,';
  IF (prpartfin IS NOT NULL) THEN
     wsql = wsql||prpartfin||',';
  ELSE
     wsql = wsql||'null,';
  wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||') TRazao ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' where (Upper(TRazao.prconciliado) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' where ((Upper(TRazao.prconciliado) = '||'''FALSE'''||') or (TRazao.prconciliado is null))';

  -- agrupa lan?amentos ________________________________________________________
  IF (pragrupar <> '') THEN
     BEGIN
       IF (bdconciliados IN (1,2)) THEN
          wsql = wsql||' and trazao.PRTIPOLAN not in ('||pragrupar||') ';
       ELSE
          wsql = wsql||' where trazao.PRTIPOLAN not in ('||pragrupar||') ';

       wsql = wsql||'union all ';
       wsql = wsql||'select null as prhistorico, TRazao.prdata, min(TRazao.prchave), TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, sum(TRazao.prcredito), sum(TRazao.prdebito), ';
       wsql = wsql||'null as prconciliado, TRazao.prempresa, ';
       wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
       wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, null as prlote, null as prdcto, null as prcompl, TRAZAO.prcnpjemp, ';
       wsql = wsql||'TRAZAO.PRGRPCTA, TRAZAO.PRCODHIST, TRAZAO.PRCODTPHI, TRAZAO.PRCODPLAPADRAO , ';
       wsql = wsql||'(substring((CAST(TRazao.prdata AS VARCHAR(10))) from 6 for 2) || ''/'' || substring((CAST(TRazao.prdata AS VARCHAR(10))) from 1 for 4)) as "BDREF", ';
       wsql = wsql||'null as prparticipanteconta, null as prcodterceiroconta, null as prcodterceirocontra, trazao.PRCODEMPFILIAL, trazao.prcodmatriz, trazao.PRCHAVEONLINE ';
     
       wsql = wsql||'from vsuc_sp_retorna_razao_contas('''||TRIM(prcodemp)||''','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',''';
       wsql = wsql||                                   TRIM(prlcc)||''',';
       wsql = wsql||TRIM(prordempresa)||',';
       wsql = wsql||prrefemp||',';
       wsql = wsql||prdetalharctaparticipante||',';
       wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
       IF (prpartini IS NOT NULL) THEN
          wsql = wsql||prpartini||',';
       ELSE
          wsql = wsql||'null,';
       IF (prpartfin IS NOT NULL) THEN
          wsql = wsql||prpartfin||',';
       ELSE
          wsql = wsql||'null,';
       wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||') TRazao ';
     
       IF (bdconciliados = 1) THEN
          wsql = wsql|| ' where (Upper(TRazao.prconciliado) = '||'''TRUE'''||')';
       ELSE
       IF (bdconciliados = 2) THEN
          wsql = wsql|| ' where ((Upper(TRazao.prconciliado) = '||'''FALSE'''||') or (TRazao.prconciliado is null))';
       IF (bdconciliados IN (1,2)) THEN
          wsql = wsql||' and trazao.PRTIPOLAN in ('||pragrupar||') ';
       ELSE
          wsql = wsql||' where trazao.PRTIPOLAN in ('||pragrupar||') ';

       wsql = wsql||'group by TRazao.prdata, trazao.PRCHAVEONLINE, TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, ';
       wsql = wsql||'TRazao.prempresa, ';
       wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
       wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRAZAO.prcnpjemp, ';
       wsql = wsql||'TRAZAO.PRGRPCTA, TRAZAO.PRCODHIST, TRAZAO.PRCODTPHI, TRAZAO.PRCODPLAPADRAO, ';
       wsql = wsql||'trazao.PRCODEMPFILIAL, trazao.prcodmatriz) TRAZAO ';
     END

  IF (prordempresa = 1) THEN
     BEGIN
       IF (prdetalharctaparticipante = 0) THEN
--          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prconta, TRazao.prdata, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prclass_conta, TRazao.prdata, TRazao.prchave';
       ELSE
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prchave';
     END
  ELSE
  IF (prordempresa = 2) THEN
     BEGIN
       IF (prdetalharctaparticipante = 0) THEN
          wsql = wsql||'order by TRazao.prnome_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
       ELSE
          wsql = wsql||'order by TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
     END
  ELSE
  IF (prordempresa = 3) THEN
     BEGIN
       IF (prdetalharctaparticipante = 0) THEN
--          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prconta, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prclass_conta, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
       ELSE
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.PRCODTERCEIROCONTA, TRazao.prchave';
     END
  ELSE
     BEGIN
       IF (prdetalharctaparticipante = 0) THEN
--          wsql = wsql||'order by TRazao.prconta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
          wsql = wsql||'order by TRazao.prclass_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
       ELSE
          wsql = wsql||'order by TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
     END
/*
  for select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta,
             TRazao.prcontra, TRazao.prentrada, TRazao.prsaida, TRazao.prconciliado, TRazao.prempresa,
             TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta,
             TRazao.prclass_contra, TRAZAO.prlote, TRAZAO.prdcto, TRAZAO.prcompl, TRAZAO.prcnpjemp
      from vsuc_sp_retorna_razao_contas(:prcodigo_empresa, :wclassini, :wclassfin,
                                        :prdata_inicial, :prdata_final, :prfiliais, :prlcc) TRazao
      order by TRazao.prconta, TRazao.prdata
*/
  FOR EXECUTE STATEMENT wsql
      INTO :bdhistorico, :bddata, :bdchave, :bdconta, :bdcontra, :bdcredito, :bddebito, /*:prcomplemento,
           /*:prcontra_longa, */:bdconciliado, :bdempresa, :bdnomeempresa, :bdcc, :bdnome_conta,
           :bdclass_conta, :bdclass_contra, :bdnome_conta_contra, :bdlote, :bddcto, :bdcompl, :bdcnpjemp, :bdgrupoconta, :bdcodhist,
           :bdcodtphi, :bdcodplapadrao, :bdref, :wparticipante, :bdcod_terceiro_conta, :bdcod_terceiro_contra, :BDEMPRESAFILIAL, :wcodmatriz, :bdchaveonline DO
      BEGIN
        bdsaldoanterior = 0;

        SELECT tpla.bdctalon, tpla.bdgrupocta FROM planos_tpla TPla
        WHERE tpla.bdcodplapadrao = :bdcodplapadrao
        AND tpla.bdcodtpla = :bdconta
        INTO :wclass, :wgrupocta;

        --Incluido a verifica??o (wconta <> bdcontra), sem isso entrava nesta rotina sempre. Bruno Borges
/* gilberto - 22/05/2013 - 5772
        if (((wconta <> bdconta) and ((wconta <> bdcontra) or (bdcontra is null and wconta is not null))) or
            (((prdetalharctaparticipante = 1) and (wparticipante = 1)) and
             (bdclass_conta <> wclass_ant)))then*/
        IF ((((wconta <> bdconta) AND ((wconta <> bdcontra) OR (bdcontra IS NULL AND wconta IS NOT NULL))) OR (bdclass_conta <> wclass_ant)) OR
            ((bdclass_conta <> wclass_ant) AND ((prdetalharctaparticipante = 1) AND (wparticipante = 1)))) THEN
           BEGIN
             bdvlraconciliar = 0;
             bdvlrconciliado = 0;

             /* INICIO Giovanni, precisa fazer um laco das empresas para trazer o saldo anterior correto */

             -- retorna as empresas selecionadas
             wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
             wsqlemp = wsqlemp||'from tempresas temp ';
             wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
             wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
             wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
             -- executa o sql das empresas

             FOR EXECUTE STATEMENT wsqlemp
                 INTO :wcodempefilial DO
             BEGIN
               wsaldo = 0;
/*               -- Detalhado por participante
               if ((prdetalharctaparticipante = 1) and (wparticipante = 1)) then
                 select bdsaldo_anterior from vsuc_sp_retorna_saldos_cta_part(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_final,:bdconta,
                                                                              0,:bdcod_terceiro_conta,0,:bdconciliados)
                 into :wsaldo;
               else
                 select SALDO_ANTERIOR from sp_retorna_saldo_emp(:wcodempefilial, :bdconta,
                 :prdata_inicial, :prdata_final, 0, :bdcc, null, :prrefemp,:bdconciliados)
                 into :wsaldo;
*/
               wsqlsaldo = 'select sum(coalesce(bdsaldo,0)) from vsuc_empresas_trazao_saldo ';
               wsqlsaldo = wsqlsaldo||'where bdcodemp = '||wcodempefilial;
               wsqlsaldo = wsqlsaldo||' and bdcodtpla = '||bdconta;
               IF (((prdetalharctaparticipante IS NULL) OR (prdetalharctaparticipante = 0)) OR ((bdcod_terceiro_conta IS NULL) OR (bdcod_terceiro_conta = 0))) THEN
                  BEGIN
                    wsqlsaldo = wsqlsaldo||' and bdparticipante is null ';
                    IF ((bdcc IS NOT NULL) AND (bdcc <> 0)) THEN
                       BEGIN
                         wsqlsaldo = wsqlsaldo||' and bdcodtpcc = '||bdcc;
                       END
                  END
               ELSE
                  BEGIN
                    wsqlsaldo = wsqlsaldo||' and bdparticipante = '||bdcod_terceiro_conta;
                    IF ((bdcc IS NOT NULL) AND (bdcc <> 0)) THEN
                       BEGIN
                         wsqlsaldo = wsqlsaldo||' and bdcodtpcc = '||bdcc;
                       END
                  END
               EXECUTE STATEMENT wsqlsaldo INTO :wsaldo;

               bdsaldoanterior = bdsaldoanterior + COALESCE(wsaldo,0);
               wsaldo = bdsaldoanterior;
             END


             SELECT FIRST 1 bdcodcentro FROM vsuc_empresas_trazao_saldo WHERE bdcodcentro > 0 INTO :bdcodcentro;


             /* FIM Giovanni, precisa fazer um laco das empresas para trazer o saldo anterior correto */

             SELECT tpla.bdctalon, tpla.bdgrupocta FROM planos_tpla TPla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :bdconta
             INTO :wclass, :wgrupocta;

             wordem = 0;

             IF (wgrupocta IN (1,2,3)) THEN
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bdcredito, 0) - COALESCE(bddebito, 0));
                  wvalor = COALESCE(bdcredito, 0) - COALESCE(bddebito, 0);
                END
             ELSE
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bddebito, 0) - COALESCE(bdcredito, 0));
                  wvalor = COALESCE(bddebito, 0) - COALESCE(bdcredito, 0);
                END
           END
        ELSE
           BEGIN
             bdsaldoanterior = wsaldo;

             IF (wgrupocta IN (1,2,3)) THEN
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bdcredito, 0) - COALESCE(bddebito, 0));
                  wvalor = COALESCE(bdcredito, 0) - COALESCE(bddebito, 0);
                END
             ELSE
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bddebito, 0) - COALESCE(bdcredito, 0));
                  wvalor = COALESCE(bddebito, 0) - COALESCE(bdcredito, 0);
                END
           END
        wordem = wordem + 1;
        bdordsaldo = wordem;
        bdsaldo = wsaldo;
        IF (wvalor < 0) THEN
           bdvalorsemsinal = wvalor * -1;
        ELSE
           bdvalorsemsinal = wvalor;
        bdvalor     = wvalor;
        wconta      = bdconta;

        -- giovanni comentei a linha abaixo, se precisar me chamar para discutir...
        -- ja que o bdcompl ja tem o completo do historico completo, pra que dois campos iguais ????
        -- bdhistorico = bdcompl;

       IF (bdhistorico IS NOT NULL) THEN
         BEGIN
           SELECT pos FROM pos('*', :bdhistorico) INTO :wpos;
             IF (wpos > 0) THEN
                bdhistorico = bdcompl;
             ELSE
               bdhistorico = bdhistorico || ' ' || bdcompl;
         END
       ELSE
         bdhistorico = bdcompl;

       IF ((UPPER(bdconciliado) <> 'TRUE') OR (bdconciliado IS NULL)) THEN
          bdvlraconciliar = bdvlraconciliar + wvalor;
       ELSE
          bdvlrconciliado = bdvlrconciliado + wvalor;

        wclass_ant  = bdclass_conta;

        SUSPEND;
      END
END
^

/* Alter (VSUC_SP_RETORNA_RAZAO_SALDO_X) */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO_X(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRDETALHARCC INTEGER,
PRLCC DM_MAXVARCHAR,
PRLANCAMENTOSEMCC INTEGER,
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDCDOISLANCAMENTOS INTEGER,
PRCONTASSEMMOVIMENTO INTEGER,
PRIGNORAZERAMENTO INTEGER = 0,
PRIGNORASALDOANTERIOR INTEGER = 0,
PRDETALHARFILIAL INTEGER = 0)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(100),
BDCODCENTRO INTEGER,
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDNOME_CONTA_ORIGINAL VARCHAR(100),
BDCLASS_CONTA VARCHAR(40),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCGC_CONTA VARCHAR(18),
BDCLASS_CONTRA VARCHAR(40),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER,
BDTIPOLANCFILIAL INTEGER,
BDVLRCONCILIADO NUMERIC(15,2),
BDVLRACONCILIAR NUMERIC(15,2),
BDCHAVEONLINE VARCHAR(120),
BDTRANSACAO INTEGER,
BDTRANFECHADA DM_BOOLEAN,
BDTIPOLAN INTEGER,
BDSEQCTA VARCHAR(7),
BDCONCILIACAOPENDENTE INTEGER)
 AS
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WSALDO NUMERIC(15,2);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WTAM INTEGER;
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WCODEMPEFILIAL INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCC_ATU INTEGER;
DECLARE VARIABLE WSALDOAUX NUMERIC(15,2);
DECLARE VARIABLE WAGRUPAPART INTEGER; --#alt:12766. Ana - 24/08/2016
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WCGCTERANT VARCHAR(10);
BEGIN
  /* BDCONCILIADOS:
      0: Conciliados
      1: N?o conciliados
      2: Pendentes
      3: Todos
  */

  wconta     = 0;
  wsaldo     = 0;
  wordem     = 0;
  bdvlraconciliar = 0;
  bdvlrconciliado = 0;
  wAgrupaPart = 1; --#alt:12766 - Inicializada vari?vel. Ana - 24/08/2016

  wsql = '';
  IF (pragrupar <> '') THEN
     wsql = wsql||'select * from (';

  wsql = wsql||'select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta, ';
  wsql = wsql||'TRazao.prcontra, TRazao.prcredito, TRazao.prdebito, ';
  wsql = wsql||'TRazao.prconciliado, TRazao.prconciliacaopendente, TRazao.prempresa, ';
  wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prnome_conta_original, TRazao.prclass_conta, TRazao.prcgc_conta, ';
  wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRazao.prlote, TRazao.prdcto, TRazao.prcompl, TRazao.prcnpjemp, ';
  wsql = wsql||'TRazao.PRGRPCTA, TRazao.PRCODHIST, TRazao.PRCODTPHI, TRazao.PRCODPLAPADRAO , ';
  --wsql = wsql||'(substring((CAST(TRazao.prdata AS VARCHAR(10))) from 6 for 2) || ''/'' || substring((CAST(TRazao.prdata AS VARCHAR(10))) from 1 for 4)) as "BDREF", ';
  wsql = wsql||'extract(month from TRazao.prdata)||''/''||extract(year from TRazao.prdata) as BDREF, '; --alt:14942 - 26/01/2017 - Simplificada a extra??o da data para facilitar a compreens?o. Pedro
  wsql = wsql||'TRazao.prparticipanteconta, TRazao.prcodterceiroconta, TRazao.prcodterceirocontra, TRazao.PRCODEMPFILIAL, TRazao.PRCHAVEONLINE, TRazao.PRCODCENTRO, ';
  wsql = wsql||'TRazao.prtransacao, TRazao.prtranfechada, TRazao.prtipolan, TRazao.prtipolancfilial, TRazao.prcodmatriz ';

  wsql = wsql||'from vsuc_sp_retorna_razao_contas_x('''||TRIM(prcodemp)||''','||:prRefEmp||','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',';
--  wsql = wsql||                                   trim(prlcc)||''','||trim(prordempresa)||','||prrefemp||','||prdetalharctacliente||','||prdetalharctafornecedor||','||PRCONCATENACODCLIFOR||',null,null) TRazao ';
  --wsql = wsql||                                   trim(prlcc)||''',';
  --alt:1186 - Adicionados par?metros. Pedro
  wsql = wsql||prIndice||', '||PRDETALHARCC||','''||TRIM(prlcc)||''','||prlancamentosemcc||',';
  --wsql = wsql||TRIM(prordempresa)||',';
  --wsql = wsql||prrefemp||',';
  wsql = wsql||prdetalharctaparticipante||',';
  --alt:9167 - Passado novo par?metro para trazer todos os participantes com a mesma raiz de CNPJ. Pedro
  wsql = wsql||PRAGRUPARPARTICIPANTEPORCNPJ||',';
  wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
  IF (prpartini IS NOT NULL) THEN
     wsql = wsql||prpartini||',';
  ELSE
     wsql = wsql||'null,';
  IF (prpartfin IS NOT NULL) THEN
     wsql = wsql||prpartfin||',';
  ELSE
     wsql = wsql||'null,';
  --alt:7794 - Adicionado novo par?metro para mostrar ou n?o lan?amentos sem centro de custo. Pedro
  --alt:1186 - Adicionados realocado para cima. Pedro
  --wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||','||prignorazeramento||') TRazao ';
  wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prContasSemMovimento||','||prignorazeramento||') TRazao ';
  --wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||','||prignorazeramento||','||prlancamentosemcc||') TRazao ';
  --alt:7794 - Fim

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' where (Upper(TRazao.prconciliado) = '||'''TRUE'''||')';
  ELSE IF (bdconciliados = 2) THEN
     wsql = wsql|| ' where ((Upper(TRazao.prconciliado) = '||'''FALSE'''||') or (TRazao.prconciliado is null))';
  ELSE IF (bdconciliados = 3) THEN --alt:14942 - 27/01/2017 - Adicionada op??o de filtragem para os lan?amentos pendentes. Pedro
    wsql = wsql|| ' where ((TRazao.prconciliacaopendente = 3) or ((TRazao.prconciliacaopendente = 1) and (TRazao.prdebcre = 0)) or ((TRazao.prconciliacaopendente = 2) and (TRazao.prdebcre = 1)))';

  -- agrupa lan?amentos ________________________________________________________
  IF (pragrupar <> '') THEN
     BEGIN
       IF (bdconciliados IN (1,2,3)) THEN
          wsql = wsql||' and TRazao.PRTIPOLAN not in ('||pragrupar||') ';
       ELSE
          wsql = wsql||' where TRazao.PRTIPOLAN not in ('||pragrupar||') ';

       wsql = wsql||'union all ';
       wsql = wsql||'select null as prhistorico, TRazao.prdata, min(TRazao.prchave), TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, sum(TRazao.prcredito), sum(TRazao.prdebito), ';
       wsql = wsql||'null as prconciliado, null as prconciliacaopendente, TRazao.prempresa, ';
       wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta,TRazao.prnome_conta_original, TRazao.prclass_conta, TRazao.prcgc_conta, ';
       wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, null as prlote, null as prdcto, null as prcompl, TRazao.prcnpjemp, ';
       wsql = wsql||'TRazao.PRGRPCTA, TRazao.PRCODHIST, TRazao.PRCODTPHI, TRazao.PRCODPLAPADRAO , ';
       --wsql = wsql||'(substring((CAST(TRazao.prdata AS VARCHAR(10))) from 6 for 2) || ''/'' || substring((CAST(TRazao.prdata AS VARCHAR(10))) from 1 for 4)) as "BDREF", ';
       wsql = wsql||'extract(month from TRazao.prdata)||''/''||extract(year from TRazao.prdata) as BDREF, '; --alt:14942 - 26/01/2017 - Simplificada a extra??o da data para facilitar a compreens?o. Pedro
       wsql = wsql||'null as prparticipanteconta, null as prcodterceiroconta, null as prcodterceirocontra, TRazao.PRCODEMPFILIAL, TRazao.PRCHAVEONLINE, TRazao.PRCODCENTRO, ';
       wsql = wsql||'null as prtransacao, null as prtranfechada, TRazao.prtipolan, TRazao.prtipolancfilial, TRazao.prcodmatriz ';
     
       wsql = wsql||'from vsuc_sp_retorna_razao_contas_x('''||TRIM(prcodemp)||''','||:prRefEmp||','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',';
       --wsql = wsql||                                   trim(prlcc)||''',';
       --alt:1186 - Adicionados par?metros. Pedro
       wsql = wsql||prIndice||', '||PRDETALHARCC||','''||TRIM(prlcc)||''','||prlancamentosemcc||',';
       --wsql = wsql||TRIM(prordempresa)||',';
       --wsql = wsql||prrefemp||',';
       wsql = wsql||prdetalharctaparticipante||',';
       --alt:9167 - Passado novo par?metro para trazer todos os participantes com a mesma raiz de CNPJ. Pedro
       wsql = wsql||PRAGRUPARPARTICIPANTEPORCNPJ||',';
       wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
       IF (prpartini IS NOT NULL) THEN
          wsql = wsql||prpartini||',';
       ELSE
          wsql = wsql||'null,';
       IF (prpartfin IS NOT NULL) THEN
          wsql = wsql||prpartfin||',';
       ELSE
          wsql = wsql||'null,';
       --alt:7794 - Adicionado novo par?metro para mostrar ou n?o lan?amentos sem centro de custo. Pedro
       --alt:1186 - Adicionados realocado para cima. Pedro
       --wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||','||prignorazeramento||') TRazao ';
       wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prignorazeramento||') TRazao ';
       --wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||','||prignorazeramento||','||prlancamentosemcc||') TRazao ';
       --alt:7794 - Fim
     
       IF (bdconciliados = 1) THEN
          wsql = wsql|| ' where (Upper(TRazao.prconciliado) = '||'''TRUE'''||')';
       ELSE
       IF (bdconciliados = 2) THEN
          wsql = wsql|| ' where ((Upper(TRazao.prconciliado) = '||'''FALSE'''||') or (TRazao.prconciliado is null))';
       IF (bdconciliados IN (1,2,3)) THEN
          wsql = wsql||' and TRazao.PRTIPOLAN in ('||pragrupar||') ';
       ELSE
          wsql = wsql||' where TRazao.PRTIPOLAN in ('||pragrupar||') ';

       /* gilberto - 08/01/2014 - alt#:7480
       wsql = wsql||'group by TRazao.prdata, TRazao.PRCHAVEONLINE, TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, ';
       wsql = wsql||'TRazao.prempresa, ';
       wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
       wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRazao.prcnpjemp, ';
       wsql = wsql||'TRazao.PRGRPCTA, TRazao.PRCODHIST, TRazao.PRCODTPHI, TRazao.PRCODPLAPADRAO, ';
       wsql = wsql||'TRazao.PRCODEMPFILIAL, TRazao.prcodmatriz) TRazao ';*/

       wsql = wsql||'group by TRazao.prdata, TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, ';
       wsql = wsql||'TRazao.prempresa, TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta,TRazao.prnome_conta_original, ';
       wsql = wsql||'TRazao.prclass_conta, TRazao.prcgc_conta, TRazao.prclass_contra, TRazao.prnome_conta_contra, ';
       wsql = wsql||'TRazao.prcnpjemp, ';
       wsql = wsql||'TRazao.PRGRPCTA, TRazao.PRCODHIST, TRazao.PRCODTPHI, TRazao.PRCODPLAPADRAO , ';
       wsql = wsql||'TRazao.PRCODEMPFILIAL, TRazao.prcodmatriz, TRazao.PRCHAVEONLINE, TRazao.PRCODCENTRO, TRazao.prtipolan, TRazao.prtipolancfilial) TRazao ';
     END

  IF (prordempresa = 1) THEN
     BEGIN
       /* gilberto - 13/01/2015 - ALT:#10519 - Raz?o alterado para detalhar participante quendo seleciona todas as contas, dessa forma ? necess?rio ordenar sempre pela conta
       IF (prdetalharctaparticipante = 0) THEN
          --wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prconta, TRazao.prdata, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prclass_conta, TRazao.prdata, TRazao.prchave';
       ELSE
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prchave';*/
       wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prclass_conta, TRazao.prdata, TRazao.prchave';
     END
  ELSE
  IF (prordempresa = 2) THEN
     BEGIN
       /* gilberto - 13/01/2015 - ALT:#10519 - Raz?o alterado para detalhar participante quendo seleciona todas as contas, dessa forma ? necess?rio ordenar sempre pela conta
       IF (prdetalharctaparticipante = 0) THEN
          wsql = wsql||'order by TRazao.prnome_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave';
       ELSE
          wsql = wsql||'order by TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave';*/
       wsql = wsql||'order by TRazao.prnome_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave';
     END
  ELSE
  IF (prordempresa = 3) THEN
     BEGIN
       /* gilberto - 13/01/2015 - ALT:#10519 - Raz?o alterado para detalhar participante quendo seleciona todas as contas, dessa forma ? necess?rio ordenar sempre pela conta
       IF (prdetalharctaparticipante = 0) THEN
          --wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prconta, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prclass_conta, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
       ELSE
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.PRCODTERCEIROCONTA, TRazao.prchave';*/
       wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prclass_conta, TRazao.prchave';
     END
  ELSE
     BEGIN
       /* gilberto - 13/01/2015 - ALT:#10519 - Raz?o alterado para detalhar participante quendo seleciona todas as contas, dessa forma ? necess?rio ordenar sempre pela conta
       IF (prdetalharctaparticipante = 0) THEN
       --  wsql = wsql||'order by TRazao.prconta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
       --  wsql = wsql||'order by TRazao.prclass_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
       --else
       --  wsql = wsql||'order by TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave';
       --alt:7823 - Adicionado a ordem por centro de custo para trazer corretamente o saldo anterior e na sequ?ncia correta. Pedro
          wsql = wsql||'order by TRazao.prclass_conta, TRazao.prcc, TRazao.prdata, TRazao.prchave, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave';
       ELSE
          wsql = wsql||'order by TRazao.PRCODTERCEIROCONTA, TRazao.prcc, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave';
       --alt:7823 - Fim*/
       wsql = wsql||'order by TRazao.prclass_conta, TRazao.prcc, TRazao.prdata, TRazao.prchave, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave';
     END

  /*for select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta,
             TRazao.prcontra, TRazao.prentrada, TRazao.prsaida, TRazao.prconciliado, TRazao.prempresa,
             TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta,
             TRazao.prclass_contra, TRazao.prlote, TRazao.prdcto, TRazao.prcompl, TRazao.prcnpjemp
      from vsuc_sp_retorna_razao_contas(:prcodigo_empresa, :wclassini, :wclassfin,
                                        :prdata_inicial, :prdata_final, :prfiliais, :prlcc) TRazao
      order by TRazao.prconta, TRazao.prdata*/

  FOR EXECUTE STATEMENT wsql
      INTO :bdhistorico, :bddata, :bdchave, :bdconta, :bdcontra, :bdcredito, :bddebito,
           :bdconciliado, :bdconciliacaopendente, :bdempresa, :bdnomeempresa, :bdcc, :bdnome_conta,:bdnome_conta_original,
           :bdclass_conta, :bdcgc_conta, :bdclass_contra, :bdnome_conta_contra, :bdlote, :bddcto, :bdcompl, :bdcnpjemp, :bdgrupoconta, :bdcodhist,
           :bdcodtphi, :bdcodplapadrao, :bdref, :wparticipante, :bdcod_terceiro_conta, :bdcod_terceiro_contra, :BDEMPRESAFILIAL, :bdchaveonline, :bdcodcentro,
           :bdtransacao, :bdtranfechada, :bdtipolan, :bdtipolancfilial, :wcodmatriz DO
      BEGIN
        bdsaldoanterior = 0;
        BDSEQCTA = NULL; --alt:10873 - Se for zero ? lan?amento normal, n?o deve excluir. Pedro

        --Incluido a verifica??o (wconta <> bdcontra), sem isso entrava nesta rotina sempre. Bruno Borges
/* gilberto - 22/05/2013 - 5772
        if (((wconta <> bdconta) and ((wconta <> bdcontra) or (bdcontra is null and wconta is not null))) or
            (((prdetalharctaparticipante = 1) and (wparticipante = 1)) and
             (bdclass_conta <> wclass_ant)))then*/
--        if ((((wconta <> bdconta) and ((wconta <> bdcontra) or (bdcontra is null and wconta is not null))) or (bdclass_conta <> wclass_ant)) or
--            ((bdclass_conta <> wclass_ant) and ((prdetalharctaparticipante = 1) and (wparticipante = 1)))) then

        --#alt:12766 - Adicionada verifica??o wAgrupaPart = 1 que controla se ja executou uma vez a consulta do saldo anterior n?o precisa executar de novo. Ana - 24/08/2016
        --#alt:14902 - Adicionado verifica??o do detalhamento de filial. Ana - 12/08/2016
        --alt:7823 - Alterado para verificar tamb?m se o centro de custo mudou, pois sem isso ele trazia o saldo anterior incorreto. E foi adicionado o coalesce para ter certeza. Pedro
        IF ( (COALESCE(wconta, 0) <> COALESCE(bdconta, 0)) OR
             (COALESCE(wcc_atu, 0) <> COALESCE(bdcc, 0)) OR
             --alt:16035 - 20/10/2016 - Alterada valida??o para caso esteja marcado para agrupar por CNPJ, diferenciar os participantes apenas pela ra?z do CNPJ. Pedro
             --((bdcod_terceiro_conta <> wcodter) AND (prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (wAgrupaPart = 1))  OR
             ((prDetalharCtaParticipante = 1) AND (wParticipante = 1) AND (((prAgruparParticipantePorCNPJ = 0) AND (bdcod_terceiro_conta <> wcodter)) OR ((prAgruparParticipantePorCNPJ = 1) AND (SUBSTRING(bdcgc_conta FROM 1 FOR 10) <> wCGCTerAnt)))) OR
             ((prDetalharFilial = 1) AND (bdempresafilial <> wFilial)) ) THEN
           BEGIN
             bdvlraconciliar = 0;
             bdvlrconciliado = 0;

             --#alt:14902 - armezena a filial anterior para comparar. Ana - 12/08/2016
             wFilial = bdempresafilial;

             --alt:10644 - 24/03/2015 - Adicionado par?metro para ignorar o saldo anterior. Pedro
             wsaldo = 0;
             IF (PRIGNORASALDOANTERIOR = 0) THEN
               BEGIN
                 --alt:13329 - 10/02/2016 - Alterada sele??o de empresas e adicionada op??o para retornar participantes matriz e filiais, para o caso de agrupar por CNPJ. Pedro
                 /*wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
                 wsqlemp = wsqlemp||'from tempresas temp ';
                 wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
                 wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
                 FOR EXECUTE STATEMENT wsqlemp
                     INTO :wcodempefilial DO*/

                 IF ((prDetalharCtaParticipante = 1) AND (wparticipante = 1) AND (prAgruparParticipantePorCNPJ = 1)) THEN
                   BEGIN
                     wsqlemp = 'select emp.bdcodemp as bdempresasefilial, ter.bdcodter ';
                     wsqlemp = wsqlemp||'from TEMPRESAS emp ';
                     wsqlemp = wsqlemp||'cross join TTERCEIRO ter ';
                     wsqlemp = wsqlemp||'where emp.bdcodemp in ('||:prCODEMP||')';
                     wsqlemp = wsqlemp||'  and exists (select BDCODTER from tterceiro terAux where terAux.BDCODTER = '||COALESCE(:bdCOD_TERCEIRO_CONTA, 0);
                     wsqlemp = wsqlemp||'  and substring(ter.BDCGCTER from 1 for 10) = substring(terAux.BDCGCTER from 1 for 10))';
                     wsqlemp = wsqlemp||'order by emp.BDCODMATRIZ asc, emp.BDCODEMP asc, ter.BDCODTER asc ';

                     wAgrupaPart = 0; --#alt:12766 - S? precisa passar por aqui uma vez. Ana - 24/08/2016
                   END
                 ELSE
                   BEGIN
                     wsqlemp = 'select emp.bdcodemp as bdempresasefilial, '||COALESCE(:bdCOD_TERCEIRO_CONTA, 0)||' as bdcodter ';
                     wsqlemp = wsqlemp||'from TEMPRESAS emp ';
                     wsqlemp = wsqlemp||'where emp.bdcodemp in ('||:prCODEMP||')';
                     wsqlemp = wsqlemp||'order by emp.BDCODMATRIZ asc, emp.BDCODEMP asc ';
                   END
                 FOR EXECUTE STATEMENT wsqlemp INTO :wCODEMPEFILIAL, :wCODTER DO
                 --alt:123329 - Fim
                 BEGIN
                   wsaldo    = 0;
                   wsaldoaux = 0;

                   -- Detalhado por participante
                   IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdcod_terceiro_conta IS NOT NULL)) THEN
                      BEGIN
                        /*#Alt:14827 (17/06/2016) - Quando possuia lan?amentos com participante utilizando a op??o "Lan?ar a" o sistema n?o
                          estava calculando corretamente o saldo anterior. Carlos Mello

                        SELECT FIRST 1 bdsaldo_anterior FROM vsuc_sp_retorna_saldos_ctaparty(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_final,:bdconta,:prindice,
                                                                                             0,:wCodTer,0,:bdconciliados,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado)
                        INTO :wsaldo; */
                        FOR SELECT bdsaldo_anterior FROM vsuc_sp_retorna_saldos_ctaparty(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_final,:bdconta,:prindice,
                                                                                         0,:wCodTer,0,:bdconciliados,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado)
                        INTO :wsaldoaux DO
                          BEGIN
                            wsaldo = wsaldo + COALESCE(wsaldoaux,0);
                          END
                      END
                   ELSE
                      --alt:7823 - Alterado para filtrar pelo c?digo do participante inicial e final quando ambos forem informados.
                      --Se n?o fizer essa filtragem, retorna o saldo de todos os participantes ou apenas de um espec?fico, o que gera uma diferen?a cont?bil. Pedro
                      /*select SALDO_ANTERIOR from sp_retorna_saldo_emp_x(:wcodempefilial, :bdconta, :prdata_inicial, :prdata_final, 0, :bdcc, null,
                                                                        :prrefemp,:bdconciliados,:prcontabilizacao ,:prmatrizfilialconsolidado) */
                      BEGIN
                        IF ((prdetalharctaparticipante = 0) AND (PRPARTINI > 0) AND (PRPARTFIN > 0)) THEN
                           SELECT SALDO_ANTERIOR FROM sp_retorna_saldo_emp_x(:wcodempefilial, :bdconta, :prdata_inicial, :prdata_final, :prIndice, 0, :bdcc, NULL,
                                                                             :prrefemp,:bdconciliados,:prcontabilizacao ,:prmatrizfilialconsolidado, :PRPARTINI, :PRPARTFIN)
                           INTO :wsaldo;
                        ELSE
                           SELECT SALDO_ANTERIOR FROM sp_retorna_saldo_emp_x(:wcodempefilial, :bdconta, :prdata_inicial, :prdata_final, :prIndice, 0, :bdcc, NULL,
                                                                             :prrefemp,:bdconciliados,:prcontabilizacao ,:prmatrizfilialconsolidado)
                           INTO :wsaldo;
                      END
                      --alt:7823 - Fim
    
    /*
                   wsqlsaldo = 'select sum(coalesce(bdsaldo,0)) from vsuc_empresas_trazao_saldo ';
                   wsqlsaldo = wsqlsaldo||'where bdcodemp = '||wcodempefilial;
                   wsqlsaldo = wsqlsaldo||' and bdcodtpla = '||bdconta;
                   if (((prdetalharctaparticipante is null) or (prdetalharctaparticipante = 0)) or ((bdcod_terceiro_conta is null) or (bdcod_terceiro_conta = 0))) then
                      begin
                        wsqlsaldo = wsqlsaldo||' and bdparticipante is null ';
                        if ((bdcc is not null) and (bdcc <> 0)) then
                           begin
                             wsqlsaldo = wsqlsaldo||' and bdcodtpcc = '||bdcc;
                           end
                      end
                   else
                      begin
                        wsqlsaldo = wsqlsaldo||' and bdparticipante = '||bdcod_terceiro_conta;
                        if ((bdcc is not null) and (bdcc <> 0)) then
                           begin
                             wsqlsaldo = wsqlsaldo||' and bdcodtpcc = '||bdcc;
                           end
                      end
                   execute statement wsqlsaldo into :wsaldo;
    */

                   --#alt:14902 - Adicionada verifica??o para pegar o saldo anterior das filiais e n?o soma-las. Ana - 12/08/2016
                   --quando agruparParticipantePorCNPJ, ent?o deve somar apenas na filial corrente. Se somar todas as filiais o saldo n?o bate. Ana - 22/09/2016
                   IF (prAgruparParticipanteporCNPJ = 0) THEN
                       IF  --quando detalharfilial e n?o detalharparticipante, ent?o soma a matriz
                          (((prDetalharFilial = 1) AND (/*(wFilial = wCodMatriz) OR*/ (prDetalharCtaParticipante = 0)) AND (wFilial = wcodempefilial)) OR
                           --quando detalharfilial e detalharparticipante, ent?o n?o soma a matriz
                           ((prDetalharFilial = 1) AND (prDetalharCtaParticipante = 1) AND (wFilial = wcodempefilial))) THEN
                           BEGIN
                             bdsaldoanterior = COALESCE(wsaldo,0);
                             wsaldo = bdsaldoanterior;
                             BREAK;
                           END
                       ELSE
                          BEGIN
                             bdsaldoanterior = bdsaldoanterior + COALESCE(wsaldo,0);
                             wsaldo = bdsaldoanterior;
                          END
                   ELSE
                       -- se detalhar por filial ent?o soma tudo
                       -- se n?o soma apenas quando for da filial corrente
                       IF ((prdetalharfilial = 0) OR (wFilial = wcodempefilial)) THEN
                          BEGIN
                             bdsaldoanterior = bdsaldoanterior + COALESCE(wsaldo,0);
                             wsaldo = bdsaldoanterior;
                          END
                   --#alt:14902. fim
                 END
               END
               --alt:10644 - Fim

--             if ((bdcodcentro is null) and (prlcc <> '')) then
--                select first 1 bdcodcentro from vsuc_empresas_trazao_saldo where bdcodcentro > 0 into :bdcodcentro;

             wordem = 0;

             IF (bdgrupoconta IN (1,2,3)) THEN
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bdcredito, 0) - COALESCE(bddebito, 0));
                  wvalor = COALESCE(bdcredito, 0) - COALESCE(bddebito, 0);
                END
             ELSE
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bddebito, 0) - COALESCE(bdcredito, 0));
                  wvalor = COALESCE(bddebito, 0) - COALESCE(bdcredito, 0);
                END
           END
        ELSE
           BEGIN
             bdsaldoanterior = wsaldo;

             IF (bdgrupoconta IN (1,2,3)) THEN
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bdcredito, 0) - COALESCE(bddebito, 0));
                  wvalor = COALESCE(bdcredito, 0) - COALESCE(bddebito, 0);
                END
             ELSE
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bddebito, 0) - COALESCE(bdcredito, 0));
                  wvalor = COALESCE(bddebito, 0) - COALESCE(bdcredito, 0);
                END
           END
        wordem = wordem + 1;
        bdordsaldo = wordem;
        bdsaldo = wsaldo;
        IF (wvalor < 0) THEN
           bdvalorsemsinal = wvalor * -1;
        ELSE
           bdvalorsemsinal = wvalor;
        bdvalor     = wvalor;

       IF (bdhistorico IS NOT NULL) THEN
         BEGIN
           wpos = POSITION('*', :bdhistorico);
             IF (wpos > 0) THEN
                bdhistorico = bdcompl;
             ELSE
                bdhistorico = bdhistorico || ' ' || bdcompl;
         END
       ELSE
         bdhistorico = bdcompl;

       IF ((UPPER(bdconciliado) <> 'TRUE') OR (bdconciliado IS NULL)) THEN
          bdvlraconciliar = bdvlraconciliar + wvalor;
       ELSE
          bdvlrconciliado = bdvlrconciliado + wvalor;

        wconta = bdconta;
        wcodter = bdcod_terceiro_conta;
        wCGCTerAnt = SUBSTRING(bdcgc_conta FROM 1 FOR 10);

        --alt:7823 - Copia o centro de que ser? gravado para a vari?vel do centro de custo, que faz verifica??o de qual centro de custo ? o atual. Pedro
        wcc_atu = bdcc;

        --alt:13893 - 09/09/2016 - Quando marcada a op??o de trazer contas sem movimento, n?o deve trazer quando n?o tiver saldo anterior. Pedro
        IF ((PRCONTASSEMMOVIMENTO = 0) OR (BDCHAVE IS NOT NULL) OR (BDSALDOANTERIOR <> 0)) THEN
          SUSPEND;

        --alt:10873 - 17/03/2015 - Adicionada fun??o para trazer lan?amentos da mesma transa??o para poder mostrar a contrapartida "virtual", de acordo com a op??o selecionada. Pedro
        IF (prdcdoislancamentos = 1) THEN
          BEGIN
            wsql = 'select count (BDTRANSACAO) from VSUC_EMPRESAS_TLAN where BDCODEMP in ('||:prcodemp||') and BDTRANFECHADA = '''||'TRUE'||''' and '||
                   'BDTRANSACAO = '||COALESCE(:bdtransacao, 0)||' and (BDDEBITO is null or BDCREDITO is null) and '||
                   '(coalesce(BDDEBITO, 0) <> coalesce('||:bdconta||', 0) and coalesce(BDCREDITO, 0) <> coalesce('||:bdconta||', 0))';
            EXECUTE STATEMENT wsql INTO :wtam;
            IF (wtam = 1) THEN
              BEGIN
                wsql = 'SELECT TLAN.BDCHAVE, TLAN.BDDATA, TLAN.BDCODPLAPADRAO, TLAN.BDTRANFECHADA, TLAN.BDTRANSACAO, '||
                       '/*Conta*/ case when TLAN.BDDEBITO = TPLA.BDCODTPLA then TLAN.BDDEBITO else TLAN.BDCREDITO end as BDCONTA, '||
                       --alt:10873 - 17/03/2015 - Nunca ir? trazer BDCONTRA ("Cr?dito"), pois o D?bito ou o Cr?dito precisa ser nulo nesse caso.
                       '/*Valor d?bito*/ case when TLAN.BDDEBITO = TPLA.BDCODTPLA then TLAN.BDVALOR end as BDDEBITO, '||
                       '/*Valor cr?dito*/ case when (TLAN.BDDEBITO is null and TLAN.BDCREDITO is not null) then TLAN.BDVALOR end as BDCREDITO '||
                       'FROM VSUC_EMPRESAS_TLAN TLAN '||
                       'LEFT OUTER JOIN PLANOS_TPLA TPLA on (tpla.BDCODPLAPADRAO = tlan.BDCODPLAPADRAO and (tpla.BDCODTPLA = tlan.BDDEBITO or tpla.BDCODTPLA = tlan.BDCREDITO)) '||
                       'WHERE BDCODEMP in ('||:prcodemp||') and BDTRANFECHADA = '''||'TRUE'||''' and BDTRANSACAO = '||:bdtransacao||' and (BDDEBITO is null or BDCREDITO is null) and '||
                       '      (coalesce(BDDEBITO, 0) <> coalesce('||:bdconta||', 0) and coalesce(BDCREDITO, 0) <> coalesce('||:bdconta||', 0))';
                EXECUTE STATEMENT wsql INTO :bdchave, :bddata, :bdcodplapadrao, :bdtranfechada, :bdtransacao, :bdconta, :bddebito, :bdcredito;
                  BEGIN
                    BDSEQCTA = 'DEL'; --alt:10873 - 17/03/2015 - Se for 'DEL' ? lan?amento utilizado para verificar contrapartida, deve excluir depois de usar. Pedro
                    SUSPEND;
                  END
              END
          END
        --alt:10873 - 17/03/2015 - Fim
      END
END
^

/* Alter (VSUC_SP_RETORNA_RAZAO_SALDO2) */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO2(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(1024),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(80),
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(30),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(20),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER)
 AS
DECLARE VARIABLE wconta INTEGER;
DECLARE VARIABLE wsaldo NUMERIC(15,2);
DECLARE VARIABLE wclass VARCHAR(20);
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wordem INTEGER;
DECLARE VARIABLE wclassini VARCHAR(30);
DECLARE VARIABLE wclassfin VARCHAR(30);
DECLARE VARIABLE wtam INTEGER;
DECLARE VARIABLE wcredito NUMERIC(15,2);
DECLARE VARIABLE wdebito NUMERIC(15,2);
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wsql VARCHAR(10240);
DECLARE VARIABLE wparticipante INTEGER;
DECLARE VARIABLE wclass_ant VARCHAR(30);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wsqlemp VARCHAR(10240);
DECLARE VARIABLE wcodempefilial INTEGER;
BEGIN
  -- BDCONCILIADOS = 0 TODOS 1 CONCILIADOS 2 NAO CONCILIADOS

  wconta     = 0;
  wsaldo     = 0;
  wordem     = 0;
  wclass_ant = '';

  wsql = 'select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta, ';
  wsql = wsql||'TRazao.prcontra, TRazao.prcredito, TRazao.prdebito, ';
  wsql = wsql||'TRazao.prconciliado, TRazao.prempresa, ';
  wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
  wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRAZAO.prlote, TRAZAO.prdcto, TRAZAO.prcompl, TRAZAO.prcnpjemp, ';
  wsql = wsql||'TRAZAO.PRGRPCTA, TRAZAO.PRCODHIST, TRAZAO.PRCODTPHI, TRAZAO.PRCODPLAPADRAO , ';
  wsql = wsql||'(substring((CAST(TRazao.prdata AS VARCHAR(10))) from 6 for 2) || ''/'' || substring((CAST(TRazao.prdata AS VARCHAR(10))) from 1 for 4)), ';
  wsql = wsql||'TRAZAO.prparticipanteconta, tRAZAO.prcodterceiroconta, tRAZAO.prcodterceirocontra, trazao.PRCODEMPFILIAL ';

  wsql = wsql||'from vsuc_sp_retorna_razao_contas('''||TRIM(prcodemp)||''','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',''';
--  wsql = wsql||                                   trim(prlcc)||''','||trim(prordempresa)||','||prrefemp||','||prdetalharctacliente||','||prdetalharctafornecedor||','||PRCONCATENACODCLIFOR||',null,null) TRazao ';
  wsql = wsql||                                   TRIM(prlcc)||''',';
  wsql = wsql||TRIM(prordempresa)||',';
  wsql = wsql||prrefemp||',';
  wsql = wsql||prdetalharctaparticipante||',';
  wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
  IF (prpartini IS NOT NULL) THEN
     wsql = wsql||prpartini||',';
  ELSE
     wsql = wsql||'null,';
  IF (prpartfin IS NOT NULL) THEN
     wsql = wsql||prpartfin||',';
  ELSE
     wsql = wsql||'null,';
  wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||') TRazao ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' where (Upper(TRazao.prconciliado) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' where ((Upper(TRazao.prconciliado) = '||'''FALSE'''||') or (TRazao.prconciliado is null))';

  IF (prordempresa = 1) THEN
--     wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prconta, TRazao.prdata, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
     wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prclass_conta, TRazao.prdata, TRazao.prchave';
  ELSE
  IF (prordempresa = 2) THEN
     wsql = wsql||'order by TRazao.prnome_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
  ELSE
  IF (prordempresa = 3) THEN
--     wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prconta, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
     wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prclass_conta, TRazao.prchave';
  ELSE
--     wsql = wsql||'order by TRazao.prconta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
     wsql = wsql||'order by TRazao.prclass_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
/*
  for select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta,
             TRazao.prcontra, TRazao.prentrada, TRazao.prsaida, TRazao.prconciliado, TRazao.prempresa,
             TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta,
             TRazao.prclass_contra, TRAZAO.prlote, TRAZAO.prdcto, TRAZAO.prcompl, TRAZAO.prcnpjemp
      from vsuc_sp_retorna_razao_contas(:prcodigo_empresa, :wclassini, :wclassfin,
                                        :prdata_inicial, :prdata_final, :prfiliais, :prlcc) TRazao
      order by TRazao.prconta, TRazao.prdata
*/
  FOR EXECUTE STATEMENT wsql
      INTO :bdhistorico, :bddata, :bdchave, :bdconta, :bdcontra, :bdcredito, :bddebito, /*:prcomplemento,
           /*:prcontra_longa, */:bdconciliado, :bdempresa, :bdnomeempresa, :bdcc, :bdnome_conta,
           :bdclass_conta, :bdclass_contra, :bdnome_conta_contra, :bdlote, :bddcto, :bdcompl, :bdcnpjemp, :bdgrupoconta, :bdcodhist,
           :bdcodtphi, :bdcodplapadrao, :bdref, :wparticipante, :bdcod_terceiro_conta, :bdcod_terceiro_contra, :BDEMPRESAFILIAL DO
      BEGIN
        bdsaldoanterior = 0;
        --Incluido a verifica??o (wconta <> bdcontra), sem isso entrava nesta rotina sempre. Bruno Borges
        IF (((wconta <> bdconta) AND (wconta <> bdcontra)) OR
            (((prdetalharctaparticipante = 1) AND (wparticipante = 1)) AND
             (bdclass_conta <> wclass_ant)))THEN
           BEGIN

             /* INICIO Giovanni, precisa fazer um laco das empresas para trazer o saldo anterior correto */

             -- retorna as empresas selecionadas
             wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
             wsqlemp = wsqlemp||'from tempresas temp ';
             wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
             wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
             wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
             -- executa o sql das empresas

             FOR EXECUTE STATEMENT wsqlemp
                 INTO :wcodempefilial DO
             BEGIN
               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN
--                 select bdsaldo_anterior from vsuc_sp_retorna_saldos_cta_part(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_final,:bdconta, -- alt:#6647 - gilberto - 12/09/2013
                 SELECT bdsaldo_anterior FROM vsuc_sp_retorna_saldos_ctaparty(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_final,:bdconta,:prindice,
                                                                              0,:bdcod_terceiro_conta,0,:BDCONCILIADOS,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado)
                 INTO :wsaldo;
               ELSE
                 SELECT /*(saldo_ant_deb - saldo_ant_cre) */     SALDO_ANTERIOR FROM sp_retorna_saldo_emp(:wcodempefilial, :bdconta,
                 :prdata_inicial, :prdata_final, 0, :bdcc, NULL, :prrefemp,:bdconciliados,:prcontabilizacao,:prmatrizfilialconsolidado)
                 INTO :wsaldo;

                 bdsaldoanterior = bdsaldoanterior + wsaldo;
             END


             /* FIM Giovanni, precisa fazer um laco das empresas para trazer o saldo anterior correto */

             SELECT tpla.bdctalon, tpla.bdgrupocta FROM planos_tpla TPla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :bdconta
             INTO :wclass, :wgrupocta;

             wordem = 0;

             /* Saldo ________________________________________________________*/
             -- Credito --------------------------------------------------------
             wcredito = bdcredito;
             IF ((wcredito IS NULL) OR (wcredito = 0)) THEN
                wcredito = 0;
             ELSE
             -- Ativo
             IF (wgrupocta = 0) THEN
                wcredito = wcredito * -1;
             ELSE
             -- Passivo
             IF (wgrupocta = 1) THEN
                wcredito = wcredito;
             ELSE
             -- Receitas
             IF (wgrupocta = 3) THEN
                wcredito = wcredito;
             ELSE
             -- Despesas
             IF (wgrupocta = 4) THEN
                wcredito = wcredito * -1;
             ELSE
             -- Outros
             IF (wgrupocta = 5) THEN
                wcredito = wcredito * -1;
           
             -- Debito ---------------------------------------------------------
             wdebito = bddebito;
             IF ((wdebito IS NULL) OR (wdebito = 0)) THEN
                wdebito = 0;
             ELSE
             -- Ativo
             IF (wgrupocta = 0) THEN
                wdebito = wdebito;
             ELSE
             -- Passivo
             IF (wgrupocta = 1) THEN
                wdebito = wdebito * -1;
             ELSE
             -- Receitas
             IF (wgrupocta = 3) THEN
                wdebito = wdebito * -1;
             ELSE
             -- Despesas
             IF (wgrupocta = 4) THEN
                wdebito = wdebito;
             ELSE
             -- Outros
             IF (wgrupocta = 5) THEN
                wdebito = wdebito;
             -------------------------------------------------------------------

             wsaldo = wsaldo + wdebito + wcredito;
             wvalor = wdebito + wcredito;
             /*_______________________________________________________________*/
           END
        ELSE
           BEGIN
             bdsaldoanterior = wsaldo;

             /* Saldo ________________________________________________________*/
             -- Credito --------------------------------------------------------
             wcredito = bdcredito;
             IF ((wcredito IS NULL) OR (wcredito = 0)) THEN
                wcredito = 0;
             ELSE
             -- Ativo
             IF (wgrupocta = 0) THEN
                wcredito = wcredito * -1;
             ELSE
             -- Passivo
             IF (wgrupocta = 1) THEN
                wcredito = wcredito;
             ELSE
             -- Receitas
             IF (wgrupocta = 3) THEN
                wcredito = wcredito;
             ELSE
             -- Despesas
             IF (wgrupocta = 4) THEN
                wcredito = wcredito * -1;
             ELSE
             -- Outros
             IF (wgrupocta = 5) THEN
                wcredito = wcredito * -1;
           
             -- Debito ---------------------------------------------------------
             wdebito = bddebito;
             IF ((wdebito IS NULL) OR (wdebito = 0)) THEN
                wdebito = 0;
             ELSE
             -- Ativo
             IF (wgrupocta = 0) THEN
                wdebito = wdebito;
             ELSE
             -- Passivo
             IF (wgrupocta = 1) THEN
                wdebito = wdebito * -1;
             ELSE
             -- Receitas
             IF (wgrupocta = 3) THEN
                wdebito = wdebito * -1;
             ELSE
             -- Despesas
             IF (wgrupocta = 4) THEN
                wdebito = wdebito;
             ELSE
             -- Outros
             IF (wgrupocta = 5) THEN
                wdebito = wdebito;
             -------------------------------------------------------------------

             wsaldo = wsaldo + wdebito + wcredito;
             wvalor = wdebito + wcredito;
             /*_______________________________________________________________*/
           END
        wordem = wordem + 1;
        bdordsaldo = wordem;
        bdsaldo = wsaldo;
        IF (wvalor < 0) THEN
           bdvalorsemsinal = wvalor * -1;
        ELSE
           bdvalorsemsinal = wvalor;
        bdvalor     = wvalor;
        wconta      = bdconta;

        -- giovanni comentei a linha abaixo, se precisar me chamar para discutir...
        -- ja que o bdcompl ja tem o completo do historico completo, pra que dois campos iguais ????
        -- bdhistorico = bdcompl;

       IF (bdhistorico IS NOT NULL) THEN
         BEGIN
           SELECT pos FROM pos('*', :bdhistorico) INTO :wpos;
             IF (wpos > 0) THEN
                bdhistorico = bdcompl;
             ELSE
               bdhistorico = bdhistorico || ' ' || bdcompl;
         END
       ELSE
         bdhistorico = bdcompl;


        wclass_ant  = bdclass_conta;

        SUSPEND;
      END
END
^

/* Alter (VSUC_SP_RETORNA_RELESTATIST_GRA) */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATIST_GRA(PRCODEMP VARCHAR(2048),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES VARCHAR(8),
BDMESVALOR INTEGER,
BDCOLOR VARCHAR(10))
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WQTDLINHA INTEGER;
DECLARE VARIABLE WQTDDEB INTEGER;
DECLARE VARIABLE WQTDCRE INTEGER;
DECLARE VARIABLE WQTGER INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTALLINHA1 INTEGER;
DECLARE VARIABLE WTOTALLINHA2 INTEGER;
DECLARE VARIABLE WTOTALLINHA3 INTEGER;
DECLARE VARIABLE WTOTALLINHA4 INTEGER;
DECLARE VARIABLE WCODEPMANT INTEGER;
DECLARE VARIABLE WNOMEMPANT VARCHAR(100);
DECLARE VARIABLE WCNPJANT VARCHAR(20);
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WQTDDAUX INTEGER;
DECLARE VARIABLE WQTDCAUX INTEGER;
DECLARE VARIABLE WQTDLINHAAUX INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafim FROM 1 FOR 4)||SUBSTRING(prdatafim FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = (CAST(SUBSTRING(prdatafim FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER)) +1;
       IF (wtotal = 0) THEN
          wtotal = 1;
     END

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
        wtotallinha1 = 0;
        wtotallinha2 = 0;
        wtotallinha3 = 0;
        wtotallinha4 = 0;
        BDCOLOR = 0;

        wcount = 1;
        WHILE (wcount-1 < wtotal) DO
          BEGIN
            -- mensal ________________________________________________________
            IF (prtipcomp = 0) THEN
              BEGIN
                wdata_inicial = addmonth(prdataini, wcount-1);
                wdata_final   = addmonth(prdataini, wcount)-1;
              END
            ELSE
           -- anual _________________________________________________________
              BEGIN
                wdata_inicial = addyear(prdataini, wcount-1);
                wdata_final   = addyear(prdataini, wcount)-1;
              END

            --#alt:5837.
            /*wSqllanc =  'select count (bdchave) totlanclinha , count(bddebito) linhadeb, count(bdcredito) linhacre from vsuc_empresas_tlan LAN ' ||
                        ' where bdcodemp = ' || :bdcodemp;
            if (prcodusu > 0) then
            wSqllanc =  'select count (bdchave) totlanclinha , count(bddebito) linhadeb, count(bdcredito) linhacre from vsuc_empresas_tlan LAN ' ||
                        ' where bdcodemp = ' || :bdcodemp || ' and bdcodusu = ' || prcodusu;*/
            wSqllanc = 'Select bdcodemp,bdfilial,bdtipolancfilial,COUNT(bdchave) totlanclinha,COUNT(bddebito) linhadeb,COUNT(bdcredito) linhacre from vsuc_empresas_tlan LAN ';
            IF (prcodusu > 0) THEN
              wSqllanc = wSqllanc||' where ((bdcodemp = '||:bdcodemp||') or (bdfilial = '||:bdcodemp||')) and bdcodusu = ' || prcodusu;
            ELSE
              wSqllanc = wSqllanc||' where ((bdcodemp = '||:bdcodemp||') or (bdfilial = '||:bdcodemp||'))';
            --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wSqllanc = wSqllanc||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';

            IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
               wsqllanc = wsqllanc ||' and (BDDATA between '''||wdata_inicial||''' and '''||wdata_final||''') ';

            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
               wsqllanc = wsqllanc || ' and  ' || prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp,bdfilial,bdtipolancfilial';
            --#alt:5837.
            /*for execute statement wsqllanc into :wqtdlinha, :WQTDDEB, :WQTDCRE   do
               begin
                 wqtger = WQTDDEB + WQTDCRE;
               end*/
            wqtddeb   = 0;
            wqtdcre   = 0;
            wqtdlinha = 0;
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodempaux,:wfilial,:wtipolancfilial,:wqtdlinhaaux,:wqtddaux,:wqtdcaux DO
              BEGIN
                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:bdcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  wqtddeb = wqtddeb + wqtddaux;

                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:bdcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  wqtdcre = wqtdcre + wqtdcaux;

                wqtdlinha = wqtdlinha + wqtdlinhaaux;
              END
            wqtger = wqtddeb + wqtdcre;

            IF (WQTDDEB IS NULL) THEN
              WQTDDEB = 0;
            IF (WQTDCRE IS NULL) THEN
              WQTDCRE = 0;
            IF (wqtger IS NULL) THEN
              wqtger = 0;

            bdmes = '';
            bdmesvalor = 0;

            IF (wcount = 1) THEN
               BDCOLOR = 'clRed';
            ELSE
            IF (wcount = 2) THEN
               BDCOLOR = 'clBlue';
            ELSE
            IF (wcount = 3) THEN
               BDCOLOR = 'clMaroon';
            ELSE
            IF (wcount = 4) THEN
               BDCOLOR = 'clYellow';
            ELSE
            IF (wcount = 5) THEN
               BDCOLOR = 'clNavy';
            ELSE
            IF (wcount = 6) THEN
               BDCOLOR = 'clLime';
            ELSE
            IF (wcount = 7) THEN
               BDCOLOR = 'clBlack';
            ELSE
            IF (wcount = 8) THEN
               BDCOLOR = 'clFuchsia';
            ELSE
            IF (wcount = 9) THEN
               BDCOLOR = 'clAqua';
            ELSE
            IF (wcount = 10) THEN
               BDCOLOR = 'clSkyBlue';
            ELSE
            IF (wcount = 11) THEN
               BDCOLOR = 'cl3DLight';
            ELSE
            IF (wcount = 12) THEN
               BDCOLOR = 'clOlive';

            wcount = wcount + 1;
            bdmesvalor =wqtdlinha;
            IF (prtipcomp <= 0) THEN
               bdmes = SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 6 FOR 2)||'/'|| SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 1 FOR 4);
            ELSE
               bdmes = SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 1 FOR 4);

            SUSPEND;

            /* inicio total geral */
            wcodepmant = bdcodemp;
            wnomempant = bdnomemp;
            wcnpjant = bdcnpjemp;

            bdcodemp = 9999;
            bdnomemp = 'TOTAL GERAL';
            bdcnpjemp = '';

            bdmesvalor =wqtdlinha;
            IF (prtipcomp <= 0) THEN
               bdmes = SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 6 FOR 2)||'/'|| SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 1 FOR 4);
            ELSE
               bdmes = SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 1 FOR 4);

            SUSPEND;

            bdcodemp = wcodepmant;
            bdnomemp = wnomempant;
            bdcnpjemp = wcnpjant;

            /* final todal geral */
          END
      END
END
^

/* Alter (VSUC_SP_RETORNA_RELESTATISTGRA) */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTGRA(PRCODEMP VARCHAR(2048),
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WQTDLINHA INTEGER;
DECLARE VARIABLE WQTDDEB INTEGER;
DECLARE VARIABLE WQTDCRE INTEGER;
DECLARE VARIABLE WQTGER INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTALLINHA1 INTEGER;
DECLARE VARIABLE WTOTALLINHA2 INTEGER;
DECLARE VARIABLE WTOTALLINHA3 INTEGER;
DECLARE VARIABLE WTOTALLINHA4 INTEGER;
DECLARE VARIABLE WCODEPMANT INTEGER;
DECLARE VARIABLE WNOMEMPANT VARCHAR(100);
DECLARE VARIABLE WCNPJANT VARCHAR(20);
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WQTDDAUX INTEGER;
DECLARE VARIABLE WQTDCAUX INTEGER;
DECLARE VARIABLE WQTDLINHAAUX INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafim FROM 1 FOR 4)||SUBSTRING(prdatafim FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = (CAST(SUBSTRING(prdatafim FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER)) +1;
       IF (wtotal = 0) THEN
          wtotal = 1;
     END

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
        bdtotal = 0;
        wtotallinha1 = 0;
        wtotallinha2 = 0;
        wtotallinha3 = 0;
        wtotallinha4 = 0;

        wcount = 1;
        WHILE (wcount-1 < wtotal) DO
          BEGIN
            -- mensal ________________________________________________________
            IF (prtipcomp = 0) THEN
              BEGIN
                wdata_inicial = addmonth(prdataini, wcount-1);
                wdata_final   = addmonth(prdataini, wcount)-1;
              END
            ELSE
           -- anual _________________________________________________________
              BEGIN
                wdata_inicial = addyear(prdataini, wcount-1);
                wdata_final   = addyear(prdataini, wcount)-1;
              END
            --#alt:5837.
            /*wSqllanc =  'select count (bdchave) totlanclinha , count(bddebito) linhadeb, count(bdcredito) linhacre from vsuc_empresas_tlan LAN ' ||
                        ' where bdcodemp = ' || :bdcodemp;*/
            wSqllanc = 'Select bdcodemp,bdfilial,bdtipolancfilial,COUNT(bdchave) totlanclinha,COUNT(bddebito) linhadeb,COUNT(bdcredito) linhacre from vsuc_empresas_tlan LAN ' ||
                       'where ((bdcodemp = '||:bdcodemp||') or (bdfilial = '||:bdcodemp||'))';
            --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wSqllanc = wSqllanc||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';

            IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
               wsqllanc = wsqllanc ||' and (BDDATA between '''||wdata_inicial||''' and '''||wdata_final||''') ';

            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
               wsqllanc = wsqllanc || ' and  ' || prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp,bdfilial,bdtipolancfilial';
            --#alt:5837.
            /*for execute statement wsqllanc into :wqtdlinha, :WQTDDEB, :WQTDCRE   do
               begin
                 wqtger = WQTDDEB + WQTDCRE;
               end*/
            wqtddeb   = 0;
            wqtdcre   = 0;
            wqtdlinha = 0;
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodempaux,:wfilial,:wtipolancfilial,:wqtdlinhaaux,:wqtddaux,:wqtdcaux DO
              BEGIN
                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:bdcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  wqtddeb = wqtddeb + wqtddaux;

                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:bdcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  wqtdcre = wqtdcre + wqtdcaux;

                wqtdlinha = wqtdlinha + wqtdlinhaaux;
              END
            wqtger = wqtddeb + wqtdcre;

            IF (WQTDDEB IS NULL) THEN
               WQTDDEB = 0;
            IF (WQTDCRE IS NULL) THEN
               WQTDCRE = 0;
            IF (wqtger IS NULL) THEN
               wqtger = 0;

            bdmes01 = 0;
            bdmes02 = 0;
            bdmes03 = 0;
            bdmes04 = 0;
            bdmes05 = 0;
            bdmes06 = 0;
            bdmes07 = 0;
            bdmes08 = 0;
            bdmes09 = 0;
            bdmes10 = 0;
            bdmes11 = 0;
            bdmes12 = 0;

            IF (wcount = 1) THEN
              BEGIN
                bdtipo = 1;
                bdmes01 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes01 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes01 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes01 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;
                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */
              END
            ELSE
            IF (wcount = 2) THEN
              BEGIN
                bdtipo = 1;
                bdmes02 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes02 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes02 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes02 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 3) THEN
              BEGIN
                bdtipo = 1;
                bdmes03 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes03 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes03 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes03 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 4) THEN
              BEGIN
                bdtipo = 1;
                bdmes04 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes04 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes04 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes04 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 5) THEN
              BEGIN
                bdtipo = 1;
                bdmes05 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes05 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes05 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes05 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 6) THEN
              BEGIN
                bdtipo = 1;
                bdmes06 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes06 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes06 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes06 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 7) THEN
              BEGIN
                bdtipo = 1;
                bdmes07 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes07 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes07 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes07 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 8) THEN
              BEGIN
                bdtipo = 1;
                bdmes08 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes08 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes08 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes08 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 9) THEN
              BEGIN
                bdtipo = 1;
                bdmes09 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes09 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes09 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes09 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 10) THEN
              BEGIN
                bdtipo = 1;
                bdmes10 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes10 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes10 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes10 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 11) THEN
              BEGIN
                bdtipo = 1;
                bdmes11 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes11 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes11 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes11 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 12) THEN
              BEGIN
                bdtipo = 1;
                bdmes12 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes12 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes12 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes12 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END

            wcount = wcount + 1;
          END
      END

END
^

/* Alter (VSUC_SP_RETORNA_RELESTATISTICA) */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTICA(PRCODEMP VARCHAR(2048),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WQTDLINHA INTEGER;
DECLARE VARIABLE WQTDDEB INTEGER;
DECLARE VARIABLE WQTDCRE INTEGER;
DECLARE VARIABLE WQTGER INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTALLINHA1 INTEGER;
DECLARE VARIABLE WTOTALLINHA2 INTEGER;
DECLARE VARIABLE WTOTALLINHA3 INTEGER;
DECLARE VARIABLE WTOTALLINHA4 INTEGER;
DECLARE VARIABLE WCODEPMANT INTEGER;
DECLARE VARIABLE WNOMEMPANT VARCHAR(100);
DECLARE VARIABLE WCNPJANT VARCHAR(20);
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WQTDDAUX INTEGER;
DECLARE VARIABLE WQTDCAUX INTEGER;
DECLARE VARIABLE WQTDLINHAAUX INTEGER;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafim FROM 1 FOR 4)||SUBSTRING(prdatafim FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = (CAST(SUBSTRING(prdatafim FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER)) +1;
       IF (wtotal = 0) THEN
          wtotal = 1;
     END

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';

  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
        bdtotal = 0;
        wtotallinha1 = 0;
        wtotallinha2 = 0;
        wtotallinha3 = 0;
        wtotallinha4 = 0;

        wcount = 1;
        WHILE (wcount-1 < wtotal) DO
          BEGIN
            -- mensal ________________________________________________________
            IF (prtipcomp = 0) THEN
              BEGIN
                wdata_inicial = addmonth(prdataini, wcount-1);
                wdata_final   = addmonth(prdataini, wcount)-1;
              END
            ELSE
           -- anual _________________________________________________________
              BEGIN
                wdata_inicial = addyear(prdataini, wcount-1);
                wdata_final   = addyear(prdataini, wcount)-1;
              END
            --#alt:5837.
            /*wSqllanc = 'select count (bdchave) totlanclinha , count(bddebito) linhadeb, count(bdcredito) linhacre from vsuc_empresas_tlan LAN ';
            if (prcodusu > 0) then
              wSqllanc = wSqllanc||' where bdcodemp = ' || :bdcodemp || ' and bdcodusu = ' || prcodusu;
            else
              wSqllanc = wSqllanc||' where bdcodemp = ' || :bdcodemp;*/
            wSqllanc = 'select bdcodemp,bdfilial,bdtipolancfilial, COUNT(bdchave) totlanclinha , COUNT(bddebito) linhadeb, COUNT(bdcredito) linhacre from vsuc_empresas_tlan LAN ';
            IF (prcodusu > 0) THEN
              wSqllanc = wSqllanc||' where ((bdcodemp = '||:bdcodemp||') or (bdfilial = '||:bdcodemp||')) and bdcodusu = '|| prcodusu;
            ELSE
              wSqllanc = wSqllanc||' where ((bdcodemp = '||:bdcodemp||') or (bdfilial = '||:bdcodemp||'))';
            --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wSqllanc = wSqllanc||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';

            IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
               wsqllanc = wsqllanc ||' and (BDDATA between '''||wdata_inicial||''' and '''||wdata_final||''') ';

            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
               wsqllanc = wsqllanc || ' and  ' || prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp,bdfilial,bdtipolancfilial';
            --#alt:5837.
            /*for execute statement wsqllanc into :wqtdlinha, :WQTDDEB, :WQTDCRE   do
              begin
                wqtger = WQTDDEB + WQTDCRE;
              end*/
            wqtddeb   = 0;
            wqtdcre   = 0;
            wqtdlinha = 0;
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodempaux,:wfilial,:wtipolancfilial,:wqtdlinhaaux,:wqtddaux,:wqtdcaux DO
              BEGIN
                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:bdcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  wqtddeb = wqtddeb + wqtddaux;

                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:bdcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  wqtdcre = wqtdcre + wqtdcaux;

                wqtdlinha = wqtdlinha + wqtdlinhaaux;
              END
            wqtger = wqtddeb + wqtdcre;

            IF (WQTDDEB IS NULL) THEN
               WQTDDEB = 0;
            IF (WQTDCRE IS NULL) THEN
               WQTDCRE = 0;
            IF (wqtger IS NULL) THEN
               wqtger = 0;

            bdmes01 = 0;
            bdmes02 = 0;
            bdmes03 = 0;
            bdmes04 = 0;
            bdmes05 = 0;
            bdmes06 = 0;
            bdmes07 = 0;
            bdmes08 = 0;
            bdmes09 = 0;
            bdmes10 = 0;
            bdmes11 = 0;
            bdmes12 = 0;

            IF (wcount = 1) THEN
              BEGIN
                bdtipo = 1;
                bdmes01 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */


                bdtipo = 2;
                bdmes01 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes01 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes01 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;
                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 2) THEN
              BEGIN
                bdtipo = 1;
                bdmes02 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes02 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes02 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes02 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 3) THEN
              BEGIN
                bdtipo = 1;
                bdmes03 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes03 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes03 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes03 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 4) THEN
              BEGIN
                bdtipo = 1;
                bdmes04 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes04 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes04 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes04 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 5) THEN
              BEGIN
                bdtipo = 1;
                bdmes05 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes05 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes05 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes05 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 6) THEN
              BEGIN
                bdtipo = 1;
                bdmes06 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes06 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes06 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes06 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 7) THEN
              BEGIN
                bdtipo = 1;
                bdmes07 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes07 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes07 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes07 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 8) THEN
              BEGIN
                bdtipo = 1;
                bdmes08 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes08 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes08 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes08 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 9) THEN
              BEGIN
                bdtipo = 1;
                bdmes09 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes09 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes09 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes09 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 10) THEN
              BEGIN
                bdtipo = 1;
                bdmes10 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes10 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes10 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes10 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 11) THEN
              BEGIN
                bdtipo = 1;
                bdmes11 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes11 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes11 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes11 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 12) THEN
              BEGIN
                bdtipo = 1;
                bdmes12 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes12 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes12 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes12 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 9999;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END

            wcount = wcount + 1;
          END
      END

END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_SALDO_LANC for: VSUC_SP_RETORNA_SALDO */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_LANC(PRCODEMP INTEGER,
PRREFEMP INTEGER,
PRCONTA_DEB INTEGER,
PRCONTA_CRED INTEGER,
PRDATA DATE,
PRPARTICIPANTED INTEGER,
PRPARTICIPANTEC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFIIALCONSOLIDADO INTEGER)
 RETURNS(ANT_AO_DIA_D NUMERIC(15,2),
DEB_DO_DIA_D NUMERIC(15,2),
CRED_DO_DIA_D NUMERIC(15,2),
ATUAL_DO_DIA_D NUMERIC(15,2),
ANT_AO_DIA_C NUMERIC(15,2),
DEB_DO_DIA_C NUMERIC(15,2),
CRED_DO_DIA_C NUMERIC(15,2),
ATUAL_DO_DIA_C NUMERIC(15,2),
ANT_AO_MES_C NUMERIC(15,2),
ATUAL_DO_MES_C NUMERIC(15,2),
ANT_AO_MES_D NUMERIC(15,2),
DEB_DO_MES_D NUMERIC(15,2),
CRED_DO_MES_D NUMERIC(15,2),
MOV_DO_MES_D NUMERIC(15,2),
ATUAL_DO_MES_D NUMERIC(15,2),
ANT_DO_MES_C NUMERIC(15,2),
DEB_DO_MES_C NUMERIC(15,2),
CRED_DO_MES_C NUMERIC(15,2),
MOV_DO_MES_C NUMERIC(15,2),
ATUTAL_DO_MES_C NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_RETORNA_SALDO) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRFORM VARCHAR(10),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
SALDO_MOVIMENTO NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WREFATUAL INTEGER;
BEGIN
  SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database INTO :wrefatual;
  EXECUTE PROCEDURE sp_seta_competencia(:prrefemp);

  --alt:10666 - Adicionado select para retornar a empresa matriz (selecionando v?rias) ou ela mesma caso
  wsql = 'select first 1 coalesce(BDCODMATRIZ, BDCODEMP) from TEMPRESAS where BDCODEMP in ('||:prcodemp||')';
  EXECUTE STATEMENT wsql INTO :WCODMATRIZ;

  -- pega a classificacao da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM vw_empresas_ref_atual tref
                                    --WHERE tref.bdcodemp = :prcodemp)
                                    --alt:10666 - Alterado para pegar o c?digo do select e n?o do par?metro, que agora pode ser uma lista de empresas. Pedro
                                    WHERE tref.bdcodemp = :wcodmatriz)
--                                    from tempresas_ref tref
--                                    where tref.bdcodemp = :prcodemp
--                                    and tref.bdrefemp <= :prrefemp
--                                    order by tref.bdrefemp desc)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  EXECUTE PROCEDURE sp_seta_competencia(:wrefatual);

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou nao as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and substring(tpla.bdctalon from 1 for '||wtamanho||') = '''||wclassificacao||''' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- SALDO A DEBITO ____________________________________________________________
  SALDO_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN '; */
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END

--  if (Trim(prform) <> '') then
--     wsql = wsql||'inner join vsuc_empresas_tlanform tform on (tform.bdcodemp = tlan.bdcodemp and tform.bdchave = tlan.bdchave) ';
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

--  if (Trim(prform) <> '') then
--     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''' or tlan.'||prform||' <> '''||'0'||''')';

  IF (TRIM(prform) <> '') THEN
     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';

  --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';  --alt:10666 - Trocado para "in" para aceitar multiplas empresas. Pedro
  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_DEB do
    if (SALDO_DEB is null) then
      SALDO_DEB=0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      --alt:10666 - Trocado do par?metro de empresa para o c?digo da matriz, pois agora o par?metro pode ser uma lista de empresas. Pedro
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:WCODMATRIZ,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_DEB = SALDO_DEB + wvlr;
    END

  -- SALDO A CREDITO ___________________________________________________________
  SALDO_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END

--  if (Trim(prform) <> '') then
--     wsql = wsql||'inner join vsuc_empresas_tlanform tform on (tform.bdcodemp = tlan.bdcodemp and tform.bdchave = tlan.bdchave) ';
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

--  if (Trim(prform) <> '') then
--     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''' or tlan.'||prform||' <> '''||'0'||''')';
  IF (TRIM(prform) <> '') THEN
    wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';

  --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';  --alt:10666 - Trocado para "in" para aceitar multiplas empresas. Pedro
  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_CRE do
    if (SALDO_CRE is null) then
      SALDO_CRE=0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      --alt:10666 - Trocado do par?metro de empresa para o c?digo da matriz, pois agora o par?metro pode ser uma lista de empresas. Pedro
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:WCODMATRIZ,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_CRE = SALDO_CRE + wvlr;
    END

  -- SALDO ANTERIOR A DEBITO _________________________________________________
  SALDO_ANT_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN '; */
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END

--  if (Trim(prform) <> '') then
--     wsql = wsql||'inner join vsuc_empresas_tlanform tform on (tform.bdcodemp = tlan.bdcodemp and tform.bdchave = tlan.bdchave) ';
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

--  if (Trim(prform) <> '') then
--     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''' or tlan.'||prform||' <> '''||'0'||''')';
  IF (TRIM(prform) <> '') THEN
     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';

  --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';  --alt:10666 - Trocado para "in" para aceitar multiplas empresas. Pedro
  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_DEB do
    if (SALDO_ANT_DEB is null) then
      SALDO_ANT_DEB=0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      --alt:10666 - Trocado do par?metro de empresa para o c?digo da matriz, pois agora o par?metro pode ser uma lista de empresas. Pedro
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:WCODMATRIZ,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_ANT_DEB = SALDO_ANT_DEB + wvlr;
    END

  -- SALDO ANTERIOR A CREDITO __________________________________________________
  SALDO_ANT_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END


  --alt:10666 - Teste da solicita??o.

--  if (Trim(prform) <> '') then
--     wsql = wsql||'inner join vsuc_empresas_tlanform tform on (tform.bdcodemp = tlan.bdcodemp and tform.bdchave = tlan.bdchave) ';
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

--  if (Trim(prform) <> '') then
--     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''' or tlan.'||prform||' <> '''||'0'||''')';
  IF (TRIM(prform) <> '') THEN
     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';

  --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) '; --alt:10666 - Trocado para "in" para aceitar multiplas empresas. Pedro
  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_CRE do
    if (SALDO_ANT_CRE is null) then
      SALDO_ANT_CRE=0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      --alt:10666 - Trocado do par?metro de empresa para o c?digo da matriz, pois agora o par?metro pode ser uma lista de empresas. Pedro
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:WCODMATRIZ,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_ANT_CRE = SALDO_ANT_CRE + wvlr;
    END

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3) OR (wgrupocta = 5)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  --SALDO_ATUAL = (SALDO_DEB-SALDO_CRE);
  IF ((wgrupocta = 0) OR (wgrupocta = 4))  THEN -- ATIVO e DESPESAS
    BEGIN
      saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
      saldo_movimento = SALDO_DEB - SALDO_CRE;
    END
  ELSE
    BEGIN
       IF ((wgrupocta = 1) OR (wgrupocta = 3) OR (wgrupocta = 5)) THEN -- PASSIVO e RECEITAS
         BEGIN
           saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;
           saldo_movimento = SALDO_CRE - SALDO_DEB;
         END
    END

  SUSPEND;
END
^

/* Alter (VSUC_SP_RETORNA_SALDO_CONS_ORCA) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONS_ORCA(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRCODTPCC INTEGER,
PRANO INTEGER,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2))
 AS
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WGRUPOCONTA INTEGER;
DECLARE VARIABLE WDATAREF VARCHAR(10);
DECLARE VARIABLE WDEB01 NUMERIC(15,2);
DECLARE VARIABLE WDEB02 NUMERIC(15,2);
DECLARE VARIABLE WDEB03 NUMERIC(15,2);
DECLARE VARIABLE WDEB04 NUMERIC(15,2);
DECLARE VARIABLE WDEB05 NUMERIC(15,2);
DECLARE VARIABLE WDEB06 NUMERIC(15,2);
DECLARE VARIABLE WDEB07 NUMERIC(15,2);
DECLARE VARIABLE WDEB08 NUMERIC(15,2);
DECLARE VARIABLE WDEB09 NUMERIC(15,2);
DECLARE VARIABLE WDEB10 NUMERIC(15,2);
DECLARE VARIABLE WDEB11 NUMERIC(15,2);
DECLARE VARIABLE WDEB12 NUMERIC(15,2);
DECLARE VARIABLE WCRE01 NUMERIC(15,2);
DECLARE VARIABLE WCRE02 NUMERIC(15,2);
DECLARE VARIABLE WCRE03 NUMERIC(15,2);
DECLARE VARIABLE WCRE04 NUMERIC(15,2);
DECLARE VARIABLE WCRE05 NUMERIC(15,2);
DECLARE VARIABLE WCRE06 NUMERIC(15,2);
DECLARE VARIABLE WCRE07 NUMERIC(15,2);
DECLARE VARIABLE WCRE08 NUMERIC(15,2);
DECLARE VARIABLE WCRE09 NUMERIC(15,2);
DECLARE VARIABLE WCRE10 NUMERIC(15,2);
DECLARE VARIABLE WCRE11 NUMERIC(15,2);
DECLARE VARIABLE WCRE12 NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
BEGIN
 wdataini = '01/'||'01/'||:prano;
 wdatafim = '12/'||'31/'||:prano;

 wgrupoconta = 0;

 SELECT bdgrupocta
 FROM PLANOS_TPLA
 WHERE bdCODPLAPADRAO = (SELECT FIRST 1 tref.bdcodplapadrao
                          FROM tempresas_ref tref
                          WHERE tref.bdcodemp = :prcodemp
                          AND tref.bdrefemp <= :prrefemp
                          ORDER BY tref.bdrefemp DESC)
 AND (bdCODTPLA = :prconta)
 INTO :wgrupoconta;

 bdsal01 = 0;
 bdsal02 = 0;
 bdsal03 = 0;
 bdsal04 = 0;
 bdsal05 = 0;
 bdsal06 = 0;
 bdsal07 = 0;
 bdsal08 = 0;
 bdsal09 = 0;
 bdsal10 = 0;
 bdsal11 = 0;
 bdsal12 = 0;
 wdeb01  = 0;
 wdeb02  = 0;
 wdeb03  = 0;
 wdeb04  = 0;
 wdeb05  = 0;
 wdeb06  = 0;
 wdeb07  = 0;
 wdeb08  = 0;
 wdeb09  = 0;
 wdeb10  = 0;
 wdeb11  = 0;
 wdeb12  = 0;
 wcre01  = 0;
 wcre02  = 0;
 wcre03  = 0;
 wcre04  = 0;
 wcre05  = 0;
 wcre06  = 0;
 wcre07  = 0;
 wcre08  = 0;
 wcre09  = 0;
 wcre10  = 0;
 wcre11  = 0;
 wcre12  = 0;

 /* saldo debito no periodo */
 IF ((prcodtpcc = 0) OR (prcodtpcc IS NULL)) THEN
   BEGIN
     wsql = '';
     --#alt:5837.
     --wsql = wsql || ' select substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' select bdcodemp,bdfilial,bdtipolancfilial,substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' SUM(bdvalor) BDVALDEB ';
     wsql = wsql || ' from vsuc_empresas_tlan LAN ';
     --wsql = wsql || ' where bdcodemp = ' || :prcodemp || 'AND (BDDEBITO = ' || :prconta || ' ) ';
     wsql = wsql || ' where ((bdcodemp = ' || :prcodemp || ') or (bdfilial = '||:prcodemp||')) AND (BDDEBITO = ' || :prconta || ' ) ';
     wsql = wsql || ' AND (BDDATA between ''' ||  wdataini || ''' and ''' ||  wdatafim || '''' || ')';
     --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
     IF (prcontabilizacao <> 99) THEN
       wsql = wsql || ' and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
     wsql = wsql || ' GROUP BY bdcodemp,bdfilial,bdtipolancfilial,bdref' ;
   END
 ELSE
   BEGIN
     wsql = '';
     --#alt:5837.
     --wsql = wsql || ' select substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || 'select TLAN.bdcodemp,bdfilial,bdtipolancfilial,substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' SUM(TLCC.BDVALOR) BDVALDEB ';
     wsql = wsql || ' from VSUC_EMPRESAS_TLCC tlcc ';
     wsql = wsql || ' join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     --wsql = wsql || ' where tlan.bdcodemp = ' || :prcodemp || 'AND (tlan.BDDEBITO = ' || :prconta || ' ) ';
     wsql = wsql || ' where ((tlan.bdcodemp = ' || :prcodemp || ') or (tlan.bdfilial = '||:prcodemp||')) AND (tlan.BDDEBITO = ' || :prconta || ' ) ';
     wsql = wsql || ' and tlcc.BDCODTPCC = ' || :prcodtpcc || 'AND (tlcc.bddebcre = 0) ';
     wsql = wsql || ' AND (BDDATA between ''' ||  wdataini || ''' and ''' ||  wdatafim || '''' || ')';
     --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
     IF (prcontabilizacao <> 99) THEN
       wsql = wsql || ' and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
     wsql = wsql || ' GROUP BY TLAN.bdcodemp,bdfilial,bdtipolancfilial,bdref';
   END

 FOR EXECUTE STATEMENT wsql  INTO :wcodemp,:wfilial,:wtipolancfilial,:wdataref,:wvalor  DO
  BEGIN
    SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
    IF (wpermite = 1) THEN
      BEGIN
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '01') THEN
          wdeb01 = wdeb01 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '02') THEN
          wdeb02 = wdeb02 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '03') THEN
          wdeb03 = wdeb03 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '04') THEN
          wdeb04 = wdeb04 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '05') THEN
          wdeb05 = wdeb05 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '06') THEN
          wdeb06 = wdeb06 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '07') THEN
          wdeb07 = wdeb07 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '08') THEN
          wdeb08 = wdeb08 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '09') THEN
          wdeb09 = wdeb09 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '10') THEN
          wdeb10 = wdeb10 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '11') THEN
          wdeb11 = wdeb11 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '12') THEN
          wdeb12 = wdeb12 + wvalor;
      END
  END

 /* saldo cr?dito no periodo */
 IF ((prcodtpcc = 0) OR (prcodtpcc IS NULL)) THEN
   BEGIN
     wsql = '';
     --#alt:5837.
     --wsql = wsql || ' select substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || 'Select bdcodemp,bdfilial,bdtipolancfilial,substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' SUM(bdvalor) BDVALCRE ';
     wsql = wsql || ' from vsuc_empresas_tlan LAN ';
     --wsql = wsql || ' where bdcodemp = ' || :prcodemp || 'AND (BDCREDITO = ' || :prconta || ' ) ';
     wsql = wsql || ' where ((bdcodemp = ' || :prcodemp || ') or (bdfilial = '||:prcodemp||')) AND (BDCREDITO = ' || :prconta || ' ) ';
     wsql = wsql || ' AND (BDDATA between ''' ||  wdataini || ''' and ''' ||  wdatafim || '''' || ')';
     --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
     IF (prcontabilizacao <> 99) THEN
       wsql = wsql || ' and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
     wsql = wsql || ' GROUP BY bdcodemp,bdfilial,bdtipolancfilial,bdref' ;
   END
 ELSE
   BEGIN
     wsql = '';
     --#alt:5837.
     --wsql = wsql || ' select substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' select TLAN.bdcodemp,bdfilial,bdtipolancfilial,substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' SUM(TLCC.BDVALOR) BDVALCRE ';
     wsql = wsql || ' from VSUC_EMPRESAS_TLCC tlcc ';
     wsql = wsql || ' join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     --wsql = wsql || ' where tlan.bdcodemp = ' || :prcodemp || 'AND (tlan.BDCREDITO = ' || :prconta || ' ) ';
     wsql = wsql || ' where ((tlan.bdcodemp = ' || :prcodemp || ') or (tlan.bdfilial = '||:prcodemp||')) AND (tlan.BDCREDITO = ' || :prconta || ' ) ';
     wsql = wsql || ' and tlcc.BDCODTPCC = ' || :prcodtpcc || 'AND (tlcc.bddebcre = 1) ';
     wsql = wsql || ' AND (BDDATA between ''' ||  wdataini || ''' and ''' ||  wdatafim || '''' || ')';
     --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
     IF (prcontabilizacao <> 99) THEN
       wsql = wsql || ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
     wsql = wsql || ' GROUP BY TLAN.bdcodemp,bdfilial,bdtipolancfilial,bdref' ;
   END

 FOR EXECUTE STATEMENT wsql  INTO :wcodemp,:wfilial,:wtipolancfilial,:wdataref,:wvalor  DO
  BEGIN
    SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
    IF (wpermite = 1) THEN
      BEGIN
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '01') THEN
          wcre01 = wcre01 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '02') THEN
          wcre02 = wcre02 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '03') THEN
          wcre03 = wcre03 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '04') THEN
          wcre04 = wcre04 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '05') THEN
          wcre05 = wcre05 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '06') THEN
          wcre06 = wcre06 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '07') THEN
          wcre07 = wcre07 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '08') THEN
          wcre08 = wcre08 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '09') THEN
          wcre09 = wcre09 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '10') THEN
          wcre10 = wcre10 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '11') THEN
          wcre11 = wcre11 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '12') THEN
          wcre12 = wcre12 + wvalor;
      END
  END

  IF ((wgrupoconta = 0) OR (wgrupoconta = 4))  THEN -- ATIVO e DESPESAS
    BEGIN
      bdsal01 = wdeb01 - wcre01;
      bdsal02 = wdeb02 - wcre02;
      bdsal03 = wdeb03 - wcre03;
      bdsal04 = wdeb04 - wcre04;
      bdsal05 = wdeb05 - wcre05;
      bdsal06 = wdeb06 - wcre06;
      bdsal07 = wdeb07 - wcre07;
      bdsal08 = wdeb08 - wcre08;
      bdsal09 = wdeb09 - wcre09;
      bdsal10 = wdeb10 - wcre10;
      bdsal11 = wdeb11 - wcre11;
      bdsal12 = wdeb12 - wcre12;
    END
  ELSE
    IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
      BEGIN
        bdsal01 = wcre01 - wdeb01;
        bdsal02 = wcre02 - wdeb02;
        bdsal03 = wcre03 - wdeb03;
        bdsal04 = wcre04 - wdeb04;
        bdsal05 = wcre05 - wdeb05;
        bdsal06 = wcre06 - wdeb06;
        bdsal07 = wcre07 - wdeb07;
        bdsal08 = wcre08 - wdeb08;
        bdsal09 = wcre09 - wdeb09;
        bdsal10 = wcre10 - wdeb10;
        bdsal11 = wcre11 - wdeb11;
        bdsal12 = wcre12 - wdeb12;
      END

  SUSPEND;
END
^

/* Alter (VSUC_SP_RETORNA_SALDO_CONTAS) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRLANCSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDATAHORA VARCHAR(30),
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
CLANOM VARCHAR(140),
TIPCONTA SMALLINT,
SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
FORMULA VARCHAR(200),
PARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WCODIGOPLANO INTEGER;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WCLANOM VARCHAR(140);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WSALDO_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCLASSINI VARCHAR(40);
DECLARE VARIABLE WCLASSFIN VARCHAR(40);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WSQL_AUX VARCHAR(32000);
BEGIN
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontainicial
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontafinal
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas anal?ticas
  SELECT BDRPOS FROM RPOS(',1,',','||:prniveisconta||',') INTO :wimpanalitica;

  -- retorna o plano de contas para a tabela temporaria
  wsql = '';
  wsql = wsql|| ' select distinct CONTAS.bdcodplapadrao, CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta,CONTAS.bdnomcta, ';
  wsql = wsql|| ' CONTAS.bdgrupocta, CONTAS.bdrelcta, CONTAS.BDCLANOM, CONTAS.bdformula, CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS(' || prcodigoemp || ', ' || prcodplapadrao ||   ',null,null,null,null,0,0,' || prnaomostracontacomp || ',3,'  || prtodasascontas ||') CONTAS';
  wsql = wsql|| ' where (contas.bdcodplapadrao = ' || :prcodplapadrao || ') and (contas.bdctalon between ''' || :wclassini || ''' and  ''' || :wclassfin || ''')';
  wsql = wsql||' order by BDCTALON';

  FOR EXECUTE STATEMENT wsql
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wnomcta, :wgrpcta, :wrelcta, :wclanom,  :wformula, :wparticipante DO
      BEGIN
        INSERT INTO vsuc_empresas_tbalancete_2 (bddatahora, bdcodemp, bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
                                                bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdrelcta, bdclanom, bdformula, bdparticipante)
        VALUES(:prdatahora, :prcodigoemp, :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta, 0.00, 0.00, 0.00, 0.00, :wrelcta, :wclanom, :wformula, :wparticipante);
      END

  -- lancamnetos sem centro de custo

  -- Valor a debito
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
        -- centro de custo
        --#alt:5837.
        --wsql = wsql||'SELECT tlan.bddebito, SUM(TLCC.BDVALOR) AS valor_debito ';
        wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bddebito, SUM(TLCC.BDVALOR) AS valor_debito ';
        wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
        wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE
     BEGIN
       -- lancamentos
       --#alt:5837.
       --wsql = wsql || 'select tlan.bddebito, coalesce(sum(tlan.bdvalor),0) as valor_debito ';
       wsql = wsql || 'select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bddebito, coalesce(sum(tlan.bdvalor),0) as valor_debito ';
       wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  -- gilberto - 15/03/2012 - para lancamentos sem centro de custo deve calcular tudo
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql||'and (TLCC.BDDEBCRE = 0) ';
  -- Giovanni - somente lancamentos sem cc
  IF (prlancsemcc = 1) THEN
     BEGIN
--     wsql = wsql || 'and not tlan.bdchave in (select bdchave from vsuc_empresas_tlcc where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'and not tlan.bdchave in ( ';
       wsql = wsql||'                         select bdchave ';
       wsql = wsql||'                         from (select bdcodemp, bdchave, count(bdchave) total ';
       wsql = wsql||'                               from (select distinct bdcodemp, bdchave, bddebcre ';
       wsql = wsql||'                                     from vsuc_empresas_tlcc ';
       wsql = wsql||'                                     where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'                               group by bdcodemp, bdchave) ';
       wsql = wsql||'                         where total = 2) ';
     END
  IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tlan.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';
  wsql = wsql || 'and (tlan.bddebito is not null) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql || 'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bddebito ';

  -- pega a classificaaoo e o saldo total das contas analiticas ______________--
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wcodtpla,:wsaldo_debito DO
    BEGIN
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          --#alt:5837.
          /*-- faz um update no debito, pq ja foi gravado o lancamento antes zerado
          update vsuc_empresas_tbalancete_2 set bdValor_debito = :wsaldo_debito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :prcodplapadrao
          and   bdcodtpla = :wcodtpla
          and   bdvalor_debito = 0
          and   bddatahora = :prdatahora; */
          wsql_aux = 'update vsuc_empresas_tbalancete_2 set ';
          wsql_aux = wsql_aux||'bdValor_debito = (coalesce((select bdValor_debito from vsuc_empresas_tbalancete_2';
          wsql_aux = wsql_aux||'                             where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||'                             and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''),0)';
          wsql_aux = wsql_aux||'                  + '||wsaldo_debito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        END
    END

--  exception ex_date;

  -- valor a credito
  wsql = '';
 IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
       -- centro de custo
       --#alt:5837.
       --wsql = wsql||'SELECT tlan.bdcredito, SUM(TLCC.BDVALOR) AS valor_credito ';
       wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bdcredito, SUM(TLCC.BDVALOR) AS valor_credito ';
       wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
       wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE
     BEGIN
       -- lancamentos
       --#alt:5837.
       --wsql = wsql || 'select tlan.bdcredito, coalesce(sum(tlan.bdvalor),0) as valor_credito ';
       wsql = wsql || 'select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bdcredito, coalesce(sum(tlan.bdvalor),0) as valor_credito ';
       wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  -- gilberto - 15/03/2012 - para lancamentos sem centro de custo deve calcular tudo
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql||'and (TLCC.BDDEBCRE = 1) ';
  -- Giovanni - somente lancamentos sem cc
  IF (prlancsemcc = 1) THEN
     BEGIN
--     wsql = wsql || 'and not tlan.bdchave in (select bdchave from vsuc_empresas_tlcc where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'and not tlan.bdchave in ( ';
       wsql = wsql||'                         select bdchave ';
       wsql = wsql||'                         from (select bdcodemp, bdchave, count(bdchave) total ';
       wsql = wsql||'                               from (select distinct bdcodemp, bdchave, bddebcre ';
       wsql = wsql||'                                     from vsuc_empresas_tlcc ';
       wsql = wsql||'                                     where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'                               group by bdcodemp, bdchave) ';
       wsql = wsql||'                         where total = 2) ';
     END
  IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tlan.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';
  wsql = wsql || 'and (tlan.bdcredito is not null) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql || 'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bdcredito ';

  -- pega a classificaaoo e o saldo total das analiticas _______________________
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wcodtpla, :wsaldo_credito DO
    BEGIN
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          -- faz update no credito, pq ja foi gravado o lancamento antes zerado __
          --#alt:5837.
          /*update vsuc_empresas_tbalancete_2 set bdValor_Credito = :wsaldo_credito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :prcodplapadrao
          and   bdcodtpla = :wcodtpla
          and   bdvalor_credito = 0
          and   bddatahora = :prdatahora;*/
          wsql_aux = 'update vsuc_empresas_tbalancete_2 set ';
          wsql_aux = wsql_aux||'bdValor_Credito = (coalesce((select bdValor_Credito from vsuc_empresas_tbalancete_2';
          wsql_aux = wsql_aux||'                             where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||'                             and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''),0)';
          wsql_aux = wsql_aux||'                  + '||wsaldo_credito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        END
    END

  -- valor a debito anterior
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
        --#alt:5837.
        --wsql = wsql||'SELECT tlan.bddebito, SUM(TLCC.BDVALOR) AS valor_debito ';
        wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bddebito, SUM(TLCC.BDVALOR) AS valor_debito ';
        wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
        wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE
     BEGIN
       --#alt:5837.
       --wsql = wsql || 'select tlan.bddebito, coalesce(sum(tlan.bdvalor),0) as valor_debito_anterior ';
       wsql = wsql || 'select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bddebito, coalesce(sum(tlan.bdvalor),0) as valor_debito_anterior ';
       wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  -- gilberto - 14/03/2012 - calcular apenas os lancamentos CC referente ao calculo atual
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql||'and (TLCC.BDDEBCRE = 1) ';
  -- Giovanni - somente lancamentos sem cc
  IF (prlancsemcc = 1) THEN
     BEGIN
--     wsql = wsql || 'and not tlan.bdchave in (select bdchave from vsuc_empresas_tlcc where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'and not tlan.bdchave in ( ';
       wsql = wsql||'                         select bdchave ';
       wsql = wsql||'                         from (select bdcodemp, bdchave, count(bdchave) total ';
       wsql = wsql||'                               from (select distinct bdcodemp, bdchave, bddebcre ';
       wsql = wsql||'                                     from vsuc_empresas_tlcc ';
       wsql = wsql||'                                     where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'                               group by bdcodemp, bdchave) ';
       wsql = wsql||'                         where total = 2) ';
     END
  -- Carlos Mello(22/06/2011) - Solicita??o.: 1028. Segundo an?lise do Celso para saldo anterior n?o deve ignorar o zeramento
  --para saldo anterior sempre deve ignorar o zeramento
  --if ((prignorazeramento is not null) and (prignorazeramento <> 0)) then
  --   wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tlan.bddata < '''||prdataini||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';
  wsql = wsql || 'and (tlan.bddebito is not null) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql || 'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bddebito ';

  -- pega a classificacao e o saldo total das contas analiticas ________________
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wcodtpla, :wsaldo_debito DO
    BEGIN
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          -- faz um update no debito, pq ja foi gravado o lancamento antes zerado
          --#alt:5837.
          /*update vsuc_empresas_tbalancete_2 set bdAnterior_debito = :wsaldo_debito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :prcodplapadrao
          and   bdcodtpla = :wcodtpla
          and   bdAnterior_debito = 0
          and bddatahora = :prdatahora; */
          wsql_aux = 'update vsuc_empresas_tbalancete_2 set ';
          wsql_aux = wsql_aux||'bdAnterior_debito = (coalesce((select bdAnterior_debito from vsuc_empresas_tbalancete_2';
          wsql_aux = wsql_aux||'                               where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||'                               and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''),0)';
          wsql_aux = wsql_aux||'                  + '||wsaldo_debito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        END
    END

  -- valor a credito anterior
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
       -- centro de custo
       --#alt:5837.
       --wsql = wsql||'SELECT tlan.bdcredito, SUM(TLCC.BDVALOR) AS valor_debito ';
       wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bdcredito, SUM(TLCC.BDVALOR) AS valor_debito ';
       wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
       wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE
     BEGIN
       -- lancamentos
       --#alt:5837.
       --wsql = wsql || 'select tlan.bdcredito, coalesce(sum(tlan.bdvalor),0) as valor_credito_anterior ';
       wsql = wsql || 'select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bdcredito, coalesce(sum(tlan.bdvalor),0) as valor_credito_anterior ';
       wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  -- gilberto - 14/03/2012 - calcular apenas os lancamentos CC referente ao calculo atual
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql||'and (TLCC.BDDEBCRE = 1) ';
  -- Giovanni - somente lancamentos sem cc
  IF (prlancsemcc = 1) THEN
     BEGIN
--     wsql = wsql || 'and not tlan.bdchave in (select bdchave from vsuc_empresas_tlcc where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'and not tlan.bdchave in ( ';
       wsql = wsql||'                         select bdchave ';
       wsql = wsql||'                         from (select bdcodemp, bdchave, count(bdchave) total ';
       wsql = wsql||'                               from (select distinct bdcodemp, bdchave, bddebcre ';
       wsql = wsql||'                                     from vsuc_empresas_tlcc ';
       wsql = wsql||'                                     where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'                               group by bdcodemp, bdchave) ';
       wsql = wsql||'                         where total = 2) ';
     END
--   Carlos Mello(22/06/2011) - Solicita??o.: 1028. Segundo an?lise do Celso para saldo anterior n?o deve ignorar o zeramento
  --para saldo anterior sempre deve ignorar o zeramento
--  if ((prignorazeramento is not null) and (prignorazeramento <> 0)) then
--     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tlan.bddata < '''||prdataini||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';
  wsql = wsql || 'and (tlan.bdcredito is not null) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql || 'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tlan.bdcredito';

  -- pega a classificaaoo e o saldo total das analiticas _______________________
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wcodtpla, :wsaldo_credito DO
    BEGIN
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          -- faz update no credito, pq ja foi gravado o lancamento antes zerado __
          --#alt:5837.
          /*update vsuc_empresas_tbalancete_2 set bdAnterior_Credito = :wsaldo_credito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :prcodplapadrao
          and   bdcodtpla = :wcodtpla
          and   bdAnterior_credito = 0
          and   bddatahora = :prdatahora; */
          wsql_aux = 'update vsuc_empresas_tbalancete_2 set ';
          wsql_aux = wsql_aux||'bdAnterior_Credito = (coalesce((select bdAnterior_Credito from vsuc_empresas_tbalancete_2';
          wsql_aux = wsql_aux||'                                where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||'                                and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''),0)';
          wsql_aux = wsql_aux||'                  + '||wsaldo_credito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        END
    END

  FOR SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta
      FROM vsuc_empresas_tbalancete_2 tbal
      WHERE tbal.bdtipcta IN (0,2)-- gilberto - 17/05/2011 - totalizando as contas consolidadas
      AND tbal.bdcodemp = :prcodigoemp
      AND tbal.bddatahora = :prdatahora
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta DO
      BEGIN
        -- fas um select para totalizar as contas titulos ______________________
        SELECT SUM(tbal.bdvalor_debito) AS valor_debito, SUM(tbal.bdvalor_credito) AS valor_credito,
               SUM(tbal.bdanterior_debito) AS anterior_debito, SUM(tbal.bdanterior_credito) AS anterior_credito
        FROM vsuc_empresas_tbalancete_2 tbal
--        where substring(bdctalon from 1 for strlen(:wclassificacao)) = :wclassificacao
        WHERE bdctalon LIKE :wclassificacao||'%'
        AND tbal.bdcodemp = :prcodigoemp
        AND tbal.bddatahora = :prdatahora
        GROUP BY SUBSTRING(bdctalon FROM 1 FOR strlen(:wclassificacao))
        INTO :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito;

        -- da um update na tabela de balancete para gravar os totais ___________
        UPDATE vsuc_empresas_tbalancete_2 SET bdvalor_debito = :wsaldo_debito,
                                            bdvalor_credito = :wsaldo_credito,
                                            bdanterior_debito = :wanterior_debito,
                                            bdanterior_credito = :wanterior_credito
        WHERE bdcodemp = :prcodigoemp
        AND   bdcodplapadrao = :wcodigoplano
        AND   bdcodtpla = :wcodtpla
        AND   bddatahora = :prdatahora
        AND   bdctalon = :wclassificacao;
      END

  -- gilberto - 07/10/2011 - retira as contas analiticas que pertencem a uma conta consolidadas
  IF ((prconsolidada IS NULL) OR (prconsolidada = 0)) THEN
     BEGIN
       FOR SELECT bdctalon FROM planos_tpla WHERE bdcodplapadrao = :prcodplapadrao AND bdtipcta = 2 INTO :wctalon DO
           BEGIN
             wsql = 'delete from vsuc_empresas_tbalancete_2 ';
             wsql = wsql||'where bdcodplapadrao = '||prcodplapadrao;
--             wsql = wsql||' and substring(bdctalon from 1 for strlen('''||wctalon||''')) = '''||wctalon||''' ';
             wsql = wsql||' and bdctalon like '''||wctalon||'%'||''' ';
             wsql = wsql||'and bdctalon <> '''||wctalon||''' ';
             wsql = wsql||'and bddatahora = '''||prdatahora||''' ';
             EXECUTE STATEMENT wsql;
           END
     END

  -- faz o select na tabela de balancete e monta os retornos para a impressao
  FOR SELECT bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
             bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdformula, bdrelcta, bdclanom, bdparticipante
      FROM vsuc_empresas_tbalancete_2 tbal
      WHERE bddatahora = :prdatahora
      ORDER BY bdctalon ASC
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta,
       :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :formula, :relconta , :clanom, :wparticipante DO
      BEGIN
        codemp = :prcodigoemp;
        codplapadrao = :wcodigoplano;
        conta  = :wcodtpla;
        classificacao = :wclassificacao;
        nomeconta = :wnomcta;
        tipconta = :wtipcta;
        grupoconta = :wgrpcta;
        participante = :wparticipante;
        saldo_ant_deb = :wanterior_debito;
        saldo_ant_cre = :wanterior_credito;
        saldo_deb = :wsaldo_debito;
        saldo_cre = :wsaldo_credito;

        IF (wgrpcta IN (1,2,3)) THEN
           saldo_anterior = (wanterior_credito - wanterior_debito);
        ELSE
           saldo_anterior = (wanterior_debito - wanterior_credito);

        IF (wgrpcta IN (1,2,3)) THEN
           saldo_atual = (saldo_anterior + :wsaldo_credito - :wsaldo_debito);
        ELSE
           saldo_atual = (saldo_anterior + :wsaldo_debito - :wsaldo_credito);

        -- Filtro pelo n?vel da conta
        SELECT contar_char FROM contar_char(:wclassificacao,'.') INTO :wnivelconta;
        wnivelconta = wnivelconta + 1;
        SELECT BDRPOS FROM RPOS(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',') INTO :windice;
        IF ((prniveisconta = '9999') OR           -- N?o tem filtro
            (wnivelconta = 1) OR                  -- O primeiro n?vel sempre imprime
            ((windice > 0) AND (:wtipcta = 0)) OR -- O n?vel da conta foi selecionado no filtro e ? t?tulo
           -- ((windice > 0) and (wimpanalitica > 0) and (:wtipcta = 1))) then -- ? do n?vel selecionado, anal?tica e foi selecionado para imprimir as contas anal?ticas
            -- alteracao abaixo pq nao esta imprimindo as contas consolidas , so imprimia as contas analiticas no balancete
            (((windice > 0) AND (wimpanalitica > 0) AND ((:wtipcta = 1) OR (:wtipcta = 2))))) THEN -- ? do n?vel selecionado, anal?tica e foi selecionado para imprimir as contas anal?ticas

          SUSPEND;
      END

  DELETE FROM vsuc_empresas_tbalancete_2 WHERE bddatahora = :prdatahora;
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_REL_ORCA for: VSUC_SP_RETORNA_SALDO_CONTAS_CC */
ALTER PROCEDURE VSUC_SP_RETORNA_REL_ORCA(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDOREALIZADO NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_RETORNA_SALDO_CONTAS_CC) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_CC(PRCODEMP INTEGER,
PRCODCTAINI INTEGER,
PRCODCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCODTPCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRNAOMOSTRACONTACOMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDGRPCTA SMALLINT,
BDRELCTA INTEGER,
BDTIPCTA SMALLINT,
BDSALANTDEB NUMERIC(15,2),
BDSALANTCRE NUMERIC(15,2),
BDSALDEB NUMERIC(15,2),
BDSALCRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDSALANT NUMERIC(15,2),
BDFORMULA VARCHAR(200))
 AS
DECLARE VARIABLE WCTALONINI VARCHAR(40);
DECLARE VARIABLE WCTALONFIN VARCHAR(40);
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WTIPCTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WCODTPLACRE INTEGER;
DECLARE VARIABLE WCODTPLADEB INTEGER;
DECLARE VARIABLE WCTALONCRE VARCHAR(40);
DECLARE VARIABLE WCTALONDEB VARCHAR(40);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WDEBCRE INTEGER;
DECLARE VARIABLE WVALDEB NUMERIC(15,2);
DECLARE VARIABLE WVALCRE NUMERIC(15,2);
DECLARE VARIABLE WVALDEBANT NUMERIC(15,2);
DECLARE VARIABLE WVALCREANT NUMERIC(15,2);
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
BEGIN
  -- N?o foi feito a modifica??o Matriz/Filial da solicita??o 5837, porque a rotina n?o
  --est? funcinado e ela n?o ? utilizada.
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcodctaini
  INTO :wctalonini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcodctafin
  INTO :wctalonfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wctalonfin)) = :wctalonfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wctalonfin;


-- giovanni... insere somente as contas com lancamentos

  wdatahora = CURRENT_TIMESTAMP;

  wsql = '';
  wsql = wsql|| ' select distinct CONTAS.bdcodplapadrao, CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta,CONTAS.bdnomcta, ';
  wsql = wsql|| ' CONTAS.bdgrupocta, CONTAS.bdrelcta,CONTAS.bdformula  from VSUC_SP_RETORNA_CONTAS_USADAS(' || prcodemp || ', ' || prcodplapadrao ||   ',null,null,null,null,0,0,' || prnaomostracontacomp || ',3,null) CONTAS'; --',3,null,null,0' || ') CONTAS'; alt:9173 - Comentado para tirar os par?metros extras que tinha aqui, estavam causando erro no SQL. Pedro
  wsql = wsql|| ' where (contas.bdcodplapadrao = ' || :prcodplapadrao || ') and (contas.bdctalon between ''' || :wctalonini || ''' and  ''' || :wctalonfin || ''' ) order by BDCTALON';


  FOR EXECUTE STATEMENT wsql
      INTO :wcodplapadrao, :wcodtpla, :wctalon, :wtipcta, :wnomcta, :wgrpcta, :wrelcta, :wformula DO
      BEGIN
        INSERT INTO vsuc_empresas_tbalancete_2 (bddatahora, bdcodemp, bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
                                              bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdrelcta, bdformula)
        VALUES(:wdatahora, :prcodemp, :wcodplapadrao, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, 0.00, 0.00, 0.00, 0.00, :wrelcta, :wformula);
      END


  -- retorna salto anterior
  FOR SELECT tbalcre.bdcodtpla "bdcodtplacre", tbalcre.bdctalon "bdctaloncre",
             tbaldeb.bdcodtpla "bdcodtpladeb", tbaldeb.bdctalon "bdctalondeb",
             TLAN.BDVALOR, tlcc.bddebcre--, tlcc.bdcodtpcc
      FROM VSUC_EMPRESAS_TLCC TLCC
      JOIN VSUC_EMPRESAS_TLAN TLAN ON ((TLCC.BDCHAVE = TLAN.BDCHAVE) AND (TLCC.BDCODEMP = TLAN.BDCODEMP))
      LEFT OUTER JOIN vsuc_empresas_tbalancete_2 tbalcre ON (tbalcre.bdcodplapadrao = tlan.bdcodplapadrao AND
                                                           tbalcre.bdcodtpla = tlan.bdcredito AND
                                                           tbalcre.bdcodplapadrao = :prcodplapadrao AND
                                                           tbalcre.bdtipcta = 1)
      LEFT OUTER JOIN vsuc_empresas_tbalancete_2 tbaldeb ON (tbaldeb.bdcodplapadrao = tlan.bdcodplapadrao AND
                                                           tbaldeb.bdcodtpla = tlan.bddebito AND
                                                           tbaldeb.bdcodplapadrao = :prcodplapadrao AND
                                                           tbaldeb.bdtipcta = 1)
      WHERE (tlan.bdtipolan <> 0)
      AND (tlan.bddata < :prdatini)
      AND (tlan.bdcodemp = :prcodemp)
      AND (TLCC.bdcodtpcc = :prcodtpcc)
      ORDER BY tbalcre.bdctalon, tbaldeb.bdctalon DESC
      INTO :wcodtplacre, :wctaloncre,
           :wcodtpladeb, :wctalondeb,
           :wvalor, :wdebcre DO
      BEGIN
        bdcodemp = prcodemp;
        bdcodplapadrao = prcodplapadrao;

        IF (wdebcre = 0) THEN
           BEGIN
             --alt:9173 - Adicionado o SUM  e o Coalesce porque estava ocorrendo erro por vir mais de um lan?amento na mesma conta quando usa Centro de Custos. Pedro
             SELECT SUM(COALESCE(tbal.bdvalor_debito, 0)), SUM(COALESCE(tbal.bdvalor_credito, 0)),
                    SUM(COALESCE(tbal.bdanterior_debito, 0)), SUM(COALESCE(tbal.bdanterior_credito, 0))
             FROM vsuc_empresas_tbalancete_2 tbal
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtplacre
             INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

             UPDATE vsuc_empresas_tbalancete_2 tbal SET
             tbal.bdvalor_debito = (:wvalcre + :wvalor)
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtplacre;
           END
        ELSE
           BEGIN
             --alt:9173 - Adicionado o SUM  e o Coalesce porque estava ocorrendo erro por vir mais de um lan?amento na mesma conta quando usa Centro de Custos. Pedro
             SELECT SUM(COALESCE(tbal.bdvalor_debito, 0)), SUM(COALESCE(tbal.bdvalor_credito, 0)),
                    SUM(COALESCE(tbal.bdanterior_debito, 0)), SUM(COALESCE(tbal.bdanterior_credito, 0))
             FROM vsuc_empresas_tbalancete_2 tbal
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtpladeb
             INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

             UPDATE vsuc_empresas_tbalancete_2 tbal SET
             tbal.bdvalor_debito = (:wvaldeb + :wvalor)
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtpladeb;
           END
      END

  -- retorna salto atual
  FOR SELECT tbalcre.bdcodtpla "bdcodtplacre", tbalcre.bdctalon "bdctaloncre",
             tbaldeb.bdcodtpla "bdcodtpladeb", tbaldeb.bdctalon "bdctalondeb",
             TLAN.BDVALOR, tlcc.bddebcre--, tlcc.bdcodtpcc
      FROM VSUC_EMPRESAS_TLCC TLCC
      JOIN VSUC_EMPRESAS_TLAN TLAN ON ((TLCC.BDCHAVE = TLAN.BDCHAVE) AND (TLCC.BDCODEMP = TLAN.BDCODEMP))
      LEFT OUTER JOIN vsuc_empresas_tbalancete_2 tbalcre ON (tbalcre.bdcodplapadrao = tlan.bdcodplapadrao AND
                                                           tbalcre.bdcodtpla = tlan.bdcredito AND
                                                           tbalcre.bdcodplapadrao = :prcodplapadrao AND
                                                           tbalcre.bdtipcta = 1)
      LEFT OUTER JOIN vsuc_empresas_tbalancete_2 tbaldeb ON (tbaldeb.bdcodplapadrao = tlan.bdcodplapadrao AND
                                                           tbaldeb.bdcodtpla = tlan.bddebito AND
                                                           tbaldeb.bdcodplapadrao = :prcodplapadrao AND
                                                           tbaldeb.bdtipcta = 1)
      WHERE (tlan.bdtipolan <> 0)
      AND (tlan.bddata BETWEEN :prdatini AND :prdatfin)
      AND (tlan.bdcodemp = :prcodemp)
      AND (TLCC.bdcodtpcc = :prcodtpcc)
      ORDER BY tbalcre.bdctalon, tbaldeb.bdctalon DESC
      INTO :wcodtplacre, :wctaloncre,
           :wcodtpladeb, :wctalondeb,
           :wvalor, :wdebcre DO
      BEGIN
        bdcodemp = prcodemp;
        bdcodplapadrao = prcodplapadrao;

        IF (wdebcre = 0) THEN
           BEGIN
             SELECT tbal.bdvalor_debito, tbal.bdvalor_credito,
                    tbal.bdanterior_debito, tbal.bdanterior_credito
             FROM vsuc_empresas_tbalancete_2 tbal
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtplacre
             INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

             UPDATE vsuc_empresas_tbalancete_2 tbal SET
             tbal.bdvalor_debito = (:wvalcre + :wvalor)
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtplacre;
           END
        ELSE
           BEGIN
             SELECT tbal.bdvalor_debito, tbal.bdvalor_credito,
                    tbal.bdanterior_debito, tbal.bdanterior_credito
             FROM vsuc_empresas_tbalancete_2 tbal
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtpladeb
             INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

             UPDATE vsuc_empresas_tbalancete_2 tbal SET
             tbal.bdvalor_debito = (:wvaldeb + :wvalor)
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtpladeb;
           END
      END

  FOR SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta
      FROM vsuc_empresas_tbalancete_2 tbal
      WHERE tbal.bdtipcta = 0
      INTO :wcodplapadrao, :wcodtpla, :wctalon, :wtipcta DO
      BEGIN
        -- fas um select para totalizar as contas titulos ______________________
        SELECT SUM(tbal.bdvalor_debito) AS valor_debito, SUM(tbal.bdvalor_credito) AS valor_credito,
               SUM(tbal.bdanterior_debito) AS anterior_debito, SUM(tbal.bdanterior_credito) AS anterior_credito
        FROM vsuc_empresas_tbalancete_2 tbal
        WHERE SUBSTRING(bdctalon FROM 1 FOR strlen(:wctalon)) = :wctalon
        GROUP BY SUBSTRING(bdctalon FROM 1 FOR strlen(:wctalon))
        INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

        -- da um update na tabela de balancete para gravar os totais ___________
        UPDATE vsuc_empresas_tbalancete_2 SET bdvalor_debito = :wvaldeb,
                                            bdvalor_credito = :wvalcre,
                                            bdanterior_debito = :wvaldebant,
                                            bdanterior_credito = :wvalcreant
        WHERE bdcodemp = :prcodemp
        AND   bdcodplapadrao = :wcodplapadrao
        AND   bdcodtpla = :wcodtpla
        AND   bdctalon = :wctalon;
      END

  -- parametros de saida
  FOR SELECT bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
             bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdformula
      FROM vsuc_empresas_tbalancete_2 tbal
      ORDER BY bdctalon ASC
      INTO :wcodplapadrao, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta,
           :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant, :wformula DO
      BEGIN
        bdcodemp = :prcodemp;
        bdcodplapadrao = :wcodplapadrao;
        bdcodcta  = :wcodtpla;
        bdctalon = :wctalon;
        bdnomcta = :wnomcta;
        bdtipcta = :wtipcta;
        bdgrpcta = :wgrpcta;
        bdsalantdeb = :wvaldebant;
        bdsalantcre = :wvalcreant;
        bdsaldeb = :wvaldeb;
        bdsalcre = :wvalcre;
        bdformula = :wformula;

        IF (wgrpcta IN (1,2,3)) THEN
           bdsalant = (wvalcreant - wvaldebant);
        ELSE
           bdsalant = (wvaldebant - wvalcreant);

        IF (wgrpcta IN (1,2,3)) THEN
           bdsalatu = (bdsalant + :wvalcre - :wvaldeb);
        ELSE
           bdsalatu = (bdsalant + :wvaldeb - :wvalcre);



        SUSPEND;
      END

  DELETE FROM vsuc_empresas_tbalancete_2 WHERE bddatahora = :wdatahora ;
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_BALANCO_PATRIMONIAL for: VSUC_SP_RETORNA_SALDO_CONTAS_X */
ALTER PROCEDURE VSUC_SP_BALANCO_PATRIMONIAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSEMCC INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSAL_ANT_DEB NUMERIC(15,2),
BDSAL_ANT_CRE NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDCODEMPFILIAL INTEGER,
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20),
BDPERTENCECONTA INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_BALANCETE for: VSUC_SP_RETORNA_SALDO_CONTAS_X */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRORDEM INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDRE INTEGER = 0,
PRTODOPLANOCONTAS INTEGER = 0,
PRDETALHAREMPREENDIMENTO INTEGER = 0,
PRDETALHARUNIDIMOB INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDCODTER INTEGER,
BDAPECTA VARCHAR(20),
BDSALDO_ANTERIOR_DRE NUMERIC(15,2),
BDSALDO_ANT_DEB_DRE NUMERIC(15,2),
BDSALDO_ANT_CRE_DRE NUMERIC(15,2),
BDRAIZCNPJPARTICIPANTE VARCHAR(10),
BDRAIZCLASSIFICACAOCTA VARCHAR(40))
 AS
 BEGIN SUSPEND; END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_BALANCO_PATRIMO for: VSUC_SP_RETORNA_SALDO_CONTAS_X */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRIMO(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRCTASEMMOV INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDANAVER NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_RETORNA_SALDO_CONTAS_X) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_X(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRINDICE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRLANCSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRNIVEISCONTA VARCHAR(50),
PREMPRESAS VARCHAR(2048),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDRE INTEGER = 0,
PRTODOPLANOCONTAS INTEGER = 0)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
CLANOM VARCHAR(140),
TIPCONTA SMALLINT,
SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
FORMULA VARCHAR(200),
PARTICIPANTE INTEGER,
APECTA VARCHAR(20),
PERTENCECONTA INTEGER,
SALDO_ANT_DEB_DRE NUMERIC(15,2),
SALDO_ANT_CRE_DRE NUMERIC(15,2),
SALDO_ANTERIOR_DRE NUMERIC(15,2))
 AS
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WCODIGOPLANO INTEGER;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WCLANOM VARCHAR(140);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WSALDO_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCLASSINI VARCHAR(40);
DECLARE VARIABLE WCLASSFIN VARCHAR(40);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WSALDO_ANT NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ATU NUMERIC(15,2);
DECLARE VARIABLE WAPECTA VARCHAR(20);
DECLARE VARIABLE WPERTENCECONTA INTEGER;
DECLARE VARIABLE WDTULTZERAMENTO DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOCTAAUX INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WSQL_AUX VARCHAR(32000);
DECLARE VARIABLE WSALDO_ANT_DRE NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_DEBITO_DRE NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_CREDITO_DRE NUMERIC(15,2);
DECLARE VARIABLE WCONT INTEGER;
DECLARE VARIABLE WSELECTCONTAS INTEGER;
BEGIN
  -- retorno da classifica??o inicial __________________________________________
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontainicial
  ORDER BY planos_tpla.bdctalon
  INTO :wclassini;
  -- retorno da classifica??o final ____________________________________________
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontafinal
  ORDER BY planos_tpla.bdctalon
  INTO :wclassfin;
  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdctalon LIKE :wclassfin||'%'
  ORDER BY planos_tpla.bdcodplapadrao DESC, planos_tpla.bdctalon DESC
  INTO :wclassfin;
  --alt:7866 - 27/10/2015 - Pedro
  -- carrega se tem alguma conta espec?fica selecionada ________________________
  SELECT FIRST 1 BDCODTPLA FROM VSUC_SELECT_CONTAS INTO :wSelectContas;

  --Solicita??o.: 4993
  --if ((prDRE <> 0) or (prDRE is not null)) then -- alt:#6976 - gilberto - 24/10/2013 - sempre entra nessa condi??o
  IF ((prDRE <> 0) AND (prDRE IS NOT NULL)) THEN
    BEGIN
      -- Retorna o ?ltimo zeramento
      SELECT FIRST 1 BDDATAINIZER FROM VSUC_EMPRESAS_TENCEXE WHERE BDCODEMP = :prCodigoEmp AND BDDATAFIMZER < :prDataIni ORDER BY BDCODEMP DESC, BDDATAFIMZER DESC INTO :wDtUltZeramento;
      IF (wDtUltZeramento IS NULL) THEN
        SELECT FIRST 1 BDDATA FROM VSUC_EMPRESAS_TLAN WHERE BDCODEMP = :prCodigoEmp ORDER BY BDCODEMP, BDDATA INTO :wDtUltZeramento;
      IF (wDtUltZeramento IS NULL) THEN
        wDtUltZeramento = :prDataIni;

      -- Limpa tabela tempor?ria de contas com zeramento
      DELETE FROM VSUC_EMP_TCTAZERADAS WHERE bdcodemp IS NOT NULL;
      -- Povoa tabela tempor?ria de contas com zeramento
      wsql = 'Insert into VSUC_EMP_TCTAZERADAS ';
      wsql = wsql||'Select bdcodemp,bdcodcta from (Select tlan.bdcodemp, tlan.bdcredito bdcodcta';
      wsql = wsql||'                               from VSUC_EMPRESAS_TLAN tlan';
      wsql = wsql||'                               where';
      wsql = wsql||'                               (tlan.bddata <= '''||prDataIni||''') and';
      wsql = wsql||'                               (tlan.bdcodemp = '||prCodigoEmp||') and';
      wsql = wsql||'                               (tlan.bdcredito is not null) and';
      wsql = wsql||'                               (tlan.bdtipolan = 10)';
      wsql = wsql||'                               Group By bdcodemp, bdcodcta';
      wsql = wsql||'                               union all';
      wsql = wsql||'                               Select tlan.bdcodemp, tlan.bddebito bdcodcta';
      wsql = wsql||'                               from VSUC_EMPRESAS_TLAN tlan';
      wsql = wsql||'                               where';
      wsql = wsql||'                               (tlan.bddata <= '''||prDataIni||''') and';
      wsql = wsql||'                               (tlan.bdcodemp = '||prCodigoEmp||') and';
      wsql = wsql||'                               (tlan.bddebito is not null) and';
      wsql = wsql||'                               (tlan.bdtipolan = 10)';
      wsql = wsql||'                               Group By bdcodemp, bdcodcta) ';
      wsql = wsql||'Group by bdcodemp,bdcodcta';
      EXECUTE STATEMENT wsql;
    END

  -- limpa tabela temporaria de saldos _________________________________________
  DELETE FROM vsuc_emp_tsaldos WHERE bdcodemp IS NOT NULL;
  -- povoa tabela tempor?ria de saldos _________________________________________
  wsql = 'insert into vsuc_emp_tsaldos (BDCODEMP,BDDATA,BDCREDITO,BDDEBITO,BDTIPOLANCFILIAL,BDFILIAL,BDTIPOLAN,BDVALOR,BDCODTPCC,BDDEBCRE) ';
  --#alt:7207
  IF ((prlancsemcc = 1) AND ((prcc IS NULL) OR (prcc = 0))) THEN
    BEGIN
      wsql_aux = 'where (tlan.bddata <= '''||prdatafim||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql_aux = wsql_aux||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
      --#alt:5837
      wsql_aux = wsql_aux||'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';

      --D?bito
      wsql = wsql||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      wsql = wsql||'sum(coalesce(tlan.bdvalor, 0)),null,null ';
      wsql = wsql||'from ';
      wsql = wsql||'     (select tlan.bdcodemp,tlan.bdchave,tlan.bddata,null as bdcredito,tlan.bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'tlan.bdvalor ';
      ELSE
        BEGIN
          wsql = wsql||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) ';
        END
      --alt:6178 - Fim
      wsql = wsql||'     from vsuc_empresas_tlan tlan ';
      wsql = wsql||      wsql_aux||') tlan ';
      --alt:14336 - 04/05/2016 - N?o estava levando as contas que s? possuem lan?amentos com Centro de Custos. Pedro
      --wsql = wsql||'left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 0) ';
      --wsql = wsql||'where (tlcc.bddebcre is null) ';
      --alt:14336 - Fim
      wsql = wsql||'Group By tlan.bdcodemp,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
      wsql = wsql||'union ';
      --Cr?dito
      wsql = wsql||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      wsql = wsql||'sum(coalesce(tlan.bdvalor, 0)),null,null ';
      wsql = wsql||'from ';
      wsql = wsql||'     (select tlan.bdcodemp,tlan.bdchave,tlan.bddata,tlan.bdcredito,null as bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'tlan.bdvalor ';
      ELSE
        BEGIN
          wsql = wsql||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) ';
        END
      --alt:6178 - Fim
      wsql = wsql||'     from vsuc_empresas_tlan tlan ';
      wsql = wsql||      wsql_aux||') tlan ';
      --alt:14336 - 04/05/2016 - N?o estava levando as contas que s? possuem lan?amentos com Centro de Custos. Pedro
      --wsql = wsql||'left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 1) ';
      --wsql = wsql||'where (tlcc.bddebcre is null) ';
      --alt:14336 - Fim
      wsql = wsql||'Group By tlan.bdcodemp,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
    END
  ELSE
    BEGIN
      wsql = wsql||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF ((prcc IS NULL) OR (prcc = 0)) THEN
        BEGIN
          IF (prindice = 0) THEN
            wsql = wsql||'sum(coalesce(tlan.bdvalor, 0)), ';
          ELSE
            BEGIN
              wsql = wsql||'sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsql = wsql||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))), ';
            END
        END
      ELSE
        BEGIN
          IF (prindice = 0) THEN
            wsql = wsql||'sum(case when (tlcc.bdcodtpcc is null) then coalesce(tlan.bdvalor, 0) else coalesce(tlcc.bdvalor, 0) end) as bdvalor, ';
          ELSE
            BEGIN
              wsql = wsql||'sum(case when (tlcc.bdcodtpcc is null) then coalesce(tlan.bdvalor, 0) else coalesce(tlcc.bdvalor, 0) end';
              wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdvalor, ';
            END
        END
      --alt:6178 - Fim
      IF ((prcc IS NULL) OR (prcc = 0)) THEN
         wsql = wsql||'null, null ';
      ELSE
         wsql = wsql||'tlcc.bdcodtpcc, tlcc.bddebcre ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      IF (NOT ((prcc IS NULL) OR (prcc = 0))) THEN
         BEGIN
           wsql = wsql||'left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave ';
           IF ((prcc IS NOT NULL) AND (prcc <> 0)) THEN
              wsql = wsql||'and tlcc.bdcodtpcc = '||prcc;
           wsql = wsql||') ';
         END

      wsql = wsql||'where (tlan.bddata <= '''||prdatafim||''') ';

      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
      --#alt:5837
      --wsql = wsql||'and (tlan.bdcodemp = '||prcodigoemp||') ';
      wsql = wsql||'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';
      wsql = wsql||'Group By tlan.bdcodemp,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
      IF (NOT ((prcc IS NULL) OR (prcc = 0))) THEN
         wsql = wsql||', tlcc.bdcodtpcc, tlcc.bddebcre ';
    END

  EXECUTE STATEMENT wsql;

  -- retorna saldos da tabela tempor?ria de saldos _____________________________
  wsql = '';
  wsql = wsql||'select bdcodemp,bdfilial,bdtipolancfilial,bddebito, 1 as bdtipcta, ';
  --Solicita??o.: 4993
  /*if ((prdre = 0) or (prdre is null)) then-- se for DRE o calculo do saldo anterior deve ignorar zeramento
     wsql = wsql||'       sum(case when (bddata < '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
  else
     wsql = wsql||'       sum(case when ((bddata < '''||prdataini||''') and (bddata >= cast('''||'01/01/'||'''||substring(addmonth('''||prdataini||''', -1) from 1 for 4) as date) and bdtipolan <> 10) or (bddata < cast('''||'01/01/'||'''||substring(addmonth('''||prdataini||''', -1) from 1 for 4) as date))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';*/
  IF (prDRE = 1) THEN-- se for DRE o calculo do saldo anterior deve considerar zeramento para demonstrar
     wsql = wsql||'       sum(case when ((bddata >= '''||wDtUltZeramento||''' and bddata < '''||prdataini||''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_dre, ';
  ELSE
     wsql = wsql||'       0 as bdvalor_ant_dre, ';
/* gilberto - 11/09/2013 - segundo celso saldo anterior sempre considera zeramento
  if (prignorazeramento = 1) then
    wsql = wsql||'       sum(case when (bddata < '''||prdataini||''' and (((bddata >= '''||wDtUltZeramento||''') or ((select first 1 BDCODCTA from VSUC_EMP_TCTAZERADAS TCtaZer where (BDCODEMP = '||prcodigoemp||') AND (TLan.BDDEBITO = TCtaZer.BDCODCTA)) is null)) and (bdtipolan <> 10))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
--     wsql = wsql||'      sum(case when ((bddata < '''||prdataini||''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';-- gilberto - 11/09/2013 - alterado para granha desempenho
  else*/
  -- gilberto - 19/09/2013
--    wsql = wsql||'       sum(case when ((bddata < '''||prdataini||''') and ((bddata >= '''||wDtUltZeramento||''') or ((select first 1 BDCODCTA from VSUC_EMP_TCTAZERADAS TCtaZer where (BDCODEMP = '||prcodigoemp||') AND (TLan.BDDEBITO = TCtaZer.BDCODCTA)) is null))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
     wsql = wsql||'      sum(case when (bddata < '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';-- gilberto - 11/09/2013 - alterado para ganha desempenho

  IF (prignorazeramento = 1) THEN
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''' and bdtipolan <> 10) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu ';
  ELSE
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu ';
  wsql = wsql||'from vsuc_emp_tsaldos tlan ';

  --alt:10233 - Implementada a valida??o das contas de compensa??o aqui, para poder diferenciar se a conta que est? sendo calculada ? de d?bito ou cr?dito. Pedro
  IF (prnaomostracontacomp = 1) THEN --alt:11108 - 08/04/2015 - Pedro
    wsql = wsql||'left outer join PLANOS_TPLA tpla on ('||prcodplapadrao||' = tpla.BDCODPLAPADRAO and tlan.BDDEBITO = tpla.BDCODTPLA) ';

  wsql = wsql||'where (bddata <= '''||prdatafim||''') ';
--  if (prignorazeramento = 1) then
--     wsql = wsql||'and ((bddata < '''||prdataini||''') or (bddata >= '''||prdataini||''' and bdtipolan <> 10)) ';-- com zeramento
--     wsql = wsql||'and (bddata >= '''||prdataini||''' and bdtipolan <> 10) ';-- gilberto - 11/09/2013 - zeramento apenas para lan?amentos do periodo

  --alt:10233 - Implementada a valida??o das contas de compensa??o aqui, para poder diferenciar se a conta que est? sendo calculada ? de d?bito ou cr?dito. Pedro
  IF (prnaomostracontacomp = 1) THEN --alt:11108 - 08/04/2015 - Pedro
    wsql = wsql||'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';

  --alt:14336 - 04/05/2016 - N?o estava levando as contas que s? possuem lan?amentos com Centro de Custos. Pedro
  /*IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
       wsql = wsql||'and (BDDEBCRE = 0) ';
       wsql = wsql||'and (bdcodtpcc = '||prcc||') ';
     END
  IF (prlancsemcc = 1) THEN
     wsql = wsql||'and (bdcodtpcc is null) ';-- somente sem centro de custo*/

  --#alt:5837
  --wsql = wsql||'and (bdcodemp = '||prcodigoemp||') ';
  wsql = wsql||'and ((bdcodemp = '||prcodigoemp||') or (bdfilial = '||prcodigoemp||')) ';
  --wsql = wsql||'Group By bdcodemp, bddebito ';
  wsql = wsql||'Group By bdcodemp,bdfilial,bdtipolancfilial,bddebito ';
  wsql = wsql||'union all ';
  wsql = wsql||'select bdcodemp,bdfilial,bdtipolancfilial,bdcredito, 0 as bdtipcta, ';
  --Solicita??o.: 4993
  /*if ((prdre = 0) or (prdre is null)) then-- se for DRE o calculo do saldo anterior deve ignorar zeramento
     wsql = wsql||'       sum(case when (bddata < '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
  else
     wsql = wsql||'       sum(case when ((bddata < '''||prdataini||''') and (bddata >= cast('''||'01/01/'||'''||substring(addmonth('''||prdataini||''', -1) from 1 for 4) as date) and bdtipolan <> 10) or (bddata < cast('''||'01/01/'||'''||substring(addmonth('''||prdataini||''', -1) from 1 for 4) as date))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';*/
  IF (prDRE = 1) THEN-- se for DRE o calculo do saldo anterior deve considerar zeramento para demonstrar
     wsql = wsql||'       sum(case when ((bddata >= '''||wDtUltZeramento||''' and bddata < '''||prdataini||''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_dre, ';
  ELSE
     wsql = wsql||'       0 as bdvalor_ant_dre, ';
/* gilberto - 11/09/2013 - segundo celso saldo anterior sempre considera zeramento
  if (prignorazeramento = 1) then
    wsql = wsql||'       sum(case when (bddata < '''||prdataini||''' and (((bddata >= '''||wDtUltZeramento||''') or ((select first 1 BDCODCTA from VSUC_EMP_TCTAZERADAS TCtaZer where (BDCODEMP = '||prcodigoemp||') AND (TLan.BDCREDITO = TCtaZer.BDCODCTA)) is null)) and (bdtipolan <> 10))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
--    wsql = wsql||'       sum(case when ((bddata < '''||prdataini||''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';-- gilberto - 11/09/2013 - alterado para ganhar desempenho
  else   */

-- gilberto - 19/09/2013
--    wsql = wsql||'       sum(case when ((bddata < '''||prdataini||''') and ((bddata >= '''||wDtUltZeramento||''') or ((select first 1 BDCODCTA from VSUC_EMP_TCTAZERADAS TCtaZer where (BDCODEMP = '||prcodigoemp||') AND (TLan.BDCREDITO = TCtaZer.BDCODCTA)) is null))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
    wsql = wsql||'       sum(case when (bddata < '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';-- gilberto - 11/09/2013 - alterado para ganhar desempenho

  IF (prignorazeramento = 1) THEN
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''' and bdtipolan <> 10) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu ';
  ELSE
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu ';
  wsql = wsql||'from vsuc_emp_tsaldos tlan ';

  --alt:10233 - Implementada a valida??o das contas de compensa??o aqui, para poder diferenciar se a conta que est? sendo calculada ? de d?bito ou cr?dito. Pedro
  IF (prnaomostracontacomp = 1) THEN --alt:11108 - 08/04/2015 - Pedro
    wsql = wsql||'left outer join PLANOS_TPLA tpla on ('||prcodplapadrao||' = tpla.BDCODPLAPADRAO and tlan.BDCREDITO = tpla.BDCODTPLA) ';

  wsql = wsql||'where (bddata <= '''||prdatafim||''') ';
--  if (prignorazeramento = 1) then
--     wsql = wsql||'and ((bddata < '''||prdataini||''') or (bddata >= '''||prdataini||''' and bdtipolan <> 10)) ';-- com zeramento
--     wsql = wsql||'and (bddata >= '''||prdataini||''' and bdtipolan <> 10) ';-- gilberto - 11/09/2013 - zeramento apenas para lan?amentos do periodo

  --alt:10233 - Implementada a valida??o das contas de compensa??o aqui, para poder diferenciar se a conta que est? sendo calculada ? de d?bito ou cr?dito. Pedro
  IF (prnaomostracontacomp = 1) THEN --alt:11108 - 08/04/2015 - Pedro
    wsql = wsql||'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';

  --alt:14336 - 04/05/2016 - N?o estava levando as contas que s? possuem lan?amentos com Centro de Custos. Pedro
  /*IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
       wsql = wsql||'and (BDDEBCRE = 1) ';
       wsql = wsql||'and (bdcodtpcc = '||prcc||') ';
     END
  IF (prlancsemcc = 1) THEN
     wsql = wsql||'and (bdcodtpcc is null) ';-- somente sem centro de custo*/

  --#alt:5837
  --wsql = wsql||'and (bdcodemp = '||prcodigoemp||') ';
  wsql = wsql||'and ((bdcodemp = '||prcodigoemp||') or (bdfilial = '||prcodigoemp||')) ';
  --wsql = wsql||'Group By bdcodemp,bdcredito ';
  wsql = wsql||'Group By bdcodemp,bdfilial,bdtipolancfilial,bdcredito ';

  -- insere os saldos na tabela tempor?ria do balancete ________________________
  DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp IS NOT NULL AND bdcodemp IS NULL;
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp, :wfilial, :wtipolancfilial, :wcodtpla, :wtipcta, :wsaldo_ant_dre, :wsaldo_ant, :wsaldo_atu DO
      BEGIN
        IF (wcodtpla IS NOT NULL) THEN
           BEGIN
             --#alt:5837.
             IF (wfilial IS NULL) THEN
               wfilial = 0;
             wtipoctaaux = 1;--D?bito
             IF (wtipcta = 0) THEN
               wtipoctaaux = 2;--Cr?dito
             SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipoctaaux,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prempresas) INTO :wpermite;
             IF (wpermite = 1) THEN
               BEGIN
                 IF (wtipcta = 1) THEN
                   BEGIN
                     --#alt:5837
                     /*update or insert into vsuc_empresas_tbalancete_3
                     (bdcodemp, bdcodplapadrao, bdcodtpla, bdanterior_debito, bdvalor_debito)
                     values
                     (:prcodigoemp, :prcodplapadrao, :wcodtpla, :wsaldo_ant, :wsaldo_atu)
                     matching (bdcodemp, bdcodplapadrao, bdcodtpla);   */
                     wsql_aux = 'update or insert into vsuc_empresas_tbalancete_3 ';
                     wsql_aux = wsql_aux||'(bdcodemp, bdcodplapadrao, bdcodtpla, bdanterior_debito_dre, bdanterior_debito, bdvalor_debito) values ';
                     wsql_aux = wsql_aux||'('||prcodigoemp||','||prcodplapadrao||','||wcodtpla||',';
                     -------------------------------------------------
                     wsql_aux = wsql_aux||' (coalesce((select bdanterior_debito_dre from vsuc_empresas_tbalancete_3 where bdcodemp = '||prcodigoemp;
                     wsql_aux = wsql_aux||'            and bdcodplapadrao = '||prcodplapadrao||' and bdcodtpla = '||wcodtpla||'),0) + '||wsaldo_ant_dre||'),';
                     -------------------------------------------------
                     wsql_aux = wsql_aux||' (coalesce((select bdanterior_debito from vsuc_empresas_tbalancete_3 where bdcodemp = '||prcodigoemp;
                     wsql_aux = wsql_aux||'            and bdcodplapadrao = '||prcodplapadrao||' and bdcodtpla = '||wcodtpla||'),0) + '||wsaldo_ant||'),';
                     wsql_aux = wsql_aux||' (coalesce((select coalesce(bdvalor_debito, 0) from vsuc_empresas_tbalancete_3 where bdcodemp = '||prcodigoemp;
                     wsql_aux = wsql_aux||'            and bdcodplapadrao = '||prcodplapadrao||' and bdcodtpla = '||wcodtpla||'),0) + '||wsaldo_atu||')) ';
                     wsql_aux = wsql_aux||'matching (bdcodemp, bdcodplapadrao, bdcodtpla)';
                     EXECUTE STATEMENT wsql_aux;
                   END
                 ELSE
                   BEGIN
                     --#alt:5837
                     /*update or insert into vsuc_empresas_tbalancete_3
                     (bdcodemp, bdcodplapadrao, bdcodtpla, bdanterior_credito, bdvalor_credito)
                     values
                     (:prcodigoemp, :prcodplapadrao, :wcodtpla, :wsaldo_ant, :wsaldo_atu)
                     matching (bdcodemp, bdcodplapadrao, bdcodtpla);*/
                     wsql_aux = 'update or insert into vsuc_empresas_tbalancete_3 ';
                     wsql_aux = wsql_aux||'(bdcodemp, bdcodplapadrao, bdcodtpla, bdanterior_credito_dre, bdanterior_credito, bdvalor_credito) values ';
                     wsql_aux = wsql_aux||'('||prcodigoemp||','||prcodplapadrao||','||wcodtpla||',';

                     wsql_aux = wsql_aux||' (coalesce((select bdanterior_credito_dre from vsuc_empresas_tbalancete_3 where bdcodemp = '||prcodigoemp;
                     wsql_aux = wsql_aux||'            and bdcodplapadrao = '||prcodplapadrao||' and bdcodtpla = '||wcodtpla||'),0) + '||wsaldo_ant_dre||'),';

                     wsql_aux = wsql_aux||' (coalesce((select bdanterior_credito from vsuc_empresas_tbalancete_3 where bdcodemp = '||prcodigoemp;
                     wsql_aux = wsql_aux||'            and bdcodplapadrao = '||prcodplapadrao||' and bdcodtpla = '||wcodtpla||'),0) + '||wsaldo_ant||'),';
                     wsql_aux = wsql_aux||' (coalesce((select coalesce(bdvalor_credito, 0) from vsuc_empresas_tbalancete_3 where bdcodemp = '||prcodigoemp;
                     wsql_aux = wsql_aux||'            and bdcodplapadrao = '||prcodplapadrao||' and bdcodtpla = '||wcodtpla||'),0) + '||wsaldo_atu||')) ';
                     wsql_aux = wsql_aux||'matching (bdcodemp, bdcodplapadrao, bdcodtpla)';
                     EXECUTE STATEMENT wsql_aux;
                   END
               END
           END
      END

  -- insere e atualiza a tabela tempor?ria do balancete com as informa??es do plano de contas
  wsql = 'select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, ';
  wsql = wsql||' tpla.BDNOMCTA, tpla.BDRELCTA, tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.BDAPECTA, tpla.bdpertenceconta ';
  wsql = wsql||'from planos_tpla tpla ';
  IF (PRLANCSEMCC = 1) THEN
     wsql = wsql||'left outer join vsuc_empresas_tbalancete_3 tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao and tlan.bdcodtpla = tpla.bdcodtpla) ';
  ELSE
    --#alt:11436 - Adiconado controle para o parametro de imprimir o plano de contas completo. Ana - 15/12/2016
    IF (PRTODOPLANOCONTAS = 1) THEN
      wsql = wsql||'';
    ELSE
     wsql = wsql||'inner join vsuc_empresas_tbalancete_3 tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao and tlan.bdcodtpla = tpla.bdcodtpla) ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||prcodplapadrao;
  wsql = wsql||' order by tpla.bdctalon';

  FOR EXECUTE STATEMENT wsql
      INTO :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta DO
      BEGIN
        UPDATE OR INSERT INTO vsuc_empresas_tbalancete_3
        (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
         BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA, bdpertenceconta) VALUES
        (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta)
        MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA);
      END

  IF (PRLANCSEMCC <> 1) THEN
     BEGIN
       -- insere contas t?tulo na tabela tempor?ria do balancete ____________________
       wsql = 'select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, ';
       wsql = wsql||'tpla.BDNOMCTA, tpla.BDRELCTA, tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.bdapecta, tpla.bdpertenceconta ';
       wsql = wsql||'from planos_tpla tpla ';
       wsql = wsql||'where tpla.BDCODPLAPADRAO = '||prcodplapadrao;
       wsql = wsql||' AND ((tpla.BDTIPCTA in (0,2)) or ((tpla.BDTIPCTA = 1) AND (TPLA.bdformula <> '''||''||'''))) ';

       IF (prnaomostracontacomp = 1) THEN
          wsql = wsql||'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';
       wsql = wsql||'order by tpla.bdctalon ';
     
       FOR EXECUTE STATEMENT wsql
           INTO :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta DO
           BEGIN
             UPDATE OR INSERT INTO vsuc_empresas_tbalancete_3
             (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
              BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,bdpertenceconta) VALUES
             (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta)
             MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA);
           END
     END

  -- totaliza contas t?tulos e consolidadas da tabela tempor?ria do balancete __
  FOR SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta
      FROM vsuc_empresas_tbalancete_3 tbal
      WHERE tbal.bdtipcta IN (0,2)-- totalizando as contas consolidadas
      AND tbal.bdcodemp = :prcodigoemp
      ORDER BY tbal.bdcodemp, tbal.bdcodplapadrao, tbal.bdctalon
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta DO
      BEGIN
        -- faz um select para totalizar as contas titulos ______________________
        FOR SELECT SUBSTRING(tbal.bdctalon FROM 1 FOR strlen(:wclassificacao)) AS bdctalonx,
                   SUM(COALESCE(tbal.bdvalor_debito, 0)) AS valor_debito,
                   SUM(COALESCE(tbal.bdvalor_credito, 0)) AS valor_credito,
                   SUM(COALESCE(tbal.bdanterior_debito, 0)) AS anterior_debito,
                   SUM(COALESCE(tbal.bdanterior_credito, 0)) AS anterior_credito,
                   SUM(COALESCE(tbal.bdanterior_debito_dre, 0)) AS anterior_debito_dre,
                   SUM(COALESCE(tbal.bdanterior_credito_dre, 0)) AS anterior_credito_dre
            FROM vsuc_empresas_tbalancete_3 tbal
            WHERE tbal.bdctalon LIKE :wclassificacao||'.%'
            AND tbal.bdcodemp = :prcodigoemp
            --Group By substring(tbal.bdctalon from 1 for strlen(:wclassificacao))
            GROUP BY bdctalonx
            INTO :wctalon, :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :wanterior_debito_dre, :wanterior_credito_dre DO
            BEGIN
              -- da um update na tabela de balancete para gravar os totais ___________
              UPDATE vsuc_empresas_tbalancete_3 SET bdvalor_debito = :wsaldo_debito,
                                                    bdvalor_credito = :wsaldo_credito,
                                                    bdanterior_debito = :wanterior_debito,
                                                    bdanterior_credito = :wanterior_credito,
                                                    bdanterior_debito_dre = :wanterior_debito_dre,
                                                    bdanterior_credito_dre = :wanterior_credito_dre
              WHERE bdcodemp = :prcodigoemp
              AND   bdcodplapadrao = :wcodigoplano
              AND   bdcodtpla = :wcodtpla
              AND   bdctalon = :wclassificacao;
            END
      END

  -- retira as contas analiticas que pertencem a uma conta consolidadas ________
  IF ((prconsolidada IS NULL) OR (prconsolidada = 0)) THEN
     BEGIN
       FOR SELECT bdctalon FROM planos_tpla WHERE bdcodplapadrao = :prcodplapadrao AND bdtipcta = 2 INTO :wctalon DO
           BEGIN
             wsql = 'delete from vsuc_empresas_tbalancete_3 ';
             wsql = wsql||'where bdcodplapadrao = '||prcodplapadrao;
             wsql = wsql||' and bdctalon like '''||wctalon||'.%'||''' ';
             wsql = wsql||'and bdctalon <> '''||wctalon||''' ';
             EXECUTE STATEMENT wsql;
           END
     END

  -- faz o select na tabela tempor?ria de balancete e monta os retornos para a impressao
  wSQL = 'SELECT  tbal.bdcodplapadrao, tbal.bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,';
  wSQL = wSQL||'  COALESCE(bdvalor_debito, 0), COALESCE(bdvalor_credito, 0),';
  wSQL = wSQL||'  COALESCE(bdanterior_debito, 0), COALESCE(bdanterior_credito, 0),';
  wSQL = wSQL||'  COALESCE(bdanterior_debito_dre, 0), COALESCE(bdanterior_credito_dre, 0),';
  wSQL = wSQL||'  bdformula, bdrelcta, bdclanom,';
  --alt:7866 - 27/10/2015 - Caso tenha a op??o de detalhar por participantes espec?ficos, precisa verificar aqui se o em quest?o
  --est? marcado ou n?o para retornar como conta participante, para depois a VSUC_SP_RETORNA_BALANCETE detalhar ou n?o. Pedro
  IF ((wSelectContas IS NOT NULL) AND (wSelectContas > 0)) THEN
    wSQL = wSQL||' case when lista.BDCODTPLA is null then 0 else BDPARTICIPANTE end as BDPARTICIPANTE,';
  ELSE
    wSQL = wSQL||' bdparticipante,';
  --alt:7866 - Fim
  wSQL = wSQL||' bdapecta, bdpertenceconta';
  wSQL = wSQL||' FROM vsuc_empresas_tbalancete_3 tbal';
  --alt:7866 - 27/10/2015 - Faz a verifica??o para saber qual o tipo de filtro que ser? aplicado aqui, para o caso de selecionar contas espec?ficas. Pedro
  IF ((wSelectContas IS NOT NULL) AND (wSelectContas > 0)) THEN
    wSQL = wSQL||' left join VSUC_SELECT_CONTAS lista on (tbal.BDCODPLAPADRAO = lista.BDCODPLAPADRAO and tbal.BDCODTPLA = lista.BDCODTPLA)';
  --alt:7866 - Fim
  wSQL = wSQL||' WHERE bdctalon BETWEEN '''||:wclassini||''' AND '''||:wclassfin||'''';
  wSQL = wSQL||' ORDER BY bdcodemp, bdcodplapadrao, bdctalon ASC';
  FOR EXECUTE STATEMENT wSQL INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta,
       :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :wanterior_debito_dre, :wanterior_credito_dre, :formula, :relconta , :clanom, :wparticipante, :wapecta, :wpertenceconta DO
      BEGIN
        codemp = :prcodigoemp;
        codplapadrao = :wcodigoplano;
        conta  = :wcodtpla;
        classificacao = :wclassificacao;
        nomeconta = :wnomcta;
        tipconta = :wtipcta;
        grupoconta = :wgrpcta;
        participante = :wparticipante;
        saldo_ant_deb = :wanterior_debito;
        saldo_ant_cre = :wanterior_credito;
        saldo_ant_deb_dre = :wanterior_debito_dre;
        saldo_ant_cre_dre = :wanterior_credito_dre;
        saldo_deb = :wsaldo_debito;
        saldo_cre = :wsaldo_credito;
        apecta = :wapecta;
        pertenceconta = :wpertenceconta;

        IF (wgrpcta IN (1,2,3)) THEN
           BEGIN
             saldo_anterior = (wanterior_credito - wanterior_debito);

             saldo_anterior_dre = (wanterior_credito_dre - wanterior_debito_dre);

             --#6040 - Bruno Borges
             saldo_atual = (saldo_anterior + :wsaldo_credito - :wsaldo_debito);
           END
        ELSE
           BEGIN
             saldo_anterior = (wanterior_debito - wanterior_credito);

             saldo_anterior_dre = (wanterior_debito_dre - wanterior_credito_dre);

             --#6040 - Bruno Borges
             saldo_atual = (saldo_anterior + :wsaldo_debito - :wsaldo_credito);
           END


        /*
        if (wgrpcta in (1,2,3)) then
           saldo_anterior = (wanterior_credito - wanterior_debito);
        else
           saldo_anterior = (wanterior_debito - wanterior_credito);

        if ((prdre = 0) or (prdre is null)) then-- gilberto - 25/10/2012 - para a dre ignora saldo anterior
           begin
             if (wgrpcta in (1,2,3)) then
                saldo_atual = (saldo_anterior + :wsaldo_credito - :wsaldo_debito);
             else
                saldo_atual = (saldo_anterior + :wsaldo_debito - :wsaldo_credito);
           end
        else
           begin
             if (wgrpcta in (1,2,3)) then
                saldo_atual = (:wsaldo_credito - :wsaldo_debito);
             else
                saldo_atual = (:wsaldo_debito - :wsaldo_credito);
           end
       */

        -- Filtro pelo n?vel da conta __________________________________________
        --select contar_char from contar_char(:wclassificacao,'.') into :wnivelconta;
        wnivelconta = 1;
        wCont = 1; --alt:6905 - Faltou inicializar vari?vel. Pedro - 25/10/2013
        WHILE (wcont <= CHAR_LENGTH(wclassificacao)) DO
          BEGIN
            IF (SUBSTRING(wclassificacao FROM wcont FOR 1) = '.') THEN
               wnivelconta = wnivelconta + 1;
            wcont = wcont + 1;
          END
        --select BDRPOS from RPOS(','||cast(:wnivelconta as varchar(100))||',',','||:prniveisconta||',') into :windice;
        windice = POSITION(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',');
        -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas anal?ticas
        --select BDRPOS from RPOS(',1,',','||:prniveisconta||',') into :wimpanalitica;
        wimpanalitica = POSITION(',1,',','||:prniveisconta||',');
        IF ((prniveisconta = '9999') OR           -- N?o tem filtro
            (wnivelconta = 1) OR                  -- O primeiro n?vel sempre imprime
            ((windice > 0) AND (:wtipcta = 0)) OR -- O n?vel da conta foi selecionado no filtro e ? t?tulo
            (((windice > 0) AND (wimpanalitica > 0) AND ((:wtipcta = 1) OR (:wtipcta = 2))))) THEN -- ? do n?vel selecionado, anal?tica e foi selecionado para imprimir as contas anal?ticas
           SUSPEND;
      END

  -- limpa tabela tempor?ria do balancete ______________________________________
  --delete from vsuc_empresas_tbalancete_3 where bdcodemp is not null;
END
^

/* Alter (VSUC_SP_RETORNA_SALDO_CONTAS_XZ) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_XZ(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRINDICE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCC VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRLANCSEMCC INTEGER,
PRORDEM INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDRE INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCONTA INTEGER,
BDCLASSIFICACAO VARCHAR(40),
BDNOMECONTA VARCHAR(100),
BDGRUPOCONTA SMALLINT,
BDRELCONTA INTEGER,
BDCLANOM VARCHAR(140),
BDTIPCONTA SMALLINT,
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDPARTICIPANTE INTEGER,
BDAPECTA VARCHAR(20),
BDPERTENCECONTA INTEGER,
BDSALDO_ANT_DEB_DRE NUMERIC(15,2),
BDSALDO_ANT_CRE_DRE NUMERIC(15,2),
BDSALDO_ANTERIOR_DRE NUMERIC(15,2),
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDTPCCLON VARCHAR(20))
 AS
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WCODIGOPLANO INTEGER;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WCLANOM VARCHAR(140);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WSALDO_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCLASSINI VARCHAR(40);
DECLARE VARIABLE WCLASSFIN VARCHAR(40);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WSALDO_ANT NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ATU NUMERIC(15,2);
DECLARE VARIABLE WAPECTA VARCHAR(20);
DECLARE VARIABLE WPERTENCECONTA INTEGER;
DECLARE VARIABLE WDTULTZERAMENTO DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOCTAAUX INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WSQL_AUX VARCHAR(32000);
DECLARE VARIABLE WSALDO_ANT_DRE NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_DEBITO_DRE NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_CREDITO_DRE NUMERIC(15,2);
DECLARE VARIABLE WCONT INTEGER;
DECLARE VARIABLE WANTERIOR_DRE_AUX NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_AUX NUMERIC(15,2);
DECLARE VARIABLE WVALOR_AUX NUMERIC(15,2);
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WNOMTPCC VARCHAR(40);
DECLARE VARIABLE WTPCCLON VARCHAR(20);
DECLARE VARIABLE WSELECTCONTAS INTEGER;
BEGIN
  -- retorno da classifica??o inicial __________________________________________
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontainicial
  ORDER BY planos_tpla.bdctalon
  INTO :wclassini;

  -- retorno da classifica??o final ____________________________________________
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontafinal
  ORDER BY planos_tpla.bdctalon
  INTO :wclassfin;
  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  --alt:7866 - 27/10/2015 - Pedro
  -- carrega se tem alguma conta espec?fica selecionada ________________________
  SELECT FIRST 1 BDCODTPLA FROM VSUC_SELECT_CONTAS INTO :wSelectContas;

  IF ((prDRE <> 0) AND (prDRE IS NOT NULL)) THEN
    BEGIN
      -- Retorna o ?ltimo zeramento
      SELECT FIRST 1 BDDATAINIZER FROM VSUC_EMPRESAS_TENCEXE WHERE BDCODEMP = :prCodigoEmp AND BDDATAFIMZER < :prDataIni ORDER BY BDDATAFIMZER DESC INTO :wDtUltZeramento;
      IF (wDtUltZeramento IS NULL) THEN
        SELECT FIRST 1 BDDATA FROM VSUC_EMPRESAS_TLAN WHERE BDCODEMP = :prCodigoEmp ORDER BY BDDATA INTO :wDtUltZeramento;
      IF (wDtUltZeramento IS NULL) THEN
        wDtUltZeramento = :prDataIni;

      -- Limpa tabela tempor?ria de contas com zeramento
      DELETE FROM VSUC_EMP_TCTAZERADAS WHERE bdcodemp IS NOT NULL;
      -- Povoa tabela tempor?ria de contas com zeramento
      wsql = 'Insert into VSUC_EMP_TCTAZERADAS ';
      wsql = wsql||'Select bdcodemp,bdcodcta from (Select tlan.bdcodemp, tlan.bdcredito bdcodcta';
      wsql = wsql||'                               from VSUC_EMPRESAS_TLAN tlan';
      wsql = wsql||'                               where';
      wsql = wsql||'                               (tlan.bddata <= '''||prDataIni||''') and';
      wsql = wsql||'                               (tlan.bdcodemp = '||prCodigoEmp||') and';
      wsql = wsql||'                               (tlan.bdcredito is not null) and';
      wsql = wsql||'                               (tlan.bdtipolan = 10)';
      wsql = wsql||'                               Group By bdcodemp, bdcodcta';
      wsql = wsql||'                               union all';
      wsql = wsql||'                               Select tlan.bdcodemp, tlan.bddebito bdcodcta';
      wsql = wsql||'                               from VSUC_EMPRESAS_TLAN tlan';
      wsql = wsql||'                               where';
      wsql = wsql||'                               (tlan.bddata <= '''||prDataIni||''') and';
      wsql = wsql||'                               (tlan.bdcodemp = '||prCodigoEmp||') and';
      wsql = wsql||'                               (tlan.bddebito is not null) and';
      wsql = wsql||'                               (tlan.bdtipolan = 10)';
      wsql = wsql||'                               Group By bdcodemp, bdcodcta) ';
      wsql = wsql||'Group by bdcodemp,bdcodcta';
      EXECUTE STATEMENT wsql;
    END

  -- limpa tabela temporaria de saldos _________________________________________
  DELETE FROM vsuc_emp_tsaldos WHERE bdcodemp IS NOT NULL;
  -- povoa tabela tempor?ria de saldos _________________________________________
  wsql = 'insert into vsuc_emp_tsaldos (BDCODEMP,BDDATA,BDCREDITO,BDDEBITO,BDTIPOLANCFILIAL,BDFILIAL,BDTIPOLAN,BDVALOR,BDCODTPCC,BDDEBCRE) ';
  IF ((prlancsemcc = 1) AND ((prcc IS NOT NULL) AND (prcc <> ''))) THEN
    BEGIN
      wsql_aux = 'where (tlan.bddata <= '''||prdatafim||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql_aux = wsql_aux||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
      wsql_aux = wsql_aux||'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';

      --D?bito
      wsql = wsql||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito as BDCREDITO,tlan.bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      wsql = wsql||'sum(coalesce(tlan.bdvalor, 0)) as BDVALOR, null as BDCODTPCC, null as BDDEBCRE ';
      wsql = wsql||'from ';
      wsql = wsql||'     (select tlan.bdcodemp,tlan.bdchave,tlan.bddata,null as bdcredito,tlan.bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'tlan.bdvalor ';
      ELSE
        BEGIN
          wsql = wsql||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdvalor ';
        END
      --alt:6178 - Fim
      wsql = wsql||'     from vsuc_empresas_tlan tlan ';

      wsql = wsql||wsql_aux;

      wsql = wsql||') tlan ';
      wsql = wsql||'left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 0) ';
      wsql = wsql||'where (tlcc.bddebcre is null) ';
      wsql = wsql||'Group By tlan.bdcodemp,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
      wsql = wsql||'union ';
      --Cr?dito
      wsql = wsql||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      wsql = wsql||'sum(coalesce(tlan.bdvalor, 0)) as BDVALOR, null as BDCODTPCC, null as BDDEBCRE ';
      wsql = wsql||'from ';
      wsql = wsql||'     (select tlan.bdcodemp,tlan.bdchave,tlan.bddata,tlan.bdcredito,null as bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'tlan.bdvalor ';
      ELSE
        BEGIN
          wsql = wsql||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdvalor ';
        END
      --alt:6178 - Fim
      wsql = wsql||'     from vsuc_empresas_tlan tlan ';

      wsql = wsql||wsql_aux;

      wsql = wsql||') tlan ';
      wsql = wsql||'left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 1) ';
      wsql = wsql||'where (tlcc.bddebcre is null) ';
      wsql = wsql||'Group By tlan.bdcodemp,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';

      wsql = wsql||' union all ';
    END

  IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
    BEGIN
      wsql = wsql||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdtipolan, ';
      IF ((prcc IS NULL) OR (prcc = '')) THEN
        BEGIN
          --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
          IF (prindice = 0) THEN
            wsql = wsql||'sum(coalesce(tlan.bdvalor, 0)) as BDVALOR, ';
          ELSE
            BEGIN
              wsql = wsql||'sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsql = wsql||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdvalor, ';
            END
          --alt:6178 - Fim
        END
      ELSE
        BEGIN
          --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
          IF (prindice = 0) THEN
            wsql = wsql||'sum(coalesce(tlcc.bdvalor, 0)) as bdvalor, ';
          ELSE
            BEGIN
              wsql = wsql||'sum(case when (tlcc.bdcodtpcc is null) then coalesce(tlan.bdvalor, 0) else coalesce(tlcc.bdvalor, 0) end';
              wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdvalor, ';
            END
          --alt:6178 - Fim
        END
      IF ((prcc IS NULL) OR (prcc = '')) THEN
         wsql = wsql||'null, null ';
      ELSE
         wsql = wsql||'tlcc.bdcodtpcc, tlcc.bddebcre ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      IF (NOT ((prcc IS NULL) OR (prcc = ''))) THEN
         BEGIN
           wsql = wsql||'inner join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave ';
           IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
              wsql = wsql||'and tlcc.bdcodtpcc in ('||prcc||')';
           wsql = wsql||') ';
         END

      wsql = wsql||'where (tlan.bddata <= '''||prdatafim||''') ';

      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

      wsql = wsql||'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';
      wsql = wsql||'Group By tlan.bdcodemp,tlan.bdtipolancfilial,tlan.bdfilial,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
      IF (NOT ((prcc IS NULL) OR (prcc = ''))) THEN
         wsql = wsql||', tlcc.bdcodtpcc, tlcc.bddebcre ';
    END

  -- Gilberto - 06/04/2015 - ALT:#9178 - inserido condi??o para verificar se a situa??o ocorre
  IF (((prlancsemcc = 1) AND ((prcc IS NOT NULL) AND (prcc <> ''))) OR
      ((prcc IS NOT NULL) AND (prcc <> ''))) THEN
     EXECUTE STATEMENT wsql;

  -- retorna saldos da tabela tempor?ria de saldos _____________________________
  wsql = '';
  wsql = wsql||'select bdcodemp,bdfilial,bdtipolancfilial,bddebito, 1 as bdtipcta, coalesce(bdcodtpcc, null) as bdcodtpcc, ';

  IF (prDRE = 1) THEN-- se for DRE o calculo do saldo anterior deve considerar zeramento para demonstrar
     wsql = wsql||'       sum(case when ((bddata >= '''||wDtUltZeramento||''' and bddata < '''||prdataini||''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_dre, ';
  ELSE
     wsql = wsql||'       0 as bdvalor_ant_dre, ';

  wsql = wsql||'      sum(case when (bddata < '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''' and bdtipolan <> 10) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu ';
  ELSE
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu ';
  wsql = wsql||'from vsuc_emp_tsaldos tlan ';

  --alt:10233 - Implementada a valida??o das contas de compensa??o aqui, para poder diferenciar se a conta que est? sendo calculada ? de d?bito ou cr?dito. Pedro
  IF (prnaomostracontacomp = 1) THEN --alt:11108 - 08/04/2015 - Pedro
    wsql = wsql||'left outer join PLANOS_TPLA tpla on ('||prcodplapadrao||' = tpla.BDCODPLAPADRAO and tlan.BDDEBITO = tpla.BDCODTPLA) ';

  wsql = wsql||'where (bddata <= '''||prdatafim||''') ';

  --alt:10233 - Implementada a valida??o das contas de compensa??o aqui, para poder diferenciar se a conta que est? sendo calculada ? de d?bito ou cr?dito. Pedro
  IF (prnaomostracontacomp = 1) THEN --alt:11108 - 08/04/2015 - Pedro
    wsql = wsql||'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';

  IF ((prcc <> '') AND (NOT (prcc IS NULL))) THEN
     BEGIN
       wsql = wsql||'and (BDDEBCRE = 0) ';
       wsql = wsql||'and (bdcodtpcc in ('||prcc||')) ';

       IF (prlancsemcc = 1) THEN
          wsql = wsql||'or (bdcodtpcc is null) ';
       ELSE
          wsql = wsql||'and (bdcodtpcc is not null) ';
     END
  ELSE
  IF (prlancsemcc = 1) THEN
     wsql = wsql||'and (bdcodtpcc is null) ';-- somente sem centro de custo

  wsql = wsql||'and ((bdcodemp = '||prcodigoemp||') or (bdfilial = '||prcodigoemp||')) ';

  wsql = wsql||'Group By bdcodemp,bdfilial,bdtipolancfilial,bddebito, bdcodtpcc ';
  wsql = wsql||'union all ';
  wsql = wsql||'select bdcodemp,bdfilial,bdtipolancfilial,bdcredito, 0 as bdtipcta, coalesce(bdcodtpcc, null) as bdcodtpcc, ';

  IF (prDRE = 1) THEN-- se for DRE o calculo do saldo anterior deve considerar zeramento para demonstrar
     wsql = wsql||'       sum(case when ((bddata >= '''||wDtUltZeramento||''' and bddata < '''||prdataini||''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_dre, ';
  ELSE
     wsql = wsql||'       0 as bdvalor_ant_dre, ';

  wsql = wsql||'       sum(case when (bddata < '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''' and bdtipolan <> 10) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu ';
  ELSE
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu ';
  wsql = wsql||'from vsuc_emp_tsaldos tlan ';

  --alt:10233 - Implementada a valida??o das contas de compensa??o aqui, para poder diferenciar se a conta que est? sendo calculada ? de d?bito ou cr?dito. Pedro
  IF (prnaomostracontacomp = 1) THEN --alt:11108 - 08/04/2015 - Pedro
    wsql = wsql||'left outer join PLANOS_TPLA tpla on ('||prcodplapadrao||' = tpla.BDCODPLAPADRAO and tlan.BDCREDITO = tpla.BDCODTPLA) ';

  wsql = wsql||'where (bddata <= '''||prdatafim||''') ';

  --alt:10233 - Implementada a valida??o das contas de compensa??o aqui, para poder diferenciar se a conta que est? sendo calculada ? de d?bito ou cr?dito. Pedro
  IF (prnaomostracontacomp = 1) THEN --alt:11108 - 08/04/2015 - Pedro
    wsql = wsql||'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';

  IF ((prcc <> '') AND (NOT (prcc IS NULL))) THEN
     BEGIN
       wsql = wsql||'and (BDDEBCRE = 1) ';
       wsql = wsql||'and (bdcodtpcc in ('||prcc||')) ';

       IF (prlancsemcc = 1) THEN
          wsql = wsql||'or (bdcodtpcc is null) ';
       ELSE
          wsql = wsql||'and (bdcodtpcc is not null) ';
     END
  ELSE
  IF (prlancsemcc = 1) THEN
     wsql = wsql||'and (bdcodtpcc is null) ';-- somente sem centro de custo 

  wsql = wsql||'and ((bdcodemp = '||prcodigoemp||') or (bdfilial = '||prcodigoemp||')) ';
  wsql = wsql||'Group By bdcodemp,bdfilial,bdtipolancfilial,bdcredito, bdcodtpcc ';

  -- insere os saldos na tabela tempor?ria do balancete ________________________
  DELETE FROM VSUC_EMPRESAS_TBALANCETE_3 WHERE bdcodemp IS NOT NULL AND bdcodemp IS NULL;
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp, :wfilial, :wtipolancfilial, :wcodtpla, :wtipcta, :wcodtpcc, :wsaldo_ant_dre, :wsaldo_ant, :wsaldo_atu DO
      BEGIN
        IF (wcodtpla IS NOT NULL) THEN
           BEGIN
             IF (wfilial IS NULL) THEN
               wfilial = 0;
             wtipoctaaux = 1;--D?bito
             IF (wtipcta = 0) THEN
               wtipoctaaux = 2;--Cr?dito

             IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
                wpermite = 1;
             ELSE
             IF (((prcodigoemp = wcodemp) AND (wfilial = 0)) OR
                 --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
                 ((prcodigoemp = wfilial) AND (wtipoctaaux = wtipolancfilial)) OR
                 --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                 ((prcodigoemp = wcodemp) AND (wfilial <> 0) AND (wtipoctaaux <> wtipolancfilial) AND (prcodigoemp > 0)) OR
                 --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
                 ((prmatrizfilialconsolidado = 1) AND (prcodigoemp <> wcodemp) AND (wfilial = 0) AND (wcodemp > 0)) OR
                 --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
                 ((prmatrizfilialconsolidado = 1) AND (prcodigoemp = wcodemp) AND (wfilial <> 0) AND (wtipoctaaux = wtipolancfilial) AND (wfilial > 0))) THEN
                wpermite = 1;
             ELSE
                wpermite = 0;

             IF (wpermite = 1) THEN
               BEGIN
                 wanterior_dre_aux = 0;
                 wanterior_aux = 0;
                 wvalor_aux = 0;

                 IF (wtipcta = 1) THEN
                   BEGIN
                     wsql = 'select coalesce(BDANTERIOR_DEBITO_DRE, 0), coalesce(BDANTERIOR_DEBITO, 0), coalesce(BDVALOR_DEBITO, 0) ';
                     wsql = wsql||'from VSUC_EMPRESAS_TBALANCETE_3 ';
                     wsql = wsql||'where BDCODEMP ='||prcodigoemp||' and ';
                     wsql = wsql||'BDCODPLAPADRAO ='||prcodplapadrao||' and ';
                     wsql = wsql||'BDCODTPLA ='||wcodtpla||' and ';

                     IF (wcodtpcc IS NULL) THEN
                        wsql = wsql||'BDCODTPCC is null';
                     ELSE
                        wsql = wsql||'BDCODTPCC ='||wcodtpcc;
      
                     EXECUTE STATEMENT wsql INTO :wanterior_dre_aux, :wanterior_aux, :wvalor_aux;

                     wsql_aux = 'update or insert into VSUC_EMPRESAS_TBALANCETE_3 ';
                     wsql_aux = wsql_aux||'(bdcodemp, bdcodplapadrao, bdcodtpla, bdcodtpcc, bdanterior_debito_dre, bdanterior_debito, bdvalor_debito) values ';
                     wsql_aux = wsql_aux||'('||prcodigoemp||','||prcodplapadrao||','||wcodtpla||',';

                     IF (wcodtpcc IS NULL) THEN
                        wsql_aux = wsql_aux||'null,';
                     ELSE
                        wsql_aux = wsql_aux||wcodtpcc||',';

                     wsql_aux = wsql_aux||'('||wanterior_dre_aux||' + '||wsaldo_ant_dre||'),';
                     wsql_aux = wsql_aux||'('||wanterior_aux||' + '||wsaldo_ant||'),';
                     wsql_aux = wsql_aux||'('||wvalor_aux||' + '||wsaldo_atu||'))';
                     wsql_aux = wsql_aux||'matching (bdcodemp, bdcodplapadrao, bdcodtpla, bdcodtpcc)';

                     EXECUTE STATEMENT wsql_aux;
                   END
                 ELSE
                   BEGIN
                     wsql = 'select coalesce(BDANTERIOR_CREDITO_DRE, 0), coalesce(BDANTERIOR_CREDITO, 0), coalesce(BDVALOR_CREDITO, 0) ';
                     wsql = wsql||'from VSUC_EMPRESAS_TBALANCETE_3 ';
                     wsql = wsql||'where BDCODEMP ='||prcodigoemp||' and ';
                     wsql = wsql||'BDCODPLAPADRAO ='||prcodplapadrao||' and ';
                     wsql = wsql||'BDCODTPLA ='||wcodtpla||' and ';

                     IF (wcodtpcc IS NULL) THEN
                        wsql = wsql||'BDCODTPCC is null';
                     ELSE
                        wsql = wsql||'BDCODTPCC ='||wcodtpcc;
      
                     EXECUTE STATEMENT wsql INTO :wanterior_dre_aux, :wanterior_aux, :wvalor_aux;

                     wsql_aux = 'update or insert into VSUC_EMPRESAS_TBALANCETE_3 ';
                     wsql_aux = wsql_aux||'(bdcodemp, bdcodplapadrao, bdcodtpla, bdcodtpcc, bdanterior_credito_dre, bdanterior_credito, bdvalor_credito) values ';
                     wsql_aux = wsql_aux||'('||prcodigoemp||','||prcodplapadrao||','||wcodtpla||',';

                     IF (wcodtpcc IS NULL) THEN
                        wsql_aux = wsql_aux||'null,';
                     ELSE
                        wsql_aux = wsql_aux||wcodtpcc||',';

                     wsql_aux = wsql_aux||'('||wanterior_dre_aux||' + '||wsaldo_ant_dre||'),';
                     wsql_aux = wsql_aux||'('||wanterior_aux||' + '||wsaldo_ant||'),';
                     wsql_aux = wsql_aux||'('||wvalor_aux||' + '||wsaldo_atu||'))';
                     wsql_aux = wsql_aux||'matching (bdcodemp, bdcodplapadrao, bdcodtpla, bdcodtpcc)';
                     EXECUTE STATEMENT wsql_aux;
                   END
               END
           END
      END

  IF (prOrdem = 1) THEN
     --IN?CIO DO C?LCULO DO MODELO CONTAS/CENTRO DE CUSTO
     BEGIN
       -- insere e atualiza a tabela tempor?ria do balancete com as informa??es do plano de contas
       wsql = 'select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, ';
       wsql = wsql||' tpla.BDNOMCTA, tpla.BDRELCTA, tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.BDAPECTA, tpla.bdpertenceconta ';
       wsql = wsql||'from planos_tpla tpla ';
       IF (PRLANCSEMCC = 1) THEN
          wsql = wsql||'left outer join VSUC_EMPRESAS_TBALANCETE_3 tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao and tlan.bdcodtpla = tpla.bdcodtpla) ';
       ELSE
          wsql = wsql||'inner join VSUC_EMPRESAS_TBALANCETE_3 tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao and tlan.bdcodtpla = tpla.bdcodtpla) ';
       wsql = wsql||'where tpla.bdcodplapadrao = '||prcodplapadrao;
       wsql = wsql||' order by tpla.bdctalon';
     
       FOR EXECUTE STATEMENT wsql
           INTO :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta DO
           BEGIN
             UPDATE OR INSERT INTO VSUC_EMPRESAS_TBALANCETE_3
             (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
              BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA, bdpertenceconta) VALUES
             (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta)
             MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA);
           END
     
       IF (PRLANCSEMCC <> 1) THEN
          BEGIN
            -- insere contas t?tulo na tabela tempor?ria do balancete ____________________
            wsql = 'select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, ';
            wsql = wsql||'tpla.BDNOMCTA, tpla.BDRELCTA, tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.bdapecta, tpla.bdpertenceconta ';
            wsql = wsql||'from planos_tpla tpla ';
            wsql = wsql||'where tpla.BDCODPLAPADRAO = '||prcodplapadrao;
            wsql = wsql||' AND ((tpla.BDTIPCTA in (0,2)) or ((tpla.BDTIPCTA = 1) AND (TPLA.bdformula <> '''||''||'''))) ';

            IF (prnaomostracontacomp = 1) THEN
               wsql = wsql||'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';
            wsql = wsql||'order by tpla.bdctalon ';
          
            FOR EXECUTE STATEMENT wsql
                INTO :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta DO
                BEGIN
                  UPDATE OR INSERT INTO VSUC_EMPRESAS_TBALANCETE_3
                  (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
                   BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,bdpertenceconta) VALUES
                  (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta)
                  MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA);
                END
          END
     
       -- totaliza contas t?tulos e consolidadas da tabela tempor?ria do balancete
       FOR SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta
           FROM VSUC_EMPRESAS_TBALANCETE_3 tbal
           WHERE tbal.bdtipcta IN (0,2)-- totalizando as contas consolidadas
           AND tbal.bdcodemp = :prcodigoemp
           ORDER BY tbal.bdcodemp, tbal.bdcodplapadrao, tbal.bdctalon
           INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta DO
           BEGIN
             -- faz um select para totalizar as contas titulos
             FOR SELECT SUBSTRING(tbal.bdctalon FROM 1 FOR strlen(:wclassificacao)) AS bdctalonx,
                        SUM(COALESCE(tbal.bdvalor_debito, 0)) AS valor_debito,
                        SUM(COALESCE(tbal.bdvalor_credito, 0)) AS valor_credito,
                        SUM(COALESCE(tbal.bdanterior_debito, 0)) AS anterior_debito,
                        SUM(COALESCE(tbal.bdanterior_credito, 0)) AS anterior_credito,
                        SUM(COALESCE(tbal.bdanterior_debito_dre, 0)) AS anterior_debito_dre,
                        SUM(COALESCE(tbal.bdanterior_credito_dre, 0)) AS anterior_credito_dre
                 FROM VSUC_EMPRESAS_TBALANCETE_3 tbal
                 WHERE tbal.bdctalon LIKE :wclassificacao||'%'
                 AND tbal.bdcodemp = :prcodigoemp
                 AND tbal.bdtipcta = 1
                 GROUP BY bdctalonx
                 INTO :wctalon, :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :wanterior_debito_dre, :wanterior_credito_dre DO
                 BEGIN
                   -- da um update na tabela de balancete para gravar os totais ___________
                   UPDATE VSUC_EMPRESAS_TBALANCETE_3 SET bdvalor_debito = :wsaldo_debito,
                                                         bdvalor_credito = :wsaldo_credito,
                                                         bdanterior_debito = :wanterior_debito,
                                                         bdanterior_credito = :wanterior_credito,
                                                         bdanterior_debito_dre = :wanterior_debito_dre,
                                                         bdanterior_credito_dre = :wanterior_credito_dre
                   WHERE bdcodemp = :prcodigoemp
                   AND   bdcodplapadrao = :wcodigoplano
                   AND   bdcodtpla = :wcodtpla
                   AND   bdctalon = :wclassificacao;
                 END
           END
     END
     --FIM DO C?LCULO DO MODELO CONTAS/CENTRO DE CUSTO
  ELSE
     --IN?CIO DO C?LCULO DO MODELO CENTRO DE CUSTO/CONTAS
     BEGIN
       -- insere e atualiza a tabela tempor?ria do balancete com as informa??es do plano de contas
       wsql = 'select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, tpla.BDNOMCTA, tpla.BDRELCTA, ';
       wsql = wsql||'tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.BDAPECTA, tpla.bdpertenceconta, tlan.bdcodtpcc ';
       wsql = wsql||'from planos_tpla tpla ';
       --alt:9179 - Trocado para inner join para melhoria de desempenho, pois n?o faz sentido trazer aqui lan?amentos sem centro de custo. Pedro
       --wsql = wsql||'left outer join VSUC_EMPRESAS_TBALANCETE_3 tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao and tlan.bdcodtpla = tpla.bdcodtpla) ';
       wsql = wsql||'inner join VSUC_EMPRESAS_TBALANCETE_3 tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao and tlan.bdcodtpla = tpla.bdcodtpla) ';
       wsql = wsql||'where tpla.bdcodplapadrao = '||prcodplapadrao;

       wsql = wsql||' union all ';
       wsql = wsql||' select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, tpla.BDNOMCTA, tpla.BDRELCTA, ';
       wsql = wsql||' tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.bdapecta, tpla.bdpertenceconta, null as bdcodtpcc ';
       wsql = wsql||' from planos_tpla tpla ';
       wsql = wsql||' where tpla.BDCODPLAPADRAO = '||prcodplapadrao;
       wsql = wsql||' AND ((tpla.BDTIPCTA in (0,2)) or ((tpla.BDTIPCTA = 1) AND (TPLA.bdformula <> '''||''||'''))) ';

       IF (prnaomostracontacomp = 1) THEN
              wsql = wsql||' and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||'''))';

       FOR EXECUTE STATEMENT wsql
           INTO :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta, :wcodtpcc DO
           BEGIN
             IF (wtipcta <> 1) THEN
                BEGIN
                  FOR SELECT SUM(COALESCE(tbal.bdvalor_debito, 0)) AS valor_debito,
                         SUM(COALESCE(tbal.bdvalor_credito, 0)) AS valor_credito,
                         SUM(COALESCE(tbal.bdanterior_debito, 0)) AS anterior_debito,
                         SUM(COALESCE(tbal.bdanterior_credito, 0)) AS anterior_credito,
                         SUM(COALESCE(tbal.bdanterior_debito_dre, 0)) AS anterior_debito_dre,
                         SUM(COALESCE(tbal.bdanterior_credito_dre, 0)) AS anterior_credito_dre,
                         tbal.bdcodtpcc
                  FROM VSUC_EMPRESAS_TBALANCETE_3 tbal
                  WHERE tbal.bdctalon LIKE :wctalon||'%'
                  AND tbal.bdcodemp = :prcodigoemp
                  AND tbal.bdtipcta = 1
                  GROUP BY tbal.bdcodtpcc
                  INTO :WSALDO_DEBITO, :WSALDO_CREDITO, :WANTERIOR_DEBITO,
                       :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE, :WANTERIOR_CREDITO_DRE, :wcodtpcc DO
                  BEGIN
                    --alt:9179 - Trocado para insert pois nunca estar? dando update, j? que aqui trata apenas contas t?tulo e at? aqui n?o tem nenhuma conta t?tulo armazenada.
                    --Assim a procedure ficou 1/7 mais r?pida por n?o ter que verificar se a conta j? existe na tabela. Pedro
                    /*update or insert into VSUC_EMPRESAS_TBALANCETE_3
                    (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA, BDNOMCTA, BDRELCTA,
                     BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA, BDPERTENCECONTA, BDCODTPCC,
                     BDVALOR_DEBITO, BDVALOR_CREDITO, BDANTERIOR_DEBITO,
                     BDANTERIOR_CREDITO, BDANTERIOR_DEBITO_DRE, BDANTERIOR_CREDITO_DRE) values
                    (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta,
                     :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta, :wcodtpcc,
                     :WSALDO_DEBITO, :WSALDO_CREDITO, :WANTERIOR_DEBITO,
                     :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE, :WANTERIOR_CREDITO_DRE)
                    matching (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCODTPCC);*/

                    INSERT INTO VSUC_EMPRESAS_TBALANCETE_3
                    (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA, BDNOMCTA, BDRELCTA,
                     BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA, BDPERTENCECONTA, BDCODTPCC,
                     BDVALOR_DEBITO, BDVALOR_CREDITO, BDANTERIOR_DEBITO,
                     BDANTERIOR_CREDITO, BDANTERIOR_DEBITO_DRE, BDANTERIOR_CREDITO_DRE) VALUES
                    (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta,
                     :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta, :wcodtpcc,
                     :WSALDO_DEBITO, :WSALDO_CREDITO, :WANTERIOR_DEBITO,
                     :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE, :WANTERIOR_CREDITO_DRE);
                  END
                END
             ELSE
                BEGIN
                  UPDATE OR INSERT INTO VSUC_EMPRESAS_TBALANCETE_3
                  (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
                   BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA, bdpertenceconta, bdcodtpcc ) VALUES
                  (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta, :wcodtpcc)
                  MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCODTPCC);
                END
           END
           
       --Inicio 17388 - Retorna as contas com formulas - Fernando Jr. 18/01/2018
       wsql = 'select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, ';
       wsql = wsql||'tpla.BDNOMCTA, tpla.BDRELCTA, tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.bdapecta, tpla.bdpertenceconta ';
       wsql = wsql||'from planos_tpla tpla ';
       wsql = wsql||' where tpla.BDCODPLAPADRAO = '||prcodplapadrao;
       wsql = wsql||' AND ((tpla.BDTIPCTA = 0) OR (TPLA.bdformula <> '''||''||'''))  ';
       wsql = wsql||'order by tpla.bdctalon ';
                  
          FOR EXECUTE STATEMENT wsql
              INTO :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta DO
              BEGIN
                UPDATE OR INSERT INTO VSUC_EMPRESAS_TBALANCETE_3
                (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
                BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,bdpertenceconta, BDCODTPCC) VALUES
                (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta, null)
                MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCODTPCC);

               wsql_aux = ' select distinct(BDCODTPCC) ';
               wsql_aux = wsql_aux || ' from VSUC_EMPRESAS_TBALANCETE_3 ';
               wsql_aux = wsql_aux || ' where BDCODTPCC is not null ';
    
               FOR EXECUTE STATEMENT wsql_aux
                   INTO :wcodtpcc DO
               BEGIN
                   UPDATE OR INSERT INTO VSUC_EMPRESAS_TBALANCETE_3
                   (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
                    BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,bdpertenceconta, BDCODTPCC) VALUES
                   (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta, :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta, :wcodtpcc)
                   MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCODTPCC);
               END
             END
       --Fim 17388
     END

  --Insere o nome e a classifica??o do centro de custo
  UPDATE VSUC_EMPRESAS_TBALANCETE_3 balan SET balan.bdnomtpcc = (
  SELECT FIRST 1 tpcc.bdnomcta
  FROM centros_tpcc tpcc
  INNER JOIN vw_empresas_ref_atual ref ON (tpcc.BDCODCENTRO = ref.bdcodcentros AND ref.bdcodemp = :prcodigoemp)
  WHERE tpcc.bdcodtpcc = balan.bdcodtpcc),
  balan.bdtpcclon = (
  SELECT FIRST 1 tpcc.bdctalon
  FROM centros_tpcc tpcc
  INNER JOIN vw_empresas_ref_atual ref ON (tpcc.BDCODCENTRO = ref.bdcodcentros AND ref.bdcodemp = :prcodigoemp)
  WHERE tpcc.bdcodtpcc = balan.bdcodtpcc);


  -- retira as contas analiticas que pertencem a uma conta consolidadas ________
  IF ((prconsolidada IS NULL) OR (prconsolidada = 0)) THEN
     BEGIN
       FOR SELECT bdctalon FROM planos_tpla WHERE bdcodplapadrao = :prcodplapadrao AND bdtipcta = 2 INTO :wctalon DO
           BEGIN
             wsql = 'delete from VSUC_EMPRESAS_TBALANCETE_3 ';
             wsql = wsql||'where bdcodplapadrao = '||prcodplapadrao;
             wsql = wsql||' and bdctalon like '''||wctalon||'%'||''' ';
             wsql = wsql||'and bdctalon <> '''||wctalon||''' ';
             EXECUTE STATEMENT wsql;
           END
     END

  -- faz o select na tabela tempor?ria de balancete e monta os retornos para a impressao
  wSQL = 'SELECT  bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,';
  wSQL = wSQL||'  COALESCE(bdvalor_debito, 0), COALESCE(bdvalor_credito, 0),';
  wSQL = wSQL||'  COALESCE(bdanterior_debito, 0), COALESCE(bdanterior_credito, 0),';
  wSQL = wSQL||'  COALESCE(bdanterior_debito_dre, 0), COALESCE(bdanterior_credito_dre, 0),';
  wSQL = wSQL||'  bdformula, bdrelcta, bdclanom,';
  --alt:7866 - 27/10/2015 - Caso tenha a op??o de detalhar por participantes espec?ficos, precisa verificar aqui se o em quest?o
  --est? marcado ou n?o para retornar como conta participante, para depois a VSUC_SP_RETORNA_BALANCETE detalhar ou n?o. Pedro
  IF ((wSelectContas IS NOT NULL) AND (wSelectContas > 0)) THEN
    wSQL = wSQL||' case when lista.BDCODTPLA is null then 0 else BDPARTICIPANTE end as BDPARTICIPANTE,';
  ELSE
    wSQL = wSQL||' bdparticipante,';
  --alt:7866 - Fim
  wSQL = wSQL||' bdapecta, bdpertenceconta, bdcodtpcc, bdnomtpcc, bdtpcclon';
  wSQL = wSQL||' FROM vsuc_empresas_tbalancete_3 tbal';
  --alt:7866 - 27/10/2015 - Faz a verifica??o para saber qual o tipo de filtro que ser? aplicado aqui, para o caso de selecionar contas espec?ficas. Pedro
  IF ((wSelectContas IS NOT NULL) AND (wSelectContas > 0)) THEN
    wSQL = wSQL||' left join VSUC_SELECT_CONTAS lista on (tbal.BDCODPLAPADRAO = lista.BDCODPLAPADRAO and tbal.BDCODTPLA = lista.BDCODTPLA)';
  --alt:7866 - Fim
  wSQL = wSQL||' where bdctalon BETWEEN '''||:wclassini||''' AND '''||:wclassfin||'''';
  wSQL = wSQL||' ORDER BY bdcodemp, bdcodplapadrao, bdctalon ASC';
  FOR EXECUTE STATEMENT wSQL INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta,
       :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :wanterior_debito_dre, :wanterior_credito_dre,
       :bdformula, :bdrelconta , :bdclanom, :wparticipante, :wapecta, :wpertenceconta, :wcodtpcc, :wnomtpcc, :wtpcclon DO
      BEGIN
        bdcodemp = :prcodigoemp;
        bdcodplapadrao = :wcodigoplano;
        bdconta  = :wcodtpla;
        bdclassificacao = :wclassificacao;
        bdnomeconta = :wnomcta;
        bdtipconta = :wtipcta;
        bdgrupoconta = :wgrpcta;
        bdparticipante = :wparticipante;
        bdsaldo_ant_deb = :wanterior_debito;
        bdsaldo_ant_cre = :wanterior_credito;
        bdsaldo_ant_deb_dre = :wanterior_debito_dre;
        bdsaldo_ant_cre_dre = :wanterior_credito_dre;
        bdsaldo_deb = :wsaldo_debito;
        bdsaldo_cre = :wsaldo_credito;
        bdapecta = :wapecta;
        bdpertenceconta = :wpertenceconta;

        bdcodtpcc = wcodtpcc;
        bdnomtpcc = wnomtpcc;
        bdtpcclon = wtpcclon;

        IF (wgrpcta IN (1,2,3)) THEN
           BEGIN
             bdsaldo_anterior = (wanterior_credito - wanterior_debito);
             bdsaldo_anterior_dre = (wanterior_credito_dre - wanterior_debito_dre);
             bdsaldo_atual = (bdsaldo_anterior + :wsaldo_credito - :wsaldo_debito);
           END
        ELSE
           BEGIN
             bdsaldo_anterior = (wanterior_debito - wanterior_credito);
             bdsaldo_anterior_dre = (wanterior_debito_dre - wanterior_credito_dre);
             bdsaldo_atual = (bdsaldo_anterior + :wsaldo_debito - :wsaldo_credito);
           END

        wnivelconta = 1;
        wCont = 1;
        WHILE (wcont <= CHAR_LENGTH(wclassificacao)) DO
          BEGIN
            IF (SUBSTRING(wclassificacao FROM wcont FOR 1) = '.') THEN
               wnivelconta = wnivelconta + 1;
            wcont = wcont + 1;
          END
        windice = POSITION(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',');
        wimpanalitica = POSITION(',1,',','||:prniveisconta||',');
        IF ((prniveisconta = '9999') OR           -- N?o tem filtro
            (wnivelconta = 1) OR                  -- O primeiro n?vel sempre imprime
            ((windice > 0) AND (:wtipcta = 0)) OR -- O n?vel da conta foi selecionado no filtro e ? t?tulo
            (((windice > 0) AND (wimpanalitica > 0) AND ((:wtipcta = 1) OR (:wtipcta = 2))))) THEN -- ? do n?vel selecionado, anal?tica e foi selecionado para imprimir as contas anal?ticas
           SUSPEND;
      END

  -- limpa tabela tempor?ria do balancete ______________________________________
  DELETE FROM VSUC_EMPRESAS_TBALANCETE_3 WHERE bdcodemp IS NOT NULL;
END
^

/* Alter (VSUC_SP_RETORNA_SALDO_LANC) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_LANC(PRCODEMP INTEGER,
PRREFEMP INTEGER,
PRCONTA_DEB INTEGER,
PRCONTA_CRED INTEGER,
PRDATA DATE,
PRPARTICIPANTED INTEGER,
PRPARTICIPANTEC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFIIALCONSOLIDADO INTEGER)
 RETURNS(ANT_AO_DIA_D NUMERIC(15,2),
DEB_DO_DIA_D NUMERIC(15,2),
CRED_DO_DIA_D NUMERIC(15,2),
ATUAL_DO_DIA_D NUMERIC(15,2),
ANT_AO_DIA_C NUMERIC(15,2),
DEB_DO_DIA_C NUMERIC(15,2),
CRED_DO_DIA_C NUMERIC(15,2),
ATUAL_DO_DIA_C NUMERIC(15,2),
ANT_AO_MES_C NUMERIC(15,2),
ATUAL_DO_MES_C NUMERIC(15,2),
ANT_AO_MES_D NUMERIC(15,2),
DEB_DO_MES_D NUMERIC(15,2),
CRED_DO_MES_D NUMERIC(15,2),
MOV_DO_MES_D NUMERIC(15,2),
ATUAL_DO_MES_D NUMERIC(15,2),
ANT_DO_MES_C NUMERIC(15,2),
DEB_DO_MES_C NUMERIC(15,2),
CRED_DO_MES_C NUMERIC(15,2),
MOV_DO_MES_C NUMERIC(15,2),
ATUTAL_DO_MES_C NUMERIC(15,2))
 AS
DECLARE VARIABLE WMES_S_ANT VARCHAR(2);
DECLARE VARIABLE WMES_S VARCHAR(2);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO VARCHAR(4);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WBDDEB VARCHAR(7);
DECLARE VARIABLE WBDCRE VARCHAR(7);
BEGIN
 /* Procedure Text */

  ANT_AO_DIA_D = 0;
  DEB_DO_DIA_D = 0;
  CRED_DO_DIA_D = 0;
  ATUAL_DO_DIA_D = 0;
  ANT_AO_DIA_C = 0;
  DEB_DO_DIA_C = 0;
  CRED_DO_DIA_C = 0;
  ATUAL_DO_DIA_C = 0;
  ANT_AO_MES_C = 0;
  ATUAL_DO_MES_C = 0;
  ANT_AO_MES_D = 0;
  DEB_DO_MES_D = 0;
  CRED_DO_MES_D = 0;
  MOV_DO_MES_D = 0;
  ATUAL_DO_MES_D = 0;
  ANT_DO_MES_C = 0;
  DEB_DO_MES_C = 0;
  CRED_DO_MES_C = 0;
  MOV_DO_MES_C = 0;
  ATUTAL_DO_MES_C = 0;

  wMes = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
  wAno = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);

  SELECT str FROM strZero(EXTRACT(MONTH FROM :prdata), 2) INTO :wmes_s;

  wbddeb = 'BDDEB' || wmes_s;
  wbdcre = 'BDCRE' || wmes_s;

  /* D?bito */

  -- Retorna saldo da conta d?bito
  SELECT SALDO_ANTERIOR, SALDO_DEB, SALDO_CRE, SALDO_ATUAL FROM
    vsuc_sp_retorna_saldo(:prcodemp, :prconta_deb, :prdata, :prdata, 0, 0, 0, :prrefemp, '',:prcontabilizacao,:prmatrizfiialconsolidado)
    INTO :ant_ao_dia_d, :deb_do_dia_d, :cred_do_dia_d, :atual_do_dia_d;

  IF (wMes = 1) THEN
    BEGIN
      wsql = 'select BDSALANT, ' || wbddeb || ', ' || wbdcre || ', ' || wbddeb || '-' || wbdcre || ', BDSAL' || wmes_s;
      wsql = wsql||' from VSUC_SP_MOVIMENTO_MENSAL(' || :prcodemp || ',' || :prconta_deb || ',' || wano || ',' || wano || ',' || :prrefemp || ',';
      wsql = wsql|| :prparticipanted || ',0,' || :prcontabilizacao || ',' || :prmatrizfiialconsolidado || ')';
    END
  ELSE
    BEGIN
      SELECT str FROM strZero(EXTRACT(MONTH FROM :prdata) -1, 2) INTO :wmes_s_ant;

      wsql = 'select BDSAL' || wmes_s_ant || ',' || wbddeb || ', ' || wbdcre || ', ' || wbddeb || '-' || wbdcre || ', BDSAL' || wmes_s;
      wsql = wsql||' from VSUC_SP_MOVIMENTO_MENSAL(' || :prcodemp || ',' || :prconta_deb || ',' || wano || ',' || wano || ',' || :prrefemp || ',';
      wsql = wsql|| :prparticipanted || ',0,' || :prcontabilizacao || ',' || :prmatrizfiialconsolidado || ')';
    END

  EXECUTE STATEMENT wsql INTO :ant_ao_mes_d, :deb_do_mes_d, :cred_do_mes_d, :mov_do_mes_d, :atual_do_mes_d;

  SUSPEND;

  /* Fim */

  /* Cr?dito */

  ANT_AO_DIA_D = 0;
  DEB_DO_DIA_D = 0;
  CRED_DO_DIA_D = 0;
  ATUAL_DO_DIA_D = 0;
  ANT_AO_DIA_C = 0;
  DEB_DO_DIA_C = 0;
  CRED_DO_DIA_C = 0;
  ATUAL_DO_DIA_C = 0;
  ANT_AO_MES_C = 0;
  ATUAL_DO_MES_C = 0;
  ANT_AO_MES_D = 0;
  DEB_DO_MES_D = 0;
  CRED_DO_MES_D = 0;
  MOV_DO_MES_D = 0;
  ATUAL_DO_MES_D = 0;
  ANT_DO_MES_C = 0;
  DEB_DO_MES_C = 0;
  CRED_DO_MES_C = 0;
  MOV_DO_MES_C = 0;
  ATUTAL_DO_MES_C = 0;

  -- Retorna saldo da conta cr?dito
  SELECT SALDO_ANTERIOR, SALDO_DEB, SALDO_CRE, SALDO_ATUAL FROM
    vsuc_sp_retorna_saldo(:prcodemp, :prconta_cred, :prdata, :prdata, 0, 0, 0, :prrefemp, '',:prcontabilizacao,:prmatrizfiialconsolidado)
    INTO :ant_ao_dia_c, :deb_do_dia_c, :cred_do_dia_c, :atual_do_dia_c;

  IF (wMes = 1) THEN
    BEGIN
      wsql = 'select BDSALANT, ' || wbddeb || ', ' || wbdcre || ', ' || wbddeb || '-' || wbdcre || ', BDSAL' || wmes_s;
      wsql = wsql||' from VSUC_SP_MOVIMENTO_MENSAL(' || :prcodemp || ',' || :prconta_cred || ',' || wano || ',' || wano || ',' || :prrefemp || ',';
      wsql = wsql|| :prparticipantec || ',0,' || :prcontabilizacao || ',' || :prmatrizfiialconsolidado || ')';
    END
  ELSE
    BEGIN
      SELECT str FROM strZero(EXTRACT(MONTH FROM :prdata) -1, 2) INTO :wmes_s_ant;

      wsql = 'select BDSAL' || wmes_s_ant || ',' || wbddeb || ', ' || wbdcre || ', ' || wbddeb || '-' || wbdcre || ', BDSAL' || wmes_s;
      wsql = wsql||' from VSUC_SP_MOVIMENTO_MENSAL(' || :prcodemp || ',' || :prconta_cred || ',' || wano || ',' || wano || ',' || :prrefemp || ',';
      wsql = wsql|| :prparticipantec || ',0,' || :prcontabilizacao || ',' || :prmatrizfiialconsolidado || ')';
    END

  EXECUTE STATEMENT wsql INTO :ant_ao_mes_c, :deb_do_mes_c, :cred_do_mes_c, :mov_do_mes_c, :atual_do_mes_c;

  SUSPEND;
  /* Fim */
END
^

/* Alter (VSUC_SP_RETORNA_SALDO_ORCA) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_ORCA(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRINDICE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRDATAHORA VARCHAR(30),
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
TIPCONTA SMALLINT,
BDORCADO INTEGER,
BDREALIZADO NUMERIC(15,2),
FORMULA VARCHAR(200))
 AS
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WCODIGOPLANO INTEGER;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WMOVIMENTO NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCLASSINI VARCHAR(40);
DECLARE VARIABLE WCLASSFIN VARCHAR(40);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WSALDO_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE SALDO_DEBSAIDA NUMERIC(15,2);
DECLARE VARIABLE SALDO_CRESAIDA NUMERIC(15,2);
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WSQL_AUX VARCHAR(32000);
BEGIN
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontainicial
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontafinal
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas anal?ticas
  SELECT BDRPOS FROM RPOS(',1,',','||:prniveisconta||',') INTO :wimpanalitica;

/* giovanni... insere somente as contas com lancamentos */
  wsql = '';
  wsql = wsql|| ' select distinct CONTAS.bdcodplapadrao, CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta,CONTAS.bdnomcta, ';
  wsql = wsql|| ' CONTAS.bdgrupocta, CONTAS.bdrelcta,CONTAS.bdformula  from VSUC_SP_RETORNA_CONTAS_USADAS(' || prcodigoemp || ', ' || prcodplapadrao ||   ',null,null,null,null,0,1,0,3,' || prtodasascontas  ||  ') CONTAS';
  wsql = wsql|| ' where (contas.bdcodplapadrao = ' || :prcodplapadrao || ') and (contas.bdctalon between ''' || :wclassini || ''' and  ''' || :wclassfin || ''' ) order by BDCTALON';

  FOR EXECUTE STATEMENT wsql
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wnomcta, :wgrpcta, :wrelcta, :wformula DO
      BEGIN
        INSERT INTO vsuc_empresas_rel_torcamento (bddatahora, bdcodemp, bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
                                                 BDORCADO, BDDEBITO, bdrelcta, bdformula)
        VALUES(:prdatahora, :prcodigoemp, :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta, 0.00, 0.00, :wrelcta, :wformula);
      END

 -- BUSCA VALORES A DEBITO INICIO -----------------------------------------------------------------------------------------------------------------
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    BEGIN
      -- centro de custo
      --#alt:5837.
      --wsql = wsql||'SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, SUM(TLCC.BDVALOR) AS valor_debito ';
      wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';

      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'sum(tlcc.bdvalor) as valor_debito ';
      ELSE
        BEGIN
          wsql = wsql||'sum(tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as valor_debito ';
        END
      --alt:6178 - Fim

      wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
      wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
    END
  ELSE
    BEGIN
      -- lancamentos
      --#alt:5837.
      --wsql = wsql || 'select tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';
      wsql = wsql || 'select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';

      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'coalesce(sum(tlan.bdvalor),0) as valor_debito ';
      ELSE
        BEGIN
          wsql = wsql||'coalesce(sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                                     (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))),0) as valor_debito ';
        END
      --alt:6178 - Fim

      wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'left outer join VSUC_EMPRESAS_REL_TORCAMENTO tbal on ((tlan.bdcodplapadrao = tbal.bdcodplapadrao) and (tlan.bddebito = tbal.bdcodtpla)) ';
  wsql = wsql || 'where (tbal.bdcodplapadrao = '||prcodplapadrao||') ';
  IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tbal.bdtipcta = 1) ';
  wsql = wsql || 'and (tlan.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql||'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon ';
  wsql = wsql || 'Order By tbal.bdctalon Desc ';

  -- pega a classificacao e o saldo total das contas analiticas ______________--
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wcodigoplano, :wcodtpla, :wclassificacao, :wsaldo_debito DO
    BEGIN
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          -- faz um update no debito, pq ja foi gravado o lancamento antes zerado
          --#alt:5837.
          /*update vsuc_empresas_rel_torcamento set BDDEBITO = :wsaldo_debito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :wcodigoplano
          and   bdcodtpla = :wcodtpla
          and   bdctalon = :wclassificacao
          and   bddatahora = :prdatahora
          and   ((BDDEBITO = 0) or (bddebito is null)); */
          wsql_aux = 'update vsuc_empresas_rel_torcamento set ';
          wsql_aux = wsql_aux||'BDDEBITO = (coalesce((select BDDEBITO from vsuc_empresas_rel_torcamento';
          wsql_aux = wsql_aux||'                      where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||wcodigoplano;
          wsql_aux = wsql_aux||'                      and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||''' and';
          wsql_aux = wsql_aux||'                      bdctalon = '''||wclassificacao||'''),0)';
          wsql_aux = wsql_aux||'            + '||wsaldo_debito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||wcodigoplano;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bdctalon = '''||wclassificacao||''' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        END
    END
  -- BUSCA VALORES A DEBITO FIM -----------------------------------------------------------------------------------------------------------------

 -- BUSCA VALORES A CREDITO INICIO -----------------------------------------------------------------------------------------------------------------
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    BEGIN
      -- centro de custo
      --#alt:5837.
      --wsql = wsql||'SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';
      wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';

      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'coalesce(sum(tlcc.bdvalor),0) as valor_credito ';
      ELSE
        BEGIN
          wsql = wsql||'coalesce(sum(tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                                     (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))),0) as valor_credito ';
        END
       --alt:6178 - Fim

      wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
      wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
    END
  ELSE
    BEGIN
      -- lancamentos
      --#alt:5837.
      --wsql = wsql || 'select tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';
      wsql = wsql || 'select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';

      --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'coalesce(sum(tlan.bdvalor),0) as valor_credito ';
      ELSE
        BEGIN
          wsql = wsql||'coalesce(sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                                     (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))),0) as valor_credito ';
        END
      --alt:6178 - Fim

      wsql = wsql || 'from vsuc_empresas_tlan tlan ';
    END
  wsql = wsql || 'left outer join VSUC_EMPRESAS_REL_TORCAMENTO tbal on ((tlan.bdcodplapadrao = tbal.bdcodplapadrao) and (tlan.bdcredito = tbal.bdcodtpla)) ';
  wsql = wsql || 'where (tbal.bdcodplapadrao = '||prcodplapadrao||') ';
  IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tbal.bdtipcta = 1) ';
  wsql = wsql || 'and (tlan.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql||'and ((tlan.bdcodemp = '||prcodigoemp||') or (tlan.bdfilial = '||prcodigoemp||')) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon ';
  wsql = wsql || 'Order By tbal.bdctalon Desc ';

  -- pega a classificacao e o saldo total das analiticas _______________________
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wcodigoplano,:wcodtpla,:wclassificacao,:wsaldo_credito DO
    BEGIN
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          -- faz update no credito, pq ja foi gravado o lancamento antes zerado __
          --#alt:5837.
          /*update vsuc_empresas_rel_torcamento set BDCREDITO = :wsaldo_credito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :wcodigoplano
          and   bdcodtpla = :wcodtpla
          and   bdctalon = :wclassificacao
          and   bddatahora = :prdatahora
          and   ((BDCREDITO = 0) or (bdcredito is null)); */
          wsql_aux = 'update vsuc_empresas_rel_torcamento set ';
          wsql_aux = wsql_aux||'BDCREDITO = (coalesce((select BDCREDITO from vsuc_empresas_rel_torcamento';
          wsql_aux = wsql_aux||'                       where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||wcodigoplano;
          wsql_aux = wsql_aux||'                       and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||''' and';
          wsql_aux = wsql_aux||'                       bdctalon = '''||wclassificacao||'''),0)';
          wsql_aux = wsql_aux||'            + '||wsaldo_credito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||wcodigoplano;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bdctalon = '''||wclassificacao||''' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        END
    END
  -- BUSCA VALORES A CREDITO FIM -----------------------------------------------------------------------------------------------------------------

  -- BUSCA VALORES ORCADOS INICIO ---------------------------------------------------------------------------------------------------------------

  -- BUSCA VALORES ORCADOS FIM ---------------------------------------------------------------------------------------------------------------

  FOR SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta
      FROM vsuc_empresas_rel_torcamento tbal
      WHERE tbal.bdtipcta = 0
            AND bddatahora = :prdatahora
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta DO
      BEGIN
        -- fas um select para totalizar as contas titulos ______________________
        SELECT SUM(tbal.BDdebito) AS valor_debito, SUM(tbal.BDcredito) AS valor_credito
        FROM vsuc_empresas_rel_torcamento tbal
        WHERE SUBSTRING(bdctalon FROM 1 FOR strlen(:wclassificacao)) = :wclassificacao
              AND bddatahora = :prdatahora
        GROUP BY SUBSTRING(bdctalon FROM 1 FOR strlen(:wclassificacao))
        INTO :wsaldo_debito, :wsaldo_credito;

        -- da um update na tabela de balancete para gravar os totais ___________
        UPDATE vsuc_empresas_rel_torcamento SET BDDEBITO = :wsaldo_debito,
                                            BDCREDITO = :wsaldo_credito
        WHERE bdcodemp = :prcodigoemp
        AND   bdcodplapadrao = :wcodigoplano
        AND   bdcodtpla = :wcodtpla
        AND   bdctalon = :wclassificacao
        AND   bddatahora = :prdatahora;
      END

  -- faz o select na tabela de balancete e monta os retornos para a impressao
  FOR SELECT bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
             BDDEBITO, BDCREDITO, bdformula, bdrelcta
      FROM vsuc_empresas_rel_torcamento tbal
      WHERE bddatahora = :prdatahora
      ORDER BY bdctalon ASC
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta,
       :wsaldo_debito, :wsaldo_credito, :formula, :relconta DO
      BEGIN
        codemp = :prcodigoemp;
        codplapadrao = :wcodigoplano;
        conta  = :wcodtpla;
        classificacao = :wclassificacao;
        nomeconta = :wnomcta;
        tipconta = :wtipcta;
        grupoconta = :wgrpcta;

        saldo_debsaida = :wsaldo_debito;
        saldo_cresaida = :wsaldo_credito;

        IF (saldo_debsaida IS NULL) THEN
           saldo_debsaida = 0;

        IF (saldo_cresaida IS NULL) THEN
           saldo_cresaida = 0;

        IF (wgrpcta IN (1,2,3)) THEN
           BDREALIZADO = (saldo_cresaida - saldo_debsaida);
        ELSE
           BDREALIZADO = (saldo_debsaida - saldo_cresaida);

        -- Filtro pelo n?vel da conta
        SELECT contar_char FROM contar_char(:wclassificacao,'.') INTO :wnivelconta;
        wnivelconta = wnivelconta + 1;
        SELECT BDRPOS FROM RPOS(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',') INTO :windice;
        IF ((prniveisconta = '9999') OR           -- N?o tem filtro
            (wnivelconta = 1) OR                  -- O primeiro n?vel sempre imprime
            ((windice > 0) AND (:wtipcta = 0)) OR -- O n?vel da conta foi selecionado no filtro e ? t?tulo
            ((windice > 0) AND (wimpanalitica > 0) AND (:wtipcta = 1))) THEN -- ? do n?vel selecionado, anal?tica e foi selecionado para imprimir as contas anal?ticas
          SUSPEND;
      END

  DELETE FROM vsuc_empresas_rel_torcamento WHERE bddatahora = :prdatahora;
END
^

/* Alter (VSUC_SP_RETORNA_SALDOS_CTA_PART) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_CTA_PART(PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDTINICIAL DATE,
PRDTFINAL DATE,
PRCONTA INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCODTERCEIRO INTEGER,
PRRETORNAAPENASCONTAS INTEGER,
PRCONCILIADOS INTEGER,
PREMPRESAS VARCHAR(2048),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDNOME VARCHAR(100),
BDCLASSIFICACAO VARCHAR(40),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDCODPARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wcodterceiro INTEGER;
DECLARE VARIABLE wnomterceiro VARCHAR(100);
DECLARE VARIABLE wdebito INTEGER;
DECLARE VARIABLE wcredito INTEGER;
DECLARE VARIABLE wsql VARCHAR(3000);
DECLARE VARIABLE wsql_aux VARCHAR(3000);
DECLARE VARIABLE wdtinicial VARCHAR(10);
DECLARE VARIABLE wdtfinal VARCHAR(10);
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wsaldo_deb NUMERIC(15,2);
DECLARE VARIABLE wsaldo_cre NUMERIC(15,2);
DECLARE VARIABLE wsaldo_ant_deb NUMERIC(15,2);
DECLARE VARIABLE wsaldo_ant_cre NUMERIC(15,2);
DECLARE VARIABLE wpos_pernamatriz INTEGER;
DECLARE VARIABLE wpos_matriz INTEGER;
DECLARE VARIABLE wpos_filial INTEGER;
DECLARE VARIABLE wcampo INTEGER;
DECLARE VARIABLE wexist_debito INTEGER;
DECLARE VARIABLE wexist_credito INTEGER;
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wposant INTEGER;
BEGIN
/*
conciliados
0 = normal
1 = conciliados
2 = n?o conciliados
3 = todos
*/
  bdnome           = '';
  bdsaldo_deb      = 0;
  bdsaldo_ant_deb  = 0;
  bdsaldo_cre      = 0;
  bdsaldo_ant_cre  = 0;
  bdsaldo_anterior = 0;
  bdsaldo_atual    = 0;

  IF ((prconta = 0) OR (prconta IS NULL)) THEN
    EXIT;

  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prconta
  INTO :bdclassificacao, :wgrupocta;

  wdtinicial = prdtinicial;
  wdtfinal   = prdtfinal;


  wsql = 'select tlan.bdcodter, terc.bdnometer, sum(bddebito), sum(bdcredito) from (';
  wsql = wsql||'select distinct tlan.bdcodterceirod as bdcodter,';--alt:#6535 - gilberto - 05/09/2013
  wsql = wsql||'1 as bddebito, 0 as bdcredito ';
  wsql = wsql||'from ';
  wsql = wsql||'( ';
  wsql = wsql||'  select distinct x.bdcodterceirod ';
  wsql = wsql||'  from vsuc_empresas_tlan x ';
  wsql = wsql||'  where x.bdcodterceirod is not null ';
  wsql = wsql||'  and ((x.bdcodemp in ('||prcodemp||')) or (x.bdfilial = '||prcodemp||'))';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'  and (x.bdcontabilizacao in (0,'||prcontabilizacao||'))';
  wsql = wsql||'  and (x.bddebito = '||prconta||') ';--alt:#6535 - gilberto - 05/09/2013

  IF (prcodterceiro > 0) THEN
    wsql = wsql||'    and x.bdcodterceirod = ' || prcodterceiro;

  wsql = wsql||') tlan ';
  wsql = wsql||'union ';
  wsql = wsql||'select distinct tlan.bdcodterceiroc as bdcodter, ';--alt:#6535 - gilberto - 05/09/2013
  wsql = wsql||'0 as bddebito, 1 as bdcredito ';
  wsql = wsql||'from ';
  wsql = wsql||'( ';
  wsql = wsql||'  select distinct x.bdcodterceiroc ';
  wsql = wsql||'  from vsuc_empresas_tlan x ';
  wsql = wsql||'  where x.bdcodterceiroc is not null ';
  wsql = wsql||'  and ((x.bdcodemp in ('||prcodemp||')) or (x.bdfilial = '||prcodemp||'))';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'  and (x.bdcontabilizacao in (0,'||prcontabilizacao||'))';
  wsql = wsql||'  and (x.bdcredito = '||prconta||') ';--alt:#6535 - gilberto - 05/09/2013

  IF (prcodterceiro > 0) THEN
    wsql = wsql||'    and x.bdcodterceiroc = ' || prcodterceiro;

  wsql = wsql||') tlan ';
  wsql = wsql||') tlan ';

  wsql = wsql||'inner join (select RF.bdcodter, RF.bdnometer ';
  wsql = wsql||'            from tterceiro_ref RF ';
  wsql = wsql||'            where RF.bdREFEMP = (select max(RF2.bdREFEMP) ';
  wsql = wsql||'                                 from TTERCEIRO_REF RF2 ';
  wsql = wsql||'                                 where RF.bdCODTER = RF2.bdCODTER)) terc on (terc.bdcodter = tlan.bdcodter) ';

  wsql = wsql||' group by bdcodter, bdnometer';

  FOR EXECUTE STATEMENT wsql
  INTO :wcodterceiro,:wnomterceiro, :WEXIST_DEBITO, :WEXIST_CREDITO DO
  BEGIN
    wsaldo_deb       = 0;
    wsaldo_cre       = 0;
    wsaldo_ant_deb   = 0;
    wsaldo_ant_cre   = 0;
    bdsaldo_deb      = 0;
    bdsaldo_ant_deb  = 0;
    bdsaldo_cre      = 0;
    bdsaldo_ant_cre  = 0;
    bdsaldo_anterior = 0;
    bdsaldo_atual    = 0;
    wsql_aux         = '';

    -- Pode ser que queira apenas montar as contas de participantes sem precisar dos saldos
    IF ((prretornaapenascontas = 0) OR (prretornaapenascontas IS NULL)) THEN
      BEGIN
        -- d?bito
        IF (wexist_debito = 1) THEN
           BEGIN
             wsql_aux = 'select tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bddebito, ';
             wsql_aux = wsql_aux||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor else 0 end) as bddebito_anterior, ';
             IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
                wsql_aux = wsql_aux||'sum(case when (((tlan.bddata > '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then tlan.bdvalor else 0 end) as bddebito_atual ';
             ELSE
                wsql_aux = wsql_aux||'sum(coalesce(tlan.bdvalor, 0)) as bddebito_atual_com_zeramento ';
             wsql_aux = wsql_aux||'from vsuc_empresas_tlan tlan ';
--             wsql_aux = wsql_aux||'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
             wsql_aux = wsql_aux||'where (tlan.bddata <= '''||prdtfinal||''') ';
             wsql_aux = wsql_aux||'and (bdcodplapadrao+0 = '||prcodplapadrao||') ';
             wsql_aux = wsql_aux||'and ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial = '||prcodemp||')) ';
             IF (prcontabilizacao <> 99) THEN
                wsql_aux = wsql_aux||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
             wsql_aux = wsql_aux||'and (tlan.bddebito = '||prconta||') ';
             wsql_aux = wsql_aux||'and (tlan.bdcodterceirod = '||wcodterceiro||') ';
             IF (prconciliados = 1) THEN
                wsql_aux = wsql_aux||' and (upper(bdconcd) = '''||'TRUE'||''') ';
             ELSE
             IF (prconciliados = 2) THEN
                wsql_aux = wsql_aux||' and ((tlan.bdconcd is null) or (upper(tlan.bdconcd) = '''||'FALSE'||''')) ';
             wsql_aux = wsql_aux||'group by tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bddebito ';
     
             FOR EXECUTE STATEMENT wsql_aux INTO :wcodemp, :wfilial, :wtipolancfilial, :wdebito, :wsaldo_ant_deb, :wsaldo_deb DO
               BEGIN
                 IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
                    BEGIN
                      wpos_pernamatriz = POSITION(wcodemp, prempresas);
                      wpos_matriz = POSITION(prcodemp, prempresas);
                      wpos_filial = POSITION(wfilial, prempresas);
                    END
                  wcampo = 1;
              
                  IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
                     wpermite = 1;
                  ELSE
                  IF (((wcodemp = prcodemp) AND (wfilial = 0)) OR
                      --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
                      ((wcodemp = wfilial) AND (wcampo = wtipolancfilial)) OR
                      --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                      ((wcodemp = prcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                      --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
                      ((prmatrizfilialconsolidado = 1) AND (wcodemp <> prcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                      --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
                      ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
                     wpermite = 1;
                  ELSE
                     wpermite = 0;
     
     --            select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prempresas) into :wpermite;
                 IF (wpermite = 1) THEN
                    BEGIN
                      bdsaldo_deb = bdsaldo_deb + wsaldo_deb;
                      bdsaldo_ant_deb = bdsaldo_ant_deb + wsaldo_ant_deb;
                    END
               END
           END

        -- cr?dito
        IF (wexist_credito = 1) THEN
           BEGIN
             wsql_aux = 'select tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bdcredito, ';
             wsql_aux = wsql_aux||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor else 0 end) as bdcredito_anterior, ';
             IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
                wsql_aux = wsql_aux||'sum(case when (((tlan.bddata > '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then tlan.bdvalor else 0 end) as bdcredito_atual ';
             ELSE
                wsql_aux = wsql_aux||'sum(coalesce(tlan.bdvalor, 0)) as bdcredito_atual_com_zeramento ';
             wsql_aux = wsql_aux||'from vsuc_empresas_tlan tlan ';
--             wsql_aux = wsql_aux||'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
             wsql_aux = wsql_aux||'where (tlan.bddata <= '''||prdtfinal||''') ';
             wsql_aux = wsql_aux||'and (bdcodplapadrao+0 = '||prcodplapadrao||') ';
             wsql_aux = wsql_aux||'and ((tlan.bdcodemp in ('||prcodemp||')) or (tlan.bdfilial = '||prcodemp||')) ';
             IF (prcontabilizacao <> 99) THEN
                wsql_aux = wsql_aux||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
             wsql_aux = wsql_aux||'and (tlan.bdcredito = '||prconta||') ';
             wsql_aux = wsql_aux||'and (tlan.bdcodterceiroc = '||wcodterceiro||') ';
             IF (prconciliados = 1) THEN
                wsql_aux = wsql_aux||' and (upper(bdconcc) = '''||'TRUE'||''') ';
             ELSE
             IF (prconciliados = 2) THEN
                wsql_aux = wsql_aux||' and ((tlan.bdconcc is null) or (upper(tlan.bdconcc) = '''||'FALSE'||''')) ';
             wsql_aux = wsql_aux||'group by tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, tlan.bdcredito ';
     
             FOR EXECUTE STATEMENT wsql_aux INTO :wcodemp, :wfilial, :wtipolancfilial, :wcredito, :wsaldo_ant_cre, :wsaldo_cre DO
               BEGIN
                 IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
                    BEGIN
                      wpos_pernamatriz = POSITION(wcodemp, prempresas);
                      wpos_matriz = POSITION(prcodemp, prempresas);
                      wpos_filial = POSITION(wfilial, prempresas);
                    END
                  wcampo = 2;
              
                  IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
                     wpermite = 1;
                  ELSE
                  IF (((wcodemp = prcodemp) AND (wfilial = 0)) OR
                      --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
                      ((wcodemp = wfilial) AND (wcampo = wtipolancfilial)) OR
                      --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                      ((wcodemp = prcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                      --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
                      ((prmatrizfilialconsolidado = 1) AND (wcodemp <> prcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                      --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
                      ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
                     wpermite = 1;
                  ELSE
                     wpermite = 0;
                  -------------------------------------------------------------------alt:#6524
     
     --            select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prempresas) into :wpermite;
                 IF (wpermite = 1) THEN
                    BEGIN
                      bdsaldo_cre = bdsaldo_cre + wsaldo_cre;
                      bdsaldo_ant_cre = bdsaldo_ant_cre + wsaldo_ant_cre;
                    END
               END
           END

      bdcodparticipante = wcodterceiro;
      bdnome            = SUBSTRING(wnomterceiro FROM 1 FOR 100);

      wpos = 0;
      wposant = 0;
      WHILE (wpos > 0) DO
        BEGIN
          wpos = POSITION('.', bdclassificacao, wpos);
          wposant = wpos;
        END
      bdclassificacao = SUBSTRING(bdclassificacao FROM 1 FOR wposant)||LPAD(wcodterceiro, 8, '0');


      IF (wgrupocta IN (1,2,3)) THEN
         bdsaldo_anterior = (bdsaldo_ant_cre - bdsaldo_ant_deb);
      ELSE
         bdsaldo_anterior = (bdsaldo_ant_deb - bdsaldo_ant_cre);
  
      IF (wgrupocta IN (1,2,3)) THEN
         bdsaldo_atual = (bdsaldo_cre - bdsaldo_deb);
      ELSE
         bdsaldo_atual = (bdsaldo_deb - bdsaldo_cre);
  
      bdsaldo_cre = bdsaldo_cre - bdsaldo_ant_cre;
      bdsaldo_deb = bdsaldo_deb - bdsaldo_ant_deb;
      SUSPEND;
    END
  END
END
^

/* Alter (VSUC_SP_RETORNA_SALDOS_CTAINCOR) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_CTAINCOR(PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDTINICIAL DATE,
PRDTFINAL DATE,
PRCONTA INTEGER,
PRINDICE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCONCILIADOS INTEGER,
PREMPRESAS VARCHAR(2048),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRCTALONANT VARCHAR(40),
PRCTATITULO INTEGER,
PRRAIZCTASEMEMPREENDIMENTOANT VARCHAR(40),
PRDETALHAREMPREENDIMENTO INTEGER,
PRDETALHARUNIDIMOB INTEGER)
 RETURNS(BDCLASSIFICACAO VARCHAR(40),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDMOVIMENTO NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDRAIZCLASSIFICACAOCTA VARCHAR(40),
BDCODEMPREENDIMENTO INTEGER,
BDCODUNIDIMOB INTEGER,
BDDESCEMPREENDIMENTO VARCHAR(500),
BDDESCUNIDIMOB VARCHAR(500),
BDRAIZCTASEMEMPREENDIMENTO VARCHAR(40))
 AS
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WSQLSUMSALDO VARCHAR(10000);
DECLARE VARIABLE WSQLWHERELAND VARCHAR(10000);
DECLARE VARIABLE WSQLWHERELANC VARCHAR(10000);
DECLARE VARIABLE WSQL_EMP VARCHAR(5000);
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPOS_PERNAMATRIZ INTEGER;
DECLARE VARIABLE WPOS_MATRIZ INTEGER;
DECLARE VARIABLE WPOS_FILIAL INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WPOSANT INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WEMPRESAS VARCHAR(2048);
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WOR VARCHAR(4);
DECLARE VARIABLE WSALDO_DEB NUMERIC(15,6);
DECLARE VARIABLE WSALDO_ANT_DEB NUMERIC(15,6);
DECLARE VARIABLE WSALDO_CRE NUMERIC(15,6);
DECLARE VARIABLE WSALDO_ANT_CRE NUMERIC(15,6);
DECLARE VARIABLE WDEBCRE INTEGER;
DECLARE VARIABLE WCODEMPREENDIMENTO INTEGER;
DECLARE VARIABLE WCODUNIDIMOB INTEGER;
DECLARE VARIABLE WDESCEMPREENDIMENTO VARCHAR(500);
DECLARE VARIABLE WDESCUNIDIMOB VARCHAR(500);
DECLARE VARIABLE WCLASSIFICACAOAUX VARCHAR(40);
DECLARE VARIABLE WCOUNTNIVELCTA INTEGER;
DECLARE VARIABLE WCOUNTNIVELCTAAUX INTEGER;
DECLARE VARIABLE WUSAEMPREENDIMENTO VARCHAR(5);
DECLARE VARIABLE WUSAUNIDIMOB VARCHAR(5);
BEGIN
  wcountnivelcta    = 0;
  wcountnivelctaaux = 0;

  SELECT BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB FROM PLANOS_TPLA
  WHERE BDCODPLAPADRAO = :PRCODPLAPADRAO AND
        BDCODTPLA = :PRCONTA
  INTO :WUSAEMPREENDIMENTO, :WUSAUNIDIMOB;

  IF (((wusaempreendimento IS NULL) OR (wusaempreendimento = '') OR (UPPER(wusaempreendimento) = 'FALSE') ) AND
      ((wusaunidimob IS NULL) OR (wusaunidimob = '') OR (UPPER(wusaunidimob) = 'FALSE'))) THEN
      EXIT;

  IF ((prconta = 0) OR (prconta IS NULL)) THEN
    EXIT;

  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prconta
  INTO :wclassificacao, :wgrupocta;

  wempresas = '';
  SELECT COALESCE(bdCODMATRIZ,0) FROM tempresas WHERE bdCODEMP = :prCodEmp INTO :wCodEmp;
  IF (wCodEmp > 0) THEN
     BEGIN
       FOR SELECT bdcodemp FROM tempresas
           WHERE (bdcodmatriz = COALESCE((SELECT FIRST 1 bdcodmatriz FROM tempresas WHERE bdcodemp = :prcodemp), :prcodemp)) OR
                 (bdcodemp = COALESCE((SELECT FIRST 1 bdcodmatriz FROM tempresas WHERE bdcodemp = :prcodemp), :prcodemp))
       INTO :wCodEmp DO
         BEGIN
           wempresas = wempresas || wCodEmp || ',';
         END
     END

  IF (wempresas = '') THEN
     wempresas = prempresas || ',';

  wsql_emp = ' and (';
  wor = '';
  WHILE (wempresas <> '') DO
    BEGIN
      wpos = POSITION(',', wempresas);
      IF (SUBSTRING(wempresas FROM 1 FOR wpos-1) <> prcodemp) THEN
         BEGIN
           wsql_emp = wsql_emp||wor||'(tlan.bdcodemp = '||SUBSTRING(wempresas FROM 1 FOR wpos-1)||' and bdfilial = '||prcodemp||')';
           wor = ' or ';
         END
      wempresas = SUBSTRING(wempresas FROM wpos+1 FOR strlen(wempresas));
    END
   IF (POSITION(',', prempresas) > 0) THEN
      wsql_emp = wsql_emp||' or (tlan.bdcodemp = '||prcodemp||')';
   ELSE
      wsql_emp = wsql_emp||wor||'(tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')';
   wsql_emp = wsql_emp||') ';

  --SQL padr?o para somar o saldo
  wsqlsumsaldo = '';
  IF (prindice = 0) THEN
    BEGIN
      wsqlsumsaldo = wsqlsumsaldo||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor else 0 end) as bdsalant, ';
      IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
        wsqlsumsaldo = wsqlsumsaldo||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then tlan.bdvalor else 0 end) as bdsalatu ';
      ELSE
        wsqlsumsaldo = wsqlsumsaldo||'sum(coalesce(tlan.bdvalor, 0)) as bdsalatu ';
    END
  ELSE
    BEGIN
      wsqlsumsaldo = wsqlsumsaldo||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      wsqlsumsaldo = wsqlsumsaldo||'                                                                                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
      IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
        BEGIN
          wsqlsumsaldo = wsqlsumsaldo||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then ';
          wsqlsumsaldo = wsqlsumsaldo||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsqlsumsaldo = wsqlsumsaldo||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END
      ELSE
        BEGIN
          wsqlsumsaldo = wsqlsumsaldo||'sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsqlsumsaldo = wsqlsumsaldo||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdsalatu ';-- com zeramento
        END
    END

  --SQL de tratamento dos lan?amentos a d?bito
  wsqlwhereland = '';
  wsqlwhereland = wsqlwhereland || 'and (tlan.bdcodplapadrao+0 = '||:prcodplapadrao||') ';
  wsqlwhereland = wsqlwhereland || 'and (tlan.bddata <= '''||:prdtfinal||''') ';
  IF (prcontabilizacao <> 99) THEN
    wsqlwhereland = wsqlwhereland||'and (tlan.bdcontabilizacao in (0,'||:prcontabilizacao||'))';
  IF (prconciliados = 1) THEN
    wsqlwhereland = wsqlwhereland||'and (upper(tlan.bdconcd) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
    wsqlwhereland = wsqlwhereland||'and ((tlan.bdconcd is null) or (upper(tlan.bdconcd) = '''||'FALSE'||''')) ';

  --SQL de tratamento dos lan?amentos a cr?dito
  wsqlwherelanc = '';
  wsqlwherelanc = wsqlwherelanc || 'and (tlan.bdcodplapadrao+0 = '||:prcodplapadrao||') ';
  wsqlwherelanc = wsqlwherelanc || 'and (tlan.bddata <= '''||:prdtfinal||''') ';
  IF (prcontabilizacao <> 99) THEN
    wsqlwherelanc = wsqlwherelanc||'and (tlan.bdcontabilizacao in (0,'||:prcontabilizacao||'))';
  IF (prconciliados = 1) THEN
    wsqlwherelanc = wsqlwherelanc||' and (upper(tlan.bdconcc) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
    wsqlwherelanc = wsqlwherelanc||' and ((tlan.bdconcc is null) or (upper(tlan.bdconcc) = '''||'FALSE'||''')) ';


  --Busca os totais das contas t?tulos
  wsql = '';
  wsql = wsql || 'select TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE, ';
  wsql = wsql || '       sum(case when (bddebcre = 0) then bdsalant else 0 end) as bddebant, ';
  wsql = wsql || '       sum(case when (bddebcre = 0) then bdsalatu else 0 end) as bddebatu, ';
  wsql = wsql || '       sum(case when (bddebcre = 1) then bdsalant else 0 end) as bdcreant, ';
  wsql = wsql || '       sum(case when (bddebcre = 1) then bdsalatu else 0 end) as bdcreatu ';
  wsql = wsql || 'from ( ';
                        --*****D?BITO****
  wsql = wsql || '      select TLAN.BDCODEMP, 0 as BDDEBCRE, case when TINCORP.BDCODEMPREENDIMENTO is null then 0 else TINCORP.BDCODEMPREENDIMENTO end as BDCODEMPREENDIMENTO, ';
  wsql = wsql ||        wsqlsumsaldo;
  wsql = wsql || '      from PLANOS_TPLA TCTA ';
  wsql = wsql || '      inner join VSUC_EMPRESAS_TLAN TLAN on (TLAN.BDCODPLAPADRAO = TCTA.BDCODPLAPADRAO and TLAN.BDDEBITO = TCTA.BDCODTPLA) ';
  wsql = wsql || '      left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';
  wsql = wsql || '      left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TINCORP.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
  wsql = wsql || '      where BDCTALON like('''||:wclassificacao||'%'') ';
  wsql = wsql ||        wsqlwhereland;
  wsql = wsql ||        wsql_emp;
  wsql = wsql || '      group by TLAN.BDCODEMP, BDDEBCRE, TINCORP.BDCODEMPREENDIMENTO ';
  wsql = wsql || '      union ';
                        --*****CR?DITO****
  wsql = wsql || '      select TLAN.BDCODEMP, 1 as BDDEBCRE, case when TINCORP.BDCODEMPREENDIMENTO is null then 0 else TINCORP.BDCODEMPREENDIMENTO end as BDCODEMPREENDIMENTO, ';
  wsql = wsql ||        wsqlsumsaldo;
  wsql = wsql || '      from PLANOS_TPLA TCTA ';
  wsql = wsql || '      inner join VSUC_EMPRESAS_TLAN TLAN on (TLAN.BDCODPLAPADRAO = TCTA.BDCODPLAPADRAO and TLAN.BDCREDITO = TCTA.BDCODTPLA) ';
  wsql = wsql || '      left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';
  wsql = wsql || '      left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TINCORP.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
  wsql = wsql || '      where BDCTALON like('''||:wclassificacao||'%'') ';
  wsql = wsql ||        wsqlwherelanc;
  wsql = wsql ||        wsql_emp;
  wsql = wsql || '      group by TLAN.BDCODEMP, BDDEBCRE, TINCORP.BDCODEMPREENDIMENTO ';
  wsql = wsql || ') TLAN ';
  wsql = wsql || 'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
  wsql = wsql || 'group by TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE ';


  FOR EXECUTE STATEMENT wsql
  INTO :wcodempreendimento, :wdescempreendimento, :wsaldo_ant_deb, :wsaldo_deb, :wsaldo_ant_cre, :wsaldo_cre DO
  BEGIN

    IF ((prdetalharempreendimento = 1) AND (prctatitulo = 0)) THEN
      BEGIN
        IF (wgrupocta IN (1,2,3)) THEN
          bdsaldo_anterior = (wsaldo_ant_cre - wsaldo_ant_deb);
        ELSE
          bdsaldo_anterior = (wsaldo_ant_deb - wsaldo_ant_cre);
     
        IF (wgrupocta IN (1,2,3)) THEN
          bdsaldo_atual = (wsaldo_cre - wsaldo_deb);
        ELSE
          bdsaldo_atual = (wsaldo_deb - wsaldo_cre);

                                   bdsaldo_ant_cre = wsaldo_ant_cre;
                                   bdsaldo_ant_deb = wsaldo_ant_deb;
        bdsaldo_cre = wsaldo_cre - wsaldo_ant_cre;
        bdsaldo_deb = wsaldo_deb - wsaldo_ant_deb;
        bdmovimento = bdsaldo_atual - bdsaldo_anterior;

        wcodtpla = 0;
        SELECT TCTA.bdcodtpla FROM PLANOS_TPLA TCTA
        WHERE BDCTALON LIKE(:prctalonant) AND
              BDCODPLAPADRAO + 0 = :prcodplapadrao
        INTO  :wcodtpla;

        wpos = 1;
        wposant = 0;
        bdclassificacao = wclassificacao;
        WHILE (POSITION('.', bdclassificacao) > 0) DO
          BEGIN
            wpos = wpos + POSITION('.', bdclassificacao);
            bdclassificacao = SUBSTRING(wclassificacao FROM wpos FOR strlen(wclassificacao));
            wposant = wpos;
            wcountnivelcta = wcountnivelcta + 1;
          END

        IF (wcodtpla <> 0) THEN
          BEGIN
            bdclassificacao = SUBSTRING(wclassificacao FROM 1 FOR wposant-1)||LPAD(wcodempreendimento, 9, '0');
            bdraizctasemempreendimento = SUBSTRING(wclassificacao FROM 1 FOR wposant-2);
          END
        ELSE
          BEGIN
            IF (prraizctasemempreendimentoant IS NOT NULL) THEN
              BEGIN
                wclassificacaoaux = prraizctasemempreendimentoant||'.'||LPAD(wcodempreendimento, 9, '0');
                wpos = strlen(wclassificacaoaux)+ 1;
                prctalonant = wclassificacaoaux||SUBSTRING(prctalonant FROM wpos FOR strlen(prctalonant));
                wclassificacaoaux = prctalonant;

                wpos = 1;
                wposant = 0;
                WHILE (POSITION('.', wclassificacaoaux) > 0) DO
                  BEGIN
                    wpos = wpos + POSITION('.', wclassificacaoaux);
                    wclassificacaoaux = SUBSTRING(prctalonant FROM wpos FOR strlen(prctalonant));
                    wposant = wpos;
                    wcountnivelctaaux = wcountnivelctaaux + 1;
                  END

                IF (wcountnivelctaaux >= wcountnivelcta) THEN
                  prctalonant = SUBSTRING(prctalonant FROM 1 FOR wposant-2);
              END
            bdclassificacao = prctalonant||'.'||bdclassificacao;
          END

        bdcodempreendimento = wcodempreendimento;
        bddescempreendimento= wdescempreendimento;

        IF (wdescempreendimento IS NULL) THEN
          bddescempreendimento = 'Sem empreendimento imobili?rio';

        SUSPEND;
      END
    ELSE
      BEGIN
        wsql = '';
        wsql = 'select TLAN.BDCODEMP, TLAN.BDFILIAL, TLAN.BDTIPOLANCFILIAL, TLAN.BDCODTPLA, TLAN.BDDEBCRE, ';
        wsql = wsql||' TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE, TLAN.BDCODIGOUNIIMOB, TCADUNID.BDDESCRICAO, ';
        wsql = wsql||'       sum(case when (bddebcre = 0) then bdsalant else 0 end) as bddebant, ';
        wsql = wsql||'       sum(case when (bddebcre = 0) then bdsalatu else 0 end) as bddebatu, ';
        wsql = wsql||'       sum(case when (bddebcre = 1) then bdsalant else 0 end) as bdcreant, ';
        wsql = wsql||'       sum(case when (bddebcre = 1) then bdsalatu else 0 end) as bdcreatu ';
        wsql = wsql||' from ( ';
        --*******D?BITO******
        wsql = wsql||'select TLAN.BDCODEMP, TLAN.BDFILIAL, TLAN.BDCODPLAPADRAO, TLAN.BDTIPOLANCFILIAL, TLAN.BDDATA, TLAN.BDTIPOLAN, ';
       wsql = wsql||'       TLAN.BDDEBITO as BDCODTPLA, TLAN.BDCODTERCEIROD as BDCODTER, 0 as BDDEBCRE, TINCORPD.BDCODEMPREENDIMENTO,';
        IF ((prdetalharunidimob = 0) AND (wusaunidimob IS NOT NULL)) THEN
          wsql = wsql||'       null as BDCODIGOUNIIMOB, ';
        ELSE
          wsql = wsql||'       TINCORPD.BDCODIGOUNIIMOB, ';
        wsql = wsql||wsqlsumsaldo;
        wsql = wsql||'from VSUC_EMPRESAS_TLAN TLAN ';
        wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORPD on (TLAN.BDCODEMP = TINCORPD.BDCODEMP and TLAN.BDCHAVE = TINCORPD.BDCHAVE and TINCORPD.BDDEBCRE = 0) ';
        wsql = wsql||'where (tlan.bddebito = '||prconta||') ';
        wsql = wsql||wsqlwhereland;
        IF ((wcodempreendimento = 0) OR (wcodempreendimento IS NULL)) THEN
          wsql = wsql||'and (TINCORPD.BDCODEMPREENDIMENTO is null) ';
        ELSE
          wsql = wsql||'and (TINCORPD.BDCODEMPREENDIMENTO ='||:wcodempreendimento||') ';
        wsql = wsql||wsql_emp;
        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDFILIAL, TLAN.BDCODPLAPADRAO, TLAN.BDTIPOLANCFILIAL, TLAN.BDDATA, TLAN.BDDEBITO, TLAN.BDCODTERCEIROD, TLAN.BDTIPOLAN, TINCORPD.BDCODEMPREENDIMENTO, TINCORPD.BDCODIGOUNIIMOB ';
        wsql = wsql||'union all ';
        --******CR?DITO******
        wsql = wsql||'select TLAN.BDCODEMP, TLAN.BDFILIAL, TLAN.BDCODPLAPADRAO, TLAN.BDTIPOLANCFILIAL, TLAN.BDDATA, TLAN.BDTIPOLAN, ';
        wsql = wsql||'       TLAN.BDCREDITO as BDCODTPLA, TLAN.BDCODTERCEIROC as BDCODTER, 1 as BDDEBCRE, TINCORPC.BDCODEMPREENDIMENTO,';
        IF ((prdetalharunidimob = 0) AND (wusaunidimob IS NOT NULL)) THEN
          wsql = wsql||'     null as BDCODIGOUNIIMOB, ';
        ELSE
          wsql = wsql||'     TINCORPC.BDCODIGOUNIIMOB, ';
        wsql = wsql||wsqlsumsaldo;
        wsql = wsql||'from vsuc_empresas_tlan tlan ';
        wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORPC on (TLAN.BDCODEMP = TINCORPC.BDCODEMP and TLAN.BDCHAVE = TINCORPC.BDCHAVE and TINCORPC.BDDEBCRE = 1) ';
        wsql = wsql||'where (tlan.bdcredito = '||prconta||') ';
        wsql = wsql||wsqlwherelanc;
        IF ((wcodempreendimento = 0) OR (wcodempreendimento IS NULL)) THEN
          wsql = wsql||'and (TINCORPC.BDCODEMPREENDIMENTO is null) ';
        ELSE
          wsql = wsql||'and (TINCORPC.BDCODEMPREENDIMENTO ='||:wcodempreendimento||') ';
        wsql = wsql||wsql_emp;
        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDFILIAL, TLAN.BDCODPLAPADRAO, TLAN.BDTIPOLANCFILIAL, TLAN.BDDATA, TLAN.BDCREDITO, TLAN.BDCODTERCEIROC, TLAN.BDTIPOLAN, TINCORPC.BDCODEMPREENDIMENTO, TINCORPC.BDCODIGOUNIIMOB ';
        wsql = wsql||') tlan ';
        wsql = wsql||'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
        wsql = wsql||'left join VEF_BASE_TCADUNIDIMOBILIARIA TCADUNID on (TLAN.BDCODEMP = TCADUNID.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADUNID.BDCODEMPREENDIMENTO and TLAN.BDCODIGOUNIIMOB = TCADUNID.BDCODIGOUNIIMOB) ';
        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDFILIAL, TLAN.BDTIPOLANCFILIAL, TLAN.BDCODTPLA, TLAN.BDDEBCRE, TLAN.BDCODEMPREENDIMENTO, TLAN.BDCODIGOUNIIMOB, TCADEMPR.BDNOMEEMPRE, TCADUNID.BDDESCRICAO ';

        
        FOR EXECUTE STATEMENT wsql
        INTO :wcodemp, :wfilial, :wtipolancfilial, :wcodtpla, :wdebcre, :wcodempreendimento, :wdescempreendimento, :wcodunidimob, :wdescunidimob,
             :wsaldo_ant_deb, :wsaldo_deb, :wsaldo_ant_cre, :wsaldo_cre DO
        BEGIN
          IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
             wpermite = 1;
          ELSE
          BEGIN
            wpos_pernamatriz = POSITION(','||wcodemp||',', ','||prempresas||',');
            wpos_matriz      = POSITION(','||prcodemp||',', ','||prempresas||',');
            wpos_filial      = POSITION(','||wfilial||',', ','||prempresas||',');
        
            IF (((wcodemp = prcodemp) AND (wfilial = 0)) OR
                --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
                ((prcodemp = wfilial) AND (wdebcre = (wtipolancfilial -1))) OR
                --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                ((wcodemp = prcodemp) AND (wfilial <> 0) AND (wdebcre <> (wtipolancfilial - 1)) AND (wpos_pernamatriz > 0)) OR
                --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
                ((prmatrizfilialconsolidado = 1) AND (wcodemp <> prcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
                ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (wdebcre <> (wtipolancfilial -1)) AND (wpos_filial > 0))) THEN
               wpermite = 1;
            ELSE
               wpermite = 0;
          END
        
          IF (wpermite = 1) THEN
            BEGIN  
              IF ((wcodempreendimento IS NULL) OR (wcodempreendimento = 0) ) THEN
                BEGIN
                  wcodempreendimento   = 0;
                  bddescempreendimento = 'Sem empreendimento imobili?rio';
                END

              bdclassificacao = wclassificacao;
              bdraizclassificacaocta = wclassificacao;
              bdcodempreendimento = wcodempreendimento;
              bdcodunidimob = wcodunidimob;
              bddescempreendimento = wdescempreendimento;
              bddescunidimob = wdescunidimob;

              IF ((prraizctasemempreendimentoant IS NOT NULL) AND (prraizctasemempreendimentoant <> '')) THEN
                BEGIN
                  bdclassificacao = prraizctasemempreendimentoant||'.'||LPAD(wcodempreendimento, 9, '0');
                  wpos = strlen(bdclassificacao)+ 1;
                  prctalonant = bdclassificacao||SUBSTRING(prctalonant FROM wpos FOR strlen(prctalonant));
                END

              wpos = 1;
              wposant = 0;
              WHILE (POSITION('.', bdclassificacao) > 0) DO
                BEGIN
                  wpos = wpos + POSITION('.', bdclassificacao);
                  bdclassificacao = SUBSTRING(wclassificacao FROM wpos FOR strlen(wclassificacao));
                  wposant = wpos;
                END

              IF  ((prdetalharunidimob = 1) AND (UPPER(wusaunidimob) = 'TRUE')) THEN
                BEGIN
                  IF (wcodunidimob IS NULL) THEN
                    wcodunidimob = 0;
                  bdclassificacao = prctalonant||'.'||LPAD(wcodunidimob, 9, '0');
                END
              ELSE
                bdclassificacao = prctalonant||'.'||bdclassificacao;
        
              IF (wgrupocta IN (1,2,3)) THEN
                bdsaldo_anterior = (wsaldo_ant_cre - wsaldo_ant_deb);
              ELSE
                bdsaldo_anterior = (wsaldo_ant_deb - wsaldo_ant_cre);
             
              IF (wgrupocta IN (1,2,3)) THEN
                bdsaldo_atual = (wsaldo_cre - wsaldo_deb);
              ELSE
                bdsaldo_atual = (wsaldo_deb - wsaldo_cre);
        
                              bdsaldo_ant_cre = wsaldo_ant_cre;
                              bdsaldo_ant_deb = wsaldo_ant_deb;
              bdsaldo_cre = wsaldo_cre - wsaldo_ant_cre;
              bdsaldo_deb = wsaldo_deb - wsaldo_ant_deb;
              bdmovimento = bdsaldo_atual - bdsaldo_anterior;

              SUSPEND;
            END
        END
      END
  END
END
^

/* empty dependent procedure body */
/* Clear: VSUC_SP_RETORNA_COMPARATIVO for: VSUC_SP_RETORNA_SALDOS_CTAPARTY */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO(PREMPRESAS VARCHAR(1024),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRINDICE INTEGER,
PRTIPCOMP INTEGER,
PRCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP /* DM_BDNOMEMP */ VARCHAR(100),
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDFORMULA VARCHAR(1024))
 AS
 BEGIN SUSPEND; END
^

/* Alter (VSUC_SP_RETORNA_SALDOS_CTAPARTY) */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_CTAPARTY(PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDTINICIAL DATE,
PRDTFINAL DATE,
PRCONTA INTEGER,
PRINDICE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCODTERCEIRO INTEGER,
PRRETORNAAPENASCONTAS INTEGER,
PRCONCILIADOS INTEGER,
PREMPRESAS VARCHAR(2048),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDNOME VARCHAR(100),
BDCLASSIFICACAO VARCHAR(40),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDMOVIMENTO NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDCODPARTICIPANTE INTEGER,
BDRAIZCNPJPARTICIPANTE VARCHAR(10),
BDRAIZCLASSIFICACAOCTA VARCHAR(40))
 AS
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WSQL_AUX VARCHAR(10000);
DECLARE VARIABLE WSQL_EMP VARCHAR(5000);
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPOS_PERNAMATRIZ INTEGER;
DECLARE VARIABLE WPOS_MATRIZ INTEGER;
DECLARE VARIABLE WPOS_FILIAL INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WEMPRESAS VARCHAR(2048);
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WOR VARCHAR(4);
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
DECLARE VARIABLE WCNPJPART VARCHAR(18);
DECLARE VARIABLE WCNPJANTPART VARCHAR(10);
DECLARE VARIABLE WSALDO_DEB NUMERIC(15,6);
DECLARE VARIABLE WSALDO_ANT_DEB NUMERIC(15,6);
DECLARE VARIABLE WSALDO_CRE NUMERIC(15,6);
DECLARE VARIABLE WSALDO_ANT_CRE NUMERIC(15,6);
DECLARE VARIABLE WSALDO_ANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WSALDO_ATUAL NUMERIC(15,6);
DECLARE VARIABLE WNOME VARCHAR(100);
DECLARE VARIABLE WCODPAIS INTEGER;
DECLARE VARIABLE WCODPAISANT INTEGER;
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WDEBCRE INTEGER;
DECLARE VARIABLE WPARTEXTERIORANT INTEGER;
BEGIN
  wpartexteriorant = 0;

/* Conciliados
    0 = normal
    1 = conciliados
    2 = n?o conciliados
    3 = todos */

  IF ((prconta = 0) OR (prconta IS NULL)) THEN
    EXIT;

  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prconta
  INTO :wclassificacao, :wgrupocta;

  -- #Alt:15233 (In?cio) - Precisamos carregar todos os lan?amentos da matriz e filiais e depois controlar se deve imprimir ou
  -- n?o os dados. Isso ? necess?rio porque o usu?rio pode selecionar s? as filiais, mas tem casos que o lan?amento foi feito na
  -- na matriz e apenas uma perna est? na filial. Por isso preciso carregar os lan?amentos.
  wempresas = '';
  SELECT COALESCE(bdCODMATRIZ,0) FROM tempresas WHERE bdCODEMP = :prCodEmp INTO :wCodEmp;
  IF (wCodEmp > 0) THEN
     BEGIN
       FOR SELECT bdcodemp FROM tempresas
           WHERE (bdcodmatriz = COALESCE((SELECT FIRST 1 bdcodmatriz FROM tempresas WHERE bdcodemp = :prcodemp), :prcodemp)) OR
                 (bdcodemp = COALESCE((SELECT FIRST 1 bdcodmatriz FROM tempresas WHERE bdcodemp = :prcodemp), :prcodemp))
       INTO :wCodEmp DO
         BEGIN
           wempresas = wempresas || wCodEmp || ',';
         END
     END

  IF (wempresas = '') THEN
     wempresas = prempresas || ',';

  wsql_emp = ' and (';
  wor = '';
  WHILE (wempresas <> '') DO
    BEGIN
      wpos = POSITION(',', wempresas);
      IF (SUBSTRING(wempresas FROM 1 FOR wpos-1) <> prcodemp) THEN
         BEGIN
           wsql_emp = wsql_emp||wor||'(bdcodemp = '||SUBSTRING(wempresas FROM 1 FOR wpos-1)||' and bdfilial = '||prcodemp||')';
           wor = ' or ';
         END
      wempresas = SUBSTRING(wempresas FROM wpos+1 FOR strlen(wempresas));
    END
   IF (POSITION(',', prempresas) > 0) THEN
      wsql_emp = wsql_emp||' or (bdcodemp = '||prcodemp||')';
   ELSE
      wsql_emp = wsql_emp||wor||'(bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')';
   wsql_emp = wsql_emp||') ';
  -- #Alt:15233 (Fim)

  --alt:9167 - Alterado select para trazer a parte inicial do CNPJ e retirado o BDNOMETER, pois ele sempre retorna null aqui, ele ? setado no final, na hora de commitar. Pedro
  wsql = 'select bdcodemp, bdfilial, bdtipolancfilial, tlan.bdcodtpla, tlan.bdcodter, bdcgcter, bddebcre, '; --alt:14679 - Adicionado campo BDDEBCRE. Pedro
  wsql = wsql||'       sum(case when (bddebcre = 0) then bdsalant else 0 end) as bddebant, ';
  wsql = wsql||'       sum(case when (bddebcre = 0) then bdsalatu else 0 end) as bddebatu, ';
  wsql = wsql||'       sum(case when (bddebcre = 1) then bdsalant else 0 end) as bdcreant, ';
  wsql = wsql||'       sum(case when (bddebcre = 1) then bdsalatu else 0 end) as bdcreatu ';
  wsql = wsql||' from ( ';

  --****************************************************************************  D?bito  **************************************************************************************************
  wsql = wsql||'select tlan.bdcodemp, tlan.bdfilial, tlan.bdcodplapadrao, tlan.bdtipolancfilial, tlan.bddata, tlan.bdtipolan, ';
  wsql = wsql||'       tlan.bddebito as bdcodtpla, tlan.bdcodterceirod as bdcodter, ';
  wsql = wsql||'       0 as bddebcre, ';

  --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
  IF (prindice = 0) THEN
    BEGIN
      wsql = wsql||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor else 0 end) as bdsalant, ';
      IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
        wsql = wsql||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then tlan.bdvalor else 0 end) as bdsalatu ';
      ELSE
        wsql = wsql||'sum(coalesce(tlan.bdvalor, 0)) as bdsalatu ';-- com zeramento
    END
  ELSE
    BEGIN
      wsql = wsql||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      wsql = wsql||'                                                                                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
      IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
        BEGIN
          wsql = wsql||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then ';
          wsql = wsql||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END
      ELSE
        BEGIN
          wsql = wsql||'sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdsalatu ';-- com zeramento
        END
    END
  --alt:6178 - 09/11/2015 - Fim

  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||prcodplapadrao||') ';
  wsql = wsql||'and (tlan.bddata <= '''||prdtfinal||''') ';
  wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
     wsql = wsql||'and (tlan.bdcodterceirod = '||prcodterceiro||') ';
  ELSE
     wsql = wsql||'and (tlan.bdcodterceirod is not null) ';
  IF (prcontabilizacao <> 99) THEN
     wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';

  IF (prconciliados = 1) THEN
     wsql = wsql||' and (upper(tlan.bdconcd) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
     wsql = wsql||' and ((tlan.bdconcd is null) or (upper(tlan.bdconcd) = '''||'FALSE'||''')) ';

  wsql = wsql||wsql_emp;

  wsql = wsql||'group by tlan.bdcodemp, tlan.bdfilial, tlan.bdcodplapadrao, tlan.bdtipolancfilial, tlan.bddata, tlan.bddebito, tlan.bdcodterceirod, tlan.bdtipolan ';
  wsql = wsql||'union ';
  --****************************************************************************  Cr?dito  *************************************************************************************************
  wsql = wsql||'select tlan.bdcodemp, tlan.bdfilial, tlan.bdcodplapadrao, tlan.bdtipolancfilial, tlan.bddata, tlan.bdtipolan, ';
  wsql = wsql||'       tlan.bdcredito as bdcodtpla, tlan.bdcodterceiroc as bdcodter, ';
  wsql = wsql||'       1 as bddebcre, ';

  --alt:6178 - 09/11/2015 - Verifica se foi informado um ?ndice, caso positivo, divide o valor do lan?amento pelo valor do ?ndice na data. Fun??o dos relat?rios em outra moeda. Pedro
  IF (prindice = 0) THEN
    BEGIN
      wsql = wsql||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor else 0 end) as bdsalant, ';
      IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
         wsql = wsql||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then tlan.bdvalor else 0 end) as bdsalatu ';
      ELSE
         wsql = wsql||'sum(coalesce(tlan.bdvalor, 0)) as bdsalatu ';-- com zeramento
    END
  ELSE
    BEGIN
      wsql = wsql||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      wsql = wsql||'                                                                                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
      IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
        BEGIN
         wsql = wsql||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then ';
         wsql = wsql||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
         wsql = wsql||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END
      ELSE
        BEGIN
          wsql = wsql||'sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdsalatu ';-- com zeramento
        END
    END
  --alt:6178 - Fim

  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||prcodplapadrao||') ';
  wsql = wsql||'and (tlan.bddata <= '''||prdtfinal||''') ';
  wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
     wsql = wsql||'and (tlan.bdcodterceiroc = '||prcodterceiro||') ';
  ELSE
     wsql = wsql||'and (tlan.bdcodterceiroc is not null) ';
  IF (prcontabilizacao <> 99) THEN
     wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';
  IF (prconciliados = 1) THEN
     wsql = wsql||' and (upper(tlan.bdconcc) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
     wsql = wsql||' and ((tlan.bdconcc is null) or (upper(tlan.bdconcc) = '''||'FALSE'||''')) ';

  wsql = wsql||wsql_emp;
  wsql = wsql||'group by tlan.bdcodemp, tlan.bdfilial, tlan.bdcodplapadrao, tlan.bdtipolancfilial, tlan.bddata, tlan.bdcredito, tlan.bdcodterceiroc, tlan.bdtipolan ';
  ------------------------------------------------------------------------------
  wsql = wsql||') tlan ';
  --alt:9167 - Adicionado join com a tabela de Terceiros para pegar o CNPJ do participante. Pedro
  wsql = wsql||'inner join TTERCEIRO terc on (terc.bdcodter = tlan.bdcodter) ';
  --alt:9167 - Adicionado CNPJ do participante no group by. Pedro
  wsql = wsql||'group by bdcodemp, bdfilial, bdtipolancfilial, bdcodtpla, bdcodter, bdcgcter, bddebcre '; --alt:14679 - Adicionado campo BDDEBCRE. Pedro

  --alt:9167 - Alterado order, deve primeiro ordenar pelo CNPJ para trazer juntas as mesmas empresas. Pedro
  wsql = wsql||'order by bdcgcter desc, bdcodter desc ';

  FOR EXECUTE STATEMENT wsql
  INTO :wcodemp, :wfilial, :wtipolancfilial, :wcodtpla, :wcodparticipante, :wcnpjpart, :wdebcre, :wsaldo_ant_deb, :wsaldo_deb, :wsaldo_ant_cre, :wsaldo_cre DO --alt:14679 - Adicionado campo BDDEBCRE. Pedro
  BEGIN
     --alt:13329 - 10/02/2016 - Retorna o CNPJ completo porque o mesmo campo ? utilizado na ordena??o, e aqui corta para poder agrupar. Pedro
     wCNPJPart = SUBSTRING(wCNPJPart FROM 1 FOR 10);
     bdraizcnpjparticipante = '';

     --alt:12008 - Creio que n?o precisa buscar novamente o CNPJ j? que ? do mesmo participante, pode apenas copiar o do atual. Pedro
     --alt:9167 - Se for para agrupar os participantes por CNPJ e o CNPJ anterior estiver nullo (somente na primeira vez que passa aqui) ele pega o CNPJ pr?prio participante. Pedro
     IF ((pragruparparticipanteporcnpj = 0) AND (wcnpjantpart IS NULL)) THEN
       wcnpjantpart = wcnpjpart;

     IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
        wpermite = 1;
     ELSE
     BEGIN
       wpos_pernamatriz = POSITION(','||wcodemp||',', ','||prempresas||',');
       wpos_matriz      = POSITION(','||prcodemp||',', ','||prempresas||',');
       wpos_filial      = POSITION(','||wfilial||',', ','||prempresas||',');

       /*#Alt:15233. Carlos Mello
         wTipoLancFilial -> 0 - Nenhum | 1 - D?bito | 2 - Cr?dito
         wDebCre         -> 0 - D?bito | 2 - Cr?dito

         Na verifica??o se deve imprimir ou n?o o registro precisei acrescentar o -1 na vari?vel wTipoLancFilial,
         pois a wDebCre utiliza 0 (D?bito) e 1 (Cr?dito) enquanto na wTipoLancFilial ? 1 (D?bito) e 2 (Cr?dito).        */
       IF (((wcodemp = prcodemp) AND (wfilial = 0)) OR
           --Estou na filial mas o lan?amento foi feito na matriz para a filial(uma perna)
           ((prcodemp = wfilial) AND (wdebcre = (wtipolancfilial -1))) OR
           --Estou na matriz e tem uma perna do lan?amento na filial, mas s? quero os lan?amentos da matriz(a perna da matriz) e que a matriz esteja no filtro
           ((wcodemp = prcodemp) AND (wfilial <> 0) AND (wdebcre <> (wtipolancfilial - 1)) AND (wpos_pernamatriz > 0)) OR
           --Estou na matriz mas tamb?m quero os lan?amentos da filial conforme o filtro(Lan?amentos que foram feito na filial -> BDCODEMP = Filial)
           ((prmatrizfilialconsolidado = 1) AND (wcodemp <> prcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
           --Estou na matriz mas tamb?m quero a perna que est? na filial conforme o filtro
           ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (wdebcre <> (wtipolancfilial -1)) AND (wpos_filial > 0))) THEN
          wpermite = 1;
       ELSE
          wpermite = 0;
     END

    --alt:9167 - Alterado m?todo como retorna os valores. Deve variar para o caso de n?o estar agrupando pelo cnpj, ou se est?, quando o cnpj for igual ou diferente ao anterior. Pedro
    IF (wpermite = 1) THEN
       BEGIN
         --alt:12008 - 15/12/2015 - Aproveito para carregar junto o nome e o c?digo do pa?s do participante, para n?o precisar executar duas vezes.
         -- Uso a ordena??o bdcodter e bdrefemp porque este ?ndice ? mais r?pido. Pedro
         SELECT FIRST 1 bdnometer, COALESCE(bdcodpais, 0), COALESCE(bdcodcid,0) FROM tterceiro_ref WHERE bdcodter = :wcodparticipante ORDER BY bdcodter DESC, bdrefemp DESC
         INTO :wnome, :wcodpais, :wcodcid;
         --#Alt:14856. N?o estava imprimindo os participantes que n?o tinha o pa?s informado.
         IF ((pragruparparticipanteporcnpj = 1) AND (wcodpais = 0) AND (wcodcid > 0)) THEN
           SELECT bdcodpais FROM tcidade WHERE bdcodcid = :wcodcid INTO :wcodpais;

         --Quando n?o est? agrupando por CNPJ.
         --Quando ? participante do exterior, que ent?o n?o deve agrupar.
         IF ((pragruparparticipanteporcnpj = 0) OR (wcodpais <> 30))  THEN
           BEGIN
             --#alt:20416. Quando mandava agrupar por cnpj mas havia algum participante do exterior inserido, n?o estava mostrando o participante agrupado anterior.
             --            E devo verificar tamb?m se o participante anterior n?o era do exterior. Ana - 19/10/2017
             IF ((wcodpaisant = 30) AND (wpartexteriorant = 0)) THEN
                BEGIN
                  IF ((pragruparparticipanteporcnpj = 1) AND (bdraizcnpjparticipante = '')) THEN
                     bdraizcnpjparticipante = SUBSTRING(wcnpjantpart FROM 1 FOR 10);

                  SUSPEND;
                END

             bdcodparticipante = wcodparticipante;
             bdclassificacao = wclassificacao;
             --#alt:20416 - Precisa retornar a classifica??o original da conta. Ana - 22/09/2017
             bdraizclassificacaocta = wclassificacao;
             bdnome                 = wnome;
             --#Alt:19049 - Preciso retornar a ra?z do CNPJ caso seja para agrupar participante pelo CNPJ
             IF (pragruparparticipanteporcnpj = 1) THEN
               bdraizcnpjparticipante = SUBSTRING(wCNPJPart FROM 1 FOR 10);
             --#Alt:24324 - Melhorado a forma de montar a classifica??o do participante.
             bdclassificacao = REVERSE(bdclassificacao);
             bdclassificacao = SUBSTRING(bdclassificacao FROM POSITION('.', bdclassificacao) FOR strlen(bdclassificacao));
             bdclassificacao = REVERSE(bdclassificacao);                       
             bdclassificacao = bdclassificacao||LPAD(wcodparticipante, 9, '0');

             IF (wgrupocta IN (1,2,3)) THEN
                bdsaldo_anterior = (wsaldo_ant_cre - wsaldo_ant_deb);
             ELSE
                bdsaldo_anterior = (wsaldo_ant_deb - wsaldo_ant_cre);
         
             IF (wgrupocta IN (1,2,3)) THEN
                bdsaldo_atual = (wsaldo_cre - wsaldo_deb);
             ELSE
                bdsaldo_atual = (wsaldo_deb - wsaldo_cre);

             bdsaldo_ant_cre = wsaldo_ant_cre;
             bdsaldo_ant_deb = wsaldo_ant_deb;
             bdsaldo_cre = wsaldo_cre - wsaldo_ant_cre;
             bdsaldo_deb = wsaldo_deb - wsaldo_ant_deb;
             bdmovimento = bdsaldo_atual - bdsaldo_anterior; --alt:9515 - Adicionado campo do movimento. Pedro
             --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb?m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
             wpartexteriorant = 1;

             SUSPEND;
           END
         ELSE
         --Quando o CNPJ atual ? diferente do anterior (outra empresa, ent?o deve comitar o anterior e substituir os valores pelos novos.
         IF (wcnpjantpart <> wcnpjpart) THEN
           BEGIN
             IF (wcodpaisant = 30) THEN --alt:12008 - 15/12/2015 - Se trocou o CNPJ e ? participante nacional, ent?o deve retornar o valor, n?o agrupar. Pedro
                BEGIN
                  --#Alt:19990 - Preciso retornar a ra?z do CNPJ caso seja para agrupar participante pelo CNPJ (19049)
                  IF ((pragruparparticipanteporcnpj = 1) AND (bdraizcnpjparticipante = '')) THEN
                     bdraizcnpjparticipante = SUBSTRING(wcnpjantpart FROM 1 FOR 10);

                  SUSPEND;
                END

             --#Alt:19990 - Preciso retornar a ra?z do CNPJ caso seja para agrupar participante pelo CNPJ
             IF (pragruparparticipanteporcnpj = 1) THEN
                bdraizcnpjparticipante = SUBSTRING(wCNPJPart FROM 1 FOR 10);

             bdcodparticipante = wcodparticipante;
             bdclassificacao = wclassificacao;
             --#alt:20416 - Precisa retornar a classifica??o original da conta. Ana - 22/09/2017
             bdraizclassificacaocta = wclassificacao;
             bdnome                 = wnome;
             --#Alt:24324 - Melhorado a forma de montar a classifica??o do participante.
             bdclassificacao = REVERSE(bdclassificacao);
             bdclassificacao = SUBSTRING(bdclassificacao FROM POSITION('.', bdclassificacao) FOR strlen(bdclassificacao));
             bdclassificacao = REVERSE(bdclassificacao);                       
             bdclassificacao = bdclassificacao||LPAD(wcodparticipante, 9, '0');

             IF (wgrupocta IN (1,2,3)) THEN
                bdsaldo_anterior = (wsaldo_ant_cre - wsaldo_ant_deb);
             ELSE
                bdsaldo_anterior = (wsaldo_ant_deb - wsaldo_ant_cre);
         
             IF (wgrupocta IN (1,2,3)) THEN
                bdsaldo_atual = (wsaldo_cre - wsaldo_deb);
             ELSE
                bdsaldo_atual = (wsaldo_deb - wsaldo_cre);

             bdsaldo_ant_cre = wsaldo_ant_cre;
             bdsaldo_ant_deb = wsaldo_ant_deb;
             bdsaldo_cre = wsaldo_cre - wsaldo_ant_cre;
             bdsaldo_deb = wsaldo_deb - wsaldo_ant_deb;
             bdmovimento = bdsaldo_atual - bdsaldo_anterior; --alt:9515 - Adicionado campo do movimento. Pedro
             --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb?m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
             wpartexteriorant = 0;
           END
         --O CNPJ atual ? igual ao anterior (mesma empresa, ent?o deve agrupar).
         ELSE
           BEGIN
             bdcodparticipante = wcodparticipante;
             bdclassificacao = wclassificacao;
             --#alt:20416 - Precisa retornar a classifica??o original da conta. Ana - 22/09/2017
             bdraizclassificacaocta = wclassificacao;
             bdnome = wnome;
             --#Alt:19049 - Preciso retornar a ra?z do CNPJ caso seja para agrupar participante pelo CNPJ
             IF (pragruparparticipanteporcnpj = 1) THEN
               bdraizcnpjparticipante = SUBSTRING(wCNPJPart FROM 1 FOR 10);
             --#Alt:24324 - Melhorado a forma de montar a classifica??o do participante.
             bdclassificacao = REVERSE(bdclassificacao);
             bdclassificacao = SUBSTRING(bdclassificacao FROM POSITION('.', bdclassificacao) FOR strlen(bdclassificacao));
             bdclassificacao = REVERSE(bdclassificacao);                       
             bdclassificacao = bdclassificacao||LPAD(wcodparticipante, 9, '0');

             IF (wgrupocta IN (1,2,3)) THEN
               BEGIN
                 bdsaldo_anterior = COALESCE(bdsaldo_anterior, 0) + (wsaldo_ant_cre - wsaldo_ant_deb);
                 bdsaldo_atual = COALESCE(bdsaldo_atual, 0) + (wsaldo_cre - wsaldo_deb);
               END
             ELSE
               BEGIN
                 bdsaldo_anterior = COALESCE(bdsaldo_anterior, 0) + (wsaldo_ant_deb - wsaldo_ant_cre);
                 bdsaldo_atual = COALESCE(bdsaldo_atual, 0) + (wsaldo_deb - wsaldo_cre);
               END
         
             bdsaldo_ant_cre = COALESCE(bdsaldo_ant_cre, 0) + wsaldo_ant_cre;
             bdsaldo_ant_deb = COALESCE(bdsaldo_ant_deb, 0) + wsaldo_ant_deb;
             bdsaldo_cre = COALESCE(bdsaldo_cre, 0) + (wsaldo_cre - wsaldo_ant_cre);
             bdsaldo_deb = COALESCE(bdsaldo_deb, 0) + (wsaldo_deb - wsaldo_ant_deb);
             bdmovimento = bdsaldo_atual - bdsaldo_anterior; --alt:9515 - Adicionado campo do movimento. Pedro
             --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb?m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
             wpartexteriorant = 0;
           END
         wcodpaisant = wcodpais;
         wcnpjantpart = wcnpjpart;
       END
  END

  --alt:9167 - Garante que, se ainda tiver algum valor, deve commitar o ?ltimo lan?amento, sem isso o ?ltimo nunca seria commitado. Pedro
  IF ((pragruparparticipanteporcnpj = 1) AND (wcodpaisant = 30) AND --alt:12008 - 11/01/2015 - S? deve retornar o ?ltimo participante caso ele seja nacional. Pedro
      ((COALESCE(bdsaldo_ant_cre, 0) <> 0) OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
      (COALESCE(bdsaldo_cre, 0) <> 0) OR (COALESCE(bdsaldo_deb, 0) <> 0))) THEN
     SUSPEND;
END
^

/* Alter (VSUC_SP_RETORNA_TOTAIS_LANC) */
ALTER PROCEDURE VSUC_SP_RETORNA_TOTAIS_LANC(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0,
PRLANCSEMTRANS INTEGER = 1,
PRDATAS VARCHAR(1024) = '')
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDQTDLINHA INTEGER,
BDVALLINHA NUMERIC(15,2),
BDQTDDEB INTEGER,
BDVALDEB NUMERIC(15,2),
BDQTDCRE INTEGER,
BDVALCRE NUMERIC(15,2),
BDQTDGERAL INTEGER,
BDVALGERAL NUMERIC(15,2),
BDDIF NUMERIC(15,2),
BDCODEMPFILIAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WEMPPRINC INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  --Retorna a empresa principal
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos = 0) THEN
    wempprinc = prcodemp;
  ELSE
    wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  wsql = 'select temp.bdcodmatriz, temp.bdcodemp, temp.bdnomemp, temp.bdcnpjemp, ';
  --#alt:5837.
  /*wsql = wsql||'       count(lan.bdchave) totlanclinha , count(lan.bddebito) linhadeb, ';
  wsql = wsql||'       count(lan.bdcredito) linhacre , sum(lan.bdvalor) totalvalor, ';
  wsql = wsql||'       count(lan.bddebito) + count(lan.bdcredito) bdqtdgeral '; */
  wsql = wsql||'       count(lan.bdchave) totlanclinha , sum(lan.bdvalor) totalvalor ';
  wsql = wsql||'       from vsuc_empresas_tlan LAN ';
  wsql = wsql||'inner join vw_empresas_ref_atual temp on (temp.bdcodemp = lan.bdcodemp) ';
  --#alt:5837.
  --wsql = wsql||'where lan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'where ((lan.bdcodemp in ('||prcodemp||')) or (lan.bdfilial in ('||prcodemp||'))) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  --#alt:16410 - Adicionei o controle pelo filtro das datas com diferen?a, sem ela estava levando os valores errados com esta op??o. Ana - 05/05/2017
  IF ((prdatas IS NOT NULL) AND (prdatas <> '')) THEN
    wsql = wsql||'and (lan.BDDATA in ('||TRIM(prdatas)||')) ';
  ELSE
  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     wsql = wsql||' and (lan.BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';

  --#alt:16410 - Adicionado filtro por status da transa??o e a op??o de mostrar os lan?amentos sem transa??o que n?o tinha e deixava os valores inv?lidos. Ana - 05/05/2017
  IF (prstatustransacao = 1) THEN
    wsql = wsql||'and (upper(LAN.BDTRANFECHADA) = ''FALSE'') ';
  ELSE IF (prstatustransacao = 2) THEN
    wsql = wsql||'and (upper(LAN.BDTRANFECHADA) = ''TRUE'') ';

  IF (prlancsemtrans = 0) THEN
       wsql = wsql||'and (lan.bdtransacao is not null) ';
  --#alt:16410. fim

  IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
     wsql = wsql||' and  '||prwhere;
  wsql = wsql||'group by temp.bdcodmatriz, temp.bdcodemp, temp.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'order by temp.bdcodmatriz, temp.bdcodemp ';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :BDQTDLINHA, /*:BDQTDDEB, :BDQTDCRE, */:bdvallinha/*, :bdqtdgeral*/ DO
      BEGIN
        bdvaldeb   = 0;
        bdvalcre   = 0;
        bdqtddeb   = 0;
        bdqtdcre   = 0;
        bdqtdgeral = 0;

        IF (bdcodemp IS NULL) THEN
           bdcodemp = bdcodempfilial;

        IF (bdqtdlinha IS NULL) THEN
           bdqtdlinha = 0;
        IF (bdvallinha IS NULL) THEN
           bdvallinha = 0;
        --#alt:5837.
        SELECT Pos FROM pos(','||:bdcodempfilial||',', ','||:prcodemp||',') INTO :wpos;
        IF (wpos > 0) THEN
          BEGIN
            -- D?bito ______________________________________________________________
            --#alt:5837.
            /*wSqllanc = 'select sum(bdvalor) from vsuc_empresas_tlan LAN where bdcodemp = '||bdcodempfilial||' and bddebito is not null ';
            if ((prdataini is not null) and (prdatafim is not null)) then
              wsqllanc = wsqllanc||' and (BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
            if ((prwhere is not null) and (prwhere <> '')) then
              wsqllanc = wsqllanc||' and  '||prwhere;
            execute statement wsqllanc into :bdvaldeb;*/
            wSqllanc = 'Select bdcodemp,bdfilial,bdtipolancfilial,sum(bdvalor),count(bdchave) from vsuc_empresas_tlan LAN ';
            wsqllanc = wsqllanc||'where ((bdcodemp = '||bdcodempfilial||') or (bdfilial= '||bdcodempfilial||')) and bddebito is not null ';
            --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wsqllanc = wsqllanc||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
            --#alt:16410 - Adicionei o controle pelo filtro das datas com diferen?a, sem ela estava levando os valores errados com esta op??o. Ana - 05/05/2017
            IF ((prdatas IS NOT NULL) AND (prdatas <> ''))THEN
              wsqllanc = wsqllanc||'and (lan.BDDATA in ('||TRIM(prdatas)||')) ';
            ELSE
            IF ((prdataini IS NOT NULL) AND (prdatafim IS NOT NULL)) THEN
              wsqllanc = wsqllanc||' and (BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
            --#alt:16410 - Adicionado filtro por status da transa??o e a op??o de mostrar os lan?amentos sem transa??o que n?o tinha e deixava os valores inv?lidos. Ana - 05/05/2017
            IF (prstatustransacao = 1) THEN
              wsqllanc = wsqllanc||'and (upper(LAN.BDTRANFECHADA) = ''FALSE'') ';
            ELSE IF (prstatustransacao = 2) THEN
              wsqllanc = wsqllanc||'and (upper(LAN.BDTRANFECHADA) = ''TRUE'')';

            IF (prlancsemtrans = 0) THEN
              wsqllanc = wsqllanc||'and (lan.bdtransacao is not null) ';
            --#alt:16410. fim
            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
              wsqllanc = wsqllanc||' and  '||prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp,bdfilial,bdtipolancfilial';
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodemp,:wfilial, :wtipolancfilial,:wvlr,:wqtd DO
              BEGIN
                IF (wvlr IS NULL) THEN
                  wvlr = 0;
                IF (wqtd IS NULL) THEN
                  wqtd = 0;
                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:bdcodempfilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  BEGIN
                    bdvaldeb = bdvaldeb + wvlr;
                    bdqtddeb = bdqtddeb + wqtd;
                  END
              END

            IF (bdqtddeb IS NULL) THEN
              bdqtddeb = 0;
            IF (bdvaldeb IS NULL) THEN
              bdvaldeb = 0;

            -- Cr?dito _____________________________________________________________
            --#alt:5837.
            /*wSqllanc = 'select sum(bdvalor) from vsuc_empresas_tlan LAN where bdcodemp = '||bdcodempfilial||' and bdcredito is not null ';
            if (prdataini is not null and prdatafim is not null) then
              wsqllanc = wsqllanc||' and (BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
            if ((prwhere is not null) and (prwhere <> '')) then
              wsqllanc = wsqllanc||' and  '||prwhere;
            execute statement wsqllanc into :bdvalcre;*/
            wSqllanc = 'Select bdcodemp,bdfilial,bdtipolancfilial,sum(bdvalor),count(bdchave) from vsuc_empresas_tlan LAN ';
            wsqllanc = wsqllanc||'where ((bdcodemp = '||bdcodempfilial||') or (bdfilial= '||bdcodempfilial||')) and bdcredito is not null ';
            --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wsqllanc = wsqllanc||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
            --#alt:16410 - Adicionei o controle pelo filtro das datas com diferen?a, sem ela estava levando os valores errados com esta op??o. Ana - 05/05/2017
            IF ((prdatas IS NOT NULL) AND (prdatas <> ''))THEN
              wsqllanc = wsqllanc||'and (lan.BDDATA in ('||TRIM(prdatas)||')) ';
            ELSE
            IF ((prdataini IS NOT NULL) AND (prdatafim IS NOT NULL)) THEN
              wsqllanc = wsqllanc||' and (BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
            --#alt:16410 - Adicionado filtro por status da transa??o e a op??o de mostrar os lan?amentos sem transa??o que n?o tinha e deixava os valores inv?lidos. Ana - 05/05/2017
            IF (prstatustransacao = 1) THEN
              wsqllanc = wsqllanc||'and (upper(LAN.BDTRANFECHADA) = ''FALSE'') ';
            ELSE IF (prstatustransacao = 2) THEN
              wsqllanc = wsqllanc||'and (upper(LAN.BDTRANFECHADA) = ''TRUE'')';

            IF (prlancsemtrans = 0) THEN
              wsqllanc = wsqllanc||'and (lan.bdtransacao is not null) ';
            --#alt:16410. fim
            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
              wsqllanc = wsqllanc||' and  '||prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp,bdfilial,bdtipolancfilial';
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodemp,:wfilial, :wtipolancfilial,:wvlr,:wqtd DO
              BEGIN
                IF (wvlr IS NULL) THEN
                  wvlr = 0;
                IF (wqtd IS NULL) THEN
                  wqtd = 0;
                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:bdcodempfilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  BEGIN
                    bdvalcre = bdvalcre + wvlr;
                    bdqtdcre = bdqtdcre + wqtd;
                  END
              END

            IF (bdqtdcre IS NULL) THEN
              bdqtdcre = 0;
            IF (bdvalcre IS NULL) THEN
              bdvalcre = 0;

            -- totais ______________________________________________________________
            bdvalgeral = bdvaldeb + bdvalcre;
            bdqtdgeral = bdqtddeb + bdqtdcre;
            bddif = bdvalcre - bdvaldeb;
          END

        IF (bdqtdgeral IS NULL) THEN
           bdqtdgeral = 0;
        IF (bdvalgeral IS NULL) THEN
           bdvalgeral = 0;
        IF (bddif IS NULL) THEN
           bddif = 0;

        SUSPEND;
      END
END
^

/* Alter (VSUC_SP_TENC_EXERCICIO) */
ALTER PROCEDURE VSUC_SP_TENC_EXERCICIO(PRCODEMP INTEGER,
PRCONTA VARCHAR(1024),
PRCTACONTRAPARTIDA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRDATALANC DATE,
PRLOTE VARCHAR(10),
PRCOMPLEMENTO VARCHAR(100),
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRCHAVEZERA INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODHIST INTEGER,
PRREFEMP INTEGER,
PRLANCCONTRAPART INTEGER)
 RETURNS(PRCHAVEZERAMENTO INTEGER,
PRZEROUCONTAS INTEGER)
 AS
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WCTADEB INTEGER;
DECLARE VARIABLE WCTACRE INTEGER;
DECLARE VARIABLE WVALLAN NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WVALDEB NUMERIC(15,2);
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WVALCRE NUMERIC(15,2);
DECLARE VARIABLE WQUERY VARCHAR(1024);
BEGIN
  wvalcre = 0;
  wvaldeb = 0;
  wvallan = 0;
  wctalon = '';

  wsql = 'select tpla.bdctalon from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||prcodplapadrao;
  wsql = wsql||' and tpla.bdcodtpla in ('||prconta||') ';
  wsql = wsql||'order by tpla.bdctalon';

  prchavezeramento = prchavezera;

  FOR EXECUTE STATEMENT wsql
      INTO :wclassificacao DO
      BEGIN
        IF ((prchavezeramento = 0) OR (prchavezeramento IS NULL))  THEN
           SELECT PRCHAVEZER FROM vsuc_sp_insert_encex(:prcodemp,:prcodplapadrao,:prctacontrapartida,:prcodhist,:prcodtphi,:prusuario,:prdataini,:prdatafim,:prdatalanc,CURRENT_DATE,CURRENT_TIME) INTO :prchavezeramento;
        -- Cr?dito
        wquery = 'select distinct(TLAN.bdcredito), sum(TLAN.bdvalor), Tpla.bdctalon ';
        wquery = wquery||'from VSUC_EMPRESAS_TLAN TLAN ';
        wquery = wquery||'join PLANOS_TPLA TPLA on (TPLA.bdcodplapadrao = TLAN.bdcodplapadrao and TPLA.bdcodtpla = TLAN.bdcredito and TPLA.bdtipcta = 1) ';
        wquery = wquery||'where (TLAN.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
        wquery = wquery||'and (coalesce(TLAN.bdtipolan,1) <> 10) ';
        wquery = wquery||'and (TLAN.bdcodplapadrao = '||prcodplapadrao||') ';
        wquery = wquery||'and (TLAN.bdcodemp = '||prcodemp||') ';
        wquery = wquery||'and (substring(TPLA.bdctalon from 1 for '||strlen(wclassificacao)||') = '''||wclassificacao||''') ';
        wquery = wquery||'group by tlan.bdcredito,Tpla.bdctalon ';
        wquery = wquery||'order by Tpla.bdctalon ';

        FOR EXECUTE STATEMENT wquery
            INTO :wctacre, :wvallan, :wctalon DO
            BEGIN
              przeroucontas = 1;
              wvalcre = wvalcre + wvallan;
              IF (wvallan <> 0) THEN -- N?o precisa efetuar o zeramento quando o valor for 0(zero)
                BEGIN
                  IF (prlanccontrapart <> 0) THEN
                     EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, :wctacre, :prctacontrapartida, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL,:prchavezeramento, :prrefemp);
                  ELSE
                    BEGIN
                      EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, :wctacre, NULL, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL,:prchavezeramento, :prrefemp);
--                    execute procedure vsuc_sp_insert_lanc(null, :prcodemp, :prcodplapadrao, null, :prctacontrapartida, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, null, 10, null, null, null,:prchavezeramento, :prrefemp);
                    END
                END
            END
        -- D?bito
        wquery = 'select distinct(TLAN.bddebito), sum(TLAN.bdvalor), Tpla.bdctalon ';
        wquery = wquery||'from VSUC_EMPRESAS_TLAN TLAN ';
        wquery = wquery||'join PLANOS_TPLA TPLA on (TPLA.bdcodplapadrao = TLAN.bdcodplapadrao and TPLA.bdcodtpla = TLAN.bddebito and TPLA.bdtipcta = 1) ';
        wquery = wquery||'where (TLAN.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
        wquery = wquery||'and (coalesce(TLAN.bdtipolan,1) <> 10) ';
        wquery = wquery||'and (TLAN.bdcodplapadrao = '||prcodplapadrao||') ';
        wquery = wquery||'and (TLAN.bdcodemp = '||prcodemp||') ';
        wquery = wquery||'and (substring(TPLA.bdctalon from 1 for '||strlen(wclassificacao)||') = '''||wclassificacao||''') ';
        wquery = wquery||'group by tlan.bddebito,Tpla.bdctalon ';
        wquery = wquery||'order by Tpla.bdctalon ';

        FOR EXECUTE STATEMENT wquery
            INTO :wctadeb, :wvallan, :wctalon DO
            BEGIN
              przeroucontas = 1;
              wvaldeb = wvaldeb + wvallan;
              IF (wvallan <> 0) THEN -- N?o precisa efetuar o zeramento quando o valor for 0(zero)
                BEGIN
                  IF (prlanccontrapart <> 0) THEN
                     EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, :prctacontrapartida, :wctadeb, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL, :prchavezeramento, :prrefemp);
                   ELSE
                     BEGIN
--                      execute procedure vsuc_sp_insert_lanc(null, :prcodemp, :prcodplapadrao, :prctacontrapartida, null, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, null, 10, null, null, null, :prchavezeramento, :prrefemp);
                        EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, NULL, :wctadeb, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL, :prchavezeramento, :prrefemp);
                     END
                END
            END
      END
  /* Carlos Mello(16/06/2011) - N?o precisa gerar um zeramento quando o valor for 0(zero) */
  IF (wvaldeb > 0) THEN
     EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, :prctacontrapartida, NULL, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvaldeb, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL, :prchavezeramento, :prrefemp);

  IF (wvalcre > 0) THEN
     EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, NULL, :prctacontrapartida, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvalcre, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL,:prchavezeramento, :prrefemp);

  --Exclui o registro na VSUC_EMPRESAS_TENCEXE caso n?o tenha feito nenhum lan?amento de zeramento
  IF ((przeroucontas = 0) OR (przeroucontas IS NULL)) THEN
    EXECUTE STATEMENT 'Delete from VSUC_EMPRESAS_TENCEXE  where (BDCHAVEZER = '||prchavezeramento||')';

  SUSPEND;
END
^

/* Alter (VSUC_SP_UPDATE_TLAN_CONC_BANC) */
ALTER PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_BANC(PREMPRESA INTEGER,
PRDEBCRE INTEGER,
PRCONTA INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCOMPL VARCHAR(200),
PRVALOR FLOAT,
PRCODPLAPADRAO INTEGER,
PRDCTO VARCHAR(15),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCHAVE INTEGER)
 AS
DECLARE VARIABLE WVALOR FLOAT;
DECLARE VARIABLE WCOMPL VARCHAR(200);
DECLARE VARIABLE WCONCC VARCHAR(5);
DECLARE VARIABLE WCONCD VARCHAR(5);
BEGIN
  bdcodemp = prempresa;
  bdcodplapadrao = prcodplapadrao;

  --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar n?meros/caracteres depois dos s?mbolos "/", "\" ou "-". Pedro
  prDCTO = UPPER(SUBSTRING(prDCTO FROM 1 FOR
                           CASE WHEN (prDCTO CONTAINING '/') THEN POSITION('/', prDCTO) -1
                                WHEN (prDCTO CONTAINING '\') THEN POSITION('\', prDCTO) -1
                                WHEN (prDCTO CONTAINING '-') THEN POSITION('-', prDCTO) -1
                           ELSE CHAR_LENGTH(prDCTO) END));

  -- verifica se ? d?bito cr?dito ou os dois
  --if (prdebcre = 0) then
  IF (prdebcre IN (0,2)) THEN
    BEGIN
      FOR SELECT bdchave,bdcompl,bdvalor FROM vsuc_empresas_tlan
      --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar n?meros/caracteres depois dos s?mbolos "/", "\" ou "-". Pedro
      --WHERE (((UPPER(bdcompl) LIKE :prcompl) AND (UPPER(bddcto) = UPPER(:prdcto))) /*OR((UPPER(bdcompl) LIKE :prcompl) OR (UPPER(bddcto) = UPPER(:prdcto)))*/)  --#alt:13456 - comentado pois estava alterando todos os lan?amentos com o mesmo complemento. Ana - 28/10/2016
      WHERE (UPPER(bdcompl) LIKE :prcompl)
      AND   (UPPER(SUBSTRING(bddcto FROM 1 FOR
                             CASE WHEN (bddcto CONTAINING '/') THEN POSITION('/', bddcto) -1
                                  WHEN (bddcto CONTAINING '\') THEN POSITION('\', bddcto) -1
                                  WHEN (bddcto CONTAINING '-') THEN POSITION('-', bddcto) -1
                             ELSE CHAR_LENGTH(bddcto) END)) = :prDCTO)
      --alt:17706 - Fim
      AND   (bdvalor = :prvalor)
      AND   (bddata BETWEEN :prdatainicial AND :prdatafinal)
      AND   (bddebito = :prconta)
      AND   (bdcodplapadrao = :prcodplapadrao)
      AND   (bdcodemp = :prempresa)
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      AND   (bdcontabilizacao IN (0,:prcontabilizacao))
      INTO :bdchave,:wcompl,:wvalor DO
        BEGIN
          --#alt:13456 - Atribuido valor ao campo do tipo de concilia??o. Ana - 27/10/2016
          UPDATE vsuc_empresas_tlan SET bdconcd = 'TRUE'/*, bdtipoconc = 1*/ WHERE (bdchave = :bdchave) AND (bdcodemp = :prempresa) AND (UPPER(COALESCE(bdconcd,'')) <> 'TRUE');
          SUSPEND;
        END
    END
  --else
  --if (prdebcre = 1) then
  IF (prdebcre IN (1,2)) THEN
    BEGIN
      FOR SELECT bdchave, bdcompl, bdvalor FROM vsuc_empresas_tlan
      --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar n?meros/caracteres depois dos s?mbolos "/", "\" ou "-". Pedro
      --WHERE (((UPPER(bdcompl) LIKE :prcompl) AND (UPPER(bddcto) = UPPER(:prdcto))) /*OR ((UPPER(bdcompl) LIKE :prcompl) OR (UPPER(bddcto) = UPPER(:prdcto)))*/) --#alt:13456 - comentado pois estava alterando todos os lan?amentos com o mesmo complemento. Ana - 28/10/2016
      WHERE (UPPER(bdcompl) LIKE :prcompl)
      AND   (UPPER(SUBSTRING(bddcto FROM 1 FOR
                             CASE WHEN (bddcto CONTAINING '/') THEN POSITION('/', bddcto) -1
                                  WHEN (bddcto CONTAINING '\') THEN POSITION('\', bddcto) -1
                                  WHEN (bddcto CONTAINING '-') THEN POSITION('-', bddcto) -1
                             ELSE CHAR_LENGTH(bddcto) END)) = :prDCTO)
      --alt:17706 - Fim
      AND   (bdvalor = :prvalor)
      AND   (bddata BETWEEN :prdatainicial AND :prdatafinal)
      AND   (bdcredito = :prconta)
      AND   (bdcodplapadrao = :prcodplapadrao)
      AND   (bdcodemp = :prempresa)
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      AND   (bdcontabilizacao IN (0,:prcontabilizacao))
      INTO :bdchave, :wcompl, :wvalor DO
        BEGIN
          --#alt:13456 - Atribuido valor ao campo do tipo de concilia??o. Ana - 27/10/2016  
          UPDATE vsuc_empresas_tlan SET bdconcc = 'TRUE'/*, bdtipoconc = 2*/ WHERE (bdchave = :bdchave) AND (bdcodemp = :prempresa) AND (UPPER(COALESCE(bdconcc,'')) <> 'TRUE');
          SUSPEND;
        END
    END
  /*else
    begin
      for select bdchave, bdcompl, bdvalor from vsuc_empresas_tlan
      where (((Upper(bdcompl) like :prcompl) and (upper(bddcto) = upper(:prdcto))) or ((Upper(bdcompl) like :prcompl) or (upper(bddcto) = upper(:prdcto))))
      and   (bdvalor = :prvalor)
      and   (bddata Between :prdatainicial and :prdatafinal)
      and   (bddebito = :prconta)
      and   (bdcodplapadrao = :prcodplapadrao)
      and   (bdcodemp = :prempresa)
      into :bdchave, :wcompl, :wvalor do
        begin
          update vsuc_empresas_tlan set bdconcd = 'TRUE' where (bdchave = :bdchave) and (bdcodemp = :prempresa) and (Upper(COALESCE(bdconcd,'')) <> 'TRUE');
          suspend;
        end

      for select bdchave, bdcompl, bdvalor from vsuc_empresas_tlan
      where (((Upper(bdcompl) like :prcompl) and (upper(bddcto) = upper(:prdcto))) or ((Upper(bdcompl) like :prcompl) or (upper(bddcto) = upper(:prdcto))))
      and   (bdvalor = :prvalor)
      and   (bddata Between :prdatainicial and :prdatafinal)
      and   (bdcredito = :prconta)
      and   (bdcodplapadrao = :prcodplapadrao)
      and   (bdcodemp = :prempresa)
      into :bdchave, :wcompl, :wvalor do
        begin
          update vsuc_empresas_tlan set bdconcc = 'TRUE' where (bdchave = :bdchave) and (bdcodemp = :prempresa) and (Upper(COALESCE(bdconcc,'')) <> 'TRUE');
          suspend;
        end
    end
    SUSPEND;*/

  --#alt:13456 - Adicionada verifica??o se os dois valores foram conciliados, tanto debito quanto cr?dito
  FOR SELECT bdconcc, bdconcd FROM vsuc_empresas_tlan
      WHERE (bdcodemp = :prempresa)
      AND   (bdchave = :bdchave)
      INTO :wConcc, :wConcd DO
        BEGIN
          IF ((wConcc = 'TRUE') AND (wConcd = 'TRUE')) THEN
             UPDATE vsuc_empresas_tlan SET bdtipoconc = 3 WHERE (bdchave = :bdchave) AND (bdcodemp = :prempresa);
          SUSPEND;
        END
  --#alt:13456. fim
END
^

/* Alter (VSUC_SP_UPDATE_TLAN_CONC_CLIFOR) */
ALTER PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL VARCHAR(10),
PRDATAFINAL VARCHAR(10),
PRCLIFOR SMALLINT,
PRCODPLAPADRAO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
DECLARE VARIABLE wchave INTEGER;
DECLARE VARIABLE wclassificacaoini VARCHAR(50);
DECLARE VARIABLE wclassificacaofim VARCHAR(50);
BEGIN
  conciliacaook = 0;

  /* pega a classifica??o inicial da conta */
  SELECT bdctalon FROM planos_tpla WHERE (bdcodplapadrao = :prcodplapadrao) AND (bdcodtpla = :prcontainicial) INTO :wclassificacaoini;

  /* pega a classifica??o final da conta */
  SELECT bdctalon FROM planos_tpla WHERE (bdcodplapadrao = :prcodplapadrao) AND (bdcodtpla = :prcontafinal) INTO :wclassificacaofim;

  /* concilia??o cliente d?dito e cr?dito */
  /*if (prclifor = 0) then
    begin*/

  /*for select bdchave from vsuc_empresas_tlan
      where (bddata Between :prdatainicial and :prdatafinal)
      and   (bddebito Between :wclassificacaoini and :wclassificacaofim)
      and   (bdcodplapadrao = :wcodpla)
      and   (bdcodemp = :prempresa) into :wchave do*/

  FOR SELECT bdchave FROM vsuc_empresas_tlan tlan, planos_tpla tpla
      WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
      AND   (tlan.bdcodplapadrao = :prcodplapadrao)
      AND   (tlan.bdcodplapadrao = tpla.bdcodplapadrao)
      AND   (tlan.bddebito = tpla.bdcodtpla)
      AND   (tpla.bdctalon BETWEEN :wclassificacaoini AND :wclassificacaofim)
      AND   (bdcodemp = :prempresa) INTO :wchave DO
      BEGIN
        UPDATE vsuc_empresas_tlan SET bdconcd = 'TRUE' WHERE (bdchave = :wchave) AND (bdcodemp = :prempresa);
        conciliacaook = 1;
      END

  /*for select bdchave from vsuc_empresas_tlan
      where (bddata Between :prdatainicial and :prdatafinal)
      and   (bdcredito Between :wclassificacaoini and :wclassificacaofim)
      and   (bdcodplapadrao = :wcodpla)
      and   (bdcodemp = :prempresa) into :wchave do*/

  FOR SELECT bdchave FROM vsuc_empresas_tlan tlan, planos_tpla tpla
      WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
      AND   (tlan.bdcodplapadrao = :prcodplapadrao)
      AND   (tlan.bdcodplapadrao = tpla.bdcodplapadrao)
      AND   (tlan.bdcredito = tpla.bdcodtpla)
      AND   (tpla.bdctalon BETWEEN :wclassificacaoini AND :wclassificacaofim)
      AND   (bdcodemp = :prempresa) INTO :wchave DO
      BEGIN
        UPDATE vsuc_empresas_tlan SET bdconcc = 'TRUE' WHERE (bdchave = :wchave) AND (bdcodemp = :prempresa);
        conciliacaook = 1;
      END
    /*end
  else
    begin

    end*/
  SUSPEND;
END
^

/* Alter (VTPO_CONSULTA_TEMPOS) */
ALTER PROCEDURE VTPO_CONSULTA_TEMPOS(PREMPRESAS DM_LISTA,
PRSISTEMAS DM_LISTA,
PRUSUARIOS DM_LISTA,
PRPROCESSOS DM_LISTA,
PRDATAINI DATE,
PRDATAFIM DATE,
PRFIELDS VARCHAR(500),
PRREPORT INTEGER,
PRORDER INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP VARCHAR(120),
BDCODSIS INTEGER,
BDORDEMSCI INTEGER,
BDDESCSIS VARCHAR(60),
BDCODUSU INTEGER,
BDNOMCOMPLUSU VARCHAR(60),
BDCODTELASIS INTEGER,
BDCAPTIONTELA VARCHAR(170),
BDQUANTIDADE INTEGER,
BDTEMPOATIVO TIMESTAMP,
BDTEMPOINATIVO TIMESTAMP,
BDPERCENTUAL DOUBLE PRECISION,
BDTEMPOMEDIO TIMESTAMP,
BDTIPOREGISTRO INTEGER)
 AS
DECLARE VARIABLE WSQL DM_MAXVARCHAR;
DECLARE VARIABLE WFILTERLOG DM_MAXVARCHAR;
DECLARE VARIABLE WFILTERLAN DM_MAXVARCHAR = '';
DECLARE VARIABLE WDESCTOTAL VARCHAR(6) = 'Total ';
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODSIS INTEGER;
DECLARE VARIABLE WORDEMSCI INTEGER;
DECLARE VARIABLE WCODUSU INTEGER;
DECLARE VARIABLE WCODTELASIS INTEGER;
DECLARE VARIABLE WCODEMP_AUX INTEGER = -1;
DECLARE VARIABLE WCODSIS_AUX INTEGER = -1;
DECLARE VARIABLE WCODUSU_AUX INTEGER = -1;
DECLARE VARIABLE WCODTELASIS_AUX INTEGER = -1;
DECLARE VARIABLE WNOMEMP VARCHAR(120);
DECLARE VARIABLE WDESCSIS VARCHAR(60);
DECLARE VARIABLE WNOMCOMPLUSU VARCHAR(60);
DECLARE VARIABLE WCAPTIONTELA VARCHAR(170);
DECLARE VARIABLE WNOMEMP_AUX VARCHAR(120);
DECLARE VARIABLE WDESCSIS_AUX VARCHAR(60);
DECLARE VARIABLE WNOMCOMPLUSU_AUX VARCHAR(60);
DECLARE VARIABLE WCAPTIONTELA_AUX VARCHAR(170);
DECLARE VARIABLE WTEMPOATIVO DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOATIVOATU DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOINATIVO DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOINATIVOATU DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOATIVOSOMA1 DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOATIVOSOMA2 DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOATIVOSOMA3 DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOATIVOTOTAL DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOINATIVOSOMA1 DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOINATIVOSOMA2 DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOINATIVOSOMA3 DECIMAL(18,9) = 0;
DECLARE VARIABLE WTEMPOINATIVOTOTAL DECIMAL(18,9) = 0;
DECLARE VARIABLE WQUANTIDADE INTEGER = 0;
DECLARE VARIABLE WQUANTIDADEATU INTEGER = 0;
DECLARE VARIABLE WQUANTIDADESOMA1 INTEGER = 0;
DECLARE VARIABLE WQUANTIDADESOMA2 INTEGER = 0;
DECLARE VARIABLE WQUANTIDADESOMA3 INTEGER = 0;
DECLARE VARIABLE WQUANTIDADETOTAL INTEGER = 0;
DECLARE VARIABLE WCOLUMN1 INTEGER;
DECLARE VARIABLE WCOLUMN2 INTEGER;
DECLARE VARIABLE WCOLUMN3 INTEGER;
DECLARE VARIABLE WCOLUMN4 INTEGER;
DECLARE VARIABLE WREPRINTLEVEL INTEGER = 0;
DECLARE VARIABLE WSEQEMP INTEGER;
DECLARE VARIABLE WSEQSIS INTEGER;
DECLARE VARIABLE WSEQUSU INTEGER;
DECLARE VARIABLE WSEQTELA INTEGER;
DECLARE VARIABLE WSEQUENCE INTEGER;
DECLARE VARIABLE WPOSITION INTEGER;
DECLARE VARIABLE WLASTLEVEL INTEGER;
BEGIN
  /*******************************
   BDTIPOREGISTRO:
    0 - Linha de registro comum;
    1 - Cabe?alho dos registros;
    2 - Totalizador dos registros;
  *******************************/

  --Corta os campos extras e retira a ordena??o para que seja usado como campos din?micos.
  prFields = UPPER(prFields);
  wLastLevel = CHAR_LENGTH(prFields) - CHAR_LENGTH(REPLACE(prFields, ',', '')) +1;
  WHILE (CHAR_LENGTH(prFields) > (CHAR_LENGTH(REPLACE(prFields, ',', '')) + 3)) DO --Somente ser?o filtradas as 4 primeiras colunas
    prFields = SUBSTRING(prFields FROM 1 FOR CHAR_LENGTH(prFields) -1);

  --Calcula a sequ?ncia dos campos.
  wPosition = 1;
  wSeqEmp = CASE WHEN POSITION('BDNOMEMP', UPPER(:prFields)) = 0 THEN CHAR_LENGTH(prFields) ELSE POSITION('BDNOMEMP', UPPER(:prFields)) END;
  wSeqSis = CASE WHEN POSITION('BDDESCSIS', UPPER(:prFields)) = 0 THEN CHAR_LENGTH(prFields) ELSE POSITION('BDDESCSIS', UPPER(:prFields)) END;
  wSeqUsu = CASE WHEN POSITION('BDNOMCOMPLUSU', UPPER(:prFields)) = 0 THEN CHAR_LENGTH(prFields) ELSE POSITION('BDNOMCOMPLUSU', UPPER(:prFields)) END;
  wSeqTela = CASE WHEN POSITION('BDCAPTIONTELA', UPPER(:prFields)) = 0 THEN CHAR_LENGTH(prFields) ELSE POSITION('BDCAPTIONTELA', UPPER(:prFields)) END;
  DELETE FROM LISTA_LANC WHERE BDCODEMP = BDCODEMP;
  INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wSeqEmp, 0, 0);
  INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wSeqSis, 0, 0);
  INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wSeqUsu, 0, 0);
  INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wSeqTela, 0, 0);
  FOR SELECT BDCODEMP FROM LISTA_LANC WHERE BDCODEMP > 0 ORDER BY BDCHAVE INTO :wSequence DO
    BEGIN
      wSeqEmp = CASE WHEN wSeqEmp = wSequence THEN wPosition ELSE wSeqEmp END;
      wSeqSis = CASE WHEN wSeqSis = wSequence THEN wPosition ELSE wSeqSis END;
      wSeqUsu = CASE WHEN wSeqUsu = wSequence THEN wPosition ELSE wSeqUsu END;
      wSeqTela = CASE WHEN wSeqTela = wSequence THEN wPosition ELSE wSeqTela END;
      wPosition = wPosition + 1;
    END
  DELETE FROM LISTA_LANC WHERE BDCODEMP = BDCODEMP;
  SELECT BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTO' INTO :wCodTelaSis;

  --Primeiro crio um filtro padr?o para que quando necessite alterar, altere em um ?nico lugar, para que n?o ocorra erros e esquecimentos nas altera??es.
  IF (TRIM(prDataIni) <> '') THEN
    wFilterLan = wFilterLan||' and (/*DATAINICIAL*/ >= '''||prDataIni||''')';
  IF (TRIM(prDataFim) <> '') THEN
    wFilterLan = wFilterLan||' and (/*DATAFINAL*/ <= '''||prDataFim||''')';
  IF (TRIM(prSistemas) <> '') THEN
    wFilterLan = wFilterLan||' and (/*SISTEMA*/ in ('||prSistemas||'))';
  IF (TRIM(prUsuarios) <> '') THEN
    wFilterLan = wFilterLan||' and (/*USUARIO*/ in ('||prUsuarios||'))';
  IF (TRIM(prProcessos) <> '') THEN
    wFilterLan = wFilterLan||' and (/*PROCESSO*/ in ('||prProcessos||'))';
  IF (TRIM(prEmpresas) <> '') THEN
    wFilterLan = wFilterLan||' and (coalesce(BDCODEMP, 0) in ('||prEmpresas||'))';

  wFilterLog = 'select BDCODEMP, /*SISTEMA*/ as BDCODSIS, /*USUARIO*/ as BDCODUSU, /*PROCESSO*/ as BDCODTELASIS, /*TIPOACAO*/ as BDTIPOACAO,';
  wFilterLog = wFilterLog||' /*DATAINICIAL*/ as BDDATAINICIAL, /*DATAFINAL*/ as BDDATAFINAL, /*HORAINICIAL*/ as BDHORAINICIAL, /*HORAFINAL*/ as BDHORAFINAL,';
  wFilterLog = wFilterLog||' /*QUANTIDADE*/ as BDQUANTIDADE from /*TABELA*/ /*APELIDO*/';
  --alt:16527 - 09/12/2016 - N?o tem mais necessidade desta filtragem, j? foi corrigido nas bases atrav?s de script. Pedro
  --wFilterLog = wFilterLog||' where (DateDiff(Second, Time '||'''00:00'''||', /*HORAINICIAL*/) > 0)';
  --wFilterLog = wFilterLog||'   and (DateDiff(Second, Time '||'''00:00'''||', /*HORAFINAL*/) > 0)';
  IF (wFilterLan <> '') THEN
    wFilterLog = wFilterLog||' where '||SUBSTRING(wFilterLan FROM 5 FOR CHAR_LENGTH(wFilterLan));
  wFilterLan = wFilterLog; --Copio o filtro para o Lan?amento

  --Agora fa?o as adapta??es dos nomes dos campos para a tabela do Log.
  wFilterLog = REPLACE(wFilterLog, '/*SISTEMA*/', 'BDCODSIS');
  wFilterLog = REPLACE(wFilterLog, '/*USUARIO*/', 'BDCODUSU');
  wFilterLog = REPLACE(wFilterLog, '/*PROCESSO*/', 'BDCODTELASIS');
  wFilterLog = REPLACE(wFilterLog, '/*TIPOACAO*/', 'case when BDTIPOACAO = 11 then BDTIPOACAO else 0 end');
  wFilterLog = REPLACE(wFilterLog, '/*DATAINICIAL*/', 'BDDATASISTEMA');
  wFilterLog = REPLACE(wFilterLog, '/*DATAFINAL*/', 'BDDATA');
  wFilterLog = REPLACE(wFilterLog, '/*HORAINICIAL*/', 'BDHORAINICIAL');
  wFilterLog = REPLACE(wFilterLog, '/*HORAFINAL*/', 'BDHORAFINAL');
  wFilterLog = REPLACE(wFilterLog, '/*QUANTIDADE*/', 'coalesce(BDQUANTIDADE, 1)');
  wFilterLog = REPLACE(wFilterLog, '/*TABELA*/', 'TLOG');
  wFilterLog = REPLACE(wFilterLog, '/*APELIDO*/', 'logsis');

  --Agora fa?o as adapta??es dos nomes dos campos para a tabela de Lan?amentos.
  wFilterLan = REPLACE(wFilterLan, '/*SISTEMA*/', '4');
  wFilterLan = REPLACE(wFilterLan, '/*USUARIO*/', 'BDCODUSU');
  wFilterLan = REPLACE(wFilterLan, '/*PROCESSO*/', wCodTelaSis);
  wFilterLan = REPLACE(wFilterLan, '/*TIPOACAO*/', '0');
  wFilterLan = REPLACE(wFilterLan, '/*DATAINICIAL*/', 'BDDATALANINICIAL');
  wFilterLan = REPLACE(wFilterLan, '/*DATAFINAL*/', 'BDDATALAN');
  wFilterLan = REPLACE(wFilterLan, '/*HORAINICIAL*/', 'BDHORALANINICIAL');
  wFilterLan = REPLACE(wFilterLan, '/*HORAFINAL*/', 'BDHORALAN');
  wFilterLan = REPLACE(wFilterLan, '/*QUANTIDADE*/', '1');
  wFilterLan = REPLACE(wFilterLan, '/*TABELA*/', 'VSUC_EMPRESAS_TLAN');
  wFilterLan = REPLACE(wFilterLan, '/*APELIDO*/', 'lan');

  --SQL completo dos tempos.
  wSQL = 'select * from (';
  wSQL = wSQL||' select emp.BDCODEMP, sis.BDCODSIS, sis.BDORDEMSCI, usu.BDCODUSU, tela.BDCODTELASIS, ';
  wSQL = wSQL||' emp.BDNOMEMP, sis.BDDESCSIS, usu.BDNOMCOMPLUSU, tela.BDCAPTIONTELA,';
  wSQL = wSQL||' sum(case when BDTIPOACAO = 0 then BDQUANTIDADE else 0 end) as BDQUANTIDADE,';
  wSQL = wSQL||' Sum(Abs(case when BDTIPOACAO = 0 then (BDDATAFINAL + BDHORAFINAL) - (BDDATAINICIAL + BDHORAINICIAL) else 0 end)) as BDTEMPOATIVO,';
  wSQL = wSQL||' Sum(Abs(case when BDTIPOACAO = 0 then 0 else (BDDATAFINAL + BDHORAFINAL) - (BDDATAINICIAL + BDHORAINICIAL) end)) as BDTEMPOINATIVO';
  wSQL = wSQL||' from ('||wFilterLog||' union all '||wFilterLan||') tempos';
  wSQL = wSQL||' join TUSUARIO usu on (usu.BDCODUSU = tempos.BDCODUSU)';
  wSQL = wSQL||' left join VW_TEMPRESAS_REF emp on (emp.BDCODEMP = tempos.BDCODEMP)';
  wSQL = wSQL||' left join TSISTEMA sis on (sis.BDCODSIS = tempos.BDCODSIS)';
  wSQL = wSQL||' left join TTELA_SISTEMA tela on (tela.BDCODTELASIS = tempos.BDCODTELASIS)';
  wSQL = wSQL||' group by emp.BDCODEMP, emp.BDNOMEMP, sis.BDCODSIS, sis.BDORDEMSCI, sis.BDDESCSIS, usu.BDCODUSU, usu.BDNOMCOMPLUSU, tela.BDCODTELASIS, tela.BDCAPTIONTELA';
  wSQL = wSQL||' union';
  wSQL = wSQL||' select first 1 null, null, null, null, null, null, null, null, null, null, null, null from RDB$FIELDS)';
  wSQL = wSQL||' order by case when (BDCODUSU is null) then 1 else 0 end, ';
  wSQL = wSQL||REPLACE(REPLACE(REPLACE(prFields, 'BDNOMEMP', 'BDCODEMP'), 'BDDESCSIS', 'BDORDEMSCI'), 'BDNOMCOMPLUSU', 'BDCODUSU');
  wSQL = wSQL||', BDTEMPOATIVO '||CASE WHEN prOrder = 0 THEN 'asc' ELSE 'desc' END;

  IF (prReport = 0) THEN
    BEGIN
      FOR EXECUTE STATEMENT wSQL INTO :wCODEMP, :wCODSIS, :wORDEMSCI, :wCODUSU, :wCODTELASIS,
                                      :wNOMEMP, :wDESCSIS, :wNOMCOMPLUSU, :wCAPTIONTELA,
                                      :wQuantidade, wTempoAtivo, :wTempoInativo DO
      BEGIN
        wTempoAtivoTotal = wTempoAtivoTotal + COALESCE(wTempoAtivo, 0);
        wTempoInativoTotal = wTempoInativoTotal + COALESCE(wTempoInativo, 0);
        wQuantidadeTotal = wQuantidadeTotal + COALESCE(wQuantidade, 0);
      END
    
      rdb$set_context('USER_SESSION', 'W_LOG_QUANTIDADE', :wQuantidadeTotal);
      rdb$set_context('USER_SESSION', 'W_LOG_TEMPOATIVOTOTAL', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + :wTempoAtivoTotal);
      rdb$set_context('USER_SESSION', 'W_LOG_TEMPOINATIVOTOTAL', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + :wTempoInativoTotal);
      rdb$set_context('USER_SESSION', 'W_LOG_TEMPOMEDIO', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + CASE WHEN :wQuantidadeTotal > 0 THEN CAST(:wTempoAtivoTotal AS DECIMAL(18,9)) / :wQuantidadeTotal ELSE 0 END);
    END

  FOR EXECUTE STATEMENT wSQL INTO :wCODEMP, :wCODSIS, :wORDEMSCI, :wCODUSU, :wCODTELASIS,
                                  :wNOMEMP, :wDESCSIS, :wNOMCOMPLUSU, :wCAPTIONTELA,
                                  :wQuantidade, wTempoAtivo, :wTempoInativo DO
  BEGIN
    wColumn1 = 0;
    wColumn2 = 0;
    wColumn3 = 0;
    wColumn4 = 0;
    wPosition = wLastLevel;
    wReprintLevel = MINVALUE(CASE WHEN wCodUSU IS NULL THEN 0 ELSE 999 END,
                             CASE WHEN COALESCE(wCODEMP, 0) <> COALESCE(wCODEMP_AUX, 0) THEN wSeqEmp ELSE 999 END,
                             CASE WHEN COALESCE(wCODSIS, 0) <> COALESCE(wCODSIS_AUX, 0) THEN wSeqSis ELSE 999 END,
                             CASE WHEN COALESCE(wCODUSU, 0) <> COALESCE(wCODUSU_AUX, 0) THEN wSeqUsu ELSE 999 END,
                             CASE WHEN COALESCE(wCODTELASIS, 0) <> COALESCE(wCODTELASIS_AUX, 0) THEN wSeqTela ELSE 999 END);
    WHILE (wPosition > 0) DO
    BEGIN
      wColumn1 = CASE WHEN wSeqEmp = wPosition THEN wPosition ELSE 0 END;
      wColumn2 = CASE WHEN wSeqSis = wPosition THEN wPosition ELSE 0 END;
      wColumn3 = CASE WHEN wSeqUsu = wPosition THEN wPosition ELSE 0 END;
      wColumn4 = CASE WHEN wSeqTela = wPosition THEN wPosition ELSE 0 END;
      BDNOMEMP = TRIM(CASE WHEN wPosition = wLastLevel THEN '' ELSE wDescTotal END||CASE WHEN wColumn1 = wPosition AND (wColumn1 >= wReprintLevel) THEN (CASE WHEN wCODEMP_AUX IS NULL THEN 'Sem v?nculo de empresa' ELSE wNOMEMP_AUX END) END);
      BDDESCSIS = TRIM(CASE WHEN wPosition = wLastLevel THEN '' ELSE wDescTotal END||CASE WHEN wColumn2 = wPosition AND (wColumn2 >= wReprintLevel) THEN wDESCSIS_AUX END);
      BDNOMCOMPLUSU = TRIM(CASE WHEN wPosition = wLastLevel THEN '' ELSE wDescTotal END||CASE WHEN wColumn3 = wPosition AND (wColumn3 >= wReprintLevel) THEN wNOMCOMPLUSU_AUX END);
      BDCAPTIONTELA = TRIM(CASE WHEN wPosition = wLastLevel THEN '' ELSE wDescTotal END||CASE WHEN wColumn4 = wPosition AND (wColumn4 >= wReprintLevel) THEN wCAPTIONTELA_AUX END);
      BDTIPOREGISTRO = CASE WHEN wPosition = wLastLevel THEN 0 ELSE 2 END;
    IF ((BDNOMEMP IS NOT NULL) OR (BDDESCSIS IS NOT NULL) OR (BDNOMCOMPLUSU IS NOT NULL) OR (BDCAPTIONTELA IS NOT NULL)) THEN
      BEGIN
          IF (wPosition = 1) THEN
            BEGIN
              wTempoAtivoAtu = wTempoAtivoSoma1;
              wTempoAtivoSoma1 = 0;
              wTempoInativoAtu = wTempoInativoSoma1;
              wTempoInativoSoma1 = 0;
              wQuantidadeAtu = wQuantidadeSoma1;
              wQuantidadeSoma1 = 0;
      END
          ELSE IF (wPosition = 2) THEN
      BEGIN
              wTempoAtivoAtu = wTempoAtivoSoma2;
              wTempoAtivoSoma2 = 0;
              wTempoInativoAtu = wTempoInativoSoma2;
              wTempoInativoSoma2 = 0;
              wQuantidadeAtu = wQuantidadeSoma2;
        wQuantidadeSoma2 = 0;
      END
          ELSE IF (wPosition = 3) THEN
            BEGIN
              wTempoAtivoAtu = wTempoAtivoSoma3;
              wTempoAtivoSoma3 = 0;
              wTempoInativoAtu = wTempoInativoSoma3;
              wTempoInativoSoma3 = 0;
              wQuantidadeAtu = wQuantidadeSoma3;
              wQuantidadeSoma3 = 0;
            END

          BDTEMPOATIVO = CAST('12/30/1899 00:00:00' AS TIMESTAMP) + wTempoAtivoAtu;
          BDTEMPOINATIVO = CAST('12/30/1899 00:00:00' AS TIMESTAMP) + wTempoInativoAtu;
          BDQUANTIDADE = wQuantidadeAtu;
          BDTEMPOMEDIO = CAST('12/30/1899 00:00:00' AS TIMESTAMP) + CASE WHEN wQuantidadeAtu > 0 THEN CAST(wTempoAtivoAtu AS DECIMAL(18,9)) / wQuantidadeAtu ELSE 0 END;
          BDPERCENTUAL = CASE WHEN (prReport = 0) AND (wTempoAtivoAtu > 0) THEN 100 / wTempoAtivoTotal ELSE 0 END;
          BDPERCENTUAL = wTempoAtivoAtu * BDPERCENTUAL;
          SUSPEND;
        END
      wPosition = wPosition -1;
    END

    --Se o c?digo da empresa for nulo, ? o registro extra adicionado no final apenas para totalizar, ent?o n?o deve imprimir nem contabilizar nada que ? feito abaixo.
    IF (wCodUsu IS NULL) THEN
      BEGIN
        --Uso estas vari?veis posteriormente para calcular a porcentagem de cada registro e apresentar totais.
        rdb$set_context('USER_SESSION', 'W_LOG_QUANTIDADE', :wQuantidadeTotal);
        rdb$set_context('USER_SESSION', 'W_LOG_TEMPOATIVOTOTAL', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + :wTempoAtivoTotal);
        rdb$set_context('USER_SESSION', 'W_LOG_TEMPOINATIVOTOTAL', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + :wTempoInativoTotal);
        rdb$set_context('USER_SESSION', 'W_LOG_TEMPOMEDIO', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + CASE WHEN :wQuantidadeTotal > 0 THEN CAST(:wTempoAtivoTotal AS DECIMAL(18,9)) / :wQuantidadeTotal ELSE 0 END);
        LEAVE;
      END

    BDCODEMP = wCODEMP;
    BDCODSIS = wCODSIS;
    BDORDEMSCI = wORDEMSCI;
    BDCODUSU = wCODUSU;
    BDCODTELASIS = wCODTELASIS;

    BDTEMPOATIVO = NULL;
    BDTEMPOINATIVO = NULL;
    BDQUANTIDADE = NULL;
    BDTEMPOMEDIO = NULL;
    BDPERCENTUAL = NULL;
    BDTIPOREGISTRO = 1;

    wColumn1 = 999;
    wColumn2 = 999;
    wColumn3 = 999;
    wColumn4 = 999;
    wPosition = 1;
    --N?o d? pra fazer a linha de registro aqui, pois precisa somar todos os registros quando est? com um n?vel a menos.
    WHILE (wPosition < wLastLevel) DO
      BEGIN
      wColumn1 = CASE WHEN wSeqEmp = wPosition AND (COALESCE(wCODEMP, 0) <> COALESCE(wCODEMP_AUX, 0) OR (wReprintLevel <= wSeqEmp)) THEN wPosition ELSE wColumn1 END;
      wColumn2 = CASE WHEN wSeqSis = wPosition AND (COALESCE(wCODSIS, 0) <> COALESCE(wCODSIS_AUX, 0) OR (wReprintLevel <= wSeqSis)) THEN wPosition ELSE wColumn2 END;
      wColumn3 = CASE WHEN wSeqUsu = wPosition AND (COALESCE(wCODUSU, 0) <> COALESCE(wCODUSU_AUX, 0) OR (wReprintLevel <= wSeqUsu)) THEN wPosition ELSE wColumn3 END;
      wColumn4 = CASE WHEN wSeqTela = wPosition AND (COALESCE(wCODTELASIS, 0) <> COALESCE(wCODTELASIS_AUX, 0) OR (wReprintLevel <= wSeqTela)) THEN wPosition ELSE wColumn4 END;
      wReprintLevel = MINVALUE(wColumn1, wColumn2, wColumn3, wColumn4);
      BDNOMEMP = TRIM(CASE WHEN wColumn1 = wPosition THEN (CASE WHEN wCODEMP IS NULL THEN 'Sem v?nculo de empresa' ELSE wNOMEMP END) END);
      BDDESCSIS = TRIM(CASE WHEN wColumn2 = wPosition THEN wDESCSIS END);
      BDNOMCOMPLUSU = TRIM(CASE WHEN wColumn3 = wPosition THEN wNOMCOMPLUSU END);
      BDCAPTIONTELA = TRIM(CASE WHEN wColumn4 = wPosition THEN wCAPTIONTELA END);
      wPosition = wPosition + 1;
      IF ((BDNOMEMP IS NOT NULL) OR (BDDESCSIS IS NOT NULL) OR (BDNOMCOMPLUSU IS NOT NULL) OR (BDCAPTIONTELA IS NOT NULL)) THEN
        SUSPEND;
    END

    wCODEMP_AUX = wCODEMP;
    wCODSIS_AUX = wCODSIS;
    wCODUSU_AUX = wCODUSU;
    wCODTELASIS_AUX = wCODTELASIS;
    wNOMEMP_AUX = wNOMEMP;
    wDESCSIS_AUX = wDESCSIS;
    wNOMCOMPLUSU_AUX = wNOMCOMPLUSU;
    wCAPTIONTELA_AUX = wCAPTIONTELA;

    wTempoAtivoAtu = wTempoAtivo;
    wTempoAtivoSoma1 = wTempoAtivoSoma1 + wTempoAtivo;
    wTempoAtivoSoma2 = wTempoAtivoSoma2 + wTempoAtivo;
    wTempoAtivoSoma3 = wTempoAtivoSoma3 + wTempoAtivo;
    wTempoInativoAtu = wTempoInativo;
    wTempoInativoSoma1 = wTempoInativoSoma1 + wTempoInativo;
    wTempoInativoSoma2 = wTempoInativoSoma2 + wTempoInativo;
    wTempoInativoSoma3 = wTempoInativoSoma3 + wTempoInativo;
    wQuantidadeAtu = wQuantidade;
    wQuantidadeSoma1 = wQuantidadeSoma1 + wQuantidade;
    wQuantidadeSoma2 = wQuantidadeSoma2 + wQuantidade;
    wQuantidadeSoma3 = wQuantidadeSoma3 + wQuantidade;
    IF (prReport = 1) THEN
      BEGIN
        wTempoAtivoTotal = wTempoAtivoTotal + COALESCE(wTempoAtivo, 0);
        wTempoInativoTotal = wTempoInativoTotal + COALESCE(wTempoInativo, 0);
        wQuantidadeTotal = wQuantidadeTotal + COALESCE(wQuantidade, 0);
      END
  END
END
^

/* Restore proc. body: DIA_SEGUINTE */
ALTER PROCEDURE DIA_SEGUINTE(PRDATA DATE)
 RETURNS(PRDIASEGUINTE DATE)
 AS
DECLARE VARIABLE WULTDIA SMALLINT;
DECLARE VARIABLE WDIA SMALLINT;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
BEGIN

  wdia = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 9 FOR 2) AS SMALLINT);
  wmes = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);

--  exception ex_date wdia||'-'||wmes||'-'||wano;

  SELECT UltDia FROM ultimo_dia_mes(:wmes,:wano) INTO :wultdia;

  IF (wultdia = wdia) THEN
     BEGIN
       wdia = 1;
       SELECT mes, ano FROM ref_seguinte(:wmes,:wano) INTO :wmes, :wAno;
     END
  ELSE
     BEGIN
       wdia = wdia + 1;
     END

  prdiaseguinte = :wmes||'/'||:wdia||'/'||:wano;

  SUSPEND;

END
^

/* Restore proc. body: MAXSCI */
ALTER PROCEDURE MAXSCI(PRCAMPO VARCHAR(1024),
PRORDEM VARCHAR(1024),
PRCONDICAO VARCHAR(1024),
PRTABELA VARCHAR(1024))
 RETURNS(BDRESULT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WORDEM_TRAN VARCHAR(150);
BEGIN
  /* procedimento criado para substituir a clausula "MAX" nos automatismos
  obs: nao esquecer de criar o indice descendente na tabela que for usar o MAXSCI*/

  SELECT bdresult FROM strtran(:prordem, ',', ' desc,') INTO wordem_tran;

  wsql = 'select first 1 coalesce('||prcampo||', 0) from '||prtabela;
  IF (prcondicao <> '') THEN
     wsql = wsql||' where '||prcondicao;
  IF (prordem <> '') THEN
     wsql = wsql||' order by '||wordem_tran||' desc';
     --wsql = wsql||' order by '||prordem||' desc';


  EXECUTE STATEMENT wsql INTO :bdresult;
  IF (bdresult IS NULL) THEN
     bdresult = 0;
--  bdresult = bdresult +1;
  SUSPEND;
END
^

/* Restore proc. body: SP_APURACAO_BLOCOM */
ALTER PROCEDURE SP_APURACAO_BLOCOM(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODCONFBLOCOM INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WWHEREEMPRESAS VARCHAR(500);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Obt?m a configura??o do Bloco M...
  SELECT BDCODCONFBLOCOM FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :prCODEMP INTO :wCODCONFBLOCOM;

  -- Quando n?o tiver configura??o de Blooo M na empresa, vai buscar uma configura??o padr?o...
  IF (wCODCONFBLOCOM IS NULL) THEN
    SELECT FIRST 1 BDCODCONF FROM VEF_BASE_TCONFBLOCOM WHERE BDPLANOPADRAO = 'TRUE' INTO :wCODCONFBLOCOM;

  wWhereEmpresas = '';
  /* Cria apura??o do Bloco M, necess?rio para os registros abaixo... */
  FOR
      SELECT ex.BDCODEMP
      FROM TEMPRESAS ex
      WHERE ex.BDCODEMP = :prCODEMP
         OR ex.BDCODMATRIZ = :prCODEMP
      INTO :wCODEMP
  DO
   BEGIN
     INSERT INTO VEF_EMP_TBLOCOMGER (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCONF) VALUES (7, :wCODEMP, :prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM);
     wWhereEmpresas = wWhereEmpresas || wCodEmp || ',';
   END

   wWhereEmpresas = ' bdCODEMP IN(' || SUBSTRING(wWhereEmpresas FROM 1 FOR CHARACTER_LENGTH(wWhereEmpresas) -1) ||') ';

  IF (:wCODCONFBLOCOM IS NOT NULL) THEN
    BEGIN
      /* REGISTRO 0111: TABELA DE RECEITA BRUTA MENSAL PARA FINS DE RATEIO DE CR?DITOS COMUNS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_0110 (:prCODEMP, :prREFERENCIA);

      /* REGISTRO M100: CR?DITO DE PIS/PASEP RELATIVO AO PER?ODO
         REGISTRO M500: CR?DITO DE COFINS RELATIVO AO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100_M500 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO 1100: CONTROLE DE CR?DITOS FISCAIS ? PIS/PASEP
         REGISTRO 1500: CONTROLE DE CR?DITOS FISCAIS ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_1100_1500 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO F600: CONTRIBUI??O RETIDA NA FONTE
         REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
         REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_F60013001700 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO M300: CONTRIBUI??O DE PIS/PASEP DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO.
         REGISTRO M700: COFINS DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M300_M700 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);

      /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP
         REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO
         REGISTRO M600: CONSOLIDA??O DA CONTRIBUI??O PARA A SEGURIDADE SOCIAL - COFINS DO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M200_M600 (:prCODEMP, :prREFERENCIA,:wWhereEmpresas);

      /* Gera ?ltimos ajustes da apura??o */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_DADOSFINAIS (:prCODEMP, :prREFERENCIA);
      
      /* Cria a contabiliza??o */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE (:prCODEMP, :prREFERENCIA);

      /* Apaga os dados das tabelas tempor?rias, faz isso pq se apura-se mais de uma vez, somava todos os valores */
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_0110_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_0111_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_TCONF_CONTAS_ONLINE_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
    END
  ELSE
    BEGIN
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC) VALUES
                                   (7, :prCODEMP, :prCODEMP, :prREFERENCIA,
                                    COALESCE((SELECT MAX(x.BDCODBLOCOM)+1 FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA),1),
                                    NULL, NULL, NULL, NULL, 5);
    END
    
END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_0110 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_0110(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,2);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,2);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,2);
DECLARE VARIABLE WRBCUM NUMERIC(15,2);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Incid?ncia tribut?ria
  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  -- Obt?m os valores das formulas apuradas
  wSQL =       'SELECT ';
  IF (:wINCTRIB IN (1,3)) THEN
    wSQL = wSQL||'       COALESCE(BDRBNCUMTRIBMI, 0) as BDRBNCUMTRIBMI, COALESCE(BDRBNCUMNTMI, 0) as BDRBNCUMNTMI, COALESCE(BDRBNCUMEXP, 0) as BDRBNCUMEXP, ';
  ELSE
    wSQL = wSQL||'       0 as BDRBNCUMTRIBMI, 0 as BDRBNCUMNTMI, 0 as BDRBNCUMEXP, ';

  IF (:wINCTRIB IN (2,3)) THEN
    wSQL = wSQL||'       COALESCE(BDRBCUM, 0) as BDRBCUM ';
  ELSE
    wSQL = wSQL||'       0 as BDRBCUM ';

  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_0110_TEMP aux ';
  wSQL = wSQL||'WHERE aux.BDCODEMP = '||:prCODEMP;
  wSQL = wSQL||'  AND aux.BDREFERENCIA = '||:prREFERENCIA;

  EXECUTE STATEMENT ( wSQL )
  INTO :wRBNCUMTRIBMI, :wRBNCUMNTMI, :wRBNCUMEXP, :wRBCUM;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 1, COALESCE(:wRBNCUMTRIBMI,0));

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 2, COALESCE(:wRBNCUMNTMI,0));

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 3, COALESCE(:wRBNCUMEXP,0));

  /* 35 - Contribui??o cumulativa */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 35, 1, COALESCE(:wRBCUM,0));

  /* 36 - Contribui??o Total (Valores n?o cumulativos + cumulativos) */
  -- Obt?m os valores das formulas apuradas
  SELECT SUM(BDVALOR)
  FROM VEF_EMP_TBLOCOMGERREG aux
  WHERE (aux.BDCODQUADRO IN (34,35)) /* 34 - Contribui??o n?o cumulativa / 35 - Contribui??o cumulativa */
    AND aux.BDCODEMP = :prCODEMP
    AND aux.BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 36, 1, COALESCE(:wRBNCUMTRIBMI,0));

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_1100_1500 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_1100_1500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDCREDITOSPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wCREDITOSPERANT;

  /* Caso tenha saldos no per?odo anterior a apura??o, vai carregar estes valores para a apura??o atual */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM) ';
  wSQL = wSQL||'SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = aux.BDCODQUADRO AND x.BDCODPERIODO = aux.BDCODPERIODO AND x.BDCODEMP = aux.BDCODEMP AND x.BDREFERENCIA = aux.BDREFERENCIA), ';
  wSQL = wSQL||       'aux.BDCODCRE_4_3_6, aux.BDPER_APU_CRED, aux.BDORIG_CRED, aux.BDCNPJ_SUC, ';
  wSQL = wSQL||       'SUM(COALESCE(aux.BDVL_CRED_APU,0)) as BDVL_CRED_APU, SUM(COALESCE(aux.BDVL_CRED_DESC_EFD,0)) as BDVL_CRED_DESC_EFD, SUM(COALESCE(aux.BDSLD_CRED_FIM,0)) as BDSLD_CRED_FIM ';
  wSQL = wSQL||'FROM ( ';
  --IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
    BEGIN
                         /* Saldos periodos anteriores a apura??o */
      wSQL = wSQL||      'SELECT m.BDCODQUADRO, m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, m.BDCODCRE_4_3_6, m.BDPER_APU_CRED, m.BDORIG_CRED, ';
      wSQL = wSQL||             'm.BDCNPJ_SUC, m.BDSLD_CRED_FIM AS BDVL_CRED_APU, 0 AS BDVL_CRED_DESC_EFD, m.BDSLD_CRED_FIM ';
      wSQL = wSQL||      'FROM VEF_EMP_TBLOCOM1100_1500 m ';
      wSQL = wSQL||      'WHERE (m.BDCODMATRIZ = '||:prCODEMP||') ';
      wSQL = wSQL||        'AND (m.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA ';
      wSQL = wSQL||                               'FROM VEF_EMP_TBLOCOM1100_1500 x ';
      wSQL = wSQL||                               'WHERE x.BDCODEMP = '||:prCODEMP||' ';
      wSQL = wSQL||                                 'AND x.BDREFERENCIA < '||:prREFERENCIA||' ';
      wSQL = wSQL||                                'ORDER BY x.BDREFERENCIA DESC)) ';
      wSQL = wSQL||        'AND m.BDSLD_CRED_FIM > 0 ';
    
      wSQL = wSQL||      'UNION ALL ';
    END
                     /* Saldos de PIS lan?ados */
  wSQL = wSQL||      'SELECT 52 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL||             's.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDCODCRE_4_3_6, s.BDREFAPUSALDO as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             's.BDCNPJCEDENTE as BDCNPJ_SUC, s.BDVLRCREPIS as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, s.BDVLRCREPIS as BDSLD_CRED_FIM ';
  wSQL = wSQL||      'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCREPIS > 0 ';

  wSQL = wSQL||      'UNION ALL ';
                     /* Saldos de Cofins lan?ados */
  wSQL = wSQL||      'SELECT 53 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL||             's.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDCODCRE_4_3_6, s.BDREFAPUSALDO as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             's.BDCNPJCEDENTE as BDCNPJ_SUC, s.BDVLRCRECOFINS as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, s.BDVLRCRECOFINS as BDSLD_CRED_FIM ';
  wSQL = wSQL||      'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCRECOFINS > 0 ';

  wSQL = wSQL||      ') aux ';
  wSQL = wSQL||'GROUP BY aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODCRE_4_3_6, ';
  wSQL = wSQL||         'aux.BDPER_APU_CRED, aux.BDORIG_CRED, aux.BDCNPJ_SUC';

  EXECUTE STATEMENT ( wSQL );
        
END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_F60013001700 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_F60013001700(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WTIPOAPURACAORET INTEGER;
DECLARE VARIABLE WINDNATPJ INTEGER;
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wRETPISCOFPERANT;

  SELECT BDTIPOAPURACAORET FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :prCODEMP
  INTO :wTIPOAPURACAORET;

  SELECT BDINDNATPJ FROM VW_VEF_BASE_TEMPPARFED WHERE BDCODEMP = :prCODEMP
  INTO :wINDNATPJ;

  wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_F600_1300 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDREFAPUSALDO, BDCODTER, BDCNPJEMP, BDDATAEMISSAO, BDVLRCONTAB, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDIND_DEC, BDCODRECPIS, BDCODRECCOFINS, BDVLRPISRET, BDVLRCOFINSRET) ';
                     /* Saldos de PIS e/ou Cofins lan?ados */
  wSQL = wSQL||'SELECT s.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDREFAPUSALDO, 0 as BDCODTER, emp.BDCNPJEMP, ';
  wSQL = wSQL||       'CAST(SUBSTRING(s.BDREFERENCIA from 1 for 4)||''-''|| SUBSTRING(s.BDREFERENCIA from 5 for 2)||''-01'' as date) as BDDATAEMISSAO, ';
  wSQL = wSQL||       '0 as BDVLRCONTAB, s.BDCODIND_NAT_RET, s.BDTIPONATREC, 0 as BDIND_DEC, ';
  wSQL = wSQL||       'null as BDCODRECPIS, null as BDCODRECCOFINS, ';
  wSQL = wSQL||       'COALESCE(s.BDVLRRETPIS, 0) as BDVLRPISRET, COALESCE(s.BDVLRRETCOFINS, 0) as BDVLRCOFINSRET ';
  wSQL = wSQL||'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||'WHERE ((s.BDVLRRETPIS > 0) or (s.BDVLRRETCOFINS > 0)) ';
  wSQL = wSQL||        'AND (s.BDCREDRETIDOS = ''TRUE'') ';
  wSQL = wSQL||        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';

  wSQL = wSQL||'UNION ALL ';

               -- Solicita??o 4962
  wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDREFAPUSALDO, aux.BDCODTER, emp.BDCNPJEMP,  ';
  wSQL = wSQL||       'aux.BDDATAEMISSAO, aux.BDVLRCONTAB, nat.BDCODIND_NAT_RET, aux.BDTIPONATREC, aux.BDIND_DEC, ';
  wSQL = wSQL||       'aux.BDCODRECPIS, aux.BDCODRECCOFINS, aux.BDVLRPISRET, aux.BDVLRCOFINSRET ';
  wSQL = wSQL||'FROM ( ';
                     -- Demais documentos
  wSQL = wSQL||      'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN as BDREFERENCIA, dem.BDREFLAN as BDREFAPUSALDO, dem.BDCODTER, indoper.BDINDICADOR,';
  wSQL = wSQL||             'dem.BDDT_OPER as BDDATAEMISSAO, dem.BDVL_OPER as BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
  wSQL = wSQL||             'ret.BDVLRPIS as BDVLRPISRET, ret.BDVLRCOFINS as BDVLRCOFINSRET,';
  wSQL = wSQL||             'case when dem.BDIND_OPER = 1 then 1 else 0 end as BDIND_DEC '; -- Aquisi??o
  wSQL = wSQL||      'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
  wSQL = wSQL||      'JOIN VEF_BASE_TAB_TIPO_OPERACAO indoper on (indoper.BDIND_OPER = dem.BDIND_OPER) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
  wSQL = wSQL||      'WHERE dem.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND (CAST(SUBSTRING(dem.BDDT_OPER FROM 1 for 4)||SUBSTRING(dem.BDDT_OPER FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
    
  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||        'AND (dem.BDCONDPGTO <> 1) ';
    
  -- Caso incid?ncia tribut?ria 2 = regime cumulativo. Sped lucro presumido somente os lan?amentos de saidas(receitas) ent?o somente os lan?amentos com tipos 1 e 2.
  IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente aquisi??o e receita n?o sujeita ao pagamento de contribui??o
    wSQL = wSQL||        'AND (dem.BDIND_OPER <> 0) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||      'UNION ALL ';
                         -- Demais documentos - Pagamentos
      wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(EMP.BDCODMATRIZ, MOV.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, indoper.BDINDICADOR,';
      wSQL = wSQL||             'pgto.BDDATAPGTOPAR as BDDATAEMISSAO,';
      wSQL = wSQL||             '((pgto.BDVALORPGTOPAR)+';
      wSQL = wSQL||              '(COALESCE(pgto.BDVALORRETPIS, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCOFINS,0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCSLL, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETIRRF, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETISSQN, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETINSS, 0))) as BDVLRCONTAB,';
      wSQL = wSQL||             'ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
      wSQL = wSQL||             'pgto.BDVALORRETPIS as BDVLRPISRET, pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||             'case when mov.BDIND_OPER = 1 then 1 else 0 end as BDIND_DEC '; -- Aquisi??o
      wSQL = wSQL||      'FROM (';
      wSQL = wSQL||            'SELECT * ';
      wSQL = wSQL||            'FROM ( ';
      wSQL = wSQL||                  'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDIND_OPER, x.BDCODCSTPIS, x.BDCODCSTCOF ';
      wSQL = wSQL||                  'FROM VEF_EMP_TMOVDEMAISDOC_F100 x ';
      wSQL = wSQL||                  'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente aquisi??o e receita n?o sujeita ao pagamento de contribui??o
        wSQL = wSQL||                   'AND (x.BDIND_OPER <> 0) ';
      wSQL = wSQL||                  ') aux ';
      wSQL = wSQL||            'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                     'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||            ') mov ';
      wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVF100PARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||      'JOIN VEF_BASE_TAB_TIPO_OPERACAO INDOPER on (indoper.BDIND_OPER = mov.BDIND_OPER) ';
      wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = mov.BDCODEMP and ret.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||      'WHERE ((mov.BDCODCSTPIS is not null) or (mov.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||        'AND (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||        'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||      'UNION ALL ';
                     -- Lan?amentos de compensa??o de reten??es de servi?os emitidos
  wSQL = wSQL||      'SELECT ret.BDCODEMP, COALESCE(emp.BDCODMATRIZ, ret.BDCODEMP) as BDCODMATRIZ, ret.BDREFERENCIA, ret.BDREFERENCIA as BDREFAPUSALDO, ret.BDCODTER, ';
  wSQL = wSQL||             '0 AS BDINDICADOR, ret.BDDATALAN AS BDDATAEMISSAO, ret.BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             '0 as BDIND_DEC ';
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT r.BDCODEMP, r.BDCODTER, r.BDREFLAN AS BDREFERENCIA, r.BDDATALAN, r.BDVLRCONTAB, r.BDCODIND_NAT_RET, r.BDCODRECPIS, ';
  wSQL = wSQL||                   'r.BDCODRECCOFINS, r.BDVLRPIS, r.BDVLRCOFINS, r.BDTIPONATREC ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVCOMPRET r ';
  wSQL = wSQL||            'WHERE r.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (CAST(SUBSTRING(r.BDDATALAN FROM 1 for 4)||SUBSTRING(r.BDDATALAN FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
  wSQL = wSQL||            ') ret ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = ret.BDCODEMP) ';

  wSQL = wSQL||      'UNION ALL ';
                     -- Servi?o
  wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFERENCIA, mov.BDREFERENCIA as BDREFAPUSALDO, mov.BDCODTER, ';
  wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, mov.BDDATAEMISSAO, mov.BDVALORNOTA AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             'case when mov.BDTIPLAN = 1 then 1 else 0 end as BDIND_DEC '; -- Recebidos
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT ser.BDCODEMP, ser.BDCHAVE, ser.BDCODTER, ser.BDDATAEMISSAO, ser.BDVALORNOTA, ser.BDTIPLAN, ser.BDREFLAN AS BDREFERENCIA ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVSER ser ';
  wSQL = wSQL||            'WHERE ser.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (ser.BDREFLAN = '||:prREFERENCIA||') ';
  wSQL = wSQL||              'AND (ser.BDCODSITNF not in (2,3,4,5)) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
  -- caso incid?ncia tribut?ria 2 = regime cumulativo, exportar somente emitidos
  IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente servi?os emitidos
    wSQL = wSQL||              'AND (ser.BDTIPLAN = 0) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||              'AND (ser.BDCONDPGTO <> 1) ';

  wSQL = wSQL||            ') mov ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSERRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||      'UNION ALL ';
     
      wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, ';
      wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, pgto.BDDATAPGTOPAR as BDDATAEMISSAO, ';
      wSQL = wSQL||             '((pgto.BDVALORPGTOPAR)+ ';
      wSQL = wSQL||              '(COALESCE(pgto.BDVALORRETPIS,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
      wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ';
      wSQL = wSQL||             'pgto.BDVALORRETPIS as BDVLRPISRET,';
      wSQL = wSQL||             'pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||             'case when mov.BDTIPLAN = 1 then 1 else 0 end as BDIND_DEC '; -- Recebidos
      wSQL = wSQL||      'FROM ( ';
      wSQL = wSQL||            'SELECT * ';
      wSQL = wSQL||            'FROM ( ';
      wSQL = wSQL||                  'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDTIPLAN, x.BDCODSITNF, x.BDDATAEMISSAO ';
      wSQL = wSQL||                  'FROM VEF_EMP_TMOVSER x ';
      wSQL = wSQL||                  'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente servi?os emitidos
        wSQL = wSQL||                    'AND (x.BDTIPLAN = 0) ';
      wSQL = wSQL||                  ') aux ';
    
      wSQL = wSQL||            'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                    'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND aux.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
      wSQL = wSQL||           ') mov ';
      wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERPARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||      'WHERE (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||        'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||      'UNION ALL ';
                     -- Sa?das
  wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFERENCIA, mov.BDREFERENCIA as BDREFAPUSALDO, mov.BDCODTER, ';
  wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, mov.BDDATAEMISSAO, mov.BDVALORNOTA AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             '0 as BDIND_DEC ';
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT sai.BDCODEMP, sai.BDCHAVE, sai.BDCODTER, sai.BDDATAEMISSAO, sai.BDVALORNOTA, sai.BDTIPLAN, sai.BDREFLAN AS BDREFERENCIA ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVSAI sai ';
  wSQL = wSQL||            'WHERE sai.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (CAST(SUBSTRING(sai.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(sai.BDDATAEMISSAO FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
  wSQL = wSQL||              'AND sai.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||              'AND (sai.BDCONDPGTO <> 1) ';

  wSQL = wSQL||            ') mov ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSAIRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||            'UNION ALL ';
    
      wSQL = wSQL||            'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, ';
      wSQL = wSQL||                   'mov.BDTIPLAN AS BDINDICADOR, pgto.BDDATAPGTOPAR as BDDATAEMISSAO, ';
      wSQL = wSQL||                   '((pgto.BDVALORPGTOPAR)+ ';
      wSQL = wSQL||                    '(COALESCE(pgto.BDVALORRETPIS,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
      wSQL = wSQL||                   'ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
      wSQL = wSQL||                   'pgto.BDVALORRETPIS as BDVLRPISRET,';
      wSQL = wSQL||                   'pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||                   '0 as BDIND_DEC ';
      wSQL = wSQL||             'FROM ( ';
      wSQL = wSQL||                   'SELECT * ';
      wSQL = wSQL||                   'FROM ( ';
      wSQL = wSQL||                          'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDTIPLAN, x.BDCODSITNF, x.BDDATAEMISSAO ';
      wSQL = wSQL||                          'FROM VEF_EMP_TMOVSAI x ';
      wSQL = wSQL||                          'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                         ') aux ';
      wSQL = wSQL||                   'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                           'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||                     'AND aux.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
    
      wSQL = wSQL||                 ') mov ';
      wSQL = wSQL||            'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIPARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||            'WHERE (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||              'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||    ') aux ';
  wSQL = wSQL||'JOIN TEMPRESAS emp on (aux.BDCODEMP = emp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TIND_NAT_RET nat on (nat.BDCODIND_NAT_RET = aux.BDCODIND_NAT_RET) ';
  wSQL = wSQL||'LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.BDCODTER = aux.BDCODTER) ';
  wSQL = wSQL||'WHERE (nat.BDREGEXP in (''01'',''02'',''03'',''04'',''05'',''99'')) ';
  wSQL = wSQL||' AND (CHAR_LENGTH(ter.BDCGCTER) >= 18) ';
  --wSQL = wSQL||'ORDER BY aux.BDCODMATRIZ, aux.BDCODEMP ';

  EXECUTE STATEMENT ( wSQL );

  -- REGISTRO F600: CONTRIBUI??O RETIDA NA FONTE
  INSERT INTO VEF_EMP_TBLOCOMF600 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODREC, BDCODIND_NAT_RET, BDDT_RET, BDVL_BC_RET, BDVL_RET, BDCNPJPART, BDNOMEPART, BDVL_RET_PIS, BDVL_RET_COFINS, BDIND_DEC, BDIND_NAT_REC)
  SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOMF600 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = aux.BDCODMATRIZ AND x.BDCODQUADRO = 48 AND x.BDREFERENCIA = aux.BDREFERENCIA) AS BDCHAVE,
         aux.BDCODREC,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN aux.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE aux.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         aux.BDCODIND_NAT_RET,
         aux.BDDT_RET,
         SUM(aux.BDVL_BC_RET) AS BDVL_BC_RET, SUM(aux.BDVL_RET) AS BDVL_RET,
         ter.BDCGCTER AS BDCNPJPART, ter.BDNOME AS BDNOMEPART,
         SUM(aux.BDVL_RET_PIS) AS BDVL_RET_PIS, SUM(aux.BDVL_RET_COFINS) AS BDVL_RET_COFINS,
         aux.BDIND_DEC, aux.BDCOD_NAT_REC AS BDIND_NAT_REC
  FROM (-- PIS
        SELECT 48 AS BDCODQUADRO, 7 AS BDCODPERIODO,
               tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODTER, tmp.BDCODRECPIS AS BDCODREC, tmp.BDCODIND_NAT_RET, tmp.BDDATAEMISSAO AS BDDT_RET,
               tmp.BDVLRCONTAB AS BDVL_BC_RET, tmp.BDVLRPISRET AS BDVL_RET, tmp.BDVLRPISRET AS BDVL_RET_PIS, 0 AS BDVL_RET_COFINS, tmp.BDIND_DEC, tmp.BDCOD_NAT_REC
        FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
        WHERE tmp.BDCODRECPIS IS NOT NULL
          AND tmp.BDVLRPISRET IS NOT NULL
          AND tmp.BDCODMATRIZ = :prCODEMP
          AND tmp.BDREFERENCIA = :prREFERENCIA
        UNION ALL
        -- COFINS
        SELECT 48 AS BDCODQUADRO, 7 AS BDCODPERIODO,
               tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODTER, tmp.BDCODRECCOFINS AS BDCODREC, tmp.BDCODIND_NAT_RET, tmp.BDDATAEMISSAO AS BDDT_RET,
               IIF((tmp.BDCODRECPIS = tmp.BDCODRECCOFINS), 0, tmp.BDVLRCONTAB) AS BDVL_BC_RET, -- Caso seja mesmo c?digo de receita, j? trouxe o valor no PIS, da? n?o soma novamente aqui...
               tmp.BDVLRCOFINSRET AS BDVL_RET, 0 AS BDVL_RET_PIS, tmp.BDVLRCOFINSRET AS BDVL_RET_COFINS, tmp.BDIND_DEC, tmp.BDCOD_NAT_REC
        FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
        WHERE tmp.BDCODRECCOFINS IS NOT NULL
          AND tmp.BDVLRCOFINSRET IS NOT NULL
          AND tmp.BDCODMATRIZ = :prCODEMP
          AND tmp.BDREFERENCIA = :prREFERENCIA
        ) aux
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.BDCODTER = aux.BDCODTER)
  WHERE aux.BDCODMATRIZ = :prCODEMP
    AND aux.BDREFERENCIA = :prREFERENCIA
  GROUP BY aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODREC,
           aux.BDCODIND_NAT_RET, aux.BDDT_RET, aux.BDIND_DEC, aux.BDCOD_NAT_REC, ter.BDCGCTER, ter.BDNOME;

  /* Saldos de reten??es de per?odos anteriores */
  --IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Verifica o par?metro "Aproveitar AS reten??es de PIS e Cofins de per?odos anteriores", caso n?o esteja habilita, apenas busca a reten??o atual...
    BEGIN 
      -- REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
      -- REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS
      INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
      SELECT ant.BDCODQUADRO, ant.BDCODPERIODO, ant.BDCODEMP, ant.BDCODMATRIZ, :prREFERENCIA as BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1)
              FROM VEF_EMP_TBLOCOM1300_1700 x
              WHERE x.BDCODPERIODO = ant.BDCODPERIODO
                AND x.BDCODEMP = ant.BDCODEMP
                AND x.BDCODMATRIZ = ant.BDCODMATRIZ
                AND x.BDCODQUADRO = ant.BDCODQUADRO
                AND x.BDREFERENCIA = :prREFERENCIA ) AS BDCHAVE,
             ant.BDCODIND_NAT_RET, ant.BDCOD_NAT_REC, ant.BDPR_REC_RET, ant.BDSLD_RET as BDVL_RET_APU, 0 as BDVL_RET_DED, 0 as BDVL_RET_PER, 0 as BDVL_RET_DCOMP, ant.BDSLD_RET as BDSLD_RET
      FROM VEF_EMP_TBLOCOM1300_1700 ant
      WHERE ant.BDSLD_RET > 0
        AND ant.BDCODMATRIZ = :prCODEMP
        AND ant.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA
                                FROM VEF_EMP_TBLOCOM1300_1700 x
                                WHERE x.BDCODMATRIZ = :prCODEMP
                                  AND x.BDREFERENCIA < :prREFERENCIA
                                  AND x.BDCODPERIODO = 7
                                ORDER BY x.BDREFERENCIA DESC);
    END

  -- REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
  INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
  SELECT 49 AS BDCODQUADRO, 7 AS BDCODPERIODO,
         tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM1300_1700 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDCODQUADRO = 49 AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCHAVE,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN tmp.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE tmp.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         tmp.BDCODIND_NAT_RET,
         tmp.BDCOD_NAT_REC,
         --(CAST(SUBSTRING(tmp.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(tmp.BDDATAEMISSAO FROM 6 for 2) AS INTEGER)) AS BDPR_REC_RET,
         tmp.BDREFAPUSALDO AS BDPR_REC_RET,
         SUM(COALESCE(tmp.BDVLRPISRET, 0)) AS BDVL_RET_APU,
         0 AS BDVL_RET_DED,
         0 AS BDVL_RET_PER, 0 AS BDVL_RET_DCOMP, SUM(COALESCE(tmp.BDVLRPISRET,0)) AS BDSLD_RET
  FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
  WHERE tmp.BDCODMATRIZ = :prCODEMP
    AND tmp.BDREFERENCIA = :prREFERENCIA
    AND tmp.BDVLRPISRET > 0
  GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODIND_NAT_RET, tmp.BDCOD_NAT_REC, tmp.BDDATAEMISSAO, tmp.BDREFAPUSALDO;

  -- REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS
  INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
  SELECT 50 AS BDCODQUADRO, 7 AS BDCODPERIODO,
         tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM1300_1700 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDCODQUADRO = 50 AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCHAVE,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN tmp.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE tmp.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         tmp.BDCODIND_NAT_RET,
         tmp.BDCOD_NAT_REC,
         --(CAST(SUBSTRING(tmp.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(tmp.BDDATAEMISSAO FROM 6 for 2) AS INTEGER)) AS BDPR_REC_RET,
         tmp.BDREFAPUSALDO AS BDPR_REC_RET,
         SUM(COALESCE(tmp.BDVLRCOFINSRET,0)) AS BDVL_RET_APU,
         0 AS BDVL_RET_DED,
         0 AS BDVL_RET_PER, 0 AS BDVL_RET_DCOMP, SUM(COALESCE(tmp.BDVLRCOFINSRET,0)) AS BDSLD_RET
  FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
  WHERE tmp.BDCODMATRIZ = :prCODEMP
    AND tmp.BDREFERENCIA = :prREFERENCIA
    AND tmp.BDVLRCOFINSRET > 0
  GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODIND_NAT_RET, tmp.BDCOD_NAT_REC, tmp.BDDATAEMISSAO, tmp.BDREFAPUSALDO;

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M100 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WMETODOAPRO INTEGER;
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,4);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configura??o da empresa na refer?ncia da apura??o...
  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDMETODOAPRO+1 -- M?todo de apropria??o
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 1
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 2
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMNTMI;

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 3
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMEXP;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      /* REGISTRO M100: CR?DITO DE PIS/PASEP RELATIVO AO PER?ODO */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM100_500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDIND_CRED_ORI, BDVL_BC, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CRED,';
      wSQL = wSQL||                                    'BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CRED_DIF, BDVL_CRED_DISP, BDIND_DESC_CRED, BDVL_CRED_DESC, BDSLD_CRED) ';
      wSQL = wSQL||'SELECT 11 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7) AS BDCHAVE,';
      wSQL = wSQL||       't436.BDCODCRE_4_3_6, 0 AS BDIND_CRED_ORI, SUM(COALESCE(tmp.BDBCPIS,0)) AS BDVL_BC, COALESCE(tmp.BDALIQPIS,0) AS BDALIQ,';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC, COALESCE(tmp.BDALIQPIS_QUANT,0) AS BDALIQ_QUANT,';
      wSQL = wSQL||       '(((SUM(COALESCE(tmp.BDBCPIS,0))*COALESCE(tmp.BDALIQPIS,1))/100)+(SUM(COALESCE(tmp.BDBCPIS_QUANT,0))*COALESCE(tmp.BDALIQPIS_QUANT,1))) AS BDVL_CRED,';
      wSQL = wSQL||       '0 AS BDVL_AJUS_ACRES, 0 AS BDVL_AJUS_REDUC, 0 AS BDVL_CRED_DIF, 0 AS BDVL_CRED_DISP,';
      wSQL = wSQL||       'NULL AS BDIND_DESC_CRED, 0 AS BDVL_CRED_DESC, 0 AS BDSLD_CRED ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED,';
      wSQL = wSQL||             'x.BDALIQPIS,';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT,';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT,';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED,';
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||            'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100  AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCPIS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
          wSQL = wSQL||             'x.BDCOD_CRED as BDCOD_CRED,';
          wSQL = wSQL||             'x.BDBCPIS ';
        END
      wSQL = wSQL||             'AS BDBCPIS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTPIS and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';
      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCPIS > 0) OR (tmp.BDBCPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQPIS > 0) OR (tmp.BDALIQPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ')';
      wSQL = wSQL||       ') ';
      --wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, t436.BDCODCRE_4_3_6, tmp.BDALIQPIS, tmp.BDALIQPIS_QUANT; ';

      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M105: DETALHAMENTO DA BASE DE CALCULO DO CR?DITO APURADO NO PER?ODO ? PIS/PASEP */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM105_M505 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCSTPIS, BDCODCSTCOF, BDCODNATBC, BDCODCRE_4_3_6,';
      wSQL = wSQL||                                     'BDVL_BC_TOT, BDVL_BC_CUM, BDVL_BC_NC, BDVL_BC, BDQUANT_BC_TOT, BDQUANT_BC, BDDESC_CRED, BDALIQ) ';
      wSQL = wSQL||'SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 11 AS BDCODQUADRO, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQPIS) OR (x.BDALIQ_QUANT = tmp.BDALIQPIS_QUANT))) AS BDCHAVE,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDORDEM)+1,1)';
      wSQL = wSQL||        'FROM VEF_EMP_TBLOCOM105_M505 x ';
      wSQL = wSQL||        'WHERE x.BDCODPERIODO = 7 ';
      wSQL = wSQL||          'AND x.BDCODEMP = tmp.BDCODEMP ';
      wSQL = wSQL||          'AND x.BDCODMATRIZ = tmp.BDCODMATRIZ ';
      wSQL = wSQL||          'AND x.BDCODQUADRO = 11 ';
      wSQL = wSQL||          'AND x.BDREFERENCIA = tmp.BDREFERENCIA ';
      wSQL = wSQL||          'AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 ';
      wSQL = wSQL||          'AND x.BDALIQ = COALESCE(tmp.BDALIQPIS,tmp.BDALIQPIS_QUANT) ';
      wSQL = wSQL||          'AND x.BDCHAVE = (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQPIS) OR (x.BDALIQ_QUANT = tmp.BDALIQPIS_QUANT))) ';
      wSQL = wSQL||        ') AS BDORDEM, ';
      wSQL = wSQL||       'tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED AS BDCODNATBC, t436.BDCODCRE_4_3_6, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPISTOTAL,0)) AS BDVL_BC_TOT, 0 AS BDVL_BC_CUM, /*(Campo 04 ? Campo 05)*/SUM(COALESCE(tmp.BDBCPISTOTAL,0)-0) AS BDVL_BC_NC, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPIS,0)) AS BDVL_BC, SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC_TOT,  SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC, NULL AS BDDESC_CRED, COALESCE(tmp.BDALIQPIS,tmp.BDALIQPIS_QUANT,0) AS BDALIQ ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED, ';
      wSQL = wSQL||             'x.BDALIQPIS, x.BDBCPIS as BDBCPISTOTAL, ';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT, ';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT, ';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED,';
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||            'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100  AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCPIS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
          wSQL = wSQL||             'x.BDCOD_CRED as BDCOD_CRED, ';
          wSQL = wSQL||             'x.BDBCPIS ';
        END
      wSQL = wSQL||             'AS BDBCPIS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTPIS and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';
      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCPIS > 0) OR (tmp.BDBCPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQPIS > 0) OR (tmp.BDALIQPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED, t436.BDCODCRE_4_3_6, tmp.BDALIQPIS, tmp.BDALIQPIS_QUANT; ';

      EXECUTE STATEMENT ( wSQL );
   
      /* REGISTRO M110: AJUSTES DO CR?DITO DE PIS/PASEP APURADO */
      INSERT INTO VEF_EMP_TBLOCOM110_M510 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, BDDESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) as BDCODMATRIZ, 11 as BDCODQUADRO, m.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = m.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) AND x.BDCODQUADRO = 11 AND x.BDREFERENCIA = m.BDREFERENCIA AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6 AND ((x.BDALIQ = m.BDALIQPIS) OR (x.BDALIQ_QUANT = m.BDALIQPIS))) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM+1),1)
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 11
                AND x.BDCODEMP = m.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                AND x.BDREFERENCIA = m.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM100_500 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODQUADRO = 11 
                                   AND x.BDCODEMP = m.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                                   AND x.BDREFERENCIA = m.BDREFERENCIA
                                   AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                                   AND ((x.BDALIQ = m.BDALIQPIS) OR (x.BDALIQ_QUANT = m.BDALIQPIS))) ) as BDORDEM,
             m.BDCODAJUEFDC, m.BDTIPOAJUSTE as BDIND_AJ, SUM(m.BDVLRAJUPIS) as BDVL_AJ, m.BDNUMERODOC as BDNUM_DOC, m.BDDESCRICAO as BDDESCR_AJ, m.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TCREDAJU_M110_M510 m
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m.BDCODEMP)
      WHERE m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM100_500 m100
                    WHERE m100.BDCODPERIODO = 7
                      AND m100.BDCODQUADRO = 11
                      AND m100.BDCODEMP = m.BDCODEMP
                      AND m100.BDREFERENCIA = m.BDREFERENCIA
                      AND m100.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND ((m100.BDALIQ = m.BDALIQPIS) OR (m100.BDALIQ_QUANT = m.BDALIQPIS)) ))
      GROUP BY m.BDCODEMP, emp.BDCODMATRIZ, m.BDREFERENCIA, m.BDCODAJUEFDC, m.BDTIPOAJUSTE, m.BDNUMERODOC, m.BDDESCRICAO, m.BDDATAREF, m.BDCODCRE_4_3_6, m.BDALIQPIS;
   
      /* REGISTRO M115: DETALHAMENTO DOS AJUSTES DO CR?DITO DE PIS/PASEP APURADO */
      INSERT INTO VEF_EMP_TBLOCOM115_M515 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM15, BDCODCSTCOF, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m115.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP) as BDCODMATRIZ, 11 as BDCODQUADRO, m110.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDCODQUADRO = 11
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDNUM_DOC = m110.BDNUMERODOC
                AND x.BDDESCR_AJ = m110.BDDESCRICAO
                AND x.BDDT_REF = m110.BDDATAREF ) as BDCHAVE,
             (SELECT x.BDORDEM
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDCODQUADRO = 11
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDNUM_DOC = m110.BDNUMERODOC
                AND x.BDDESCR_AJ = m110.BDDESCRICAO
                AND x.BDDT_REF = m110.BDDATAREF ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM15+1),1)
              FROM VEF_EMP_TBLOCOM115_M515 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 11
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m115.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                                   AND x.BDCODQUADRO = 11
                                   AND x.BDREFERENCIA = m110.BDREFERENCIA
                                   AND x.BDNUM_DOC = m110.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m110.BDDESCRICAO
                                   AND x.BDDT_REF = m110.BDDATAREF)
                AND x.BDORDEM = (SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m115.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                                   AND x.BDCODQUADRO = 11
                                   AND x.BDREFERENCIA = m110.BDREFERENCIA
                                   AND x.BDNUM_DOC = m110.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m110.BDDESCRICAO
                                   AND x.BDDT_REF = m110.BDDATAREF) ) as BDORDEM15,
             m115.BDCODCSTCOF, m115.BDCODCSTPIS, m115.BDCODPLAPADRAO, m115.BDCODTPLA, SUM(m110.BDVLRAJUPIS) as BDDET_VALOR_AJ, SUM(m115.BDBCPIS) as BDDET_BC_CRED,
             m115.BDALIQPIS as BDDET_ALIQ, m115.BDDATAOPEPIS as BDDT_OPER_AJ, m115.BDDESCRICAOAJU as BDDESC_AJ, m115.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TCREDAJU_M110_M510 m110
      JOIN VEF_EMP_TDETAJU_M115_M515 m115 on (m115.BDCODEMP = m110.BDCODEMP AND m115.BDCHAVE = m110.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m110.BDCODEMP)
      WHERE m115.BDCODEMP IS NOT NULL
        AND m115.BDBCPIS > 0
        AND m110.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m110.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM110_M510 x
                    WHERE x.BDCODPERIODO = 7
                      AND x.BDCODEMP = m115.BDCODEMP
                      AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                      AND x.BDCODQUADRO = 11
                      AND x.BDREFERENCIA = m110.BDREFERENCIA
                      AND x.BDNUM_DOC = m110.BDNUMERODOC
                      AND x.BDDESCR_AJ = m110.BDDESCRICAO
                      AND x.BDDT_REF = m110.BDDATAREF ))
      GROUP BY m115.BDCODEMP, emp.BDCODMATRIZ, m110.BDREFERENCIA, m110.BDCODCRE_4_3_6,  m115.BDCODCSTCOF, m115.BDCODCSTPIS, m115.BDCODPLAPADRAO, m115.BDCODTPLA,
               m115.BDALIQPIS, m115.BDDATAOPEPIS, m115.BDDESCRICAOAJU, m115.BDINFCOMP,
               m110.BDNUMERODOC, m110.BDDESCRICAO, m110.BDDATAREF;
    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M100_M500AUX */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WMOD_COMTELE VARCHAR(10);
DECLARE VARIABLE WMOD_ENERGAS VARCHAR(10);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
DECLARE VARIABLE WMOD_PROD VARCHAR(50);
DECLARE VARIABLE wMOD_COD_CRED_8 VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
-- Concatena todos os modelos anteriores, usar "NOT IN"...
wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;
-- Modelos que geram "Tipo de Cr?dito" com final 8, exporta??o...
wMOD_COD_CRED_8 = '1,100,4,55,65';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDCODCRIT    -- Crit?rio de escritura??o (cumulativo)
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR (:prCODEMP, :prREFERENCIA, :prWHEREEMPRESAS);

      wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M100_M500 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDPREFIXONAT, BDVL_ITEM, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCPIS_QUANT, BDALIQPIS_QUANT, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT, BDNAT_BC_CRED, BDCOD_CRED) ';

      wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDPREFIXONAT, aux.BDVL_ITEM, aux.BDCODCTA, aux.BDCODCSTPIS, aux.BDBCPIS,';
      wSQL = wSQL||       'aux.BDALIQPIS, aux.BDVLRPIS, aux.BDBCPIS_QUANT, aux.BDALIQPIS_QUANT, aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, aux.BDBCCOFINS_QUANT, aux.BDALIQCOFINS_QUANT, ';
      wSQL = wSQL||       'aux.BDNAT_BC_CRED,';

      wSQL = wSQL||       'Coalesce(aux.BDCOD_CRED,';
      wSQL = wSQL||                '(CASE WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 108 '; -- 108 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 208 '; -- 208 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 201 '; -- 201 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 202 '; -- 202 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
 
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 308 '; -- 308 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 301 '; -- 301 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 302 '; -- 302 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
 
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 202 '; -- 202 - Quando for al?quota diferente da b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 301 '; -- 301 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for al?quota b?sica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 302 '; -- 302 - Quando for aliquota for diferente da basica.  Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for al?quota for diferente da  b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 208 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da segunda linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 202 '; -- 202 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando ? usado CFOP do exterior que tem cr?dito. E a empresa usa rateio para este c?digo deve ser verificado o percentual relativo a primeira linha do 0111 com rela??o a ultima e calcular o montante do cr?dito da CFOP do exterior com CST 56 para este c?digo.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 60) OR (aux.BDCODCSTCOF = 60)) THEN 106 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 61) OR (aux.BDCODCSTCOF = 61)) THEN 206 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 62) OR (aux.BDCODCSTCOF = 62)) THEN 306 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 63) OR (aux.BDCODCSTCOF = 63)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 64) OR (aux.BDCODCSTCOF = 64)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 65) OR (aux.BDCODCSTCOF = 65)) THEN 206 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 66) OR (aux.BDCODCSTCOF = 66)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                 'else NULL end)';
      wSQL = wSQL||               ') AS BDCOD_CRED ';
      wSQL = wSQL||'FROM ( ';
                          /* Entradas - Produtos */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 1 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'p.BDVLRITEM AS BDVL_ITEM, p.BDCODCTA, p.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||              'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                'AND (e.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROENT p on (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'WHERE p.BDCODPROD is not null ';
      wSQL = wSQL||         'AND ((p.BDCODCSTPIS is not null) OR (p.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Servi?o de comunica??o e telecomunica??o (D500) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, d500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'd500.BDVLRSER AS BDVL_ITEM, d500.BDCODCTA, d500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'd500.BDCODCSTPIS, d500.BDVL_BC_PIS AS BDBCPIS, d500.BDALIQ_PIS AS BDALIQPIS, d500.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'd500.BDCODCSTCOF, d500.BDVL_BC_COF AS BDBCCOFINS, d500.BDALIQ_COF AS BDALIQCOFINS, d500.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_COMTELE||')) '; -- Servi?o de comunica??o e telecomunica??o
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||               'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||               'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = mov.BDCODEMP AND d500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE d500.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((d500.BDCODCSTPIS is not null) OR (d500.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'c500.BDVLRCONSFOR AS BDVL_ITEM, NULL AS BDCODCTA, c500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'c500.BDCODCSTPIS, c500.BDVL_BC_PIS AS BDBCPIS, c500.BDALIQ_PIS AS BDALIQPIS, c500.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'c500.BDCODCSTCOF, c500.BDVL_BC_COF AS BDBCCOFINS, c500.BDALIQ_COF AS BDALIQCOFINS, c500.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_ENERGAS||')) '; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||            ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = mov.BDCODEMP AND c500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE c500.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((c500.BDCODCSTPIS is not null) OR (c500.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Transporte (D100) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, d100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'mov.BDVALORNOTA AS BDVL_ITEM, d100.BDCODCTA, d100.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDVALORNOTA, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE d100.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((d100.BDCODCSTPIS is not null) OR (d100.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Demais documentos */
      wSQL = wSQL||       'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN AS BDREFERENCIA, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
      wSQL = wSQL||              'dem.BDVL_OPER AS BDVL_ITEM, NULL AS BDCODCTA, dem.BDNAT_BC_CRED, ';
      wSQL = wSQL||              'CASE WHEN ((dem.BDCODCSTPIS = 60) or (dem.BDCODCSTCOF = 60)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 61) or (dem.BDCODCSTCOF = 61)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 62) or (dem.BDCODCSTCOF = 62)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 307 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 63) or (dem.BDCODCSTCOF = 63)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 64) or (dem.BDCODCSTCOF = 64)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 65) or (dem.BDCODCSTCOF = 65)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 66) or (dem.BDCODCSTCOF = 66)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||              'ELSE NULL ';
      wSQL = wSQL||              'END AS BDCOD_CRED,';
      wSQL = wSQL||              'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM  VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||       'WHERE ((dem.BDCODCSTPIS is not null) OR (dem.BDCODCSTCOF is not null)) ';
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||         'AND (dem.BDIND_OPER <> 1) '; -- Opera??o Representativa de Aquisi??o...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||         'AND (dem.BDCONDPGTO <> 1) ';
      wSQL = wSQL||           'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND dem.BDREFLAN = '||:prREFERENCIA||' ';

      wSQL = wSQL||       'union all ';
                          /* Servi?os tomados(Recebidos), tipolan = 1 */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL as BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'a.BDVL_ITEM, NULL AS BDCODCTA, a.BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||                'AND (s.BDTIPLAN = 0) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TA170 a on (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'WHERE a.BDCODPROD is not null ';
      wSQL = wSQL||         'AND ((a.BDCODCSTPIS is not null) OR (a.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT bem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, bem.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA,';
      wSQL = wSQL||               'bem.BDCODBEM AS BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
--Sol. 22905 Gabriel Ariel (27/02/2018) - Buscar primeiro o valor da depreciacao
      wSQL = wSQL||                'bem.BDVL_ITEM, ';
      wSQL = wSQL||                'bem.BDCODTPLA AS BDCODCTA,';

      wSQL = wSQL||               'CASE bem.BDTIPOAPROCRED ';
      wSQL = wSQL||                 'WHEN 0 THEN ''10'' ';
      wSQL = wSQL||                 'WHEN 1 THEN ''09'' ';
      wSQL = wSQL||                 'WHEN 2 THEN ''11'' ';
      wSQL = wSQL||               'end AS BDNAT_BC_CRED, ';

      wSQL = wSQL||               'case ';
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 50) or (bem.BDCODCSTCOF = 50)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 51) or (bem.BDCODCSTCOF = 51)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 203 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 52) or (bem.BDCODCSTCOF = 52)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 303 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 53) or (bem.BDCODCSTCOF = 53)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 54) or (bem.BDCODCSTCOF = 54)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 55) or (bem.BDCODCSTCOF = 55)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 203 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 56) or (bem.BDCODCSTCOF = 56)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||               'else 101 ';
      wSQL = wSQL||               'end as BDCOD_CRED, ';

      wSQL = wSQL||               'bem.BDCODCSTPIS,';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDBCPIS,';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, bem.BDALIQPIS) AS BDALIQPIS,'; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)

      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDVLRPIS, ';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM), NULL)) AS BDBCPIS_QUANT, ';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), bem.BDALIQPIS, NULL) AS BDALIQPIS_QUANT,';
      wSQL = wSQL||               'bem.BDCODCSTCOF,';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) AS BDBCCOFINS,';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, bem.BDALIQCOFINS) AS BDALIQCOFINS,'; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)

      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDVLRCOFINS, ';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM), NULL)) as BDBCCOFINS_QUANT, ';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), bem.BDALIQCOFINS, NULL) AS BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT tbem.*, ';
      wSQL = wSQL||                'coalesce((select cast(coalesce(PRDEPRECIACAOPERIODO, 0) as numeric(15,2)) PRDEPRECIACAOPERIODO ';
      wSQL = wSQL||                           'from SP_CONS_CALC_DEP('||:PRCODEMP||', TBEM.BDCODBEM, (substring('||:prREFERENCIA||' from 5 for 2) || ''/01/'' || substring('||:prREFERENCIA||' from 1 for 4)), (substring('||:prREFERENCIA||' from 5 for 2) || ''/'' ||(select ULTDIA ';
      wSQL = wSQL||                                                                                                                                                                                                ' from ULTIMO_DIA_MES(cast(substring('||:prREFERENCIA||' from 5 for 2) as integer), cast(substring('||:prREFERENCIA||' from 1 for 4) as integer))) || ''/'' || substring('||:prREFERENCIA||' from 1 for 4)), 0, 0) ';
      wSQL = wSQL||                           'where exists (select dep.bdcodemp from EMPRESAS_TDEPRECIACAO dep where dep.bdcodemp = TBEM.BDCODEMP and dep.bdcodbem = TBEM.BDCODBEM) and TBEM.BDTIPOAPROCRED <> 0), ';
--      wSQL = wSQL||                           'where PRDEPRECIACAOPERIODO > 0), ';
      wSQL = wSQL||               '(case TBEM.BDTIPOAPROCRED ';
      wSQL = wSQL||                  'when 0 then (TBEM.BDBCCALC/COALESCE(case Tbem.BDCODNRPARC '; -- F130 n?o deve abater a exclus?o
      wSQL = wSQL||                                                               'when 0 then 1 ';  -- 1 - Integral
      wSQL = wSQL||                                                               'when 1 then 12 '; -- 2 - 12 Meses
      wSQL = wSQL||                                                               'when 2 then 24 '; -- 3 - 24 Meses
      wSQL = wSQL||                                                               'when 3 then 48 '; -- 4 - 48 Meses
      wSQL = wSQL||                                                               'when 4 then 6 ';  -- 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                                                         'when 5 then COALESCE(Tbem.BDNUMPARC, 1) '; -- 9 - Outra periodicidade definida em Lei. #OBS.: Nesses casos pega o n?mero de parcelas do campo "Quantidade" da aba EFD - PIS/Cofins
      wSQL = wSQL||                                                             'end, 1)) ';
      wSQL = wSQL||                  'else (TBEM.BDBCCALC)-(Tbem.BDEXCBASE/COALESCE(Tbem.BDNUMPARC,1)) '; -- F120 deve abater a exclus?o
      wSQL = wSQL||                  'end)) as BDVL_ITEM ';
      wSQL = wSQL||              'FROM (SELECT TBEM.*, ';     
  --Sol. 22905 - Faz a proporcao para o primeiro e ultimo mes, que depender? dos par?metros do bem
      wSQL = wSQL||               'CASE WHEN ((BDDEPDIARIA = ''TRUE'') and (TBEM.BDTIPOAPROCRED <> 0)) THEN CASE WHEN ('||:PRREFERENCIA||' = extract(year from BDDTINI) || LPAD(extract(month from BDDTINI),2,''0'')) then cast(cast(TBEM.BDBASECALC * (iif(BDNUMDIAS <= 1, 30, (select ULTDIA  from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) - iif((BDNUMDIAS <= 1) and ((extract(day from BDDTINI) ) > 30), 30, (extract(day from BDDTINI) ))) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) as numeric(15,2))';
      wSQL = wSQL||               '                                                                              WHEN ('||:PRREFERENCIA||' = extract(year from BDDTFIM) || LPAD(extract(month from BDDTFIM),2,''0'')) then cast(cast(TBEM.BDBASECALC * (iif((BDNUMDIAS <= 1) and (extract(day from BDDTFIM) > 30), 30, extract(day from BDDTFIM) )) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTFIM), extract(year from BDDTFIM)))) as numeric(15,2))';
      wSQL = wSQL||               '                                                                         ELSE TBEM.BDBASECALC ';
      wSQL = wSQL||               '                                         END ';
      wSQL = wSQL||               '     ELSE TBEM.BDBASECALC ';
      wSQL = wSQL||               'END BDBCCALC ';
      wSQL = wSQL||                'FROM (SELECT TBEM.*, ';           
  --Sol. 22905 - Pega a data da primeira e ultima parcela, para verificar se o bem est? no primeiro ou ?ltimo m?s, onde o c?lculo ? diferente
      wSQL = wSQL||                    'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end))BDDTFIM,';
      wSQL = wSQL||                    'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end))BDDTINI ';
      Wsql = wSQL||                 'FROM EMPRESAS_TBEM tbem ';
      wSQL = wSQL||                'WHERE tbem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND ((tbem.BDCODCSTPIS is not null) OR (tbem.BDCODCSTCOF is not null)) ';
                                   -- sol:15691 - deve trazer os registros sem data de baixa OU
                                   --             (se tiver baixa) todos que a baixa seja posterior ao periodo de apura??o OU
                                   --             (se a baixa for menor que a data final da apura??o) os registros em que o mes da baixa seja igual ao da apura??o E estiver parametrizado para depreciar no mes da baixa
      wSQL = wSQL||                'AND ((tbem.BDDATABAIXA is null) OR ';
      wSQL = wSQL||                     '(Cast(SubString(tbem.BDDATABAIXA FROM 1 for 4)||SubString(tbem.BDDATABAIXA FROM 6 for 2) AS Integer) > '||:prREFERENCIA||') OR ';
      wSQL = wSQL||                     '((tbem.BDDEPMESBAIXABEM = ''TRUE'') AND (LPAD(EXTRACT(MONTH FROM tbem.BDDATABAIXA), 2, ''0'') = SubString('||:prREFERENCIA||' FROM 5 for 2)) AND ';
      wSQL = wSQL||                      '(tbem.BDTIPOAPROCRED <> 0))) '; -- sol:15691 - n?o levar no mes da baixa se for bdtipoaprocred = 0(10), que ? do F130
                                   -- sol:15691 - obedecer o parametro BDDEPMESAQUIBEM que diz se deve depreciar no mes da aquisi??o ou no pr?ximo
      wSQL = wSQL||                'AND (';
      wSQL = wSQL||                     '(Cast(SubString((CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC - 1 + 1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end) FROM 1 for 4)||';
      wSQL = wSQL||                           'SubString((CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC - 1 + 1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end) FROM 6 for 2) AS Integer) >= '||:prREFERENCIA||') AND ';
      wSQL = wSQL||                     '((Cast(SubString((CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end) FROM 1 for 4)||';
      wSQL = wSQL||                            'SubString((CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end) FROM 6 for 2) AS Integer) <= '||:prREFERENCIA||')) ';
      wSQL = wSQL||                     ') ';
                                   -- sol:15653 - somente se cst for diferente de 70
      wSQL = wSQL||                'AND (tbem.BDCODCSTPIS <> 70) AND (tbem.BDCODCSTCOF <> 70) ';
      wSQL = wSQL||              ')TBEM ';
      wSQL = wSQL||           ')TBEM ';
      wSQL = wSQL||             ') bem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = bem.BDCODEMP) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, (cast(substring(pgto.BDDATAPGTO FROM 1 for 4)||substring(pgto.BDDATAPGTO FROM 6 for 2) AS integer)) AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, pgto.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVLRTOTRECPAR AS BDVL_ITEM, NULL AS BDCODCTA, 109 AS BDNAT_BC_CRED, 109 AS BDCOD_CRED,';
      wSQL = wSQL||              'f205.BDCODCSTPIS, f205.BDBASEPIS AS BDBCPIS, f205.BDALIQPIS, f205.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'f205.BDCODCSTCOF, f205.BDBASECOFINS AS BDBCCOFINS, f205.BDALIQCOFINS, f205.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT f.* FROM VEF_EMP_TMOVOPIMOBI_F200_PGTO f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND (cast(substring(f.BDDATAPGTO FROM 1 for 4)||substring(f.BDDATAPGTO FROM 6 for 2) AS integer) = '||:prREFERENCIA||') ';
      wSQL = wSQL||             ') pgto ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVOPIMOBCUSINCOR f205) f205 on (f205.BDCODEMP = pgto.BDCODEMP AND f205.BDCHAVE = pgto.BDCHAVE AND f205.BDORDEMPGTO = pgto.BDORDEMPGTO) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, (cast(substring(pgto.BDDATAPGTO FROM 1 for 4)||substring(pgto.BDDATAPGTO FROM 6 for 2) AS integer)) AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, pgto.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVLRTOTRECPAR AS BDVL_ITEM, NULL AS BDCODCTA, 109 AS BDNAT_BC_CRED, 109 AS BDCOD_CRED,';
      wSQL = wSQL||              'f210.BDCODCSTPIS, f210.BDBASEPIS AS BDBCPIS, f210.BDALIQPIS, f210.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'f210.BDCODCSTCOF, f210.BDBASECOFINS AS BDBCCOFINS, f210.BDALIQCOFINS, f210.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT f.* FROM VEF_EMP_TMOVOPIMOBI_F200_PGTO f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND (cast(substring(f.BDDATAPGTO FROM 1 for 4)||substring(f.BDDATAPGTO FROM 6 for 2) AS integer) = '||:prREFERENCIA||') ';
      wSQL = wSQL||             ') pgto ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVOPIMOBCUSORCA f210) f210 on (f210.BDCODEMP = pgto.BDCODEMP AND f210.BDCHAVE = pgto.BDCHAVE AND f210.BDORDEMPGTO = pgto.BDORDEMPGTO) ';

      wSQL = wSQL||      ') aux ';
      wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS not in (4,6,7,8,9)) or ((aux.BDCODCSTPIS = 5) and ((aux.BDALIQPIS = 0) or (aux.BDALIQCOFINS = 0)))) '; -- CSTs que n?o geram regitros M100/500...

      EXECUTE STATEMENT ( wSQL );

    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M100_M500PAR */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WMOD_COMTELE VARCHAR(10);
DECLARE VARIABLE WMOD_ENERGAS VARCHAR(10);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
DECLARE VARIABLE WMOD_PROD VARCHAR(50);
DECLARE VARIABLE wMOD_COD_CRED_8 VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
-- Concatena todos os modelos anteriores, usar "NOT IN"...
wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;
-- Modelos que geram "Tipo de Cr?dito" com final 8, exporta??o...
wMOD_COD_CRED_8 = '1,100,4,55,65';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDCODCRIT    -- Crit?rio de escritura??o (cumulativo)
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M100_M500 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDPREFIXONAT, BDVL_ITEM, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCPIS_QUANT, BDALIQPIS_QUANT, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT, BDNAT_BC_CRED, BDCOD_CRED) ';
    
          wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDPREFIXONAT, aux.BDVL_ITEM, aux.BDCODCTA, aux.BDCODCSTPIS, aux.BDBCPIS,';
          wSQL = wSQL||       'aux.BDALIQPIS, aux.BDVLRPIS, aux.BDBCPIS_QUANT, aux.BDALIQPIS_QUANT, aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, aux.BDBCCOFINS_QUANT, aux.BDALIQCOFINS_QUANT, ';
          wSQL = wSQL||       'aux.BDNAT_BC_CRED,';

          wSQL = wSQL||       'Coalesce(aux.BDCOD_CRED,';
          wSQL = wSQL||                '(CASE WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 108 '; -- 108 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 208 '; -- 208 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 201 '; -- 201 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 202 '; -- 202 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
     
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 308 '; -- 308 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 301 '; -- 301 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 302 '; -- 302 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
     
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 202 '; -- 202 - Quando for al?quota diferente da b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 301 '; -- 301 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for al?quota b?sica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 302 '; -- 302 - Quando for aliquota for diferente da basica.  Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for al?quota for diferente da  b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 208 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da segunda linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 202 '; -- 202 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando ? usado CFOP do exterior que tem cr?dito. E a empresa usa rateio para este c?digo deve ser verificado o percentual relativo a primeira linha do 0111 com rela??o a ultima e calcular o montante do cr?dito da CFOP do exterior com CST 56 para este c?digo.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 60) OR (aux.BDCODCSTCOF = 60)) THEN 106 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 61) OR (aux.BDCODCSTCOF = 61)) THEN 206 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 62) OR (aux.BDCODCSTCOF = 62)) THEN 306 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 63) OR (aux.BDCODCSTCOF = 63)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 64) OR (aux.BDCODCSTCOF = 64)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 65) OR (aux.BDCODCSTCOF = 65)) THEN 206 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 66) OR (aux.BDCODCSTCOF = 66)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

          wSQL = wSQL||                 'else NULL end)';
          wSQL = wSQL||               ') AS BDCOD_CRED ';
          wSQL = wSQL||'FROM ( ';

          wSQL = wSQL||'SELECT ent.BDCODEMP, COALESCE(emp.BDCODMATRIZ, ent.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 1 AS BDCODTP, ent.BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||      '(CAST(ROUND(('; -- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                   '(IIF(qtdepro.BDQTDEPRO < 1, pgto.bdvalorpgtopar,'; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                              '((COALESCE(pgto.bdvalorpgtopar,0)*(( COALESCE(movpro.BDVLRITEM,0)/i.BDVLRCONTAB)))) ))+';
          wSQL = wSQL||                   '(IIF(qtdepro.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETINSS,0) ),+';
          wSQL = wSQL||                                             '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) )))';
          wSQL = wSQL||                   ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM,';
          wSQL = wSQL||      'movpro.BDCODCTA, movpro.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||      'movpro.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'movpro.BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'movpro.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'movpro.BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||      'WHERE (e.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||        'AND (e.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||        'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||              'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') ent ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = ent.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVENTPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = ent.BDCODEMP AND x.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTPAR par on (par.BDCODEMP = ent.BDCODEMP AND par.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVENTPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = ent.BDCODEMP AND i.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, Count(*) AS BDQTDEPRO FROM VEF_EMP_TMOVPROENT p group by p.BDCODEMP, p.BDCHAVE, p.BDORDEM) qtdepro on ';
          wSQL = wSQL||                                             '(qtdepro.BDCODEMP = i.BDCODEMP AND qtdepro.BDCHAVE = i.BDCHAVE AND qtdepro.BDORDEM = i.BDORDEM) ';
          wSQL = wSQL||'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODNATBC, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||             'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVPROENT p) movpro on (i.BDCODEMP = movpro.BDCODEMP AND i.BDCHAVE = movpro.BDCHAVE AND i.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||'WHERE ((movpro.BDCODCSTPIS is not null) OR (movpro.BDCODCSTCOF is not null)) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT ent.BDCODEMP, ent.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, ent.BDCHAVE, ent.BDORDEM, ent.BDORDEMPRO, ent.BDCODTP, ent.BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||         '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETINSS,0) ) AS BDVL_ITEM,';

          wSQL = wSQL||      'ent.BDCODCTA, ent.BDNAT_BC_CRED, ent.BDCOD_CRED,';
          wSQL = wSQL||      'ent.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'ent.BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'ent.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'ent.BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
                             /* Entradas - Servi?o de comunica??o e telecomunica??o (D500) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'd500.BDVLRSER AS BDVL_ITEM, d500.BDCODCTA, d500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'd500.BDCODCSTPIS, d500.BDVL_BC_PIS AS BDBCPIS, d500.BDALIQ_PIS AS BDALIQPIS, d500.BDVLRPIS,';
          wSQL = wSQL||             'd500.BDCODCSTCOF, d500.BDVL_BC_COF AS BDBCCOFINS, d500.BDALIQ_COF AS BDALIQCOFINS, d500.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM (';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_COMTELE||' )) '; -- Servi?o de comunica??o e telecomunica??o
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||              'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                    'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = mov.BDCODEMP AND d500.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE d500.BDCHAVE is not null ';
      
          wSQL = wSQL||      'union all ';
                             /* Entradas - Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'c500.BDVLRCONSFOR AS BDVL_ITEM, NULL AS BDCODCTA, c500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'c500.BDCODCSTPIS, c500.BDVL_BC_PIS AS BDBCPIS, c500.BDALIQ_PIS AS BDALIQPIS, c500.BDVLRPIS,';
          wSQL = wSQL||             'c500.BDCODCSTCOF, c500.BDVL_BC_COF AS BDBCCOFINS, c500.BDALIQ_COF AS BDALIQCOFINS, c500.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM ( ';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_ENERGAS||')) '; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||             'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                   'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = mov.BDCODEMP AND c500.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE c500.BDCHAVE is not null ';
      
          wSQL = wSQL||      'union all ';
                             /* Entradas - Transporte (D100) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'd100.BDVLR_FCP_UF_DEST AS BDVL_ITEM, d100.BDCODCTA, d100.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
          wSQL = wSQL||             'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM ( ';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||             'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                   'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE d100.BDCHAVE is not null ';

          wSQL = wSQL||    ') ent ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVENTPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = ent.BDCODEMP AND x.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTPAR par on (par.BDCODEMP = ent.BDCODEMP AND par.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVENTPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = ent.BDCODEMP AND i.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||'WHERE ((ent.BDCODCSTPIS is not null) OR (ent.BDCODCSTCOF is not null)) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL as BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||      '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||      'NULL AS BDCODCTA, a170.BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||      'a170.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'a170.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||      'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||        'AND (s.BDTIPLAN = 0) ';
          wSQL = wSQL||        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||              'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') mov ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||' )) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVSERITENS i on (mov.BDCODEMP = i.BDCODEMP AND mov.BDCHAVE = i.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TA170 a170 on (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND i.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit on (mov.BDCODSITNF = sit.BDCODSITNF) ';
          wSQL = wSQL||'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
          wSQL = wSQL||       '(pgto.bdvalorpgtopar +(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||       'NULL AS BDCODCTA, mov.BDNAT_BC_CRED, ';
          wSQL = wSQL||       'CASE WHEN ((mov.BDCODCSTPIS = 60) or (mov.BDCODCSTCOF = 60)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 61) or (mov.BDCODCSTCOF = 61)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 62) or (mov.BDCODCSTCOF = 62)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 307 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 63) or (mov.BDCODCSTCOF = 63)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 64) or (mov.BDCODCSTCOF = 64)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 65) or (mov.BDCODCSTCOF = 65)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 66) or (mov.BDCODCSTCOF = 66)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||       'ELSE NULL ';
          wSQL = wSQL||       'END AS BDCOD_CRED,';
          wSQL = wSQL||       'mov.BDCODCSTPIS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||       'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||       'NULL as BDBCPIS_QUANT, 0 as BDALIQPIS_QUANT,';
          wSQL = wSQL||       'mov.BDCODCSTCOF,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||       'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||       'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT dem.BDCODEMP, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.BDIND_ORIG_CRED, dem.BDNAT_BC_CRED,';
          wSQL = wSQL||             'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||             'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||      'WHERE ((dem.BDCODCSTPIS is not null) OR (dem.BDCODCSTCOF is not null)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||        'AND (dem.BDIND_OPER <> 1) '; -- Opera??o Representativa de Aquisi??o...
          wSQL = wSQL||        'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||             ' WHERE e.BDCODEMP = dem.BDCODEMP AND e.BDREFEMP <= dem.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') mov ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'WHERE ((mov.BDCODCSTPIS is not null) OR (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||  'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||      ') aux ';
          wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS not in (4,6,7,8,9)) or ((aux.BDCODCSTPIS = 5) and ((aux.BDALIQPIS = 0) or (aux.BDALIQCOFINS = 0)))) '; -- CSTs que n?o geram regitros M100/500...

          EXECUTE STATEMENT ( wSQL );
          
        END
    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M200 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M200(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WVLRAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRUP NUMERIC(15,2);
DECLARE VARIABLE WVLRUPAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRSLD NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT_ORIGINAL NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT_TOTAL NUMERIC(15,2);
DECLARE VARIABLE WINTAUX INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WPER_APU_CRED INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCRE_4_3_6 INTEGER;
DECLARE VARIABLE WIND_CRED_ORI INTEGER;
DECLARE VARIABLE WCOD_NAT_REC INTEGER;
DECLARE VARIABLE WCHAVEAUX INTEGER;
DECLARE VARIABLE WORDENACAO INTEGER;
DECLARE VARIABLE WIND_DESC_CRED INTEGER;
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCREDITOSPERANT, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCREDITOSPERANT, :wRETPISCOFPERANT;

  /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  /* 1 - Exclusivamente no regime n?o-cumulativo */
  IF (wINCTRIB IN (1,3)) THEN
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      wVLRTOTCONT = 0;
      SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR
      FROM VEF_EMP_TBLOCOM210_M610 m
      LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL)
      WHERE (t435.BDCODCSOCIALEXP IN (01,02,03,04,32,71))
        AND (m.BDCODQUADRO = 19) -- M210 - Detalhamento da contribui??o para o PIS/PASEP
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRTOTCONT;

      wVLRTOTCONT_ORIGINAL = wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 2, COALESCE(:wVLRTOTCONT,0));

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100)
         Caso esteja configurado para usar saldo do per?odo anterior, deve descontar ele primeiro, antes do cr?dito do per?odo atual... */
      wVLRCREDPERANT = 0;
      wVLRCREDPERANT_TOTAL = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 52) -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL = wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
              END
          END
        END

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      SELECT COUNT(m.BDCHAVE) as BDQTD
      FROM VEF_EMP_TBLOCOM100_500 m
      WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO wQTD;

      IF ((wQTD = 0) OR (wVLRTOTCONT = 0) OR (wVLRTOTCONT IS NULL))  THEN -- Caso n?o tenha dados no M100/M500 ou o valor do cr?dito seja zerado...
        BEGIN
          UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                               VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, 0)
                                             MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
            UPDATE VEF_EMP_TBLOCOM100_500 m
            SET m.BDIND_DESC_CRED = 1,
                m.BDVL_CRED_DESC  = 0,
                m.BDSLD_CRED      = m.BDVL_CRED_DISP
            WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA;

            /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
            SELECT COUNT(*)
            FROM VEF_EMP_TBLOCOM1100_1500 m
            WHERE m.BDCODPERIODO = 7
              AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA
              AND m.BDPER_APU_CRED = :prREFERENCIA
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDORIG_CRED = :wIND_CRED_ORI
            INTO :wQTD;
  
            IF (:wQTD > 0) THEN
              BEGIN
                /* Caso tenha registros atualiza */
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                    m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                    m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
      ELSE
        BEGIN
                /* Caso n?o tenha lan?amento de saldos insere */
                INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                              VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                      (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                      7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
              END
          END
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            IF (:wVLRTOTCONT > 0) THEN
              BEGIN
                /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
                IF (:wVLR < :wVLRTOTCONT) THEN
                  BEGIN
                    wVLRSLD        = 0;
                    wVLRTOTCONT    = :wVLRTOTCONT - :wVLR;
                    wIND_DESC_CRED = 0; -- 0 ? Utiliza??o do valor total para desconto da contribui??o apurada no per?odo, no Registro M200;
                  END
                ELSE
                  BEGIN
                    /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                    wVLRSLD        = :wVLR - :wVLRTOTCONT;
                    wVLR           = :wVLR - :wVLRSLD;
                    wVLRTOTCONT    = 0;
                    wIND_DESC_CRED = 1; -- 1 ? Utiliza??o de valor parcial para desconto da contribui??o apurada no per?odo, no Registro M200.
                  END

                -- Atualiza os cr?ditos descontados do M100...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = :wIND_DESC_CRED,
                    m.BDVL_CRED_DESC  = :wVLR,
                    m.BDSLD_CRED      = :wVLRSLD
                WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDCHAVE = :wCHAVE
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI;

                IF (wVLRSLD > 0) THEN
                  BEGIN
                /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                SELECT COUNT(*)
                FROM VEF_EMP_TBLOCOM1100_1500 m
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI
                INTO :wQTD;
      
                IF (:wQTD > 0) THEN
                  BEGIN
                    /* Caso tenha registros atualiza */
                    UPDATE VEF_EMP_TBLOCOM1100_1500 m
                    SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI;
                  END
                ELSE
                  BEGIN
                    /* Caso n?o tenha lan?amento de saldos insere */
                    INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                  VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                          (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                              7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', (:wVLR + :wVLRSLD) /*:wVLR*/, :wVLR/*0*/, :wVLRSLD/*:wVLR*/);
                  END
              END

                wVLRAUX = 0;
                SELECT COALESCE(BDVALOR, 0)
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
                  AND BDREFERENCIA = :prREFERENCIA
                  AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
                  AND BDNUMCAMPO   = 3
                INTO wVLRAUX;
         
                IF (wVLRAUX IS NULL) THEN
                  wVLRAUX = 0;
         
                UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, COALESCE(:wVLR+:wVLRAUX,0))
                                                   MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

                  END
                ELSE
                  BEGIN
                -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = 1,
                    m.BDVL_CRED_DESC  = 0,
                    m.BDSLD_CRED      = m.BDVL_CRED_DISP
                WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDCHAVE = :wCHAVE;
          
                    /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                    SELECT COUNT(*)
                    FROM VEF_EMP_TBLOCOM1100_1500 m
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI
                    INTO :wQTD;
          
                    IF (:wQTD > 0) THEN
                      BEGIN
                        /* Caso tenha registros atualiza */
                        UPDATE VEF_EMP_TBLOCOM1100_1500 m
                        SET m.BDVL_CRED_APU = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                        WHERE m.BDCODPERIODO = 7
                          AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                          AND m.BDCODEMP = :wCODEMP
                          AND m.BDCODMATRIZ = :wCODMATRIZ
                          AND m.BDREFERENCIA = :prREFERENCIA
                          AND m.BDPER_APU_CRED = :prREFERENCIA
                          AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                          AND m.BDORIG_CRED = :wIND_CRED_ORI;
                      END
                    ELSE
                      BEGIN
                        /* Caso n?o tenha lan?amento de saldos insere */
                        INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                      VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                              (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                          7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
                      END
                          END
                          END
                      END

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      wVLR = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          wVLR = wVLRCREDPERANT_TOTAL;
        END
      ELSE
        BEGIN
          wVLRCREDPERANT_TOTAL = 0;
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 52) -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END
    
                wVLRCREDPERANT_TOTAL =  wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
          END

          wVLR = wVLRCREDPERANT_TOTAL;
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 4, COALESCE(:wVLR,0));

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (2))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (3,4))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP,  :prCODEMP, :prREFERENCIA, 15, 5, COALESCE(:wVLR,0));

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';
    
      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
              AND BDNUMCAMPO   = 6
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END


      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRPIS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 1 -- 0 - Dedu??o de Natureza N?o Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 7, COALESCE(:wVLR,0));

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR) as BDVALOR, SUM(aux.BDVLRSUB) as BDVALORSUB
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (5))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (6,7))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR, :wVLRAUX;

      IF ((wVLR - wVLRAUX) >= 0) THEN -- Se tiver valor de contribbui??o, calcula os campos a somar e subtrair...
        wVLR = (wVLR - wVLRAUX);
      ELSE
      /* Se o valor do campo 5(Valor Total da Contribui??o) menos o valor do campo 6(Valor Retido na Fonte) for menor que zero, ent?o este valor deve ser levado como saldo no registro 1300. */
      IF ((wVLR - wVLRAUX) < 0) THEN -- Se n?o tiver valor de contribbui??o, leva zerado...
        BEGIN
          /* Atualiza o valor do campo 6, Valor Retido na Fonte, s? pode usar aquilo que abater e n?o o total... */
          UPDATE VEF_EMP_TBLOCOMGERREG
          SET BDVALOR = :wVLR
          WHERE BDCODMATRIZ  = :prCODEMP
            AND BDREFERENCIA = :prREFERENCIA
            AND BDCODQUADRO  = 15
            AND BDNUMCAMPO   = 6;

          /* Caso tenha lan?amentos, desconta o valor da contribui??o deles */
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, COALESCE(m.BDVL_RET_APU, 0)
              FROM VEF_EMP_TBLOCOM1300_1700 m
              WHERE (m.BDCODQUADRO = 49) -- 1300 - Ficha de reten??o do PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUP
          DO
            BEGIN
              IF (wVLR > 0) THEN
                BEGIN
                  /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                  IF (:wVLRUP < :wVLR) THEN
                    BEGIN
                      wVLRUPAUX = :wVLRUP;
                      wVLRSLD   = 0;
                      wVLR      = :wVLR-:wVLRUP; /* Cr?dito j? descontado vai ser abatido... */
                    END
                  ELSE
                    BEGIN
                      wVLRUPAUX = :wVLR;
                      wVLRSLD   = :wVLRUP - :wVLR;
                    END
    
                  UPDATE OR INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDVL_RET_DED, BDSLD_RET)
                                                          VALUES (:wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUPAUX  , :wVLRSLD)
                                                        MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE);
                END
            END

          wVLR = 0; -- Se n?o tiver valor de contribbui??o, leva zerado...
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 8, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 2, 0);

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, 0);

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 4, 0);

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 5, 0);

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, 0);

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 7, 0);

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 8, 0);
    END

  /* 2 - Exclusivamente no regime cumulativo */
  IF (wINCTRIB IN (2,3)) THEN
    BEGIN
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      wVLRTOTCONT = 0;
      wSQL =        'SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM210_M610 m ';
      wSQL = wSQL|| 'LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL) ';
      IF (wINCTRIB IN (3)) THEN -- Quando ? regime n?o-cumulativo e cumulativo, j? considerou algumas contribui??es no campo 2...
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,51,52,53,54,72)) ';
      ELSE
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,32,51,52,53,54,72)) ';
      wSQL = wSQL|| '  AND (m.BDCODQUADRO = 19) '; -- M210 - Detalhamento da contribui??o para o PIS/PASEP
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 9, COALESCE(:wVLRTOTCONT,0));

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
                  AND BDNUMCAMPO   = 10
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                         VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRPIS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 2 -- 1 - Dedu??o de Natureza Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 11, COALESCE(:wVLR,0));

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (9))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (10,11))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 12, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN -- Joga os valores zerados...
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 9, 0);

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, 0);

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 11, 0);

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 12, 0);
    END

  /* 3 - Regimes n?o-cumulativo e cumulativo */
  /* 13 - VL_TOT_CONT_REC - VALOR TOTAL DA CONTRIBUI??O A RECOLHER/PAGAR NO PER?ODO (08 + 12) */
  WVLR = 0;
  SELECT SUM(COALESCE(M.BDVALOR,0)) AS BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG M
  WHERE (M.BDCODQUADRO = 15)
    AND (M.BDNUMCAMPO IN (8,12))
    AND M.BDCODMATRIZ = :PRCODEMP
    AND M.BDREFERENCIA = :PRREFERENCIA
  INTO :WVLR;
 
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, 15, 13, COALESCE(:WVLR,0));

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M210_M610 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M210_M610(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32000);
declare variable WMOD_TRANSPORTE varchar(30);
declare variable WMOD_PROD varchar(50);
declare variable WALIQ_PIS_IT_1 varchar(5);
declare variable WALIQ_COF_IT_1 varchar(5);
declare variable WALIQ_PIS_IT_2 varchar(5);
declare variable WALIQ_COF_IT_2 varchar(5);
BEGIN
/* ***** Constantes das CFOPs que geram "NAT_BC_CRED" da tabela 4.3.7. ***** */
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
--wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
--wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
--wMOD_CFe = '59'; -- CF-e
-- Concatena todos os modelos anteriores, usar "NOT IN"...
--wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;--||','||wMOD_CFe;
wMOD_PROD = wMOD_TRANSPORTE;--||','||wMOD_CFe;

--wCST_NAO_CUM = '1,2,3,4,32,71'; -- CSTs do regime n?o cumulativo
--wCST_CUM = '31,32,51,52,53,54,72'; -- CSTs do regime cumulativo

/* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
wALIQ_PIS_IT_1 = '1.65';
wALIQ_COF_IT_1 = '7.60';
/* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
wALIQ_PIS_IT_2 = '0.65';
wALIQ_COF_IT_2 = '3.00';
/*****************************************************************************/
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
--      IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
--        wCST = wCST_NAO_CUM; -- CSTs do regime n?o cumulativo
--      ELSE
--      IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
--        wCST = wCST_CUM; -- CSTs do regime cumulativo
--      ELSE
--      IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
--        wCST = wCST_NAO_CUM||','||wCST_CUM; -- CSTs do regime n?o cumulativo e cumulativo

      wSQL =        'INSERT INTO TMP_VEF_EMP_TBLOCOM_M210_M610 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDCODCSTPIS, BDCODCSTCOF, BDCOD_CONT_PIS, BDCOD_CONT_COF, BDVL_REC_BRT, BDVL_BC_CONT_PIS, BDVL_BC_CONT_COF, BDALIQ_PIS, BDALIQ_COF, BDQUANT_BC_PIS, BDQUANT_BC_COF, BDALIQ_QUANT_PIS, BDALIQ_QUANT_COF) ';

      wSQL = wSQL|| 'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDCODCSTPIS, aux.BDCODCSTCOF, ';
      IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                        'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))), 01, null) ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                        'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))), 01, null) ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_1||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      ELSE
      IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                       'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 51, null) ';
          wSQL = wSQL||                                       'WHEN 2 THEN 52 ';
          wSQL = wSQL||                                       'WHEN 3 THEN 53 ';
          wSQL = wSQL||                                       'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                       'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 51, null) ';
          wSQL = wSQL||                                       'WHEN 2 THEN 52 ';
          wSQL = wSQL||                                       'WHEN 3 THEN 53 ';
          wSQL = wSQL||                                       'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      ELSE
      IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                        'WHEN 1 THEN ';
          wSQL = wSQL||                                           'CASE CAST(aux.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 01 ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 51 ';
          wSQL = wSQL||                                           'END ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                        'WHEN 1 THEN ';
          wSQL = wSQL||                                           'CASE CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 01 ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 51 ';
          wSQL = wSQL||                                           'END ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      wSQL = wSQL||        'aux.BDVL_ITEM AS BDVL_REC_BRT,';
      /* Se tiver campo de valor da base de calculo por quandtidade e al?quota em R$, leva os mesmo, caso contr?rio, verifica pela CST, se for = 3, vai nas quantidades e al?quotas em R$... */
      wSQL = wSQL||        'iif(((aux.BDQUANT_BC_PIS is null) AND (AUX.BDCODCSTPIS = 3)), 0, AUX.BDBCPIS) AS BDVL_BC_CONT_PIS,';
      wSQL = wSQL||        'iif(((aux.BDQUANT_BC_COF is null) AND (AUX.BDCODCSTCOF = 3)), 0, AUX.BDBCCOFINS) AS BDVL_BC_CONT_COF,';
      wSQL = wSQL||        'iif(((aux.BDALIQ_PIS_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQPIS) AS BDALIQ_PIS,';
      wSQL = wSQL||        'iif(((aux.BDALIQ_COF_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQCOFINS) AS BDALIQ_COF,';
      wSQL = wSQL||        'COALESCE(aux.BDQUANT_BC_PIS, iif(aux.BDCODCSTPIS = 3, aux.BDBCPIS, 0)) AS BDQUANT_BC_PIS,';
      wSQL = wSQL||        'COALESCE(aux.BDQUANT_BC_COF, iif(AUX.BDCODCSTCOF = 3, AUX.BDBCCOFINS, 0)) AS BDQUANT_BC_COF,';
      wSQL = wSQL||        'COALESCE(aux.BDALIQ_PIS_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQPIS, 0)) AS BDALIQ_QUANT_PIS,';
      wSQL = wSQL||        'COALESCE(aux.BDALIQ_COF_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQCOFINS, 0)) AS BDALIQ_QUANT_COF ';
      wSQL = wSQL|| 'FROM ( ';

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 2 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||              '(CAST(ROUND(( '; -- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                     '(IIF(mov.BDQTDEPRO < 1, pgto.bdvalorpgtopar, '; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                                '((COALESCE(pgto.bdvalorpgtopar,0)*((CAST( COALESCE(movpro.BDVLRITEM,0) AS NUMERIC(15,6))/i.BDVLRCONTAB)))) ))+ ';
          wSQL = wSQL||                     '(IIF(mov.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETINSS,0) ),+ ';
          wSQL = wSQL||                                               '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) ))) ';
          wSQL = wSQL||                     ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM, ';
          wSQL = wSQL||              'movpro.BDCODCSTPIS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS, ';
          wSQL = wSQL||              'movpro.BDALIQPIS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS, ';
          wSQL = wSQL||              'movpro.BDCODCSTCOF, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS, ';
          wSQL = wSQL||              'movpro.BDALIQCOFINS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT, ';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM ( ';
          wSQL = wSQL||                'SELECT aux.BDCODEMP, aux.BDCHAVE, aux.BDREFLAN, SUM(aux.BDQTDEPRO) AS BDQTDEPRO, SUM(aux.BDQTDEPARC) AS BDQTDEPARC ';
          wSQL = wSQL||                'FROM ( ';
          wSQL = wSQL||                       'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, COUNT(pro.bdCODEMP) AS BDQTDEPRO, 0 AS BDQTDEPARC ';
          wSQL = wSQL||                       'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE) ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVPROSAI pro ON (pro.bdCODEMP = i.bdCODEMP AND pro.bdCHAVE = i.bdCHAVE AND pro.bdORDEM = i.bdORDEM) ';
          wSQL = wSQL||                       'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                        'AND (s.'||TRIM(:prWHEREEMPRESAS)||') ';
          wSQL = wSQL||                        'AND (s.BDMODELO not in ('||wMOD_PROD||')) ';  -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                       'GROUP BY s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||                       'UNION ALL ';
          wSQL = wSQL||                       'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, 0 AS BDQTDEPRO, COUNT(par.bdCODEMP) AS BDQTDEPARC ';
          wSQL = wSQL||                       'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVSAIPAR par ON (par.bdCODEMP = s.bdCODEMP AND par.bdCHAVE = s.bdCHAVE) ';
          wSQL = wSQL||                       'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                         'AND (s.'||TRIM(:prWHEREEMPRESAS)||') ';
          wSQL = wSQL||                         'AND (s.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                       'GROUP BY s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||                      ') aux ';
          wSQL = wSQL||                'WHERE ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                        'WHERE p.BDCODEMP = aux.BDCODEMP AND p.BDREFEMP <= aux.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||                'GROUP BY aux.BDCODEMP, aux.BDCHAVE, aux.BDREFLAN ';
          wSQL = wSQL||              ') mov ';
          wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIPAR par on (par.BDCODEMP = mov.BDCODEMP AND par.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||              'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                 'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||        'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||                      'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS ';
          wSQL = wSQL||               'FROM VEF_EMP_TMOVPROSAI p ';
          wSQL = wSQL||               'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              ') movpro on (i.BDCODEMP = movpro.BDCODEMP AND i.BDCHAVE = movpro.BDCHAVE AND i.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||        'WHERE (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, mov.BDORDEM, mov.BDORDEMPRO, mov.BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||                '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETINSS,0) ) AS BDVL_ITEM,';
          wSQL = wSQL||                'mov.BDCODCSTPIS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||                'mov.BDALIQPIS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||                'mov.BDCODCSTCOF,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||                'mov.BDALIQCOFINS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||                'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||                'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
                                      /* Sa?das - Transporte (D100) */
          wSQL = wSQL||               'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 16 AS BDCODTP,';
          wSQL = wSQL||                      'mov.BDVALORNOTA AS BDVL_ITEM,';
          wSQL = wSQL||                      'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
          wSQL = wSQL||                      'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS ';
          wSQL = wSQL||               'FROM (';
          wSQL = wSQL||                      'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
          wSQL = wSQL||                      'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                      'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||                        'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
          wSQL = wSQL||                        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                        'AND s.BDREFLAN = '||:prREFERENCIA;
          wSQL = wSQL||                        'AND ((SELECT first 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                              'FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                              'WHERE p.BDCODEMP = s.BDCODEMP ';
          wSQL = wSQL||                                'AND p.BDREFEMP <= s.BDREFLAN ';
          wSQL = wSQL||                              'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||                      ') mov ';
          wSQL = wSQL||               'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||               'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||               'WHERE d100.BDCHAVE is not null ';

          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = mov.BDCODEMP AND x.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIPAR par on (par.BDCODEMP = mov.BDCODEMP AND par.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||              'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||          ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||        'WHERE (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||               '(COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'a170.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'a170.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||             'AND (s.BDTIPLAN = 0) ';
          wSQL = wSQL||               'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT FIRST 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                     'FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP ';
          wSQL = wSQL||                       'AND e.BDREFEMP <= s.BDREFLAN ';
          wSQL = wSQL||                     'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||                'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                 ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||' )) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSERITENS i on (mov.BDCODEMP = i.BDCODEMP AND mov.BDCHAVE = i.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TA170 a170 on (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND i.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit on (mov.BDCODSITNF = sit.BDCODSITNF) ';
          wSQL = wSQL||        'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||               '(pgto.bdvalorpgtopar +';
          wSQL = wSQL||                '(COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||               'mov.BDCODCSTPIS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||               'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||               'mov.BDCODCSTCOF,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||               'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
          wSQL = wSQL||              'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.BDNAT_BC_CRED,';
          wSQL = wSQL||                     'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||                     'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
          wSQL = wSQL||              ' WHERE DEM.'||TRIM(:prWHEREEMPRESAS)||' ';

          if (wINCTRIB = 2) then
            wSQL = wSQL||              ' AND (dem.BDIND_OPER <> 1) '; -- Opera??o de Aquisi??o...
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                      'FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = dem.BDCODEMP ';
          wSQL = wSQL||                        'AND e.BDREFEMP <= dem.BDREFLAN ';
          wSQL = wSQL||                      'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||               'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'WHERE ((mov.BDCODCSTPIS is not null) or (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||          'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';
        END
                           /* Sa?das - Produtos */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, mov.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 2 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'p.BDVLRITEM AS BDVL_ITEM,';
      wSQL = wSQL||               'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS,';
      wSQL = wSQL||               'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                 'AND (s.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||               'AND (s.BDCONDPGTO <> 1) ';
       wSQL = wSQL||                'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 'AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVPROSAI p on (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||        'WHERE (p.BDCODPROD is not null) ';

      wSQL = wSQL||        'union all ';
                           /* Sa?das - Transporte (D100) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 16 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'mov.BDVALORNOTA AS BDVL_ITEM,';
      wSQL = wSQL||               'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
      wSQL = wSQL||               'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                 'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                   'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 ' AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'WHERE (d100.BDCHAVE is not null) ';

      wSQL = wSQL||        'union all ';
                           /* Demais documentos - Receita */
      wSQL = wSQL||        'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN AS BDREFERENCIA, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'dem.BDVL_OPER AS BDVL_ITEM,';
      wSQL = wSQL||               'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS,';
      wSQL = wSQL||               'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||        'WHERE DEM.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         ' AND dem.BDREFLAN = '||:prREFERENCIA;
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||        'AND (dem.BDIND_OPER <> 1) '; -- Opera??o de Aquisi??o...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||          'AND (dem.BDCONDPGTO <> 1) ';

      wSQL = wSQL||        ' union all ';
                           /* Servi?os tomados(Emitidos) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'a.BDVL_ITEM, ';
      wSQL = wSQL||               'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS,';
      wSQL = wSQL||               'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM ( ';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||                 'AND (s.BDTIPLAN = 0) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                 'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 ' AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TA170 a on (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||        'WHERE (a.BDCODPROD is not null) ';

      wSQL = wSQL||        'union all ';
                           /* C425 - Varias al?quotas */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMICMS AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE,  r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZVARALIQ aliq on (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425ALIQ c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE AND c425.BDORDEMICMS = aliq.BDORDEMICMS) ';

      wSQL = wSQL||        'union all ';
                           /* C425 */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMTOT AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 6 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE, r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425 c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||        'union all ';
                           /* C470 */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c470.BDCHAVE, c470.BDORDEMDOCECF AS BDORDEM, c470.BDORDEMITEM AS BDORDEMPRO, 8 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c470.BDVLRTOTPRO AS BDVL_ITEM,';
      wSQL = wSQL||               'c470.BDCODCSTPIS, c470.BDVL_BC_PIS AS BDBCPIS, c470.BDALIQ_PIS AS BDALIQPIS, c470.BDVLRPIS,';
      wSQL = wSQL||               'c470.BDCODCSTCOF, c470.BDVL_BC_COFINS AS BDBCCOFINS, c470.BDALIQ_COFINS AS BDALIQCOFINS, c470.BDVLRCOFINS,';
      wSQL = wSQL||               'c470.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c470.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c470.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c470.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE, r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TDOCECF c460 on (c460.BDCODEMP = mov.BDCODEMP AND c460.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TITEMDOCECF c470 on (c470.BDCODEMP = c460.BDCODEMP AND c470.BDCHAVE = c460.BDCHAVE AND c470.BDORDEMDOCECF = c460.BDORDEMDOCECF) ';

      wSQL = wSQL||        'union all ';
                           /* Lan?amento de opera??es imobili?rias(F200) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, Cast((SubString(i.BDDATAPGTO FROM 1 for 4)||SubString(i.BDDATAPGTO FROM 6 for 2)) AS Integer) AS BDREFERENCIA, ';
      wSQL = wSQL||               'i.BDCHAVE, i.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, ';
      IF (wINCTRIB = 1) THEN
        BEGIN
          wSQL = wSQL||             'iif(((i.BDCODCSTPIS = 1) AND (CAST(i.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)))), 4, null) AS BDCOD_CONT_PIS, ';
          wSQL = wSQL||             'iif(((i.BDCODCSTCOF = 1) AND (CAST(i.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)))), 4, null) AS BDCOD_CONT_COF, ';
        END
      ELSE
      IF (wINCTRIB = 2) THEN
        BEGIN
          wSQL = wSQL||             'iif(((i.BDCODCSTPIS = 1) AND (CAST(i.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)))), 54, null) AS BDCOD_CONT_PIS, ';
          wSQL = wSQL||             'iif(((i.BDCODCSTCOF = 1) AND (CAST(i.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)))), 54, null) AS BDCOD_CONT_COF, ';
        END
      ELSE
      IF (wINCTRIB = 3) THEN
        BEGIN
          wSQL = wSQL||           'CASE i.BDCODCSTPIS ';
          wSQL = wSQL||             'WHEN 1 THEN CASE CAST(i.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 04 ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE null ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'WHEN 5 THEN CASE CAST(i.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE 32 ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'ELSE null ';
          wSQL = wSQL||           'END AS BDCOD_CONT_PIS, ';

          wSQL = wSQL||           'CASE i.BDCODCSTCOF ';
          wSQL = wSQL||             'WHEN 1 THEN CASE CAST(i.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 04 ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE null ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'WHEN 5 THEN CASE CAST(i.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE 32 ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'ELSE null ';
          wSQL = wSQL||           'END AS BDCOD_CONT_COF, ';
        END
      wSQL = wSQL||               'i.BDVLRTOTRECPAR AS BDVL_ITEM,';
      wSQL = wSQL||               'i.BDCODCSTPIS, i.BDBASEPIS AS BDBCPIS, i.BDALIQPIS, i.BDVLRPIS,';
      wSQL = wSQL||               'i.BDCODCSTCOF, i.BDBASECOFINS AS BDBCCOFINS, i.BDALIQCOFINS, i.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT f.BDCODEMP, f.BDCHAVE ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 f ';
      wSQL = wSQL||               'WHERE F.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'WHERE (i.BDDATAPGTO is not null) ';
      wSQL = wSQL||          'AND (Cast((SubString(i.BDDATAPGTO FROM 1 for 4)||SubString(i.BDDATAPGTO FROM 6 for 2)) AS Integer) = '||:prREFERENCIA||') ';

      wSQL = wSQL||        'union all ';
                           /* I100 */
      wSQL = wSQL||        'SELECT i100.BDCODEMP, COALESCE(emp.BDCODMATRIZ, i100.BDCODEMP) as BDCODMATRIZ, i100.BDREFERENCIA, i100.BDCHAVE, NULL as BDORDEM,';
--      wSQL = wSQL||               'NULL as BDORDEMPRO, 9 as BDCODTP, NULL as BDCOD_CONT_PIS, NULL as BDCOD_CONT_COF, (i100.BDVLRREC-i100.BDVLRTOTDEDGER-i100.BDVLRTOTDEDESP) as BDVL_ITEM,';
      wSQL = wSQL||               'NULL as BDORDEMPRO, 9 as BDCODTP, NULL as BDCOD_CONT_PIS, NULL as BDCOD_CONT_COF, i100.BDVLRREC as BDVL_ITEM,';
      wSQL = wSQL||               'i100.BDCODCSTPISCOF as BDCODCSTPIS, i100.BDBASEPIS as BDBCPIS, i100.BDALIQPIS, i100.BDVLRPIS,';
      wSQL = wSQL||               'i100.BDCODCSTPISCOF as BDCODCSTCOF, i100.BDBASECOFINS as BDBCCOFINS, i100.BDALIQCOFINS, i100.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL as BDQUANT_BC_PIS, NULL as BDALIQ_PIS_QUANT, NULL as BDQUANT_BC_COF, NULL as BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM VEF_EMP_TMOVFINI100 i100 ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = i100.BDCODEMP) ';
      wSQL = wSQL||        'WHERE i100.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         ' AND i100.BDREFERENCIA = '||:prREFERENCIA||' ';

      wSQL = wSQL||        ') aux ';
--      wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS in (1,2,3,5)) OR (aux.BDCODCSTCOF in (1,2,3,5))) '; -- CSTs que geram regitros M200/600...

      EXECUTE STATEMENT ( wSQL );

      /* Insere os valores no nas tabelas do M210 e M610, pois j? atingiu o tamanho m?ximo da SP */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX (:prCODEMP, :prREFERENCIA);

    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M210_M610AUX */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCSOCIAL INTEGER;
DECLARE VARIABLE WINDNATPJ INTEGER;
DECLARE VARIABLE WALIQ_PIS_IT_1 VARCHAR(5);
DECLARE VARIABLE WALIQ_COF_IT_1 VARCHAR(5);
DECLARE VARIABLE WALIQ_PIS_IT_2 VARCHAR(5);
DECLARE VARIABLE WALIQ_COF_IT_2 VARCHAR(5);
BEGIN
  /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
  wALIQ_PIS_IT_1 = '1.65';
  wALIQ_COF_IT_1 = '7.60';
  /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
  wALIQ_PIS_IT_2 = '0.65';
  wALIQ_COF_IT_2 = '3.00';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  SELECT BDINDNATPJ FROM VW_VEF_BASE_TEMPPARFED WHERE BDCODEMP = :prCODEMP INTO :wINDNATPJ;

  /* REGISTRO M210: DETALHAMENTO DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER) ';
  wSQL = wSQL||'SELECT 19 as BDCODQUADRO, 7 as BDCODPERIODO, tmp.BDCODEMP, COALESCE(emp.BDCODMATRIZ, tmp.BDCODEMP) as BDCODMATRIZ, tmp.BDREFERENCIA, ';
  wSQL = wSQL||'       (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7) as BDCHAVE, ';
  wSQL = wSQL||'       t435.BDCODCSOCIAL, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDVL_REC_BRT,0)) as BDVL_REC_BRT, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDVL_BC_CONT_PIS,0)) as BDVL_BC_CONT, tmp.BDALIQ_PIS as BDALIQ, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDQUANT_BC_PIS,0)) as BDQUANT_BC, tmp.BDALIQ_QUANT_PIS as BDALIQ_QUANT, ';
  wSQL = wSQL||'       (SUM(IIF(COALESCE(tmp.BDVL_BC_CONT_PIS,0) > 0, tmp.BDVL_BC_CONT_PIS, COALESCE(tmp.BDQUANT_BC_PIS, 0))*IIF(COALESCE(tmp.BDALIQ_PIS,0) > 0, tmp.BDALIQ_PIS, COALESCE(tmp.BDALIQ_QUANT_PIS,1)))) as BDVL_CONT_APUR, ';
  wSQL = wSQL||'       0 as BDVL_AJUS_ACRES, ';
  wSQL = wSQL||'       0 as BDVL_AJUS_REDUC, ';
  wSQL = wSQL||'       0 as BDVL_CONT_DIFER, ';
  wSQL = wSQL||'       0 as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||'       0 as BDVL_CONT_PER ';
  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = tmp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIALEXP = tmp.BDCOD_CONT_PIS) ';
  wSQL = wSQL||'WHERE (((tmp.BDVL_BC_CONT_PIS > 0) or (tmp.BDALIQ_PIS > 0)) or ';
  wSQL = wSQL||'       ((tmp.BDQUANT_BC_PIS > 0) or (tmp.BDALIQ_QUANT_PIS > 0))) ';
  wSQL = wSQL||'  AND (tmp.BDCODCSTPIS in (1,2,3,5)) '; -- CSTs que geram regitros M200/600...
  wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS <> 5) OR ((tmp.BDCODCSTPIS = 5) and ((tmp.BDALIQ_PIS > 0) or (tmp.BDALIQ_QUANT_PIS > 0)))) '; -- CST 05 com al?quota zerada vai no M400/M800...
  wSQL = wSQL||'  AND ((tmp.BDCODTP NOT IN (3,10,11,16)) OR '; -- Lan?amentos de transporte com CST inv?lida, tem inconsist?ncia...
  wSQL = wSQL||'       ((tmp.BDCODTP IN (3,10,11,16)) AND (tmp.BDCODCSTPIS <> (03))) ) ';
  wSQL = wSQL||'  AND (tmp.BDCOD_CONT_PIS IS NOT NULL) ';
  wSQL = wSQL||'  AND (t435.BDCODCSOCIAL IS NOT NULL) ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))) ) ';
     END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) ) ';
     END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Exclusivamente no regime n?o-cumulativo / Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       ((CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))) OR (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4)))) ) ';
     END
   wSQL = wSQL||'GROUP BY tmp.BDCODEMP, emp.BDCODMATRIZ, tmp.BDREFERENCIA, t435.BDCODCSOCIAL, tmp.BDALIQ_PIS, tmp.BDALIQ_QUANT_PIS; ';

   EXECUTE STATEMENT ( wSQL );

  /* REGISTRO M610: DETALHAMENTO DA CONTRIBUI??O PARA A SEGURIDADE SOCIAL - COFINS DO PER?ODO */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER) ';
  wSQL = wSQL||'SELECT 37 as BDCODQUADRO, 7 as BDCODPERIODO, tmp.BDCODEMP, COALESCE(emp.BDCODMATRIZ, tmp.BDCODEMP) as BDCODMATRIZ, tmp.BDREFERENCIA, ';
  wSQL = wSQL||'      (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7) as BDCHAVE, ';
  wSQL = wSQL||'      t435.BDCODCSOCIAL, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDVL_REC_BRT,0)) as BDVL_REC_BRT, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDVL_BC_CONT_COF,0)) as BDVL_BC_CONT, tmp.BDALIQ_COF as BDALIQ, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDQUANT_BC_COF,0)) as BDQUANT_BC, tmp.BDALIQ_QUANT_COF as BDALIQ_QUANT, ';
  wSQL = wSQL||'      (SUM(IIF(COALESCE(tmp.BDVL_BC_CONT_COF,0) > 0, tmp.BDVL_BC_CONT_COF, COALESCE(tmp.BDQUANT_BC_COF, 0))*IIF(COALESCE(tmp.BDALIQ_COF,0) > 0, tmp.BDALIQ_COF, COALESCE(tmp.BDALIQ_QUANT_COF,1)))) as BDVL_CONT_APUR, ';
  wSQL = wSQL||'      0 as BDVL_AJUS_ACRES, ';
  wSQL = wSQL||'      0 as BDVL_AJUS_REDUC, ';
  wSQL = wSQL||'      0 as BDVL_CONT_DIFER, ';
  wSQL = wSQL||'      0 as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||'      0 as BDVL_CONT_PER ';
  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = tmp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIALEXP = tmp.BDCOD_CONT_COF) ';
  wSQL = wSQL||'WHERE (((tmp.BDVL_BC_CONT_COF > 0) or (tmp.BDALIQ_COF > 0)) or ';
  wSQL = wSQL||'       ((tmp.BDQUANT_BC_COF > 0) or (tmp.BDALIQ_QUANT_COF > 0))) ';
  wSQL = wSQL||'  AND (tmp.BDCODCSTCOF in (1,2,3,5)) '; -- CSTs que geram regitros M200/600...
  wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF <> 5) OR ((tmp.BDCODCSTCOF = 5) and ((tmp.BDALIQ_COF > 0) or (tmp.BDALIQ_QUANT_COF > 0)))) '; -- CST 05 com al?quota zerada vai no M400/M800...
  wSQL = wSQL||'  AND ((tmp.BDCODTP NOT IN (3,10,11,16)) OR '; -- Lan?amentos de transporte com CST inv?lida, tem inconsist?ncia...
  wSQL = wSQL||'       ((tmp.BDCODTP IN (3,10,11,16)) AND (tmp.BDCODCSTCOF <> (03))) ) ';
  wSQL = wSQL||'  AND (tmp.BDCOD_CONT_COF IS NOT NULL) ';
  wSQL = wSQL||'  AND (t435.BDCODCSOCIAL IS NOT NULL) ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(7.60 as NUMERIC(7,4))) ) ';
    END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(3.00 as NUMERIC(7,4))) ) ';
    END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Exclusivamente no regime n?o-cumulativo / Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       ((CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(7.60 as NUMERIC(7,4))) OR (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(3.00 as NUMERIC(7,4)))) ) ';
    END
   wSQL = wSQL||'GROUP BY tmp.BDCODEMP, emp.BDCODMATRIZ, tmp.BDREFERENCIA, t435.BDCODCSOCIAL, tmp.BDALIQ_COF, tmp.BDALIQ_QUANT_COF; ';

  EXECUTE STATEMENT ( wSQL );
   
  /* Atualiza os valores ap?s inserir, n?o faz no insert/select acima para n?o matriciar */
  FOR
      SELECT BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL
      FROM VEF_EMP_TBLOCOM210_M610 x
      WHERE x.BDCODMATRIZ = :prCODEMP
        AND x.BDREFERENCIA = :prREFERENCIA
      INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCODCSOCIAL
  DO
    BEGIN
      /* Verifica o quadros para pegar os campos corretos, PIS ou Cofins */
      /* Quando alterar os Selects dos campos, n?o esquecer de atualizar os Selects do campos 13... */
      UPDATE VEF_EMP_TBLOCOM210_M610 x
      SET -- 04 - VL_BC_CONT - Valor da Base de C?lculo da Contribui??o
          -- Se a empresa for sociedade cooperativa, vai descontar os lan?amentos de ajuste do M211...
          x.BDVL_BC_CONT = IIF(:wINDNATPJ IN (1,4),
--                               (IIF(((COALESCE(x.BDVL_BC_CONT,0) > 0) OR (x.BDCODCSOCIAL = 3)), COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))- -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
                               (x.BDVL_BC_CONT-
                                COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0)+COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0)+COALESCE(m211.BDVLREXCLUBCCOFINS,0) ))
                                          FROM VEF_EMP_TSOCCOOPM211M611 m211
                                          WHERE m211.BDCODEMP = x.BDCODEMP
                                            AND m211.BDREFERENCIA = x.BDREFERENCIA
                                            AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                            AND (((x.BDCODQUADRO = 19) AND (m211.BDALIQPIS = x.BDALIQ)) OR
                                                 ((x.BDCODQUADRO = 37) AND (m211.BDALIQCOFINS = x.BDALIQ)))),0)
                                        ),
--                               IIF(((COALESCE(x.BDVL_BC_CONT,0) > 0) OR (x.BDCODCSOCIAL = 3)), COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))), -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
                               x.BDVL_BC_CONT), -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
          -- 08 - VL_CONT_APUR - Valor total da contribui??o social apurada
          x.BDVL_CONT_APUR = (((IIF(:wINDNATPJ IN (1,4),
                                    (IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))-
                                     COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19),COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) FROM VEF_EMP_TSOCCOOPM211M611 m211
                                     WHERE m211.BDCODEMP = x.BDCODEMP
                                       AND m211.BDREFERENCIA = x.BDREFERENCIA
                                       AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                                 AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT))) OR
                                                      ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))))),0) ),
                                    IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0)))
                                )*IIF(COALESCE(x.BDALIQ,0) > 0, COALESCE(x.BDALIQ,0), COALESCE(x.BDALIQ_QUANT,1)))/IIF(COALESCE(x.BDALIQ,0) > 0, 100, 1)), -- Caso seja por quantidade, multiplica sem al?quota....
          -- 09 - VL_AJUS_ACRES - Valor total dos ajustes de acr?scimo
          x.BDVL_AJUS_ACRES = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 1 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 10 - VL_AJUS_REDUC - Valor total dos ajustes de redu??o
          x.BDVL_AJUS_REDUC = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 0 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 11 - VL_CONT_DIFER - Valor da contribui??o a diferir no per?odo
          x.BDVL_CONT_DIFER = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m230.BDVLRCONDEFPIS,0), COALESCE(m230.BDVLRCONDEFCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 m230 WHERE m230.BDCODEMP = x.BDCODEMP AND m230.BDREFERENCIA = x.BDREFERENCIA AND m230.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m230.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m230.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 12 - VL_CONT_DIFER_ANT - Valor da contribui??o diferida em per?odos anteriores
          x.BDVL_CONT_DIFER_ANT = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), (COALESCE(m300.BDVLRCONTRIPIS,0)-COALESCE(m300.BDVLRCREPIS,0)), (COALESCE(m300.BDVLRCONTRICOFINS,0)-COALESCE(m300.BDVLRCRECOFINS,0)))) FROM VEF_EMP_TINFADIDEFM300M700 m300 WHERE m300.BDCODEMP = x.BDCODEMP AND m300.BDREFERENCIA = x.BDREFERENCIA AND m300.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m300.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m300.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 13 - VL_CONT_PER - Valor Total da Contribui??o do Per?odo (08 + 09 ? 10 ? 11 + 12)
          x.BDVL_CONT_PER = (
          /*   08 - VL_CONT_APUR */       (((IIF(:wINDNATPJ IN (1,4),
                                                 (IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))-
                                                  COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19),COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) FROM VEF_EMP_TSOCCOOPM211M611 m211
                                                  WHERE m211.BDCODEMP = x.BDCODEMP
                                                    AND m211.BDREFERENCIA = x.BDREFERENCIA
                                                    AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                                              AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT))) OR
                                                                   ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))))),0) ),
                                                 IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0)))
                                             )*IIF(COALESCE(x.BDALIQ,0) > 0, COALESCE(x.BDALIQ,0), COALESCE(x.BDALIQ_QUANT,1)))/IIF(COALESCE(x.BDALIQ,0) > 0, 100, 1)) -- Caso seja por quantidade, multiplica sem al?quota....
          /* + 09 - VL_AJUS_ACRES */     +(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 1 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* ? 10 - VL_AJUS_REDUC */     -(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 0 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* ? 11 - VL_CONT_DIFER */     -(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m230.BDVLRCONDEFPIS,0), COALESCE(m230.BDVLRCONDEFCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 m230 WHERE m230.BDCODEMP = x.BDCODEMP AND m230.BDREFERENCIA = x.BDREFERENCIA AND m230.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m230.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m230.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* + 12 - VL_CONT_DIFER_ANT */ +(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), (COALESCE(m300.BDVLRCONTRIPIS,0)-COALESCE(m300.BDVLRCREPIS,0)), (COALESCE(m300.BDVLRCONTRICOFINS,0)-COALESCE(m300.BDVLRCRECOFINS,0)))) FROM VEF_EMP_TINFADIDEFM300M700 m300 WHERE m300.BDCODEMP = x.BDCODEMP AND m300.BDREFERENCIA = x.BDREFERENCIA AND m300.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m300.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m300.BDALIQCOFINS = x.BDALIQ))) ),0))
                             )
      WHERE x.BDCODPERIODO = :wCODPERIODO
        AND x.BDCODEMP = :wCODEMP
        AND x.BDCODMATRIZ = :wCODMATRIZ
        AND x.BDCODQUADRO = :wCODQUADRO
        AND x.BDREFERENCIA = :wREFERENCIA
        AND x.BDCHAVE = :wCHAVE;

  IF (:wINDNATPJ IN (1,4)) THEN -- Apenas se a empresa for "01 ? Sociedade cooperativa" ou "04 ? Sociedade cooperativa participante de SCP como s?cia ostensiva"
    BEGIN
          /* REGISTRO M211: SOCIEDADES COOPERATIVAS ? COMPOSI??O DA BASE DE CALCULO ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM211_M611 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDTIPOSOCCOOP, BDVL_BC_CONT_ANT_EXC, BDVL_EXC_COOP_GER, BDVL_EXC_ESP_COOP, BDVL_BC_CONT)
      SELECT :wCODPERIODO AS BDCODPERIODO, m211.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m211.BDCODEMP) AS BDCODMATRIZ, :wCODQUADRO AS BDCODQUADRO, m211.BDREFERENCIA, :wCHAVE AS BDCHAVE,
                 (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
                  FROM VEF_EMP_TBLOCOM211_M611 x
                  WHERE x.BDCODPERIODO = :wCODPERIODO
                    AND x.BDCODEMP = :wCODEMP
                    AND x.BDCODMATRIZ = :wCODMATRIZ
                    AND x.BDCODQUADRO = :wCODQUADRO
                    AND x.BDREFERENCIA = :wREFERENCIA
                    AND x.BDCHAVE = :wCHAVE) AS BDORDEM,
             m211.BDTIPOSOCCOOP,
             -- 03 - VL_BC_CONT_ANT_EXC_COOP - Valor da Base de C?lculo da Contribui??o, conforme Registros escriturados nos Blocos A, C, D e F, antes das Exclus?es das Cooperativas.
                 (SELECT ( SUM(x.BDVL_BC_CONT)+
                           -- Como j? abateu as exclus?es no select complementar acima, adiciona esses valores aqui...
                           SUM(IIF((x.BDCODQUADRO = 19), COALESCE(SUM(m211.BDVLREXCLUGERPIS),0)+COALESCE(SUM(m211.BDVLREXCLUBCPIS),0),
                                                         COALESCE(SUM(m211.BDVLREXCLUGERCOFINS),0)+COALESCE(SUM(m211.BDVLREXCLUBCCOFINS),0) )) ) as BDVL_BC_CONT


                  FROM VEF_EMP_TBLOCOM210_M610 x
                  WHERE x.BDCODPERIODO = :wCODPERIODO
                    AND x.BDCODEMP = :wCODEMP
                    AND x.BDCODMATRIZ = :wCODMATRIZ
                    AND x.BDCODQUADRO = :wCODQUADRO
                    AND x.BDREFERENCIA = :wREFERENCIA
                    AND x.BDCHAVE = :wCHAVE
                    AND x.BDCODCSOCIAL = :wCODCSOCIAL
                    AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT)) ) OR
                         ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))) ) ) AS BDVL_BC_CONT_ANT_EXC,
             -- 04 - VL_EXC_COOP_GER - Valor de Exclus?o Especifica das Cooperativas em Geral, decorrente das Sobras Apuradas na DRE, destinadas a constitui??o do Fundo de Reserva e do FATES.
             SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0))) AS BDVL_EXC_COOP_GER,
             -- 05 - VL_EXC_ESP_COOP - Valor das Exclus?es da Base de C?lculo Especifica do Tipo da Sociedade Cooperativa, conforme Campo 02 (IND_TIP_COOP).
             SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) AS BDVL_EXC_ESP_COOP,
             -- 06 - VL_BC_CONT - Valor da Base de C?lculo, Ap?s as Exclus?es Especificas da Sociedade Cooperativa (04 ? 05 ? 06) ? Transportar para M210.
                 /* 03 - VL_BC_CONT_ANT_EXC_COOP */ ( (SELECT SUM(x.BDVL_BC_CONT) as BDVL_BC_CONT
                                                       FROM VEF_EMP_TBLOCOM210_M610 x
                                                       WHERE x.BDCODPERIODO = :wCODPERIODO
                                                         AND x.BDCODEMP = :wCODEMP
                                                         AND x.BDCODMATRIZ = :wCODMATRIZ
                                                         AND x.BDCODQUADRO = :wCODQUADRO
                                                         AND x.BDREFERENCIA = :wREFERENCIA
                                                         AND x.BDCHAVE = :wCHAVE
                                                         AND x.BDCODCSOCIAL = :wCODCSOCIAL)
                 -- J? abateu as exclus?es no select complementar acima...
                 --/* 04 - VL_EXC_COOP_GER */          -SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0)))
                 --/* 05 - VL_EXC_ESP_COOP */          -SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0)))
                                                      ) AS BDVL_BC_CONT
      FROM VEF_EMP_TSOCCOOPM211M611 m211
      LEFT OUTER JOIN TEMPRESAS emp ON (emp.BDCODEMP = m211.BDCODEMP)
      WHERE m211.BDCODEMP = :wCODEMP
        AND m211.BDREFERENCIA = :wREFERENCIA
            AND m211.BDCODCSOCIAL = :wCODCSOCIAL
            AND ( ((:wCODQUADRO = 19) AND ((m211.BDALIQPIS > 0) OR (m211.BDVLREXCLUGERPIS > 0) OR (m211.BDVLREXCLUBCPIS > 0))) OR
                  ((:wCODQUADRO = 37) AND ((m211.BDALIQCOFINS > 0) OR (m211.BDVLREXCLUGERCOFINS > 0) OR (m211.BDVLREXCLUBCCOFINS > 0))) )
            AND (EXISTS(SELECT *
                        FROM VEF_EMP_TBLOCOM210_M610 x
                        WHERE x.BDCODEMP = m211.BDCODEMP
                          AND x.BDREFERENCIA = m211.BDREFERENCIA
                          AND x.BDCODCSOCIAL = m211.BDCODCSOCIAL
                          AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT)) ) OR
                               ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))) )
                        ))
          GROUP BY m211.BDCODEMP, emp.BDCODMATRIZ, m211.BDREFERENCIA, m211.BDTIPOSOCCOOP, m211.BDALIQPIS, m211.BDALIQCOFINS;
        END

  END
  
  /* Aliquota diferente do padr?o nos lan?amentos do M210 e M610 #Inconsist?ncia# */
  wSQL =       'INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC) ';
  wSQL = wSQL||'SELECT aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = aux.BDCODMATRIZ AND x.BDREFERENCIA = '||:prREFERENCIA||') AS BDCODBLOCOM, ';
  wSQL = wSQL||       'aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODINC ';
  wSQL = wSQL||'FROM ( ';
  -- PIS/PASEP
  wSQL = wSQL||       'SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '       aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 6 AS BDCODINC ';
  wSQL = wSQL||       'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux ';
  wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
  --wSQL = wSQL||       'WHERE (aux.BDCODCSTPIS NOT IN (02,03,05)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||       'WHERE (aux.BDCODCSTPIS IN (01)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||         'AND aux.BDCODEMP in (SELECT ex.BDCODEMP ';
  wSQL = wSQL||                              'FROM TEMPRESAS ex ';
  wSQL = wSQL||                              'WHERE ex.BDCODEMP = '||:prCODEMP||' ';
  wSQL = wSQL||                                 'OR ex.BDCODMATRIZ = '||:prCODEMP||') ';
  wSQL = wSQL||         'AND (aux.BDREFERENCIA = '||:prREFERENCIA||') ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))) ';
     END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))) ';
     END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
     BEGIN
      wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))) AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)))) ';
     END

  wSQL = wSQL||       'UNION ALL ';
  -- Cofins
  wSQL = wSQL||       'SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '       aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 7 AS BDCODINC ';
  wSQL = wSQL||       'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux ';
  wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
  --wSQL = wSQL||       'WHERE (aux.BDCODCSTCOF NOT IN (02,03,05)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||       'WHERE (aux.BDCODCSTCOF IN (01)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||         'AND aux.BDCODEMP in (SELECT ex.BDCODEMP ';
  wSQL = wSQL||                              'FROM TEMPRESAS ex ';
  wSQL = wSQL||                              'WHERE ex.BDCODEMP = '||:prCODEMP||' ';
  wSQL = wSQL||                                 'OR ex.BDCODMATRIZ = '||:prCODEMP||') ';
  wSQL = wSQL||         'AND (aux.BDREFERENCIA = '||:prREFERENCIA||') ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))) ';
    END
  ELSE
  IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))) ';
    END
  ELSE
  IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
    BEGIN
      wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))) AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)))) ';
    END

   wSQL = wSQL||      ') aux ';

   EXECUTE STATEMENT ( wSQL );

  /* CST 03 n?o permitida nos lan?amentos "A100/A170, C600/C601,D200/D201,D300,D600/D601" #Inconsist?ncia# */
  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
  SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
         aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 4 AS BDCODINC
  FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux
  WHERE ((aux.BDCODCSTPIS IN (03)) OR (aux.BDCODCSTCOF IN (03)))
    AND (aux.BDCODTP IN (3,10,11,16))
    AND (aux.BDCODMATRIZ = :prCODEMP)
    AND (aux.BDREFERENCIA = :prREFERENCIA);

  /* CST diferente de 01, a ?nica permitida nos lan?amentos de opera??es imobili?rias  #Inconsist?ncia# */
  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
  SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
         aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 10 AS BDCODINC
  FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux
  WHERE ((aux.BDCODCSTPIS <> 01) OR (aux.BDCODCSTCOF <> 01))
    AND (aux.BDCODTP IN (14))
    AND (aux.BDCODMATRIZ = :prCODEMP)
    AND (aux.BDREFERENCIA = :prREFERENCIA);

  IF (:wINDNATPJ IN (1,4)) THEN -- Apenas se a empresa for "01 ? Sociedade cooperativa" ou "04 ? Sociedade cooperativa participante de SCP como s?cia ostensiva"
    BEGIN
      /* Registros de M210/M610 sem M211/M611 respectivo #Inconsist?ncia# */
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDREPLACES)
      SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
             NULL as BDCODTP, NULL as BDCHAVE, NULL as BDORDEM, NULL as BDORDEMPRO, 11 AS BDCODINC,
             aux.BDCODCSOCIAL||'?'||CASE WHEN aux.BDCODQUADRO = 19 THEN 'PIS' ELSE 'Cofins' END||'?'||IIF(aux.BDALIQ > 0, aux.BDALIQ, aux.BDALIQ_QUANT) as BDREPLACES
      FROM VEF_EMP_TBLOCOM210_M610 aux
      WHERE (aux.BDCODMATRIZ = :prCODEMP)
        AND (aux.BDREFERENCIA = :prREFERENCIA)
        AND (NOT EXISTS(SELECT *
                        FROM VEF_EMP_TBLOCOM211_M611 m211
                        WHERE m211.BDCODPERIODO = aux.BDCODPERIODO
                          AND m211.BDCODEMP = aux.BDCODEMP
                          AND m211.BDCODMATRIZ = aux.BDCODMATRIZ
                          AND m211.BDCODQUADRO = aux.BDCODQUADRO
                          AND m211.BDREFERENCIA = aux.BDREFERENCIA
                          AND m211.BDCHAVE = aux.BDCHAVE ));
    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M220_M620 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M220_M620(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  -- INSERE A COMPET?NCIA DA APURA??O...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT;

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* REGISTRO M220: AJUSTES DA CONTRIBUI??O PARA O PIS/PASEP APURADA */
      INSERT INTO VEF_EMP_TBLOCOM220_M620 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, DESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m220.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m220.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m220.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m220.BDCODEMP AND x.BDREFERENCIA = m220.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) ) as BDORDEM,
             m220.BDCODAJUEFDC, m220.BDTIPOAJUSTE as BDIND_AJ, m220.BDVLRAJUPIS as BDVL_AJ, m220.BDNUMERODOC as BDNUM_DOC, m220.BDDESCRICAO as DESCR_AJ, m220.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TAJUAPUPCM220620 m220
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m220.BDCODEMP)
      WHERE m220.BDVLRAJUPIS > 0
        AND m220.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m220.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m220.BDCODEMP
                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL));

      /* REGISTRO M225: DETALHAMENTO DOS AJUSTES DA CONTRIBUI??O PARA O PIS/PASEP APURADA */
      INSERT INTO VEF_EMP_TBLOCOM225_M625 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM25, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCSTPIS, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m220.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m220.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m220.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m220.BDCODEMP AND x.BDREFERENCIA = m220.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) as BDCHAVE,
             (SELECT FIRST 1 x.BDORDEM
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDNUM_DOC = m220.BDNUMERODOC
                AND x.DESCR_AJ  = m220.BDDESCRICAO
                AND x.BDDT_REF  = m220.BDDATAREF
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM25)+1, 1)
              FROM VEF_EMP_TBLOCOM225_M625 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL)
                AND x.BDORDEM = (SELECT FIRST 1 x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM220_M620 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDNUM_DOC = m220.BDNUMERODOC
                                   AND x.DESCR_AJ  = m220.BDDESCRICAO
                                   AND x.BDDT_REF  = m220.BDDATAREF
                                   AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                                    FROM VEF_EMP_TBLOCOM210_M610 x
                                                    WHERE x.BDCODEMP = m220.BDCODEMP
                                                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                                                      AND x.BDCODQUADRO = 19
                                                      AND x.BDCODPERIODO = 7
                                                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL)) ) as BDORDEM25,
             m625.BDCODCSTCOF, m625.BDCODPLAPADRAO, m625.BDCODTPLA, m625.BDCODCSTPIS, m625.BDVALORPIS as BDDET_VALOR_AJ, m625.BDBCPIS as BDDET_BC_CRED, m625.BDALIQPIS as BDDET_ALIQ,
             m625.BDDATAOPEPIS as BDDT_OPER_AJ, m625.BDDESCRICAOAJU as BDDESC_AJ, m625.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TAJUAPUPCM220620 m220
      JOIN VEF_EMP_TDETAJUM225625 m625 on (m220.BDCODEMP = m625.BDCODEMP AND m220.BDCHAVE = m625.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m220.BDCODEMP)
      WHERE m220.BDVLRAJUPIS > 0
        AND m220.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m220.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m220.BDCODEMP
                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL));

      /* REGISTRO M620: AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM220_M620 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, DESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m620.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m620.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m620.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m620.BDCODEMP AND x.BDREFERENCIA = m620.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) ) as BDORDEM,
             m620.BDCODAJUEFDC, m620.BDTIPOAJUSTE as BDIND_AJ, m620.BDVLRAJUCOFINS as BDVL_AJ, m620.BDNUMERODOC as BDNUM_DOC, m620.BDDESCRICAO as DESCR_AJ, m620.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TAJUAPUPCM220620 m620
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m620.BDCODEMP)
      WHERE m620.BDVLRAJUCOFINS > 0
        AND m620.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m620.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m620.BDCODEMP
                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL));

      /* REGISTRO M625: DETALHAMENTO DOS AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM225_M625 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM25, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCSTPIS, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m620.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m620.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m620.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m620.BDCODEMP AND x.BDREFERENCIA = m620.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) as BDCHAVE,
             (SELECT FIRST 1 x.BDORDEM
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDNUM_DOC = m620.BDNUMERODOC
                AND x.DESCR_AJ  = m620.BDDESCRICAO
                AND x.BDDT_REF  = m620.BDDATAREF
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM25)+1, 1)
              FROM VEF_EMP_TBLOCOM225_M625 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL)
                AND x.BDORDEM = (SELECT FIRST 1 x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM220_M620 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDNUM_DOC = m620.BDNUMERODOC
                                   AND x.DESCR_AJ  = m620.BDDESCRICAO
                                   AND x.BDDT_REF  = m620.BDDATAREF
                                   AND x.BDCHAVE = (SELECT x.BDCHAVE
                                                    FROM VEF_EMP_TBLOCOM210_M610 x
                                                    WHERE x.BDCODEMP = m620.BDCODEMP
                                                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                                                      AND x.BDCODQUADRO = 37
                                                      AND x.BDCODPERIODO = 7
                                                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL)) ) as BDORDEM25,
             m625.BDCODCSTCOF, m625.BDCODPLAPADRAO, m625.BDCODTPLA, m625.BDCODCSTPIS, m625.BDVALORCOFINS as BDDET_VALOR_AJ, m625.BDBCCOFINS as BDDET_BC_CRED, m625.BDALIQCOFINS as BDDET_ALIQ,
             m625.BDDATAOPECOFINS as BDDT_OPER_AJ, m625.BDDESCRICAOAJU as BDDESC_AJ, m625.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TAJUAPUPCM220620 m620
      JOIN VEF_EMP_TDETAJUM225625 m625 on (m620.BDCODEMP = m625.BDCODEMP AND m620.BDCHAVE = m625.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m620.BDCODEMP)
      WHERE m620.BDVLRAJUCOFINS > 0
        AND m620.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m620.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m620.BDCODEMP
                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL));
    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M230_M630 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M230_M630(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  -- INSERE A COMPET?NCIA DA APURA??O...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT;

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* REGISTRO M230: INFORMA??ES ADICIONAIS DE DIFERIMENTO */
      INSERT INTO VEF_EMP_TBLOCOM230_M630 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCRE_4_3_6, BDCNPJ, BDVL_VEND, BDVL_NAO_RECEB, BDVL_CONT_DIF, BDVL_CRED_DIF)
      SELECT 7 as BDCODPERIODO, m230.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m230.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m230.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m230.BDCODEMP AND x.BDREFERENCIA = m230.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM230_M630 x
              WHERE x.BDCODEMP = m230.BDCODEMP
                AND x.BDREFERENCIA = m230.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m230.BDCODEMP
                                   AND x.BDREFERENCIA = m230.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL) ) as BDORDEM,
             m230.BDCODCRE_4_3_6, m230.BDCNPJPJRELACIONADA as BDCNPJ,
             m230.BDVLRVENDAPIS as BDVL_VEND, m230.BDVLRNRECPIS as BDVL_NAO_RECEB, m230.BDVLRCONDEFPIS as BDVL_CONT_DIF, m230.BDVLRCREDEFPIS as BDVL_CRED_DIF
      FROM VEF_EMP_TINFADIDEFM230630 m230
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m230.BDCODEMP)
      WHERE m230.BDALIQPIS > 0
        AND m230.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m230.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m230.BDCODEMP
                      AND x.BDREFERENCIA = m230.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL));

      /* REGISTRO M630: INFORMA??ES ADICIONAIS DE DIFERIMENTO */
      INSERT INTO VEF_EMP_TBLOCOM230_M630 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCRE_4_3_6, BDCNPJ, BDVL_VEND, BDVL_NAO_RECEB, BDVL_CONT_DIF, BDVL_CRED_DIF)
      SELECT 7 as BDCODPERIODO, m630.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m630.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m630.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m630.BDCODEMP AND x.BDREFERENCIA = m630.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM230_M630 x
              WHERE x.BDCODEMP = m630.BDCODEMP
                AND x.BDREFERENCIA = m630.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m630.BDCODEMP
                                   AND x.BDREFERENCIA = m630.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL) ) as BDORDEM,
             m630.BDCODCRE_4_3_6, m630.BDCNPJPJRELACIONADA as BDCNPJ,
             m630.BDVLRVENDACOFINS as BDVL_VEND, m630.BDVLRNRECCOFINS as BDVL_NAO_RECEB, m630.BDVLRCONDEFCOFINS as BDVL_CONT_DIF, m630.BDVLRCREDEPCOFINS as BDVL_CRED_DIF
      FROM VEF_EMP_TINFADIDEFM230630 m630
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m630.BDCODEMP)
      WHERE m630.BDALIQCOFINS > 0
        AND m630.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m630.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m630.BDCODEMP
                      AND x.BDREFERENCIA = m630.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL));

    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M300_M700 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M300_M700(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  /*
    REGISTRO M300: CONTRIBUI??O DE PIS/PASEP DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO.
    REGISTRO M700: COFINS DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO
  */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM300_M700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_CONT_APUR_DIFER, BDNAT_CRED_DESC, BDVL_CRED_DESC_DIFER, BDVL_CONT_DIFER_ANT, BDALIQ, BDPER_APUR, BDDT_RECEB) ';
  wSQL = wSQL||'SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE+1),1) FROM VEF_EMP_TBLOCOM300_M700 x WHERE x.BDCODPERIODO = aux.BDCODPERIODO AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) AND x.BDCODQUADRO = aux.BDCODQUADRO AND x.BDREFERENCIA = aux.BDREFERENCIA) AS BDCHAVE, ';
  wSQL = wSQL||       'aux.BDCODCSOCIAL, aux.BDVL_CONT_APUR_DIFER, aux.BDNAT_CRED_DESC, aux.BDVL_CRED_DESC_DIFER, aux.BDVL_CONT_DIFER_ANT, aux.BDALIQ, aux.BDPER_APUR, aux.BDDT_RECEB ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||      'SELECT 24 as BDCODQUADRO, '; -- M300 - Diferimentos Per?odos Anteriores de PIS/PASEP
  wSQL = wSQL||             '7 as BDCODPERIODO, m300.BDCODEMP, m300.BDREFERENCIA, m300.BDCODCSOCIAL, m300.BDVLRCONTRIPIS as BDVL_CONT_APUR_DIFER, ';
  wSQL = wSQL||             'm300.BDCODNATDEF as BDNAT_CRED_DESC, m300.BDVLRCREPIS as BDVL_CRED_DESC_DIFER, (m300.BDVLRCONTRIPIS-m300.BDVLRCREPIS) as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||             'm300.BDALIQPIS as BDALIQ, m300.BDREFERENCIA as BDPER_APUR, m300.BDDATAREC as BDDT_RECEB ';
  wSQL = wSQL||      'FROM VEF_EMP_TINFADIDEFM300M700 m300 ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 soc ON (soc.BDCODCSOCIAL = m300.BDCODCSOCIAL) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABNATCREDEF nat ON (nat.BDCODNATDEF = m300.BDCODNATDEF) ';
  wSQL = wSQL||      'WHERE m300.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND m300.BDREFERENCIA = '||:prREFERENCIA||' ';
  
  wSQL = wSQL||      ' UNION ALL ';
  
  wSQL = wSQL||      'SELECT 42 as BDCODQUADRO, '; -- M700 - Diferimentos Per?odos Anteriores de Cofins
  wSQL = wSQL||             '7 as BDCODPERIODO, m700.BDCODEMP, m700.BDREFERENCIA, m700.BDCODCSOCIAL, m700.BDVLRCONTRICOFINS as BDVL_CONT_APUR_DIFER, ';
  wSQL = wSQL||             'm700.BDCODNATDEF as BDNAT_CRED_DESC, m700.BDVLRCRECOFINS as BDVL_CRED_DESC_DIFER, (m700.BDVLRCONTRICOFINS-m700.BDVLRCRECOFINS) as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||             'm700.BDALIQCOFINS as BDALIQ, m700.BDREFERENCIA as BDPER_APUR, m700.BDDATAREC as BDDT_RECEB ';
  wSQL = wSQL||      'FROM VEF_EMP_TINFADIDEFM300M700 m700 ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 soc ON (soc.BDCODCSOCIAL = m700.BDCODCSOCIAL) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABNATCREDEF nat ON (nat.BDCODNATDEF = m700.BDCODNATDEF) ';
  wSQL = wSQL||      'WHERE m700.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND m700.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||      ') aux ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP); ';

  EXECUTE STATEMENT wSQL;

  /* REGISTRO M350: PIS/PASEP ? FOLHA DE SAL?RIOS */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M350 (:prCODEMP, :prREFERENCIA);
  
END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M350 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M350(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WALIQ NUMERIC(15,6);
DECLARE VARIABLE WCODIMP INTEGER;
DECLARE VARIABLE WVLRBRUTO NUMERIC(15,2);
DECLARE VARIABLE WVLRPIS NUMERIC(15,2);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT FIRST 1 i.BDCODIMP, i.BDALIQIMPOSTO
  FROM VW_TEMPRESAIMPOSTO e
  LEFT OUTER JOIN TIMPOSTO i ON (i.BDCODIMP = e.BDCODIMP)
  WHERE e.BDCODEMP = :prCODEMP
    AND i.BDCLASSIMP LIKE '01.01.01.04.%' -- "Classifica??o" PIS - Programa integra??o social
    AND i.BDCODSIS = 2 -- "Sistema" Folha
    AND i.BDDOCARRECADACAO = 1 -- "Documento arrecada??o" DARF
    AND i.BDCODTIPIMP = 6 -- "Tipo de imposto" PIS/Pasep
    AND i.BDTIPOIMPDOC = 2 -- "Tipo c?lculo imposto" PIS
    AND i.BDTIPORETENCAO = 1 -- "Reten??o" PIS
  INTO :wCODIMP, :wALIQ;

  IF (wALIQ IS NOT NULL) THEN -- A empresa deve ter o imposto cadastrado na empresa, caso contr?rio, n?o obriga...
    BEGIN
      SELECT --calc.BDCODEMP,calc.BDREFFN,
             SUM(CASE WHEN vr.BDTIPOCODVER = 0 THEN COALESCE(calc.BDVALVFN,0) ELSE 0 END) AS BDVLRBRUTO
             --SUM(CASE WHEN vr.BDPISVER = 'TRUE' THEN calc.BDVALVFN ELSE 0 END) AS BDVLRPIS -- Apenas verbas cadastradas como PIS
      FROM (
            SELECT fn.BDCODEMP, fn.BDCODCOL, fn.BDREFFN, fn.BDCODVER, fn.BDVALVFN
            FROM VRHF_EMP_TVERBAFN fn -- Folha normal
            WHERE fn.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND fn.BDREFFN = :prREFERENCIA
      
            UNION ALL
      
            SELECT rh.BDCODEMP, ad.BDCODCOL, ad.BDREFCOMP, ad.BDCODVER, ad.BDVALVFC
            FROM VRHF_EMP_TVERBAFC ad -- Folha normal complementar
            JOIN VW_VRHF_EMPRESAS_REF_ATUAL rh ON (ad.BDCODEMP = rh.BDCODEMP)
            WHERE (rh.BDCALCFCNAFNEMP <> 'TRUE')
              AND ad.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ad.BDREFCOMP = :prREFERENCIA
      
            UNION ALL
      
            SELECT ft.BDCODEMP, ft.BDCODCOL, ft.BDREFTOMADOR, ft.BDCODVER, ft.BDVALVFT
            FROM VRHF_EMP_TVERBATOMADOR ft -- Folha por tomador
            WHERE ft.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ft.BDREFTOMADOR = :prREFERENCIA
      
            UNION ALL
      
            SELECT ad.BDCODEMP, ad.BDCODCOL, ad.BDREFCOMP, ad.BDCODVER, ad.BDVALVFC
            FROM VRHF_EMP_TVERBAFCTOMADOR ad -- Folha por tomador complementar
            JOIN VW_VRHF_EMPRESAS_REF_ATUAL rh ON (ad.BDCODEMP = rh.BDCODEMP)
            WHERE (rh.BDCALCFCNAFNEMP <> 'TRUE')
              AND ad.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ad.BDREFCOMP = :prREFERENCIA
      
            UNION ALL
      
            SELECT dt.BDCODEMP, dt.BDCODCOL, dt.BDREF13, dt.BDCODVER, dt.BDVALV13
            FROM VRHF_EMP_TVERBA13 dt -- 13?
            WHERE dt.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND dt.BDREF13 = :prREFERENCIA
      
            UNION ALL
      
            SELECT cdt.BDCODEMP, cdt.BDCODCOL, cdt.BDREFC13, cdt.BDCODVER, cdt.BDVALVC13
            FROM VRHF_EMP_TVERBAC13 cdt -- Complemento 13o
            WHERE cdt.BDCODEMP in (SELECT ex.BDCODEMP
                                   FROM TEMPRESAS ex
                                   WHERE ex.BDCODEMP = :prCODEMP
                                      OR ex.BDCODMATRIZ = :prCODEMP)
              AND cdt.BDREF13 = :prREFERENCIA
            ) calc
      JOIN VW_VRH_EMP_TCOLCON_VINC col ON (col.BDCODEMP = calc.BDCODEMP AND col.BDCODCOL = calc.BDCODCOL)
      JOIN VRH_BASE_TCLASSE cla ON (col.BDCODCLA = cla.BDCODCLA)
      JOIN VW_VERBAS_REF_ATUAL vr ON (vr.BDCODVER = calc.BDCODVER)
      --GROUP BY calc.BDCODEMP, calc.BDREFFN
      INTO :wVLRBRUTO;--, :wVLRPIS;

      /* Caso n?o tenha apura??o da folha #Inconsist?ncia# */
      --IF (:wVLRBRUTO IS NULL) THEN
      --  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
      --                        VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA), NULL, NULL, NULL, NULL, 3);

      SELECT SUM(COALESCE(d.BDBASEIMP,0)) as BDBASEIMP
      FROM TDARFPADRAO d
      WHERE d.BDCODIMP = :wCODIMP
        AND d.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND d.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRPIS;

      /* Caso n?o tenha apura??o do Darf PIS #Inconsist?ncia# */
      IF (:wVLRPIS IS NULL) THEN
        INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
                              VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA), NULL, NULL, NULL, NULL, 12);

    END

  IF ((wALIQ IS NULL) OR (wVLRBRUTO IS NULL) OR (wVLRPIS IS NULL)) THEN
    EXIT;

  /* 02 - VL_TOT_FOL - Valor Total da Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 2, :wVLRBRUTO);

  /* 03 - VL_EXC_BC - Valor Total das Exclus?es ? Base de C?lculo */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 3, (:wVLRBRUTO - :wVLRPIS));

  /* 04 - VL_TOT_BC - Valor Total da Base de C?lculo */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 4, :wVLRPIS);

  IF ((wVLRBRUTO = 0) AND (wVLRPIS = 0)) THEN -- Caso venham valores zerados, leva tudo zerado...
    wALIQ = 0;

  /* 05 - ALIQ_PIS_FOL - Al?quota do PIS/PASEP ? Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 5, :wALIQ);

  /* 06 - VL_TOT_CONT_FOL - Valor Total da Contribui??o Social sobre a Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 6, ((:wVLRPIS*:wALIQ)/100) );

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M400_M800 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX (:prCODEMP, :prREFERENCIA, :prWHEREEMPRESAS);

      /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM400_M800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODCSTPIS, BDVL_TOT_REC, BDDESC_COMPL)
      SELECT 26 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM400_M800 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 26) AS BDCHAVE,
             tmp.BDCODCSTCOF, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTPIS, SUM(COALESCE(tmp.BDVL_ITEM,0)) AS BDVL_TOT_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTPIS > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

      /* REGISTRO M410: DETALHAMENTO DAS RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM410_M810 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODNATREC, BDVL_REC, BDDESC_COMPL)
      SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 26 AS BDCODQUADRO, tmp.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM400_M800 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                AND x.BDCODQUADRO = 26
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                ) AS BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1,1) FROM VEF_EMP_TBLOCOM410_M810 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 26
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                AND x.BDCHAVE = (SELECT z.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM400_M800 z
                                 WHERE z.BDCODEMP = tmp.BDCODEMP
                                   AND z.BDCODMATRIZ = tmp.BDCODMATRIZ
                                   AND z.BDREFERENCIA = tmp.BDREFERENCIA
                                   AND z.BDCODCSTCOF = tmp.BDCODCSTCOF
                                   AND z.BDCODCSTPIS = tmp.BDCODCSTPIS
                                   AND z.BDCODQUADRO = 26
                                   AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                                   AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
                                   ) AS BDORDEM,
             tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODNATREC, SUM(tmp.BDVL_ITEM) AS BDVL_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTPIS > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM400_M800 x
                    WHERE x.BDCODEMP = tmp.BDCODEMP
                      AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                      AND x.BDREFERENCIA = tmp.BDREFERENCIA
                      AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                      AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                      AND x.BDCODQUADRO = 26
                      AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                      AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))) ))
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODNATREC, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

      /* REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      INSERT INTO VEF_EMP_TBLOCOM400_M800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODCSTCOF, BDVL_TOT_REC, BDDESC_COMPL)
      SELECT 43 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM400_M800 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 43) AS BDCHAVE,
             tmp.BDCODCSTPIS, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, SUM(COALESCE(tmp.BDVL_ITEM,0)) AS BDVL_TOT_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTCOF > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF;

      /* REGISTRO M810: DETALHAMENTO DAS RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      INSERT INTO VEF_EMP_TBLOCOM410_M810 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODNATREC, BDVL_REC, BDDESC_COMPL)
      SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 43 AS BDCODQUADRO, tmp.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM400_M800 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                AND x.BDCODQUADRO = 43
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                ) AS BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1,1) FROM VEF_EMP_TBLOCOM410_M810 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 43
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                AND x.BDCHAVE = (SELECT z.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM400_M800 z
                                 WHERE z.BDCODEMP = tmp.BDCODEMP
                                   AND z.BDCODMATRIZ = tmp.BDCODMATRIZ
                                   AND z.BDREFERENCIA = tmp.BDREFERENCIA
                                   AND z.BDCODCSTPIS = tmp.BDCODCSTPIS
                                   AND z.BDCODCSTCOF = tmp.BDCODCSTCOF
                                   AND z.BDCODQUADRO = 43
                                   AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                                   AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
                                   ) AS BDORDEM,
             tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODNATREC, SUM(tmp.BDVL_ITEM) AS BDVL_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTCOF > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM400_M800 x
                    WHERE x.BDCODEMP = tmp.BDCODEMP
                      AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                      AND x.BDREFERENCIA = tmp.BDREFERENCIA
                      AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                      AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                      AND x.BDCODQUADRO = 26
                      AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                      AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))) ))
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODNATREC, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

    END

   /* Lan?amentos sem natureza da base de c?lculo  #Inconsist?ncia# */
   INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
   SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCODBLOCOM, tmp.BDCODTP, tmp.BDCHAVE, tmp.BDORDEM, tmp.BDORDEMPRO, 2 AS BDCODINC
   FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
   WHERE tmp.BDCODNATREC IS NULL
     AND tmp.BDCODMATRIZ = :prCODEMP
     AND tmp.BDREFERENCIA = :prREFERENCIA;

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M400_M800AUX */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP
           REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR (:prcodemp,  :prREFERENCIA, :prWHEREEMPRESAS);

      wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA) ';

      wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
      wSQL = wSQL||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
      wSQL = wSQL||       'aux.BDCODCSTPIS, aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
      wSQL = wSQL||       'aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
      wSQL = wSQL||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA ';
      wSQL = wSQL||'FROM (';
                          /* Sa?das - Produtos */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 2 AS BDCODTP, ';
      wSQL = wSQL||              'p.BDVLRITEM AS BDVL_ITEM, p.BDCODNATREC, p.BDCODCTA, ';
      wSQL = wSQL||              'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS,';
      wSQL = wSQL||              'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROSAI p ON (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = COALESCE(p.BDCODPLAPADRAO,lan.BDCODPLAPADRAO) and ccl.BDCODTPLA = COALESCE(p.BDCODTPLA,lan.BDCREDITO)) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = COALESCE(p.BDCODPLAPADRAO,lanrat.BDCODPLAPADRAO) and cclrat.BDCODTPLA = COALESCE(p.BDCODTPLA,lanrat.BDCREDITO)) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Sa?das - Transporte (D100) */
      wSQL = wSQL||       'select mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL as BDORDEM,';
      wSQL = wSQL||              'NULL as BDORDEMPRO, 16 as BDCODTP, mov.BDVALORNOTA as BDVL_ITEM, d100.BDCODNATREC, NULL as BDCODCTA,';
      wSQL = wSQL||              'd100.BDCODCSTPIS, d100.BDVL_BC_PIS as BDBCPIS, d100.BDALIQ_PIS as BDALIQPIS, d100.BDVLRPIS,';
      wSQL = wSQL||              'd100.BDCODCSTCOF, d100.BDVL_BC_COF as BDBCCOFINS, d100.BDALIQ_COF as BDALIQCOFINS, d100.BDVLRCOFINS,';
      wSQL = wSQL||              'COALESCE(CCL.BDCODPLAPADRAO, CCLRAT.BDCODPLAPADRAO) as BDCODPLAPADRAO,';
      wSQL = wSQL||              'COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Servi?o */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, ';
      wSQL = wSQL||              'a.BDVL_ITEM, a.BDCODNATREC, NULL AS BDCODCTA, ';
      wSQL = wSQL||              'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS,';
      wSQL = wSQL||              'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||              'WHERE s.BDTIPLAN = 0 '; -- Servi?os Emitidos
      wSQL = wSQL||                'AND (s.BDCODSITNF not in (2,3,4,5)) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TA170 a ON (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESER, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSER GROUP BY BDCODEMP, BDCHAVESER, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESER = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSER GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Demais documentos */
      wSQL = wSQL||       'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, ';
      wSQL = wSQL||              'dem.BDVL_OPER AS BDVL_ITEM, dem.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS, dem.BDVLR_PIS AS BDVLRPIS,';
      wSQL = wSQL||              'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(dem.bdCODPLAPADRAO, lan.bdCODPLAPADRAO) AS bdCODPLAPADRAO, COALESCE(dem.bdCODTPLA, lan.bdCREDITO) AS bdCODTPLA ';
      wSQL = wSQL||       'FROM ( ';
      wSQL = wSQL||               'SELECT dem.BDCODEMP, dem.BDREFLAN, dem.BDCHAVE, dem.bdIND_OPER, dem.BDVL_OPER, dem.BDCODNATREC, dem.bdCODPLAPADRAO, dem.bdCODTPLA, '; -- Caso tenha v?rios lan?amentos na contabiliza??o, vai buscar apenas a primeira conta...
      wSQL = wSQL||                      'dem.BDCODCSTPIS, dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS, ';
      wSQL = wSQL||                      'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||               'WHERE dem.bdIND_OPER IN (2,3) '; -- Opera??o Representativa de Receita
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (dem.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND dem.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||       ' ) dem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT tol.bdCODEMP, tol.bdCHAVEDEMDOC, lan.bdCODPLAPADRAO, MIN(lan.bdDATA) AS bdDATA, MIN(lan.bdREFERENCIA) AS bdREFERENCIA, MIN(lan.bdCREDITO) AS bdCREDITO, MIN(lan.bdDEBITO) AS bdDEBITO ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVDEMAISDOC tol ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = tol.bdCODEMP AND lan.bdCHAVE = tol.bdCHAVE) ';
      wSQL = wSQL||                        'GROUP BY bdCODEMP, bdCHAVEDEMDOC, bdCODPLAPADRAO) lan ON (lan.bdCODEMP = dem.bdCODEMP AND lan.bdCHAVEDEMDOC = dem.bdCHAVE) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Redu??o Z */
      wSQL = wSQL||       'SELECT redz.BDCODEMP, redz.BDCODMATRIZ, redz.BDREFLAN, redz.BDCHAVE, redz.BDORDEM, redz.BDORDEMPRO, redz.BDCODTP,  ';
      wSQL = wSQL||              'redz.BDVL_ITEM, redz.BDCODNATREC, redz.BDCODCTA,';
      wSQL = wSQL||              'redz.BDCODCSTPIS, redz.BDBCPIS, redz.BDALIQPIS, redz.BDVLRPIS,';
      wSQL = wSQL||              'redz.BDCODCSTCOF, redz.BDBCCOFINS, redz.BDALIQCOFINS, redz.BDVLRCOFINS, ';
      wSQL = wSQL||              'ccl.BDCODPLAPADRAO, ccl.BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, c425.BDCHAVE, c425.BDORDEMTOT AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 6 AS BDCODTP, ';
      wSQL = wSQL||                     'c425.BDVLRACU AS BDVL_ITEM, c425.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||                     'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425 c425 ON (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL ';

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, aliq.BDCHAVE, aliq.BDORDEMICMS AS BDORDEM, aliq.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, ';
      wSQL = wSQL||                     'aliq.BDVLRACU AS BDVL_ITEM, aliq.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'aliq.BDCODCSTPIS, aliq.BDVL_BC_PIS AS BDBCPIS, aliq.BDALIQ_PIS AS BDALIQPIS, aliq.BDVLRPIS,';
      wSQL = wSQL||                     'aliq.BDCODCSTCOF, aliq.BDVL_BC_COFINS AS BDBCCOFINS, aliq.BDALIQ_COFINS AS BDALIQCOFINS, aliq.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425ALIQ aliq ON (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL ';

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, i.BDCHAVE, i.BDORDEMDOCECF AS BDORDEM, i.BDORDEMITEM AS BDORDEMPRO, 8 AS BDCODTP, ';
      wSQL = wSQL||                     'i.BDVLRTOTPRO AS BDVL_ITEM, i.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'i.BDCODCSTPIS, i.BDVL_BC_PIS AS BDBCPIS, i.BDALIQ_PIS AS BDALIQPIS, i.BDVLRPIS AS BDVLRPIS,';
      wSQL = wSQL||                     'i.BDCODCSTCOF, i.BDVL_BC_COFINS AS BDBCCOFINS, i.BDALIQ_COFINS AS BDALIQCOFINS, i.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TDOCECF doc ON (doc.BDCODEMP = mov.BDCODEMP AND doc.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TITEMDOCECF i ON (i.BDCODEMP = doc.BDCODEMP AND i.BDCHAVE = doc.BDCHAVE AND i.BDORDEMDOCECF = doc.BDORDEMDOCECF) ';
      wSQL = wSQL||            ') redz ';
      wSQL = wSQL||       'LEFT OUTER JOIN (';
      wSQL = wSQL||                         'SELECT v.BDCODEMP, v.BDCHAVECFOP,';
      wSQL = wSQL||                                '(SELECT FIRST 1 x.BDCHAVE FROM TOL_VEF_EMP_TREDZVARCFOP x WHERE x.BDCODEMP = v.BDCODEMP AND x.BDCHAVECFOP = v.BDCHAVECFOP) as BDCHAVE ';
      wSQL = wSQL||                         'FROM TOL_VEF_EMP_TREDZVARCFOP v ';
      wSQL = wSQL||                         'WHERE v.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                         'GROUP BY v.BDCODEMP, v.BDCHAVECFOP ';
      wSQL = wSQL||                         ') tol on (tol.BDCODEMP = redz.BDCODEMP and tol.BDCHAVECFOP = redz.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* I100 */
      wSQL = wSQL||       'SELECT i100.BDCODEMP, COALESCE(emp.BDCODMATRIZ, i100.BDCODEMP) as BDCODMATRIZ, i100.BDREFERENCIA AS BDREFLAN, i100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 9 AS BDCODTP, ';
      --wSQL = wSQL||              '(i100.BDVLRREC-i100.BDVLRTOTDEDGER-i100.BDVLRTOTDEDESP) AS BDVL_ITEM, i100.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'i100.BDVLRREC AS BDVL_ITEM, i100.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'i100.BDCODCSTPISCOF AS BDCODCSTPIS, i100.BDBASEPIS AS BDBCPIS, i100.BDALIQPIS, i100.BDVLRPIS,';
      wSQL = wSQL||              'i100.BDCODCSTPISCOF AS BDCODCSTCOF, i100.BDBASECOFINS AS BDBCCOFINS, i100.BDALIQCOFINS, i100.BDVLRCOFINS, ';
      wSQL = wSQL||              'i200.BDCODPLAPADRAO, i200.BDCODTPLA ';
      wSQL = wSQL||       'FROM VEF_EMP_TMOVFINI100 i100 ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = i100.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN ( SELECT i.BDCODEMP, i.BDCHAVE, i.BDORDEMI200 as BDORDEMI200, i.BDCODPLAPADRAO, i.BDCODTPLA ';
      wSQL = wSQL||                         'FROM VEF_EMP_TMOVFIN_I200 i ';
      wSQL = wSQL||                         'WHERE i.BDORDEMI200 = (SELECT FIRST 1 x.BDORDEMI200 ';
      wSQL = wSQL||                                                'FROM VEF_EMP_TMOVFIN_I200 x ';
      wSQL = wSQL||                                                'WHERE x.BDCODEMP = i.BDCODEMP ';
      wSQL = wSQL||                                                  'AND x.BDCHAVE = i.BDCHAVE ';
      wSQL = wSQL||                                                  'AND x.BDCODPLAPADRAO IS NOT NULL ';
      wSQL = wSQL||                                                  'AND x.BDCODTPLA IS NOT NULL) ) i200 on (i200.BDCODEMP = i100.BDCODEMP and i200.BDCHAVE = i100.BDCHAVE) ';
      wSQL = wSQL||       'WHERE i100.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND i100.BDREFERENCIA = '||:prREFERENCIA||' ';

      wSQL = wSQL||     ') aux ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
      wSQL = wSQL||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
      wSQL = wSQL||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';

      EXECUTE STATEMENT ( wSQL );

    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M400_M800PAR */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA) ';
          wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
          wSQL = wSQL||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
          wSQL = wSQL||       'aux.BDCODCSTPIS, aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
          wSQL = wSQL||       'aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
          wSQL = wSQL||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA ';
          wSQL = wSQL||'FROM (';
                              /* Sa?das - Produtos */
          wSQL = wSQL||       'SELECT sai.BDCODEMP, COALESCE(emp.BDCODMATRIZ, sai.BDCODEMP) as BDCODMATRIZ, sai.BDREFLAN, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 2 AS BDCODTP, ';
          wSQL = wSQL||              '(CAST(ROUND((';-- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                           '(IIF(qtdepro.BDQTDEPRO < 1, pgto.bdvalorpgtopar,'; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                                      '((COALESCE(pgto.bdvalorpgtopar,0)*((CAST( COALESCE(movpro.BDVLRITEM,0) AS NUMERIC(15,6))/itens.BDVLRCONTAB)))) ))+';
          wSQL = wSQL||                           '(IIF(qtdepro.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETINSS,0) ),+';
          wSQL = wSQL||                                                     '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) )))';
          wSQL = wSQL||                           ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM,';
          wSQL = wSQL||              'movpro.BDCODNATREC, movpro.BDCODCTA, movpro.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'movpro.BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'movpro.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'movpro.BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') SAI ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = sai.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x ON (sai.BDCODEMP = x.BDCODEMP AND sai.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (sai.BDCODEMP = par.BDCODEMP AND sai.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (sai.BDCODEMP = itens.BDCODEMP AND sai.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, Count(*) AS BDQTDEPRO FROM VEF_EMP_TMOVPROSAI p group by p.BDCODEMP, p.BDCHAVE, p.BDORDEM) qtdepro ON ';
          wSQL = wSQL||                                                    '(qtdepro.BDCODEMP = itens.BDCODEMP AND qtdepro.BDCHAVE = itens.BDCHAVE AND qtdepro.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODNATREC, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||                    'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS, p.BDCODPLAPADRAO, p.BDCODTPLA ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVPROSAI p) movpro ON (itens.BDCODEMP = movpro.BDCODEMP AND itens.BDCHAVE = movpro.BDCHAVE AND itens.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = movpro.BDCODCSTPIS) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = movpro.BDCODCSTCOF) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = COALESCE(movpro.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) and ccl.BDCODTPLA = COALESCE(movpro.BDCODTPLA, lan.BDCREDITO)) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = COALESCE(movpro.BDCODPLAPADRAO, lanrat.BDCODPLAPADRAO) and cclrat.BDCODTPLA = COALESCE(movpro.BDCODTPLA, lanrat.BDCREDITO)) ';
          wSQL = wSQL||       'WHERE ((movpro.BDCODCSTPIS is not null) OR (movpro.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wSQL = wSQL||         'AND ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (movpro.BDALIQPIS = 0)) OR ';
          wSQL = wSQL||              '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (movpro.BDALIQCOFINS = 0))) ';

          wSQL = wSQL||       'UNION ALL ';
                              /* Sa?das - Transporte (D100) */
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, d100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'd100.BDCODNATREC, d100.BDCODCTA, d100.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'd100.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(cast((COALESCE(d100.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'd100.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'd100.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x ON (x.BDCODEMP = mov.BDCODEMP AND x.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TD100SAI d100 ON (mov.BDCODEMP = d100.BDCODEMP AND mov.BDCHAVE = d100.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((d100.BDCODCSTPIS is not null) OR (d100.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, d500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'd500.BDCODNATREC,d500.BDCODCTA,d500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'd500.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'd500.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'd500.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS numeric(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5))';
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TD500SAI x ';
          wSQL = wSQL||             'WHERE not exists(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||             ') d500 ON (mov.BDCODEMP = d500.BDCODEMP AND mov.BDCHAVE = d500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((d500.BDCODCSTPIS is not null) OR (d500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, c500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'c500.BDCODNATREC, NULL AS BDCODCTA, c500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(c500.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'c500.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(c500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'c500.BDCODCSTCOF,';
          wSQL = wSQL||              'CAST((COALESCE(c500.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8)) AS BDBCCOFINS,';
          wSQL = wSQL||              'c500.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              'CAST((COALESCE(c500.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8)) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TC500SAI x ';
          wSQL = wSQL||             'WHERE not exists(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||             ') c500 ON (mov.BDCODEMP = C500.BDCODEMP AND mov.BDCHAVE = C500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((C500.BDCODCSTPIS is not null) OR (C500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, f500.BDCHAVE, f500.BDORDEM, f500.BDORDEMF500 AS BDORDEMPRO, 13 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'f500.BDCODNATREC, NULL AS BDCODCTA, f500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDBASEPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'f500.BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'f500.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDBASECOF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'f500.BDALIQCOF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDVLRCOF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||              ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT X.* FROM VEF_EMP_TF500SAI X ';
          wSQL = wSQL||             'WHERE not exists(SELECT Y.BDCODEMP, Y.BDCHAVE FROM VEF_EMP_TMOVPROSAI Y WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCHAVE = Y.BDCHAVE) ';
          wSQL = wSQL||             ') F500 ON (mov.BDCODEMP = F500.BDCODEMP AND mov.BDCHAVE = F500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((F500.BDCODCSTPIS is not null) OR (F500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'a170.BDCODNATREC, NULL AS BDCODCTA, a170.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'a170.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP, aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSERPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSERITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TA170 a170 ON (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND itens.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit ON (mov.BDCODSITNF = sit.BDCODSITNF) ';

          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESER, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSER GROUP BY BDCODEMP, BDCHAVESER, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESER = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSER GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';

          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.bdvalorpgtopar +(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'mov.BDCODNATREC, NULL AS BDCODCTA, mov.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'mov.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'ccl.BDCODPLAPADRAO, COALESCE(mov.bdCODTPLA, ccl.bdCODTPLA) as bdCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT dem.BDCODEMP, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.bdCODTPLA, ';
          wSQL = wSQL||                    'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||                    'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||             'WHERE dem.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = dem.BDCODEMP AND e.BDREFEMP <= dem.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVF100PAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT tol.bdCODEMP, tol.bdCHAVEDEMDOC, lan.bdCODPLAPADRAO, MIN(lan.bdDATA) AS bdDATA, MIN(lan.bdREFERENCIA) AS bdREFERENCIA, MIN(lan.bdCREDITO) AS bdCREDITO, MIN(lan.bdDEBITO) AS bdDEBITO ';
          wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVDEMAISDOC tol ';
          wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = tol.bdCODEMP AND lan.bdCHAVE = tol.bdCHAVE) ';
          wSQL = wSQL||                        'GROUP BY bdCODEMP, bdCHAVEDEMDOC, bdCODPLAPADRAO) lan ON (lan.bdCODEMP = mov.bdCODEMP AND lan.bdCHAVEDEMDOC = mov.bdCHAVE) ';

          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((mov.BDCODCSTPIS is not null) OR (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

         wSQL = wSQL||     ') aux ';
         wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
         wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
         wSQL = wSQL||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
         wSQL = wSQL||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';
   
         EXECUTE STATEMENT ( wSQL );

        END

    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M500 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WMETODOAPRO INTEGER;
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,4);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configura??o da empresa na refer?ncia da apura??o...
  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDMETODOAPRO+1 -- M?todo de apropria??o
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 1
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 2
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMNTMI;

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 3
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMEXP;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      /* REGISTRO M500: CR?DITO DE COFINS RELATIVO AO PER?ODO */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM100_500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDIND_CRED_ORI, BDVL_BC, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CRED,';
      wSQL = wSQL||                                    'BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CRED_DIF, BDVL_CRED_DISP, BDIND_DESC_CRED, BDVL_CRED_DESC, BDSLD_CRED) ';
      wSQL = wSQL||'SELECT 29 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7) AS BDCHAVE,';
      wSQL = wSQL||       't436.BDCODCRE_4_3_6, 0 AS BDIND_CRED_ORI, SUM(COALESCE(tmp.BDBCCOFINS,0)) AS BDVL_BC, COALESCE(tmp.BDALIQCOFINS,0) AS BDALIQ,';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC, COALESCE(tmp.BDALIQCOFINS_QUANT,0) AS BDALIQ_QUANT,';
      wSQL = wSQL||       '(((SUM(COALESCE(tmp.BDBCCOFINS,0))*COALESCE(tmp.BDALIQCOFINS,1))/100)+(SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0))*COALESCE(tmp.BDALIQCOFINS_QUANT,1))) AS BDVL_CRED,';
      wSQL = wSQL||       '0 AS BDVL_AJUS_ACRES, 0 AS BDVL_AJUS_REDUC, 0 AS BDVL_CRED_DIF, 0 AS BDVL_CRED_DISP,';
      wSQL = wSQL||       'NULL AS BDIND_DESC_CRED, 0 AS BDVL_CRED_DESC, 0 AS BDSLD_CRED ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED,';
      wSQL = wSQL||             'x.BDALIQCOFINS,';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT,';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT,';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                    -- Rateio
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||             'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED, ';
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||             'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
         wSQL = wSQL||          'x.BDCOD_CRED as BDCOD_CRED, ';
         wSQL = wSQL||          'x.BDBCCOFINS ';
        END
      wSQL = wSQL||             'AS BDBCCOFINS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTCOF and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';

      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCCOFINS > 0) OR (tmp.BDBCCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQCOFINS > 0) OR (tmp.BDALIQCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      --wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, t436.BDCODCRE_4_3_6, tmp.BDALIQCOFINS, tmp.BDALIQCOFINS_QUANT; ';
 
      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M505: DETALHAMENTO DA BASE DE CALCULO DO CR?DITO APURADO NO PER?ODO ? COFINS */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM105_M505 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCSTPIS, BDCODCSTCOF, BDCODNATBC, BDCODCRE_4_3_6,';
      wSQL = wSQL||                                     'BDVL_BC_TOT, BDVL_BC_CUM, BDVL_BC_NC, BDVL_BC, BDQUANT_BC_TOT, BDQUANT_BC, BDDESC_CRED, BDALIQ) ';
      wSQL = wSQL||'SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 29 AS BDCODQUADRO, tmp.BDREFERENCIA, ';
      wSQL = wSQL||       '(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQCOFINS) OR (x.BDALIQ_QUANT = tmp.BDALIQCOFINS_QUANT))) AS BDCHAVE, ';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDORDEM)+1,1)';
      wSQL = wSQL||        'FROM VEF_EMP_TBLOCOM105_M505 x ';
      wSQL = wSQL||        'WHERE x.BDCODPERIODO = 7 ';
      wSQL = wSQL||          'AND x.BDCODEMP = tmp.BDCODEMP ';
      wSQL = wSQL||          'AND x.BDCODMATRIZ = tmp.BDCODMATRIZ ';
      wSQL = wSQL||          'AND x.BDCODQUADRO = 29 ';
      wSQL = wSQL||          'AND x.BDREFERENCIA = tmp.BDREFERENCIA ';
      wSQL = wSQL||          'AND x.BDCHAVE = (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQCOFINS) OR (x.BDALIQ_QUANT = tmp.BDALIQCOFINS_QUANT)))) AS BDORDEM, ';
      wSQL = wSQL||       'tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED AS BDCODNATBC, t436.BDCODCRE_4_3_6, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINSTOTAL,0)) AS BDVL_BC_TOT, 0 AS BDVL_BC_CUM, /*(Campo 04 ? Campo 05)*/SUM(COALESCE(tmp.BDBCCOFINSTOTAL,0)-0) AS BDVL_BC_NC, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINS,0)) AS BDVL_BC, SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC_TOT, SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC, NULL AS BDDESC_CRED, COALESCE(tmp.BDALIQCOFINS,tmp.BDALIQCOFINS_QUANT) AS BDALIQ ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT, ';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED, ';
      wSQL = wSQL||             'x.BDALIQCOFINS, x.BDBCCOFINS as BDBCCOFINSTOTAL, ';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT, ';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT, ';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED, ';
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||             'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
         wSQL = wSQL||          'x.BDCOD_CRED as BDCOD_CRED, ';
         wSQL = wSQL||          'x.BDBCCOFINS ';
        END
      wSQL = wSQL||             'AS BDBCCOFINS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTCOF and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';

      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCCOFINS > 0) OR (tmp.BDBCCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQCOFINS > 0) OR (tmp.BDALIQCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '('; -- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED, t436.BDCODCRE_4_3_6, tmp.BDALIQCOFINS, tmp.BDALIQCOFINS_QUANT; ';
 
      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M510: AJUSTES DO CR?DITO DE COFINS APURADO */
      INSERT INTO VEF_EMP_TBLOCOM110_M510 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, BDDESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) as BDCODMATRIZ,  29 as BDCODQUADRO, m.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = m.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) AND x.BDCODQUADRO = 29 AND x.BDREFERENCIA = m.BDREFERENCIA AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6 AND ((x.BDALIQ = m.BDALIQCOFINS) OR (x.BDALIQ_QUANT = m.BDALIQCOFINS))) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM+1),1)
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 29
                AND x.BDCODEMP = m.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                AND x.BDREFERENCIA = m.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM100_500 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDCODEMP = m.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                                   AND x.BDREFERENCIA = m.BDREFERENCIA
                                   AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                                   AND ((x.BDALIQ = m.BDALIQCOFINS) OR (x.BDALIQ_QUANT = m.BDALIQCOFINS))) ) as BDORDEM,
             m.BDCODAJUEFDC, m.BDTIPOAJUSTE as BDIND_AJ, SUM(m.BDVLRAJUCOFINS) as BDVL_AJ, m.BDNUMERODOC as BDNUM_DOC, m.BDDESCRICAO as BDDESCR_AJ, m.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TCREDAJU_M110_M510 m
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m.BDCODEMP)
      WHERE m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM100_500 m100
                    WHERE m100.BDCODPERIODO = 7
                      AND m100.BDCODQUADRO = 29
                      AND m100.BDCODEMP = m.BDCODEMP
                      AND m100.BDREFERENCIA = m.BDREFERENCIA
                      AND m100.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND ((m100.BDALIQ = m.BDALIQCOFINS) OR (m100.BDALIQ_QUANT = m.BDALIQCOFINS)) ))
      GROUP BY m.BDCODEMP, emp.BDCODMATRIZ, m.BDREFERENCIA, m.BDCODAJUEFDC, m.BDTIPOAJUSTE, m.BDNUMERODOC, m.BDDESCRICAO, m.BDDATAREF, m.BDCODCRE_4_3_6, m.BDALIQCOFINS;
 
      /* REGISTRO 515: DETALHAMENTO DOS AJUSTES DO CR?DITO DE COFINS APURADO */
      INSERT INTO VEF_EMP_TBLOCOM115_M515 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM15, BDCODCSTCOF, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m515.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP) as BDCODMATRIZ, 29 as BDCODQUADRO, m510.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDCODQUADRO = 29
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDNUM_DOC = m510.BDNUMERODOC
                AND x.BDDESCR_AJ = m510.BDDESCRICAO
                AND x.BDDT_REF = m510.BDDATAREF ) as BDCHAVE,
             (SELECT x.BDORDEM
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDCODQUADRO = 29
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDNUM_DOC = m510.BDNUMERODOC
                AND x.BDDESCR_AJ = m510.BDDESCRICAO
                AND x.BDDT_REF = m510.BDDATAREF ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM15+1),1)
              FROM VEF_EMP_TBLOCOM115_M515 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 29
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF )
                AND x.BDORDEM = (SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF ) ) as BDORDEM15,
             m515.BDCODCSTCOF, m515.BDCODCSTPIS, m515.BDCODPLAPADRAO, m515.BDCODTPLA, SUM(m510.BDVLRAJUCOFINS) as BDDET_VALOR_AJ, SUM(m515.BDBCCOFINS) as BDDET_BC_CRED,
             m515.BDALIQCOFINS as BDDET_ALIQ, m515.BDDATAOPECOFINS as BDDT_OPER_AJ, m515.BDDESCRICAOAJU as BDDESC_AJ, m515.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TCREDAJU_M110_M510 m510
      JOIN VEF_EMP_TDETAJU_M115_M515 m515 on (m515.BDCODEMP = m510.BDCODEMP AND m515.BDCHAVE = m510.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m510.BDCODEMP)
      WHERE m515.BDCODEMP IS NOT NULL
        AND m515.BDBCCOFINS > 0
        AND m510.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m510.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF ))
      GROUP BY m515.BDCODEMP, emp.BDCODMATRIZ, m510.BDREFERENCIA, m510.BDCODCRE_4_3_6,  m515.BDCODCSTCOF, m515.BDCODCSTPIS, m515.BDCODPLAPADRAO, m515.BDCODTPLA,
               m515.BDALIQCOFINS, m515.BDDATAOPECOFINS, m515.BDDESCRICAOAJU, m515.BDINFCOMP, m510.BDNUMERODOC, m510.BDDESCRICAO, m510.BDDATAREF;
 
    END

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_M600 */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M600(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WVLRAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRUP NUMERIC(15,2);
DECLARE VARIABLE WVLRUPAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRSLD NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT_ORIGINAL NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT_TOTAL NUMERIC(15,2);
DECLARE VARIABLE WINTAUX INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WPER_APU_CRED INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCRE_4_3_6 INTEGER;
DECLARE VARIABLE WIND_CRED_ORI INTEGER;
DECLARE VARIABLE WCOD_NAT_REC INTEGER;
DECLARE VARIABLE WCHAVEAUX INTEGER;
DECLARE VARIABLE WORDENACAO INTEGER;
DECLARE VARIABLE WIND_DESC_CRED INTEGER;
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCREDITOSPERANT, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCREDITOSPERANT, :wRETPISCOFPERANT;

  /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  /* 1 - Exclusivamente no regime n?o-cumulativo */
  IF (wINCTRIB IN (1,3)) THEN
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M610, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      wVLRTOTCONT = 0;
      SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR
      FROM VEF_EMP_TBLOCOM210_M610 m
      LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL)
      WHERE (t435.BDCODCSOCIALEXP IN (01,02,03,04,32,71))
        AND (m.BDCODQUADRO = 37) -- M610 - Detalhamento da contribui??o para o Cofins
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRTOTCONT;

      wVLRTOTCONT_ORIGINAL = wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 2, COALESCE(:wVLRTOTCONT,0));

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100)
         Caso esteja configurado para usar saldo do per?odo anterior, deve descontar ele primeiro, antes do cr?dito do per?odo atual... */
      wVLRCREDPERANT = 0;
      wVLRCREDPERANT_TOTAL = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 53) -- 1500 - Controle de cr?ditos fiscais Cofins
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL = wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
              END
          END
        END

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      SELECT COUNT(m.BDCHAVE) as BDQTD
      FROM VEF_EMP_TBLOCOM100_500 m
      WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO wQTD;

      IF ((wQTD = 0) OR (wVLRTOTCONT = 0) OR (wVLRTOTCONT IS NULL)) THEN -- Caso n?o tenha dados no M100/M500 ou o valor do cr?dito seja zerado...
        BEGIN
          UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                               VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, 0)
                                             MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
            UPDATE VEF_EMP_TBLOCOM100_500 m
            SET m.BDIND_DESC_CRED = 1,
                m.BDVL_CRED_DESC  = 0,
                m.BDSLD_CRED      = m.BDVL_CRED_DISP
            WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA;
 
            /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
            SELECT COUNT(*)
            FROM VEF_EMP_TBLOCOM1100_1500 m
            WHERE m.BDCODPERIODO = 7
              AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA
              AND m.BDPER_APU_CRED = :prREFERENCIA
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDORIG_CRED = :wIND_CRED_ORI
            INTO :wQTD;
  
            IF (:wQTD > 0) THEN
              BEGIN
                /* Caso tenha registros atualiza */
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                    m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                    m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
      ELSE
        BEGIN
                /* Caso n?o tenha lan?amento de saldos insere */
                INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                              VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                      (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA),
                                                      7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
              END
          END
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            IF (:wVLRTOTCONT > 0) THEN
              BEGIN
                /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
                IF (:wVLR < :wVLRTOTCONT) THEN
                  BEGIN
                    wVLRSLD        = 0;
                    wVLRTOTCONT    = wVLRTOTCONT - wVLR;
                    wIND_DESC_CRED = 0; -- 0 ? Utiliza??o do valor total para desconto da contribui??o apurada no per?odo, no Registro M200;
                  END
                ELSE
                  BEGIN
                    /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                    wVLRSLD        = :wVLR - :wVLRTOTCONT;
                    wVLR           = :wVLR - :wVLRSLD;
                    wVLRTOTCONT    = 0;
                    wIND_DESC_CRED = 1; -- 1 ? Utiliza??o de valor parcial para desconto da contribui??o apurada no per?odo, no Registro M200.
                  END
    
                -- Atualiza os cr?ditos descontados do M500...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = :wIND_DESC_CRED,
                    m.BDVL_CRED_DESC  = :wVLR,
                    m.BDSLD_CRED      = :wVLRSLD
                WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDCHAVE = :wCHAVE
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI;

                IF (wVLRSLD > 0) THEN
                  BEGIN
                /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                SELECT COUNT(*)
                FROM VEF_EMP_TBLOCOM1100_1500 m
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI
                INTO :wQTD;
      
                IF (:wQTD > 0) THEN
                  BEGIN
                    /* Caso tenha registros atualiza */
                    UPDATE VEF_EMP_TBLOCOM1100_1500 m
                    SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI;
                  END
                ELSE
                  BEGIN
                    /* Caso n?o tenha lan?amento de saldos insere */
                    INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                  VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                              (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                              7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', (:wVLR + :wVLRSLD) /*:wVLR*/, :wVLR/*0*/, :wVLRSLD/*:wVLR*/);
                  END
              END

                wVLRAUX = 0;
                SELECT COALESCE(BDVALOR, 0)
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
                  AND BDREFERENCIA = :prREFERENCIA
                  AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
                  AND BDNUMCAMPO   = 3
                INTO wVLRAUX;
         
                IF (wVLRAUX IS NULL) THEN
                  wVLRAUX = 0;
         
                UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, COALESCE(:wVLR+:wVLRAUX,0))
                                                   MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

                  END
                ELSE
                  BEGIN
                -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = 1,
                    m.BDVL_CRED_DESC  = 0,
                    m.BDSLD_CRED      = m.BDVL_CRED_DISP
                WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDCHAVE = :wCHAVE;
          
                    /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                    SELECT COUNT(*)
                    FROM VEF_EMP_TBLOCOM1100_1500 m
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI
                    INTO :wQTD;
          
                    IF (:wQTD > 0) THEN
                      BEGIN
                        /* Caso tenha registros atualiza */
                        UPDATE VEF_EMP_TBLOCOM1100_1500 m
                        SET m.BDVL_CRED_APU = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                        WHERE m.BDCODPERIODO = 7
                          AND m.BDCODQUADRO = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                          AND m.BDCODEMP = :wCODEMP
                          AND m.BDCODMATRIZ = :wCODMATRIZ
                          AND m.BDREFERENCIA = :prREFERENCIA
                          AND m.BDPER_APU_CRED = :prREFERENCIA
                          AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                          AND m.BDORIG_CRED = :wIND_CRED_ORI;
                      END
                    ELSE
                      BEGIN
                        /* Caso n?o tenha lan?amento de saldos insere */
                        INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                      VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                          (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                          7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
                      END
                          END
                          END
                      END

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      wVLR = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          wVLR = wVLRCREDPERANT_TOTAL;
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 53) -- 1500 - Controle de cr?ditos fiscais Cofins
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL =  wVLRCREDPERANT_TOTAL + wVLR;
    
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
          END

          wVLR = wVLRCREDPERANT_TOTAL;
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 4, COALESCE(:wVLR,0));

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (2))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (3,4))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 5, COALESCE(:wVLR,0));

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1700. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
              AND BDNUMCAMPO   = 6
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRCOFINS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 1 -- 0 - Dedu??o de Natureza N?o Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 7, COALESCE(:wVLR,0));

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR) as BDVALOR, SUM(aux.BDVLRSUB) as BDVALORSUB
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (5))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (6,7))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR, wVLRAUX;

      IF ((wVLR - wVLRAUX) >= 0) THEN -- Se tiver valor de contribbui??o, calcula os campos a somar e subtrair...
        wVLR = (wVLR - wVLRAUX);
      ELSE
      /* Se o valor do campo 5(Valor Total da Contribui??o) menos o valor do campo 6(Valor Retido na Fonte) for menor que zero, ent?o este valor deve ser levado como saldo no registro 1300. */
      IF ((wVLR - wVLRAUX) < 0) THEN -- Se n?o tiver valor de contribbui??o, leva zerado...
        BEGIN
          /* Atualiza o valor do campo 6, Valor Retido na Fonte, s? pode usar aquilo que abater e n?o o total... */
          UPDATE VEF_EMP_TBLOCOMGERREG
          SET BDVALOR = :wVLR
          WHERE BDCODMATRIZ  = :prCODEMP
            AND BDREFERENCIA = :prREFERENCIA
            AND BDCODQUADRO  = 33
            AND BDNUMCAMPO   = 6;

          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, COALESCE(m.BDVL_RET_APU, 0)
              FROM VEF_EMP_TBLOCOM1300_1700 m
              WHERE (m.BDCODQUADRO = 50) -- 1700 - Ficha de reten??o do Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUP
          DO
            BEGIN
              IF (wVLR > 0) THEN
                BEGIN
                  /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                  IF (:wVLRUP < :wVLR) THEN
                    BEGIN
                      wVLRUPAUX = :wVLRUP;
                      wVLRSLD   = 0;
                      wVLR      = :wVLR-:wVLRUP; /* Cr?dito j? descontado vai ser abatido... */
                    END
                  ELSE
                    BEGIN
                      wVLRUPAUX = :wVLR;
                      wVLRSLD   = :wVLRUP - :wVLR;
                    END
    
                  UPDATE OR INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDVL_RET_DED, BDSLD_RET)
                                                          VALUES (:wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUPAUX  , :wVLRSLD)
                                                        MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE);
                END
            END

          wVLR = 0; -- Se n?o tiver valor de contribbui??o, leva zerado...
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 8, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 2, 0);

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, 0);

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 4, 0);

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 5, 0);

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, 0);

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 7, 0);

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 8, 0);
    END

  /* 2 - Exclusivamente no regime cumulativo */
  IF (wINCTRIB IN (2,3)) THEN
    BEGIN
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      wVLRTOTCONT = 0;
      wSQL =        'SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM210_M610 m ';
      wSQL = wSQL|| 'LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL) ';
      IF (wINCTRIB IN (3)) THEN -- Quando ? regime n?o-cumulativo e cumulativo, j? considerou algumas contribui??es no campo 2...
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,51,52,53,54,72)) ';
      ELSE
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,32,51,52,53,54,72)) ';
      wSQL = wSQL|| '  AND (m.BDCODQUADRO = 37) '; -- M610 - Detalhamento da contribui??o para o Cofins
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 9, COALESCE(:wVLRTOTCONT,0));

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1700. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
                  AND BDNUMCAMPO   = 10
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                         VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRCOFINS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 2 -- 1 - Dedu??o de Natureza Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 11, COALESCE(:wVLR,0));

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (9))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (10,11))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 12, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN -- Joga os valores zerados...
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 9, 0);

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, 0);

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 11, 0);

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 12, 0);
    END

  /* 3 - Regimes n?o-cumulativo e cumulativo */
  /* 13 - VL_TOT_CONT_REC - Valor Total da Contribui??o a Recolher/Pagar no Per?odo (08 + 12) */
  wVLR = 0;
  SELECT SUM(COALESCE(m.BDVALOR,0)) as BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG m
  WHERE (m.BDCODQUADRO = 33)
    AND (m.BDNUMCAMPO in (8,12))
    AND m.BDCODMATRIZ = :prCODEMP
    AND m.BDREFERENCIA = :prREFERENCIA
  INTO :wVLR;

  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 13, COALESCE(:wVLR,0));

END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_ONLINE */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
BEGIN
  -- Limpa a tabela de contabiliza??o do Bloco M
  DELETE FROM TMP_TCONF_CONTAS_ONLINE_TEMP WHERE bdCODMATRIZ = :prCODEMP AND bdREFERENCIA = :prREFERENCIA;

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Incid?ncia tribut?ria
  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  IF (:wINCTRIB IN (1,3)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo e 3 - Regimes n?o-cumulativo e cumulativo
    BEGIN
      -- Valida as contas da contabiliza??o da apura??o do Bloco M...
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDAONLINE (:prCODEMP, :prREFERENCIA);
    
      -- Verifica se possui alguma inconsist?ncia de contas online...
      SELECT FIRST 1 i.bdCODINC
      FROM VEF_INCON_BLOCOM i
      WHERE i.bdCODMATRIZ = :prCODEMP
        AND i.bdREFERENCIA = :prREFERENCIA
        -- "Outras Dedu??es" n?o ? um campo obrigat?rio
        AND i.bdCODINC IN (13,/*"Cr?dito" do PIS*/    14,/*"D?bito" do PIS*/    /*15,/*"Outras Dedu??es" do PIS*/    16,/*"Compensa??o" do PIS*/
                           17,/*"Cr?dito" do Cofins*/ 18,/*"D?bito" do Cofins*/ /*19,/*"Outras Dedu??es" do Cofins*/ 20,/*"Compensa??o" do Cofins*/
                           21/*Inconsist?ncias gen?rica da contabiliza??o detalhada*/)
      INTO :wCODINC;
    
      -- Deleta os registros da tabela da contabiliza??o, caso exista algum lan?amento
      DELETE FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
      WHERE t.bdCODMATRIZ = :prCODEMP
        AND t.bdREFERENCIA = :prREFERENCIA;

      IF (:wCODINC IS NULL) THEN
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO (:prCODEMP, :prREFERENCIA);
    END
 
END
^

/* Restore proc. body: SP_APURACAO_BLOCOM_ONLINE_CONSO */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCONTDETALHADA VARCHAR(5);
BEGIN
  /* PIS */
  /****************************************************************************/
  /********************************** Cr?ditos ********************************/
  -- "Cr?dito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS');
  -- "Cr?dito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 247);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED');
  /********************************** D?bitos *********************************/
  -- "D?bito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS');
  -- "D?bito Detalhado"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 248);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED');

          -- "Outras Dedu??es"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de PIS Outras Dedu??es - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, g.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 249)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
            AND g.bdNUMCAMPO  = 07 -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
            AND g.bdVALOR > 0;

          -- "Compensa??o"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de PIS Compensa??o - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, SUM(g.bdVALOR) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 250)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
    AND (
         (g.bdNUMCAMPO  = 03) OR -- VL_TOT_CRED_DESC - Valor do Cr?dito Descontado
                 (g.bdNUMCAMPO  = 04) OR -- VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior
                 (g.bdNUMCAMPO  = 06) OR -- VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo
                 (g.bdNUMCAMPO  = 07)    -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
                 )
            AND g.bdVALOR > 0
  GROUP BY g.bdCODMATRIZ, g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdORDENACAO;
  /****************************************************************************/

  /****************************************************************************/
  /********************************** Cr?ditos ********************************/
          /* Cofins */
  -- "Cr?dito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins');
  -- "Cr?dito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 251);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED');
  /********************************** D?bitos *********************************/
  -- "D?bito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins');
  -- "D?bito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 252);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED');

          -- "Outras Dedu??es"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de Cofins Outras Dedu??es - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, g.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 253)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 33 -- M600 - Consolida??o da contribui??o para o Cofins
            AND g.bdNUMCAMPO  = 07 -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
            AND g.bdVALOR > 0;

          -- "Compensa??o"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de Cofins Compensa??o - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, SUM(g.bdVALOR) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 254)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 33 -- M600 - Consolida??o da contribui??o para o Cofins
    AND (
         (g.bdNUMCAMPO  = 03) OR -- VL_TOT_CRED_DESC - Valor do Cr?dito Descontado
                 (g.bdNUMCAMPO  = 04) OR -- VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior
                 (g.bdNUMCAMPO  = 06) OR -- VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo
                 (g.bdNUMCAMPO  = 07)   -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
                 )
            AND g.bdVALOR > 0
  GROUP BY g.bdCODMATRIZ, g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdORDENACAO;
  /****************************************************************************/
END
^

/* Restore proc. body: SP_APURADOS_VALREF */
ALTER PROCEDURE SP_APURADOS_VALREF(PRCODEMP VARCHAR(6000),
PRCOLABORADOR VARCHAR(6000),
PRCOMPETENCIA INTEGER,
PRNRVIAS INTEGER)
 RETURNS(BDNRVIA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCONVREF INTEGER,
BDCOMPETENCIA INTEGER,
BDQUANTIDADE INTEGER,
BDTPAPURACAO INTEGER,
BDDTINICIAL DATE,
BDDTFINAL DATE,
BDDESCCONVREF VARCHAR(50),
BDNOMCOL DM_BDNOMCOL,
BDNOMCOLUPPER DM_BDNOMCOL,
BDRGCOL VARCHAR(20),
BDCPFCOL VARCHAR(14),
BDVALUNI NUMERIC(18,6),
BDVALCUSTOEMP NUMERIC(18,6),
BDVALDESCONTO NUMERIC(18,6),
BDQTDCONVENIOREF INTEGER)
 AS
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WVIA INTEGER;
DECLARE VARIABLE WBDCODEMP INTEGER;
DECLARE VARIABLE WBDCODCOL INTEGER;
DECLARE VARIABLE WFECHAVTEMP INTEGER;
DECLARE VARIABLE WBDCODCONVREF INTEGER;
DECLARE VARIABLE WBDCOMPETENCIA INTEGER;
DECLARE VARIABLE WBDQUANTIDADE INTEGER;
DECLARE VARIABLE WBDTAPURACAO INTEGER;
DECLARE VARIABLE WBDDTINICIAL DATE;
DECLARE VARIABLE WBDDTFINAL DATE;
DECLARE VARIABLE WBDDESCCONVREF VARCHAR(50);
DECLARE VARIABLE WBDNOMCOL DM_BDNOMCOL;
DECLARE VARIABLE WBDNOMCOLUPPER DM_BDNOMCOL;
DECLARE VARIABLE WBDRGCOL VARCHAR(20);
DECLARE VARIABLE WBDCPFCOL VARCHAR(30);
DECLARE VARIABLE WBDVALUNI NUMERIC(18,6);
DECLARE VARIABLE WBDVALCUSTOEMP NUMERIC(18,6);
DECLARE VARIABLE WBDVALDESCONTO NUMERIC(18,6);
DECLARE VARIABLE WBDQTDCONVENIOREF INTEGER;
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLDATA VARCHAR(10000);
DECLARE VARIABLE WSQLCUSTOEMP VARCHAR(20000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WBDDATAADMCOL DATE;
DECLARE VARIABLE WBDDATARESCISAO DATE;
BEGIN
  WBDQTDCONVENIOREF = 0;
  WVIA = 1;

  WSQL = 'select ValeRef.*, cast (null as Date) BDDTINICIAL, cast(null as Date) BDDTFINAL, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, DOCREF.BDRGCOL, ColCon.BDCPFCOL, '||
        'Conv.BDVALUNI BDVALUNI, 0 BDVALCUSTOEMP, 0 BDVALDESCONTO, COLCON.BDDATAADMCOL, Resc.BDDATARESCISAO, Conv.BDDESC BDDESCCONVREF '||
        'from VRHF_EMP_TAPVALREF ValeRef '||
        'left outer join VRH_EMP_TCOLCON ColCon on (ColCon.BDCODEMP = ValeRef.BDCODEMP and ColCon.BDCODCOL = ValeRef.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = VALEREF.BDCODEMP and COLCAD.BDCODCOL = VALEREF.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = VALEREF.BDCODEMP and DOCREF.BDCODCOL = VALEREF.BDCODCOL) '||
        'left outer join VRH_EMP_TCOLCON_DOC ColConDoc on (ColConDoc.BDCODEMP = ValeRef.BDCODEMP and ColConDoc.BDCODCOL = ValeRef.BDCODCOL) '||
        'left outer join VW_VRHF_BASE_TCONVREFEICAO_REF Conv on (Conv.BDCODCONVREF = ValeRef.BDCODCONVREF)  '||
        'left outer join VW_RESCISAO Resc on (Resc.BDCODEMP = ValeRef.BDCODEMP and Resc.BDCODCOL = ValeRef.BDCODCOL) ';

  WWHERE = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     BEGIN
      WWHERE = ' where '||PRCODEMP||' ';

      IF (PRCOLABORADOR IS NOT NULL AND PRCOLABORADOR <> '') THEN
         WWHERE = WWHERE||' and '||PRCOLABORADOR||' ';
     END

   IF (PRCOMPETENCIA IS NOT NULL AND PRCOMPETENCIA <> 0) THEN
      BEGIN
        IF (WWHERE = '') THEN
           WWHERE = WWHERE||' where ValeRef.BDCOMPETENCIA = '||PRCOMPETENCIA;
        ELSE
           WWHERE = WWHERE||' and ValeRef.BDCOMPETENCIA = '||PRCOMPETENCIA;
      END

   WSQL = WSQL||WWHERE||' order by ValeRef.BDCODEMP, ValeRef.BDCODCOL, ValeRef.BDCODCONVREF, ValeRef.BDCOMPETENCIA';

   FOR EXECUTE STATEMENT WSQL INTO
     WBDCODEMP,
     WBDCODCOL,
     WBDCODCONVREF,
     WBDCOMPETENCIA,
     WBDQUANTIDADE,
     WBDTAPURACAO,
     WBDDTINICIAL,
     WBDDTFINAL,
     WBDNOMCOL,
     WBDNOMCOLUPPER,
     WBDRGCOL,
     WBDCPFCOL,
     WBDVALUNI,
     WBDVALCUSTOEMP,
     WBDVALDESCONTO,
     WBDDATAADMCOL,
     WBDDATARESCISAO,
     WBDDESCCONVREF
   DO
   BEGIN
     WVIA = 1;
     WHILE (WVIA <= PRNRVIAS) DO
       BEGIN
         BDNRVIA = WVIA;
         BDCODEMP = WBDCODEMP;
         BDCODCOL = WBDCODCOL;
         BDCODCONVREF = WBDCODCONVREF;
         BDCOMPETENCIA = WBDCOMPETENCIA;
         BDQUANTIDADE = WBDQUANTIDADE;
         BDTPAPURACAO = WBDTAPURACAO;

         --Sol. 19620 - Bruno L. R. - 28/07/2017
         EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRCOMPETENCIA);

         WSQLDATA = 'select BDFECHAVTEMP from VW_VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP;
         EXECUTE STATEMENT WSQLDATA INTO WFECHAVTEMP;

         IF (((WFECHAVTEMP > 28) AND (WFECHAVTEMP <> 30)) AND ((WFECHAVTEMP IS NOT NULL) AND (WFECHAVTEMP > 0))) THEN
            BEGIN
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
            END
         ELSE
         IF (WFECHAVTEMP = 30) THEN
            BEGIN
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||', '||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4)||')' INTO WDIA;
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WDIA|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
            END
         ELSE
         IF ((WFECHAVTEMP IS NULL) OR (WFECHAVTEMP = 0)) THEN
            BEGIN
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTFINAL = NULL;
            END
         ELSE
            BEGIN
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTINICIAL = DATEADD(DAY, -30, WBDDTFINAL);
            END
         --Sol. 19620 - Bruno L. R. - 28/07/2017

    
         IF (WBDDTINICIAL < WBDDATAADMCOL) THEN
            BEGIN
              WBDDTINICIAL = WBDDATAADMCOL;
            END
    
         IF (((SUBSTRING(WBDDATARESCISAO FROM 1 FOR 4) || SUBSTRING(WBDDATARESCISAO FROM 6 FOR 2)) = BDCOMPETENCIA) AND (WBDDTFINAL > WBDDATARESCISAO)) THEN
            BEGIN
              WBDDTFINAL = WBDDATARESCISAO;
            END
    
         BDDTINICIAL = WBDDTINICIAL;
         BDDTFINAL = WBDDTFINAL;


         WSQLCUSTOEMP = 'select distinct (ValRef.BDQUANTIDADE * Conv.BDVALUNI) from VRHF_EMP_TAPVALREF ValRef '||
            'left outer join VW_VRHF_BASE_TCONVREFEICAO_REF Conv on (Conv.BDCODCONVREF = ValRef.BDCODCONVREF) '||
            'left outer join VWRH_UNION_FN_FT_MES Val on (Val.BDREFFN = ValRef.BDCOMPETENCIA and Val.BDCODEMP = ValRef.BDCODEMP and Val.BDCODCOL = ValRef.BDCODCOL) '||
            'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = Val.BDCODVER) '||
         'where ValRef.BDCODEMP='||BDCODEMP||' and ValRef.BDCODCOL='||BDCODCOL||' and ValRef.BDCOMPETENCIA='||PRCOMPETENCIA;

         EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP;


         BDNOMCOL = WBDNOMCOL;
         BDNOMCOLUPPER = WBDNOMCOLUPPER;
         BDRGCOL = WBDRGCOL;
         BDCPFCOL = WBDCPFCOL;
         BDVALUNI = WBDVALUNI;
         BDVALCUSTOEMP = WBDVALCUSTOEMP;
         BDVALDESCONTO = WBDVALDESCONTO;
         WBDQTDCONVENIOREF = WBDQTDCONVENIOREF + 1;
         BDQTDCONVENIOREF = WBDQTDCONVENIOREF;
         BDDESCCONVREF = WBDDESCCONVREF;
         WVIA = WVIA + 1;
         SUSPEND;
       END
     END
END
^

/* Restore proc. body: SP_APURADOS_VALTRANS */
ALTER PROCEDURE SP_APURADOS_VALTRANS(PRCODEMP VARCHAR(25000),
PRCOLABORADOR VARCHAR(32700),
PRCOMPETENCIA INTEGER,
PRNRVIAS INTEGER)
 RETURNS(BDNRVIA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODITI INTEGER,
BDCOMPETENCIA INTEGER,
BDQUANTIDADE INTEGER,
BDTPAPURACAO INTEGER,
BDDTINICIAL DATE,
BDDTFINAL DATE,
BDNOMCOL DM_BDNOMCOL,
BDNOMCOLUPPER DM_BDNOMCOL,
BDRGCOL VARCHAR(20),
BDCPFCOL VARCHAR(14),
BDDESCITI VARCHAR(40),
BDLINHAITI VARCHAR(20),
BDVALUNI NUMERIC(18,6),
BDVALCUSTOEMP NUMERIC(18,6),
BDVALDESCONTO NUMERIC(18,6),
BDQTDITINERARIOS INTEGER,
BDFECHAMENTOVT INTEGER,
BDFECHAMENTO INTEGER)
 AS
declare variable WVIA integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDCODITI integer;
declare variable WBDCOMPETENCIA integer;
declare variable WBDQUANTIDADE integer;
declare variable WBDTAPURACAO integer;
declare variable WBDDTINICIAL date;
declare variable WBDDTFINAL date;
declare variable WBDNOMCOL DM_BDNOMCOL;
declare variable WBDNOMCOLUPPER DM_BDNOMCOL;
declare variable WBDRGCOL varchar(20);
declare variable WBDCPFCOL varchar(30);
declare variable WBDDESCITI varchar(50);
declare variable WBDLINHAITI varchar(20);
declare variable WBDVALUNI numeric(18,6);
declare variable WBDVALCUSTOEMP numeric(18,6);
declare variable WBDVALDESCONTO numeric(18,6);
declare variable WBDQTDITINERARIOS integer;
declare variable WSQL varchar(30000);
declare variable WSQLDATA varchar(10000);
declare variable WWHERE varchar(10000);
declare variable WBDDATAADMCOL date;
declare variable WBDDATARESCISAO date;
declare variable WSQLCUSTOEMP varchar(2000);
declare variable WFECHAVTEMP integer;
declare variable WFECHAEMP integer;
declare variable WULTDIA integer;
BEGIN
  WBDQTDITINERARIOS = 0;
  WVIA = 1;

  WSQL = 'select ValeTrans.*, cast (null as Date) BDDTINICIAL, cast(null as Date) BDDTFINAL, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, DOCREF.BDRGCOL, ColCon.BDCPFCOL, Iti.BDDESCITI, '||
        'Iti.BDLINHAITI, Iti.BDVALITI BDVALUNI, 0 BDVALCUSTOEMP, 0 BDVALDESCONTO, ColCon.BDDATAADMCOL, Resc.BDDATARESCISAO '||
        'from VRHF_EMP_TAPVALTRANS ValeTrans '||
        'left outer join VRH_EMP_TCOLCON ColCon on (ColCon.BDCODEMP = ValeTrans.BDCODEMP and ColCon.BDCODCOL = ValeTrans.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = VALETRANS.BDCODEMP and COLCAD.BDCODCOL = VALETRANS.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = VALETRANS.BDCODEMP and DOCREF.BDCODCOL = VALETRANS.BDCODCOL) '||
        'left outer join VRH_EMP_TCOLCON_DOC ColConDoc on (ColConDoc.BDCODEMP = ValeTrans.BDCODEMP and ColConDoc.BDCODCOL = ValeTrans.BDCODCOL) '||
        'left outer join VW_VRHF_BASE_TITINERARIOS_REF Iti on (Iti.BDCODITI = ValeTrans.BDCODITI) '||
        'left outer join VW_RESCISAO Resc on (Resc.BDCODEMP = ValeTrans.BDCODEMP and Resc.BDCODCOL = ValeTrans.BDCODCOL) ';

  WWHERE = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     BEGIN
      WWHERE = ' where '||PRCODEMP||' ';

      IF (PRCOLABORADOR IS NOT NULL AND PRCOLABORADOR <> '') THEN
         WWHERE = WWHERE||' and '||PRCOLABORADOR||' ';
     END

   IF (PRCOMPETENCIA IS NOT NULL AND PRCOMPETENCIA <> 0) THEN
      BEGIN
        IF (WWHERE = '') THEN
           WWHERE = WWHERE||' where ValeTrans.BDCOMPETENCIA = '||PRCOMPETENCIA;
        ELSE
           WWHERE = WWHERE||' and ValeTrans.BDCOMPETENCIA = '||PRCOMPETENCIA;
      END

   WSQL = WSQL||WWHERE||' order by ValeTrans.BDCODEMP, ValeTrans.BDCODCOL, ValeTrans.BDCODITI, ValeTrans.BDCOMPETENCIA';

   EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(prcompetencia FROM 5 FOR 2)||', '||SUBSTRING(prcompetencia FROM 1 FOR 4)||')' INTO :wultdia;

   FOR EXECUTE STATEMENT WSQL INTO
     WBDCODEMP,
     WBDCODCOL,
     WBDCODITI,
     WBDCOMPETENCIA,
     WBDQUANTIDADE,
     WBDTAPURACAO,
     WBDDTINICIAL,
     WBDDTFINAL,
     WBDNOMCOL,
     WBDNOMCOLUPPER,
     WBDRGCOL,
     WBDCPFCOL,
     WBDDESCITI,
     WBDLINHAITI,
     WBDVALUNI,
     WBDVALCUSTOEMP,
     WBDVALDESCONTO,
     WBDDATAADMCOL,
     WBDDATARESCISAO
   DO
   BEGIN
     WVIA = 1;
     BDVALCUSTOEMP = 0;
     WHILE (WVIA <= PRNRVIAS) DO
       BEGIN
         BDNRVIA = WVIA;
         BDCODEMP = WBDCODEMP;
         BDCODCOL = WBDCODCOL;
         BDCODITI = WBDCODITI;
         BDCOMPETENCIA = WBDCOMPETENCIA;
         BDQUANTIDADE = WBDQUANTIDADE;
         BDTPAPURACAO = WBDTAPURACAO;

         --Sol. 19620 - Bruno L. R. - 28/07/2017
         EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRCOMPETENCIA);

         WSQLDATA = 'select BDFECHAVTEMP, BDFECHAMESEMP from VW_VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP;
         WFECHAVTEMP = null;
         EXECUTE STATEMENT WSQLDATA INTO :WFECHAVTEMP, :WFECHAEMP;
    
         BDFECHAMENTOVT = wfechavtemp;
         BDFECHAMENTO   = wfechaemp;

         if ((coalesce(wfechavtemp, 0) = 0) or (wfechavtemp > wultdia)) then
            begin
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);

              if (coalesce(wfechavtemp, 0) = 0) then
                 WBDDTFINAL = null;
              else
                 WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||wultdia|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
            end
         else
            begin
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTINICIAL = DATEADD(DAY, 1, DATEADD(MONTH, -1, WBDDTFINAL));
            end
         --Sol. 19620 - Bruno L. R. - 28/07/2017
    
         IF (WBDDTINICIAL < WBDDATAADMCOL) THEN
            BEGIN
              WBDDTINICIAL = WBDDATAADMCOL;
            END
    
         IF (((SUBSTRING(WBDDATARESCISAO FROM 1 FOR 4) || SUBSTRING(WBDDATARESCISAO FROM 6 FOR 2)) = BDCOMPETENCIA) AND (WBDDTFINAL > WBDDATARESCISAO)) THEN
            BEGIN
              WBDDTFINAL = WBDDATARESCISAO;
            END
    
         BDDTINICIAL = WBDDTINICIAL;
         BDDTFINAL = WBDDTFINAL;


         WSQLCUSTOEMP = 'select distinct (ValTrans.BDQUANTIDADE * Iti.BDVALITI) from VRHF_EMP_TAPVALTRANS ValTrans '||
            'left outer join VW_VRHF_BASE_TITINERARIOS_REF Iti on (Iti.BDCODITI = ValTrans.BDCODITI) '||
            'left outer join VWRH_UNION_FN_FT_MES Val on (Val.BDREFFN = ValTrans.BDCOMPETENCIA and Val.BDCODEMP = ValTrans.BDCODEMP and Val.BDCODCOL = ValTrans.BDCODCOL) '||
            'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = Val.BDCODVER) '||
         'where ValTrans.BDCODEMP='||BDCODEMP||' and ValTrans.BDCODCOL='||BDCODCOL||' and ValTrans.BDCOMPETENCIA='||PRCOMPETENCIA;

         FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALCUSTOEMP = BDVALCUSTOEMP + WBDVALCUSTOEMP;
           END

         BDNOMCOL = WBDNOMCOL;
         BDNOMCOLUPPER = WBDNOMCOLUPPER;
         BDRGCOL = WBDRGCOL;
         BDCPFCOL = WBDCPFCOL;
         BDDESCITI = WBDDESCITI;
         BDLINHAITI = WBDLINHAITI;
         BDVALUNI = WBDVALUNI;
         BDVALDESCONTO = WBDVALDESCONTO;
         WBDQTDITINERARIOS = WBDQTDITINERARIOS + 1;
         BDQTDITINERARIOS = WBDQTDITINERARIOS;

         WVIA = WVIA + 1;
         SUSPEND;
         BDVALCUSTOEMP = 0;

       END
   END
END
^

/* Restore proc. body: SP_ATU_CAMPOS_GERADOR */
ALTER PROCEDURE SP_ATU_CAMPOS_GERADOR AS
DECLARE VARIABLE WCODTABELA INTEGER;
DECLARE VARIABLE WTABELA VARCHAR(256);
DECLARE VARIABLE WCAMPO VARCHAR(256);
DECLARE VARIABLE WDESCCAMPO VARCHAR(256);
BEGIN
  /* Procedure Text */
  EXECUTE PROCEDURE sp_seta_competencia(201110,NULL,NULL);

--  suspend;
  FOR SELECT t.bdcodtabger,t.bdtabela FROM ttabelagerador t INTO :wcodtabela,:wtabela DO
    BEGIN
      FOR SELECT rdb$field_name, CAST(rdb$description AS VARCHAR(256)) FROM RDB$RELATION_FIELDS
        WHERE UPPER(rdb$relation_name) = UPPER(:wtabela) INTO :wcampo, :wdesccampo DO
        BEGIN
           UPDATE OR INSERT INTO TCAMPOSGERADOR (BDCODTABGER, BDCODCAMPOGER, BDCAMPO, BDDESCRICAO, BDDESCRICAOAUX, bdfiltro)
                                         VALUES (:wcodtabela, NULL, :wcampo, :wdesccampo, :wdesccampo, 'TRUE')
                                       MATCHING (BDCODTABGER, BDCODCAMPOGER);

        END
    END

END
^

/* Restore proc. body: SP_CALC_DEPRECIACAO */
ALTER PROCEDURE SP_CALC_DEPRECIACAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
PRCORRECAOPERIODO NUMERIC(15,2),
PRVALORCORRIGIDOATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
PRDEPRECIACAOPERIODO NUMERIC(15,2),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
PRVALORRESIDUALCONTABIL NUMERIC(15,2),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,2),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
PRVALORBAIXAREAL NUMERIC(15,2),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2))
 AS
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDTINI DATE;
DECLARE VARIABLE WDTFIM DATE;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIAMES INTEGER;
DECLARE VARIABLE WCONTINUACALCULO VARCHAR(5);
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALDEPACUMUBEM NUMERIC(15,6);
DECLARE VARIABLE WMESESDEPACUMUBEM INTEGER;
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WCODMOEDA INTEGER;
DECLARE VARIABLE WDESCMOEDA VARCHAR(20);
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,2);
DECLARE VARIABLE WVALORBAIXAAUX NUMERIC(15,2);
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WVALORAQUISICAO NUMERIC(15,6);
DECLARE VARIABLE WPOSSUIBAIXA VARCHAR(5);
DECLARE VARIABLE WREFMOEDAINI VARCHAR(10);
DECLARE VARIABLE WREFMOEDAFIM VARCHAR(10);
DECLARE VARIABLE WVALORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPDIASADEPRECIAR INTEGER;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WTOTALMESESDOPERIODO INTEGER;
DECLARE VARIABLE WDATAOFICIALINICIOLCALCULO DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WDATATOTALMESESDEPDIA DATE;
DECLARE VARIABLE WDATATOTALMESESULTIMODIA DATE;
DECLARE VARIABLE WDEPDIAFINAL VARCHAR(5);
DECLARE VARIABLE WDATAATUAL DATE;
DECLARE VARIABLE WDIFERENCAMESES INTEGER;
DECLARE VARIABLE WVALORAQUISICAOMOEDA NUMERIC(15,7);
DECLARE VARIABLE WVALORDEPRECIACAOMENSAL NUMERIC(15,7);
DECLARE VARIABLE WVALORDEPRECIACAODIARIA NUMERIC(15,6);
DECLARE VARIABLE WDATAINICIAL DATE;
DECLARE VARIABLE WDATAFINAL DATE;
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,2);
BEGIN
  /*Stored procedure para calcular a deprecia??o dos bens*/

  --#alt:6598.
  /*Esta stored procedure foi iniciada para calcular de uma forma mais r?pida, mas conseguimos melhorar a rotina anterior.
  Caso a rotina SP_CONS_CALC_DEP volte a dar problema j? tem essa meia encaminhada.
  OBS_1: Est? rotina est? no in?cio, por isso precisa implementar v?rias situa??es e testar muito bem.
  OBS_2: Tem algumas stored procedure que podem ser trocadas por rotinas do pr?prio banco para melhorar o desempenho. 
  Ex: select BDNOVADATA from diminui_meses(:wdatatotalmesesultimodia,1) into wdatatotalmesesultimodia;   --->  wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);
      select bdMESES from DIFERENCA_MESES(:wdatainicial,:wdatafinal) into :wtotalmesesdoperiodo;         --->  wtotalmesesdoperiodo = datediff(month,:wdatainicial,:wdatafinal);                 
  */

  -- Inicializa par?metros
  PRVALORCORRIGIDOANTERIOR        = 0;
  PRCORRECAOPERIODO               = 0;
  PRVALORCORRIGIDOATUAL           = 0;
  PRDEPRECIACAOACUMULADAANTERIOR  = 0;
  PRDEPRECIACAOPERIODO            = 0;
  PRDEPRECIACAOPERIODOMOEDA       = 0;
  PRDEPRECIACAOACUMULADAATUAL     = 0;
  PRDEPRECIACAOACUMULADAATUALMOED = 0;
  PRCORRECAOMONETARIADEPRECIACAO  = 0;
  PRVALORRESIDUALCONTABIL         = 0;
  PRVALORRESIDUALCONTABILMOEDA    = 0;
  PRTOTALMESESDEPRECIACAO         = 0;
  PRMESESDEPRECIADOS              = 0;
  PRMESESDEPRECIAR                = 0;
  PRTAXADEPRECIACAOANUAL          = 0;
  PRDATATAXADEPRECIACAO           = NULL;
  PRVALORBAIXA                    = 0;
  PRDEPRECIACAOBAIXAMOEDA         = 0;
  PRVALORBAIXAREAL                = 0;
  PRVALORMOEDA                    = 0;
  PRDATABAIXA                     = NULL;
  PRVALORAQUISICAOMOEDA           = 0;
  PRVALORCORRIGIDOANTERIORMOEDA   = 0;
  PRVALORAQUISICAOORIGINAL        = 0;
  PRCTADEBITODEPRE                = NULL;
  PRVALORDEPRECIACAODIARIAFIM     = 0;

  wcodbemoriginal            = 0;
  wdataorigaquisicao         = NULL;
  wdepdia                    = 'FALSE';
  wdepmensal                 = 'FALSE';
  wdepmesbaixa               = 'FALSE';
  wdatainiciocalc            = NULL;
  wdatafimcalc               = NULL;
  wdataultimoitemdep         = NULL;
  wvaldepacumubem            = 0;
  wnumdias                   = 0;
  wcodmoeda                  = 0;
  wdescmoeda                 = '';
  wvalormoeda                = 0;

  SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  INTO :wvalorbaixa;

  IF (wvalorbaixa > 0) THEN
    wpossuibaixa = 'TRUE';
  --Tipo 2 somente baixas
  IF ((prtipo = 2) AND (wvalorbaixa = 0)) THEN
    EXIT;

  SELECT tind.bddescind,tbem.bdcodind
  FROM (SELECT COALESCE(tbem.bdcodind,0) bdcodind FROM empresas_tbem tbem
        WHERE (tbem.bdcodemp = :prcodemp)
        AND   (tbem.bdcodbem = :prcodbem)) tbem
  LEFT OUTER JOIN TINDICES tind ON (tind.bdcodind = tbem.bdcodind)
  INTO :wdescmoeda,:wcodmoeda;

  SELECT tbem.bdDATORIAQUIBEM FROM empresas_tbem tbem
  WHERE (tbem.bdcodemp = :prcodemp) AND
        (tbem.bdcodbem = :prcodbem)
  INTO :wdataaquisicao;

  wmes = CAST(SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(EXTRACT(YEAR FROM wdataaquisicao) AS INTEGER);
  SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;

  --wdtini           = wmes||'-01-'||wano;
  wdtini           = wdataaquisicao;
  wdtfim           = wmes||'-'||wultdiames||'-'||wano;
  wrefatu          = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim          = CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER);
  wcontinuacalculo = 'TRUE';
  WHILE ((wrefatu <= wreffim) AND (wcontinuacalculo = 'TRUE')) DO
    BEGIN
      -- Inicializa vari?veis
      wdatainicial               = wdtini;
      wdatafinal                 = wdtfim;
      wdepdiafinal               = 'FALSE';
      wmesesdepacumubem          = 0;
      wvalorbaixa                = 0;
      wvalorbaixaaux             = 0;
      wdatabaixa                 = NULL;
      wvaloraquisicao            = 0;
      wpossuibaixa               = 'FALSE';
      wrefmoedaini               = '';
      wrefmoedafim               = '';
      wdepdiasadepreciar         = 0;
      wtotalmesesdepreciacao     = 0;
      wmesesdepreciados          = 0;
      wmesesdepreciar            = 0;
      wtotalmesesdoperiodo       = 0;
      wdataoficialiniciolcalculo = NULL;
      wdatatotalmeses            = NULL;
      wdatatotalmesesdepdia      = NULL;
      wdatatotalmesesultimodia   = NULL;
      wdataatual                 = wdatafinal;
      wdiferencameses            = NULL;
      wvaloraquisicaomoeda       = 0;
      wvalordepreciacaomensal    = 0;
      wvalordepreciacaodiaria    = 0;
      wdepreciacaoperiodo        = 0;
      wdepreciacaoperiodomoeda   = 0;

      -- Quando o valor da deprecia??o acumulada passou do valor do bem n?o precisa continuar o processo at? chegar na data informada
      IF ((wcontinuacalculo = 'TRUE') AND (prvaloraquisicaooriginal > 0) AND (prdepreciacaoacumuladaatual > COALESCE(prvaloraquisicaooriginal,0))) THEN
        wcontinuacalculo = 'FALSE';

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((prtaxadepreciacaoanual = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        SELECT tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem,
               tbem.bddepmesbaixabem, tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, tdep.bdvaldepacumubem,tdep.bdctadebitodepre, tbem.bdnumdias
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :prtaxadepreciacaoanual, :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,           :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre,       :wnumdias;

      IF ((wvaloraquisicao = 0) AND (prvaloraquisicaooriginal > 0)) THEN
        wvaloraquisicao = prvaloraquisicaooriginal;

      wvalorbaixa = 0;
      IF (wpossuibaixa = 'TRUE') THEN
        BEGIN
          FOR SELECT bddatbai,COALESCE(SUM(bdvalbai),0) AS TotalBaixa FROM empresas_tbai
              WHERE (bdcodemp = :prcodemp) AND (bdcodbem = :prcodbem)
              AND   (bddatbai BETWEEN :wdtini AND :wdtfim) GROUP BY bddatbai
              INTO :wdatabaixa,:wvalorbaixaaux DO
            BEGIN
              wvalorbaixa = wvalorbaixa + wvalorbaixaaux;
            END
        END

      IF (prvaloraquisicaooriginal IS NULL) THEN
        BEGIN
          EXCEPTION ex_date;
          SUSPEND;
          EXIT;
        END

      --if (prdatainicial > wdatafimcalc) then
      --  begin
      --    suspend;
      --    exit;
      --  end

      wvaloraquisicao = (wvaloraquisicao - wvalorbaixa);
    
      IF ((UPPER(wdepmesbaixa) = 'TRUE') AND (wvalorbaixa >= wvaloraquisicao)) THEN
        BEGIN
          wdatafinal = wdatabaixa; -- tinha prdatafinal
    
          IF (CAST((SUBSTRING(wdatabaixa FROM 1 FOR 4)) || (SUBSTRING(wdatabaixa FROM 6 FOR 2)) AS INTEGER) <=
              CAST((SUBSTRING(wdtfim FROM 1 FOR 4)) || (SUBSTRING(wdtfim FROM 6 FOR 2)) AS INTEGER)) THEN
            wdepmesbaixa = 'TRUE';
          ELSE
            wdepmesbaixa = 'FALSE';
        END
      ELSE
        wdepmesbaixa = 'FALSE';
    
      IF (UPPER(wdepmesbaixa) = 'TRUE') THEN
        wvaloraquisicao = (wvaloraquisicao + wvalorbaixa);

      IF ((((wvaloraquisicao IS NULL) OR (wvaloraquisicao <=0))) AND (UPPER(wdepmesbaixa) = 'FALSE')) THEN
        BEGIN
          SUSPEND;
          EXIT;
        END
    
      IF (prtipo = 2) THEN
        BEGIN
          prvaloraquisicaooriginal = wvalorbaixa;
          wvaloraquisicao          = wvalorbaixa;
        END

      -- C?LCULO DE DEPRECIA??O
      prvalorcorrigidoatual = wvaloraquisicao;

      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      IF ((wvalormoeda IS NULL) OR (wvalormoeda = 0) OR (POSITION('UFIR',UPPER(wdescmoeda)) = 0))  THEN
        BEGIN
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
          wrefmoedafim = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
          IF (wdataorigaquisicao IS NOT NULL) THEN
            BEGIN
              wrefmoedaini = SUBSTRING(CAST(:wdataorigaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
              wrefmoedafim = SUBSTRING(CAST(:wdataorigaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
            END
    
          SELECT MAX(tind.bdvalind) FROM tindval tind
                 WHERE (tind.bdcodind = :wcodmoeda) AND
                       (tind.bdrefind BETWEEN :wrefmoedaini AND :wrefmoedafim)
          INTO :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          IF (wvalormoeda IS NULL) THEN
            BEGIN
              SELECT FIRST 1 tind.bdvalind FROM tindval tind
                     WHERE tind.bdcodind = :wcodmoeda AND
                     tind.bdrefind <= :wrefmoedaini
                     ORDER BY tind.bdrefind
              INTO :wvalormoeda;
            END
        END

      -- Deprecia??o di?ria (In?cio)
      IF (UPPER(wdepdia) = 'TRUE' ) THEN
        IF ((SUBSTRING(wdatainiciocalc FROM 9 FOR 2)) = '01') THEN
          wdepdia = 'FALSE';
    
      IF (UPPER(wdepdia) = 'TRUE') THEN
        BEGIN
          wdepdiasadepreciar = (SUBSTRING(wdatainiciocalc FROM 9 FOR 2));
    
          wmes = CAST(SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano = CAST(SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;
    
          IF (wnumdias = 2) THEN
            wdepdiasadepreciar = wultdiames - wdepdiasadepreciar;
          ELSE
            wdepdiasadepreciar = 30 - wdepdiasadepreciar;
        END
      -- Deprecia??o di?ria (Fim)

      IF (prtaxadepreciacaoanual >= 0.1) THEN
        wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
      ELSE
        BEGIN
          prvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / wvalormoeda;
          prvalorresidualcontabil       = wvaloraquisicao;
          prvalorresidualcontabilmoeda  = (wvaloraquisicao / wvalormoeda);
          prdatataxadepreciacao         = wdataultimoitemdep;
          prvalorbaixa                  = wvalorbaixa;
          prvalorbaixareal              = wvalorbaixa;
          prvalormoeda                  = wvalormoeda;
          prdatabaixa                   = wdatabaixa;
          prvaloraquisicaomoeda         = (wvaloraquisicao / wvalormoeda);
    
          SUSPEND;
          EXIT;
        END

      IF (wdatainiciocalc IS NOT NULL) THEN
        wdataoficialiniciolcalculo = wdatainiciocalc;
      ELSE
        wdataoficialiniciolcalculo =  wdataaquisicao;

      IF (wvaloraquisicao = 0) THEN
        EXIT;
      -- Joga para uma vari?vel o numero de meses que j? foi depreciado em outro sistema
      IF (wvaldepacumubem > 0) THEN
        wmesesdepacumubem = ((wvaldepacumubem) / (wvaloraquisicao / wtotalmesesdepreciacao));

      wdatatotalmeses       = addmonth(wdataoficialiniciolcalculo, wtotalmesesdepreciacao-wmesesdepacumubem);
      wdatatotalmesesdepdia = addmonth(wdatatotalmeses, 1);
      -- Transforma no primeiro dia do m?s
      wdatatotalmeses       = SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
      wdataaquisicao        = SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
    
      SELECT bdMESES FROM DIFERENCA_MESES(:wdatatotalmeses,:wdataatual) INTO :wdiferencameses ;
      ---------------wdiferencameses = datediff(month,:wdatatotalmeses,:wdataatual); --------------------
      IF (wdiferencameses-1 > 0) THEN
        BEGIN
         IF (wdepmensal = 'FALSE') THEN
           SELECT BDNOVADATA FROM add_meses(:wdatatotalmeses,1) INTO wdataatual;
         ELSE
           wdataatual = wdatatotalmeses;
        END

      IF ((wdepmensal = 'FALSE') AND
          (CAST(EXTRACT(YEAR FROM wdatainicial) || EXTRACT(MONTH FROM wdatainicial) AS INTEGER) = --
           CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
        BEGIN
        SELECT BDNOVADATA FROM diminui_meses(:wdatafinal,1) INTO wdatafinal; -- tinha prdatafinal ---------------
        ---------------wdatafinal = addmonth(:wdatafinal,-1);
        END
    
      -- Se for relatorio de baixas, a data atual devera ser o do mes da baixa.
      IF ((prtipo = 2) OR ((wdatabaixa IS NOT NULL) AND (wvalorbaixa >= wvaloraquisicao))) THEN
        BEGIN
          wdataatual  = wdatabaixa;
          wdatafinal = wdatabaixa; -- tinha prdatafinal
        END
    
       IF ((wdatafimcalc IS NOT NULL) AND (wdatafimcalc < wdatafinal)) THEN -- tinha prdatafinal
         BEGIN
           wdataatual = wdatafimcalc;
           wdatafinal = wdatafimcalc; -- tinha prdatafinal
         END

      SELECT bdMESES FROM DIFERENCA_MESES(:wdataoficialiniciolcalculo,:wdataatual) INTO :wmesesdepreciados;
      ---------------wmesesdepreciados = datediff(month,:wdataoficialiniciolcalculo,:wdataatual); --------------------
      IF ((wdepmensal = 'FALSE') OR (wvaldepacumubem > 0)) THEN
        wmesesdepreciados = wmesesdepreciados - 1;
    
      -- Adiciona no total de meses depreciados o valor j? depreciado de outro sistema
      IF ((wvaldepacumubem > 0) AND (wmesesdepreciados >= 0)) THEN
        wmesesdepreciados = wmesesdepreciados + ((wvaldepacumubem) / (wvaloraquisicao / wtotalmesesdepreciacao));
    
      IF (wmesesdepreciados > wtotalmesesdepreciacao) THEN
        wmesesdepreciados = wtotalmesesdepreciacao;

      -- Se os meses decreciados for menor que zero, significa que foi informado uma data inferior a data de aquisicao do bem
      IF (wmesesdepreciados > 0) THEN
        BEGIN
          -- Total de meses da diferen?a do periodo de deprecia??o
          wmes = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;
          wdatatotalmesesultimodia = wmes||'-'||wultdiames||'-'||wano;
          IF (wdatafinal > wdatatotalmesesultimodia) THEN -- tinha prdatafinal
            BEGIN
              IF (wdepdia = 'TRUE') THEN
                BEGIN
                  -- Caso seja o ?ltimo m?s para depreciar
                  IF (wmesesdepreciar = 0) THEN
                    wdepdiafinal = 'TRUE';
        
                  wdatatotalmesesultimodia = addmonth(wdatatotalmesesultimodia, 1);
                  wdatatotalmesesultimodia = SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                                             SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
                END
            END
        
          IF (wdatafinal > wdatatotalmeses) THEN -- tinha prdatafinal
            wdatafinal = wdatatotalmeses; -- tinha prdatafinal
        
          IF (wdatainicial < :wdataoficialiniciolcalculo) THEN --
            wdatainicial = wdataoficialiniciolcalculo; --
        
          SELECT bdMESES FROM DIFERENCA_MESES(:wdatainicial,:wdatafinal) INTO :wtotalmesesdoperiodo; -- tinha prdatafinal
          ---------------wtotalmesesdoperiodo = datediff(month,:wdatainicial,:wdatafinal); --------------------
          IF ((wvaldepacumubem > 0) AND (wdatainicial <= wdataorigaquisicao)) THEN --
            wtotalmesesdoperiodo = wtotalmesesdoperiodo-1;
          
          -- Meses ? depreciar
          wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);
          wvaloraquisicaomoeda = (wvaloraquisicao / wvalormoeda);
          -- Deprecia??o do per?odo
          wvalordepreciacaomensal = (wvaloraquisicaomoeda / wtotalmesesdepreciacao);
    
          IF (wdepdiasadepreciar > 0) THEN
            BEGIN
              wvalordepreciacaodiaria     = (wvalordepreciacaomensal * wvalormoeda) / 30 * wdepdiasadepreciar;
              prvalordepreciacaodiariafim = (wvalordepreciacaomensal * wvalormoeda) - wvalordepreciacaodiaria;
            END
        
          IF (wdepdia = 'TRUE') THEN
            BEGIN
              -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
              wmesesdepreciar      = wmesesdepreciar + 1;
              wmesesdepreciados    = wmesesdepreciados - 1;
              wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;
            END
    
          IF (wdatainicial <= :wdataaquisicao) THEN
            BEGIN
              wdepreciacaoperiodo      = ((wvalordepreciacaodiaria) + wvalordepreciacaomensal * wtotalmesesdoperiodo * wvalormoeda);
              wdepreciacaoperiodomoeda = ((wvalordepreciacaodiaria / wvalormoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
            END
          ELSE
          IF (wdepdia = 'TRUE') THEN
            BEGIN
              wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo + 1) * wvalormoeda);
              wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo+1);
            END
          ELSE
            BEGIN
              wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo) * wvalormoeda);
              wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo);
            END
    
          -----------------------------------------------------------------------------------
          IF ((wvalordepreciacaodiaria > 0) AND (wdatainicial <= :wdataaquisicao))  THEN
            BEGIN
              wdepreciacaoacumuladaatual = wvalordepreciacaomensal * wmesesdepreciados;
              wdepreciacaoacumuladaatual = wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * wvalormoeda;
        
              wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
            END
          ELSE
            BEGIN
              wdepreciacaoacumuladaatual = wvalordepreciacaomensal * wmesesdepreciados;
              wdepreciacaoacumuladaatual = wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * wvalormoeda;
        
              IF (wvalordepreciacaodiaria > 0) THEN
                wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
              ELSE
                wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual -  ((wvalordepreciacaomensal * (wtotalmesesdoperiodo) * wvalormoeda)));
            END
    
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            wvalorcorrigidoanterior = wvaloraquisicao;
        
          IF (wdepreciacaoacumuladaanterior < 0) THEN
            wdepreciacaoacumuladaanterior = 0;
    
          wdepreciacaoacumuladaatualmoed = (wvalordepreciacaodiaria/wvalormoeda) + wvalordepreciacaomensal * wmesesdepreciados;
          wcorrecaomonetariadepreciacao  = 0;
          wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          wvalorresidualcontabilmoeda    = wvalorresidualcontabil / wvalormoeda;
          wdepreciacaobaixamoeda         = (wvalorbaixa / wtotalmesesdepreciacao);
          wdepreciacaobaixamoeda         = (wdepreciacaobaixamoeda / wvalormoeda);
    
          IF (prtipo = 2) THEN
            BEGIN
              prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
              prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior) / wvalormoeda;
            END
          ELSE
            BEGIN
              prvalorcorrigidoanterior      = wvalorcorrigidoanterior + wvalorbaixa;
              prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior + wvalorbaixa) / wvalormoeda;
            END
    
          IF ((wdepdia = 'TRUE')  AND (wdepdiafinal = 'TRUE')) THEN
            BEGIN
              IF (wdatainicial <= :wdataaquisicao) THEN
                BEGIN
                  wdepreciacaoperiodo      = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo * wvalormoeda);
                  wdepreciacaoperiodomoeda = (((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) / wvalormoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
        
                  wdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim;
                  wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual / wvalormoeda;
        
                  wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
                  wvalorresidualcontabilmoeda = 0;
        
                  wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
                END
              ELSE
                BEGIN
                  SELECT BDNOVADATA FROM diminui_meses(:wdatatotalmesesultimodia,1) INTO wdatatotalmesesultimodia;
                  ---------------wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);----------------------
        
                  wdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim;
                  wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual / wvalormoeda;
        
                  wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
                  wvalorresidualcontabilmoeda = 0;
        
                  IF (wdatainicial <> :wdatatotalmesesultimodia) THEN
                    BEGIN
                      wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
                      wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaanterior / wvalormoeda);
                    END
        
                  wdepreciacaoperiodo = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;
        
                  IF (wdepreciacaoperiodo <= 0) THEN
                    wdepreciacaoperiodomoeda = 0;
                  ELSE
                    wdepreciacaoperiodomoeda = ((wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior) / wvalormoeda);
                END
        
              wmesesdepreciados = wmesesdepreciados + 1;
              wmesesdepreciar   = 0;
            END
    
          prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;
          prdepreciacaoperiodo            = wdepreciacaoperiodo;
          prdepreciacaoperiodomoeda       = wdepreciacaoperiodomoeda;
          prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
          prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
          prcorrecaomonetariadepreciacao  = wcorrecaomonetariadepreciacao;
          prvalorresidualcontabil         = wvalorresidualcontabil;
          prvalorresidualcontabilmoeda    = wvalorresidualcontabilmoeda;
          prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
          prmesesdepreciados              = wmesesdepreciados;
          prmesesdepreciar                = wmesesdepreciar;
          prdatataxadepreciacao           = wdataultimoitemdep;
          prvalorbaixa                    = wvalorbaixa;
          prdepreciacaobaixamoeda         = wdepreciacaobaixamoeda;
          prvalorbaixareal                = wvalorbaixa;
          prvalormoeda                    = wvalormoeda;
          prdatabaixa                     = wdatabaixa;
          prvaloraquisicaomoeda           = wvaloraquisicaomoeda;
        END

      wdtini  = addmonth(wdtini, 1);
      wmes    = CAST(SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
      wano    = CAST(EXTRACT(YEAR FROM wdtini) AS INTEGER);
      wdtini  = wmes||'-01-'||wano;
      wdtfim  = addmonth(wdtini, 1)-1;
      wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  SUSPEND;
END
^

/* Restore proc. body: SP_COMMIT_UNIDADEMEDIDA */
ALTER PROCEDURE SP_COMMIT_UNIDADEMEDIDA(PRSESSAO INTEGER,
PRCODEMP INTEGER,
PRREF INTEGER)
 AS
DECLARE VARIABLE WCODINCONSISTENCIA INTEGER;
DECLARE VARIABLE wAtuUnidMed VARCHAR(5);
DECLARE VARIABLE wEditChave  INTEGER;
DECLARE VARIABLE wDescUnimed VARCHAR(100);
DECLARE VARIABLE wApeUniMed  VARCHAR(5);
DECLARE VARIABLE wCodTipo    INTEGER;
BEGIN
  wCodInconsistencia = NULL;
  SELECT S.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) S INTO :wCodInconsistencia;

  IF ((:wCodInconsistencia IS NULL) OR (:wCodInconsistencia = 0)) THEN
    SELECT I.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS I WHERE UPPER(I.BDPLANODEFAULT) = 'TRUE' INTO :wCodInconsistencia;

  /* **********************Insere unidades de medida que n?o existem no banco********************** */
  INSERT INTO TUNIDADEMEDIDA(bdcodunimed, bddescunimed, bdapeunimed, bdcodtipo)
  SELECT un.bdeditchave bdcodunimed, un.bddescunimed, un.bdapeunimed, un.bdcodtipo
  FROM TMP_TUNIDADEMEDIDA_TEMP un
  WHERE un.bdsessao = :PRSESSAO
  AND NOT EXISTS(
                 SELECT u.bdcodunimed, u.bddescunimed,
                        u.bdapeunimed, u.bdcodtipo
                 FROM TUNIDADEMEDIDA U
                 WHERE U.BDAPEUNIMED = un.BDAPEUNIMED
                );

  /*Existe plano de inconsistencia no cadastro da empresa ou plano default*/
  IF ((:wCodInconsistencia IS NOT NULL) OR (:wCodInconsistencia > 0)) THEN
    BEGIN
      SELECT COALESCE(UPPER(I.BDATUUNIDMED), 'FALSE') BDATUUNIDMED FROM VEF_BASE_TACOESINCONS I WHERE I.BDCODPLANOINCONS = :wCodInconsistencia INTO :wAtuUnidMed;

      /*Atualiza as unidades de medida*/
      IF (:wAtuUnidMed = 'TRUE') THEN
        BEGIN
          FOR SELECT un.bdeditchave bdcodunimed, un.bddescunimed, un.bdapeunimed, un.bdcodtipo
              FROM TMP_TUNIDADEMEDIDA_TEMP un
              WHERE un.bdsessao = :PRSESSAO
              AND EXISTS(
                         SELECT u.bdcodunimed, u.bddescunimed,
                                u.bdapeunimed, u.bdcodtipo
                         FROM TUNIDADEMEDIDA U
                         WHERE U.BDAPEUNIMED = un.BDAPEUNIMED
                        )
              INTO :wEditChave, :wDescUniMed, :wApeUniMed, :wCodTipo
          DO
            UPDATE TUNIDADEMEDIDA U SET U.BDDESCUNIMED = :wDescUniMed, U.BDAPEUNIMED = :wApeUniMed, U.BDCODTIPO = :wCodTipo WHERE U.BDCODUNIMED = :wEditChave;
        END
    END


END
^

/* Restore proc. body: SP_COMP_ACUMULADO_GPS */
ALTER PROCEDURE SP_COMP_ACUMULADO_GPS(PRCODEMP INTEGER,
PRAGRUPADO INTEGER,
PRCODTPCC INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOFOLHA INTEGER,
PRCHAVEDARF INTEGER = 0,
PRCOMPL13 SMALLINT = 1)
 RETURNS(BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULADO NUMERIC(15,6),
BDACUMULADOTERC NUMERIC(15,6))
 AS
DECLARE VARIABLE WVALACUTER NUMERIC(15,6);
DECLARE VARIABLE WVALACU NUMERIC(15,6);
DECLARE VARIABLE WTOTACUTER NUMERIC(15,6);
DECLARE VARIABLE WTOTACU NUMERIC(15,6);
DECLARE VARIABLE WQUOTA INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WREFUTIMAL INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WAUXCODCENTO VARCHAR(3000);
DECLARE VARIABLE WSQL VARCHAR(3000);
DECLARE VARIABLE WSQLMOVICOL VARCHAR(3000);
DECLARE VARIABLE WCOMPENSACAO NUMERIC(15,6);
DECLARE VARIABLE WINICIOCOMPENSACAO INTEGER;
DECLARE VARIABLE WFIMCOMPENSACAO INTEGER;
DECLARE VARIABLE WBUSCACOMP INTEGER;
DECLARE VARIABLE WACUMULADO NUMERIC(15,6);
DECLARE VARIABLE WACUMULADOTERC NUMERIC(15,6);
DECLARE VARIABLE WCODIMP INTEGER;
DECLARE VARIABLE WAUX1 NUMERIC(15,6);
DECLARE VARIABLE WAUX2 INTEGER;
DECLARE VARIABLE WAUX3 INTEGER;
BEGIN
  /* Procedure Text */
   IF (pranomespag IS NULL) THEN
      pranomespag = pranomes;

   wsql = 'select colcon.bdcodimp from vw_tempresaimpostoref colcon where colcon.bddocarrecadacao = 12 and colcon.bdcodemp = '||prcodemp;
   wcompensacao = 0;
   winiciocompensacao = 999999;
   wfimcompensacao = 0;
   wbuscacomp = 0;
   wacumulado = 0;
   wacumuladoterc = 0;

   IF (wtotacu IS NULL) THEN
      wtotacu = 0;

   IF (wtotacuter IS NULL) THEN
      wtotacuter = 0;

   EXECUTE PROCEDURE sp_seta_competencia(pranomespag);
   FOR EXECUTE STATEMENT wsql INTO : wcodimp DO
     BEGIN
       waux1 = NULL;
       IF (prtipofolha IN (0,1,2)) THEN
          BEGIN
            IF (prcodtpcc IS NULL) THEN
               wsqlmovicol = 'null';
            ELSE
               wsqlmovicol = ''||prcodtpcc;
            wsqlmovicol = 'select sum(comp.BDVALOR),min(comp.BDMESINI),max(comp.BDMESFIM) from vrhf_sp_tcompensacaogps('||wcodimp||','||prcodemp||','||prtipofolha||','||pragrupado||','||wsqlmovicol||','||wbuscacomp||','||pranomespag||','||prchavedarf||') comp';
            EXECUTE STATEMENT wsqlmovicol INTO waux1,waux2,waux3;
          END

       wbuscacomp = 1;
       IF (waux1 IS NOT NULL) THEN
          BEGIN
            IF (waux1 IS NULL) THEN
               waux1 = 0;
            IF (waux2 IS NULL) THEN
               waux2 = 999999;
            IF (waux3 IS NULL) THEN
               waux3 = 0;

            wcompensacao = wcompensacao + waux1;

            IF (waux2 < winiciocompensacao) THEN
               winiciocompensacao = waux2;

            IF (waux3 > wfimcompensacao) THEN
               wfimcompensacao = waux3;
          END

       /*Inicio acumulado*/
       /*****************************************************************************/
       wauxcodcento = '';
       IF (pragrupado = 3) THEN
          BEGIN
            IF (prcodtpcc IS NULL) THEN
               wauxcodcento = 'and x.bdcodtpcc is null';
            ELSE
               wauxcodcento = 'and x.bdcodtpcc = '||prcodtpcc;
          END

       wsqlmovicol = 'select first 1 x.bdchavedarf from tdarfpadrao x '||
                     'where x.bdreferencia = '||pranomes||
                     ' and x.bdcodemp = '||prcodemp||
                     ' and x.bdcodimp = '||wcodimp||
                     ' and x.bdrefpag = '||pranomespag||
                     wauxcodcento||
                     ' and x.BDTIPOIMPOSTO = '||prtipofolha;

       wordem = NULL;
       EXECUTE STATEMENT wsqlmovicol INTO wordem;
       wsqlmovicol = 'select first 1 '||
                     'x.bdreferencia,'||
                     'x.bdordem,'||
                     'x.BDCODPERIODO,'||
                     'x.BDQUOTA from tdarfpadrao x ';

       IF (wordem IS NULL) THEN
          BEGIN
            wsqlmovicol = wsqlmovicol||
                     ' where '||
                     ' x.bdcodemp = '||prcodemp||
                     ' and x.bdcodimp = '||wcodimp||
                     ' and x.bdrefpag <= '||pranomespag||
                     wauxcodcento||
                     ' and x.BDTIPOIMPOSTO = '||prtipofolha;
          END
       ELSE
          BEGIN
            wsqlmovicol = wsqlmovicol||
                      ' where '||
                      ' x.bdcodemp = '||prcodemp||
                      ' and x.bdcodimp = '||wcodimp||
                      ' and ((x.bdrefpag < '||pranomespag||') or (x.bdrefpag = '||pranomespag||' and x.bdordem < '||wordem||'))'||
                      ' and x.bdchavedarf < '||wordem||
                      wauxcodcento;

            IF ((prcompl13 IS NULL) OR (prcompl13 = 0)) THEN
               wsqlmovicol = wsqlmovicol||' and x.BDTIPOIMPOSTO <> 3 ';

          END

       wsqlmovicol = wsqlmovicol||' order by x.bdrefpag desc, x.bdordem desc';
    
       wrefutimal = NULL;
       EXECUTE STATEMENT wsqlmovicol INTO wrefutimal,wordem,wcodperiodo,wquota;

       IF ((wrefutimal IS NOT NULL) AND (wrefutimal > 0)) THEN
          BEGIN
            wsqlmovicol = 'select y.bdvalcampo6,y.bdvalcampo9 from VRHF_SP_HIST_ACUMU_GPS('||''''||'x.bdcodemp = '||prcodemp||' and x.bdcodimp = '||wcodimp||' and x.bdreferencia = '||wrefutimal||
                      ' and x.bdordem = '||wordem||' and x.BDCODPERIODO = '||wcodperiodo||' and x.BDQUOTA = '||wquota||''''||') y';
    
            FOR EXECUTE STATEMENT wsqlmovicol INTO
              : wvalacu,
              : wvalacuter
            DO
              BEGIN
                IF (wvalacu IS NOT NULL) THEN
                   wtotacu = wtotacu + wvalacu;

                IF (wvalacuter IS NOT NULL) THEN
                   wtotacuter = wtotacuter + wvalacuter;
              END
          END

       wacumulado = wtotacu;
       wacumuladoterc = wvalacuter;
       /*****************************************************************************/
       /*Fim acumulado*/
     END

   IF ((wcompensacao = 0) OR (wcompensacao IS NULL)) THEN
      BEGIN
        winiciocompensacao = 0;
        wfimcompensacao = 0;
      END

  bdacumulado = wacumulado;
  bdacumuladoterc = wacumuladoterc;
  bdcompensacao = wcompensacao;
  bdinicomp = winiciocompensacao;
  bdfimcomp = wfimcompensacao;
  SUSPEND;
END
^

/* Restore proc. body: SP_CONS_CALC_DEP */
ALTER PROCEDURE SP_CONS_CALC_DEP(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER,
PRDETALHARTAXADEP INTEGER = 0)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,6),
PRCORRECAOPERIODO NUMERIC(15,6),
PRVALORCORRIGIDOATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6),
PRDEPRECIACAOPERIODO NUMERIC(15,6),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6),
PRVALORRESIDUALCONTABIL NUMERIC(15,6),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,6),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,6),
PRVALORBAIXAREAL NUMERIC(15,6),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,6),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,6),
BDCODEMP INTEGER,
BDCODBEM INTEGER,
PRSOMARDEPRECIACAO INTEGER,
PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDTINI DATE;
DECLARE VARIABLE WDTFIM DATE;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIAMES INTEGER;
DECLARE VARIABLE WCORRECAOPERIODO NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOATUAL NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOSAUX INTEGER;
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,6);
DECLARE VARIABLE WVALORBAIXABEM NUMERIC(15,6);
DECLARE VARIABLE WPOSSUIBAIXA VARCHAR(5);
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,6);
DECLARE VARIABLE WVALORBAIXAREAL NUMERIC(15,6);
DECLARE VARIABLE WVALORAQUISICAOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WTAXAAUX NUMERIC(6,6);
DECLARE VARIABLE WTAXAANT NUMERIC(6,6);
DECLARE VARIABLE WDEPRECIACAOPERIODOAUX NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6);
DECLARE VARIABLE WCODMOEDA INTEGER;
DECLARE VARIABLE WVALORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WREFMOEDAINI VARCHAR(10);
DECLARE VARIABLE WREFMOEDAFIM VARCHAR(10);
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALDEPACUMUBEM NUMERIC(15,6);
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WDEPDIADATA INTEGER;
DECLARE VARIABLE WFIRST VARCHAR(5);
DECLARE VARIABLE WDTBAIXAAUX DATE;
DECLARE VARIABLE WMESESDEPRECIADOSOUTRATAXA INTEGER;
DECLARE VARIABLE WDEPRECIACAOACUMULADA NUMERIC(15,6);
DECLARE VARIABLE WDATAINIMES DATE;
DECLARE VARIABLE WDATAINICIALCALCULO DATE;
DECLARE VARIABLE WDIASDEPRECIADOS INTEGER;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,6);
DECLARE VARIABLE WTIPO INTEGER;
BEGIN
  /*Stored procedure para somar os valores das deprecia??es. Principalmente
  quando houver v?rias deprecia??es cadastradas no bem. O c?lculo da deprecia??o
  ? feito na verdade na sp_cons_calc_dep_correcao*/
  prvalorcorrigidoanterior        = 0;
  prcorrecaoperiodo               = 0;
  prvalorcorrigidoatual           = 0;
  prdepreciacaoacumuladaanterior  = 0;
  prdepreciacaoperiodo            = 0;
  prdepreciacaoperiodomoeda       = 0;
  prdepreciacaoacumuladaatual     = 0;
  prdepreciacaoacumuladaatualmoed = 0;
  prcorrecaomonetariadepreciacao  = 0;
  prvalorresidualcontabil         = 0;
  prvalorresidualcontabilmoeda    = 0;
  prtotalmesesdepreciacao         = 0;
  prmesesdepreciados              = 0;
  prmesesdepreciar                = 0;
  prtaxadepreciacaoanual          = 0;
  prdatataxadepreciacao           = NULL;
  prvalorbaixa                    = 0;
  prdepreciacaobaixamoeda         = 0;
  prvalorbaixareal                = 0;
  prvalormoeda                    = 0;
  prdatabaixa                     = NULL;
  prvaloraquisicaomoeda           = 0;
  prvalorcorrigidoanteriormoeda   = 0;
  prvaloraquisicaooriginal        = 0;
  prctadebitodepre                = 0;
  prvalordepreciacaodiariafim     = 0;

  wdepreciacaoperiodo             = 0;
  wdepreciacaoperiodoaux          = 0;
  wtaxaaux                        = 0;
  wdepreciacaoperiodomoeda        = 0;
  wmesesdepreciadosaux            = 0;
  wdepreciacaoacumuladaanterior   = 0;
  wcodmoeda                       = 0;
  wvalormoeda                     = 0;
  wrefmoedaini                    = '';
  wrefmoedafim                    = '';
  wvalorbaixabem                  = 0;
  wpossuibaixa                    = 'FALSE';
  wcodbemoriginal                 = 0;
  wdataorigaquisicao              = NULL;
  wdepdia                         = 'FALSE';
  wdepmensal                      = 'FALSE';
  wdepmesbaixa                    = 'FALSE';
  wdatainiciocalc                 = NULL;
  wdatafimcalc                    = NULL;
  wdataultimoitemdep              = NULL;
  wvaldepacumubem                 = 0;
  wnumdias                        = 0;
  wdepdiadata                     = 0;
  wfirst                          = 'TRUE';
  wdtbaixaaux                     = NULL;
  wdepreciacaoacumulada           = 0;
  WDATAINIMES                     = NULL;
  WDATAINICIAlCALCULO             = NULL;
  WDEPRECIACAOACUMULADAATUAL      = 0;

  BDCODEMP = PRCODEMP;
  BDCODBEM = PRCODBEM;

  --#alt:85169. Os c?lculos para a op??o de relat?rio 2 devem ser os mesmo da deprecia??o, se n?o os valores ficam incorretos. Ana - 21/06/2018
  WTIPO = PRTIPO;
  if (WTIPO = 2) then
    WTIPO = 0;

  --alt:16006 - 03/11/2016 - Comentado aqui e implementado no SP_CONS_CALC_DEP_CORRECAO, pois deve verificar para cada per?odo se possui baixa. Pedro
  /* In?cio deprecia??o anteriores */
  --Processo para calcular os meses anteriores ao per?odo informado, pois posso ter v?rias
  --deprecia??es cadastradas
  /*SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  AND   (tbai.BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
  INTO :wvalorbaixabem;

  IF (wvalorbaixabem > 0) THEN
    wpossuibaixa = 'TRUE';
  --Tipo 2 somente baixas
  IF ((prtipo = 2) AND (wvalorbaixabem = 0)) THEN
    EXIT;*/
  --alt:16006 - Fim

  SELECT tbem.bdDATORIAQUIBEM FROM empresas_tbem tbem
  WHERE (tbem.bdcodemp = :prcodemp) AND
        (tbem.bdcodbem = :prcodbem)
  INTO :wdataaquisicao;

  --SELECT tind.bddescind,tbem.bdcodind
  SELECT tbem.bdcodind
  FROM (SELECT COALESCE(tbem.bdcodind,0) bdcodind FROM empresas_tbem tbem
        WHERE (tbem.bdcodemp = :prcodemp)
        AND   (tbem.bdcodbem = :prcodbem)) tbem
  LEFT OUTER JOIN TINDICES tind ON (tind.bdcodind = tbem.bdcodind)
  --INTO :wdescmoeda,:wcodmoeda;
  INTO :wcodmoeda;

  --#alt:21384 - Estava sempre pegando o maior valor da moeda do ano da aquisi??o do bem, quando na verdade deve pegar sempre o valor mais pr?ximo ao m?s da aquisi??o. Ana - 13/11/2017
  SELECT FIRST 1 tind.bdvalind FROM tindval tind
         WHERE tind.bdcodind = :wcodmoeda AND
         tind.bddataind <= :wdataaquisicao
         ORDER BY tind.bdrefind DESC
   INTO :wvalormoeda;

  --Converte a moeda para cruzeiros reias
  IF (wdataaquisicao <= '06/30/1994') THEN
    wvalormoeda = wvalormoeda / 1000;

  IF ((wvalormoeda = 0) OR (wvalormoeda IS NULL)) THEN
    wvalormoeda = 0.8287;

  /*wrefmoedaini = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
  wrefmoedafim = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
  SELECT MAX(tind.bdvalind) FROM tindval tind
         WHERE (tind.bdcodind = :wcodmoeda) AND
               (tind.bdrefind BETWEEN :wrefmoedaini AND :wrefmoedafim)
  INTO :wvalormoeda;
  --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
  IF (wvalormoeda IS NULL) THEN
    BEGIN
      SELECT FIRST 1 tind.bdvalind FROM tindval tind
             WHERE tind.bdcodind = :wcodmoeda AND
             tind.bdrefind <= :wrefmoedaini
             ORDER BY tind.bdrefind DESC    --#alt:17142 - Alterado para pegar da ultima referencia. Ana - 02/02/2017
      INTO :wvalormoeda;
    END*/
  --#alt:21384. fim

  wmes = CAST(SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(EXTRACT(YEAR FROM wdataaquisicao) AS INTEGER);--cast(substring(cast(wdataaquisicao as varchar(10)) from 1 for 4) as integer);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultdiames;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultdiames = EXTRACT(DAY FROM (wdataaquisicao - EXTRACT(DAY FROM wdataaquisicao) +
                       32 - EXTRACT(DAY FROM wdataaquisicao - EXTRACT(DAY FROM wdataaquisicao) + 32)));

  wdtini  = wmes||'-01-'||wano;
  wdtfim  = wmes||'-'||wultdiames||'-'||wano;
  wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim = CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER);

  --#alt:18204 - Adicionei a verifica??o da data da aquisi??o com a data final para n?o executar quando n?o pertencer ao per?odo de aquisi??o do bem. Ana - 28/04/2017
  WHILE ((wrefatu < wreffim) AND (prdatafinal >= wdataaquisicao)) DO
    BEGIN
      /* A antiga rotina da deprecia??o estava pegando sempre o valor da moeda do m?s de aquisi??o, por isso
         fiz a busca do valor fora do while das refer?ncias, mas deixei como coment?rio caso seja feito
         para busca o valor da moeda conforme o m?s em que esta calculando
      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      if ((wvalormoeda is null) or (wvalormoeda = 0) or (position('UFIR',upper(wdescmoeda)) = 0))  then
        begin
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'0101';
          wrefmoedafim = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'1231';
    
          select max(tind.bdvalind) from tindval tind
                 where (tind.bdcodind = :wcodmoeda) and
                       (tind.bdrefind between :wrefmoedaini and :wrefmoedafim)
          into :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          if (wvalormoeda is null) then
            begin
              select first 1 tind.bdvalind from tindval tind
                     where tind.bdcodind = :wcodmoeda and
                     tind.bdrefind <= :wrefmoedaini
                     order by tind.bdrefind
              into :wvalormoeda;
            end
        end*/

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((COALESCE(prtaxadepreciacaoanual,0) = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        --#alt:16415 - Alterada a verifica??o do case, pois quando n?o havia nehuma contabiliza??o ele n?o levava o valor do bem. Ana - 05/12/2016
        --Faz o select com o First, pois um bem pode ter mais de uma deprecia??o cadastrada.
        --alt:14255 - 28/06/2016 - Adicionado case para verificar o tipo da contabiliza??o e ver de onde ir? buscar valor da aquisi??o. Pedro
        --SELECT FIRST 1 tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem,
        SELECT FIRST 1 tbem.bdcodorigbem, COALESCE(CASE WHEN ((tdep.BDCONTABILIZACAO = 0) OR (tdep.BDCONTABILIZACAO IS NULL) ) THEN tbem.BDVALAQUIBEM ELSE tdep.BDVALAQUISOC END, 0),
               tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem, tbem.bddepmesbaixabem,
               tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, COALESCE(tdep.bdvaldepacumubem,0),tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        ORDER BY tdep.bddatinicalcbem DESC
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :wtaxaaux,         :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,     :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre, :wnumdias,        :wdepdiadata;

      --alt:13784 - 12/04/2016 - Se tiver trocado de taxa de deprecia??o, precisa levar os meses j? depreciados com a taxa anterior para o c?lculo da pr?xima. Pedro
      IF ((wtaxaant <> 0) AND (wtaxaant <> wtaxaaux)) THEN
        BEGIN
          wmesesdepreciadosoutrataxa = prmesesdepreciados;
          --alt:13784 - 12/04/2016 - Se estiver marcado para detalhar por taxa de deprecia??o, precisa retornar aqui a taxa. Pedro
          IF (prdetalhartaxadep = 1) THEN
            BEGIN
              prmesesdepreciar = prtotalmesesdepreciacao - prmesesdepreciados;
              prsomardepreciacao = 0; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
              SUSPEND;
            END
        END

      wdepreciacaoperiodoaux = COALESCE(wdepreciacaoperiodo,0);
      SELECT prcorrecaoperiodo, prvalorcorrigidoatual, prdepreciacaoperiodo, prmesesdepreciados, prvalorbaixa,
             prdepreciacaoperiodomoeda, prvalorresidualcontabil, prvalorresidualcontabilmoeda,
             prdepreciacaobaixamoeda, prvalorbaixareal, prvaloraquisicaomoeda,
             prdepreciacaoacumuladaanterior, prtaxadepreciacaoanual, prdepreciacaoacumuladaatualmoed,
             prtotalmesesdepreciacao, prvaloraquisicaooriginal, prdatabaixa, prdepreciacaoacumuladaatual
      FROM sp_cons_calc_dep_correcao(:prcodemp, :prcodbem, :wdtini, :wdtfim, :WTIPO /*:prtipo*/, :prcontabilizacao,:wvalormoeda,:wpossuibaixa,:wcodbemoriginal,
                                     :prvaloraquisicaooriginal,:wtaxaaux,:wdataaquisicao,:wdataorigaquisicao,:wdepdia,:wdepmensal,
                                     :wdepmesbaixa,:wdatainiciocalc,:wdatafimcalc,:wdataultimoitemdep,:wvaldepacumubem,:prctadebitodepre,:wnumdias,
                                     :wdepdiadata, :wvalorbaixabem, :wmesesdepreciadosoutrataxa, :wdepreciacaoacumulada)
      INTO :wcorrecaoperiodo, :wvalorcorrigidoatual, :wdepreciacaoperiodo, :wmesesdepreciados, :wvalorbaixa,
           :wdepreciacaoperiodomoeda, :wvalorresidualcontabil, :wvalorresidualcontabilmoeda,
           :wdepreciacaobaixamoeda, :wvalorbaixareal, :wvaloraquisicaomoeda,
           :wdepreciacaoacumuladaanterior, :prtaxadepreciacaoanual, :wdepreciacaoacumuladaatualmoed,
           :prtotalmesesdepreciacao, :prvaloraquisicaooriginal, :prdatabaixa, wdepreciacaoacumulada;

      IF (wcorrecaoperiodo > 0) THEN
        BEGIN
          wcorrecaoperiodo = ABS(wcorrecaoperiodo - prcorrecaoperiodo);
          IF (wcorrecaoperiodo > 0) THEN
            prcorrecaoperiodo = prcorrecaoperiodo + wcorrecaoperiodo;
        END

      IF (wvalorcorrigidoatual > 0) THEN
        BEGIN
          wvalorcorrigidoatual = ABS(wvalorcorrigidoatual - prvalorcorrigidoatual);
          --alt:9013 - Foi retirada a incrementa??o do valor corrigido atual daqui pois estava duplicando a corre??o baseada no valor da baixa. Pedro
          /*if (wvalorcorrigidoatual > 0) then
            prvalorcorrigidoatual = abs(prvalorcorrigidoatual - wvalorcorrigidoatual);*/
        END

      --Feito esse tratamento pois posso ter v?rias taxas cadastradas para o bem. N?o posso utilizar o
      --prdepreciacaoacumuladaanterior pois a rotina calcula como se sempre fosse a taxa do m?s em quest?o
      -- In?cio
      IF ((prdepreciacaoacumuladaanterior = 0) AND (prtaxadepreciacaoanual > 0) AND (wdepreciacaoacumuladaanterior > 0)) THEN
        BEGIN
          wdepreciacaoacumuladaanterior = ABS(wdepreciacaoacumuladaanterior - prdepreciacaoacumuladaanterior);
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoacumuladaanterior;
        END
      ELSE
      IF (wdepreciacaoperiodoaux > 0) THEN
        prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoperiodoaux;

      IF ((prdepreciacaoacumuladaatualmoed = 0) AND (prtaxadepreciacaoanual > 0) AND (wdepreciacaoacumuladaatualmoed > 0)) THEN
        BEGIN
          wdepreciacaoacumuladaatualmoed = ABS(wdepreciacaoacumuladaatualmoed - prdepreciacaoacumuladaatualmoed);
          IF (wdepreciacaoacumuladaatualmoed > 0) THEN
            prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoacumuladaatualmoed;
        END
      ELSE
      IF (wdepreciacaoperiodomoeda > 0) THEN
        prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoperiodomoeda;
      -- Fim

      IF (wvalorresidualcontabil > 0) THEN
        BEGIN
          wvalorresidualcontabil = ABS(wvalorresidualcontabil - prvalorresidualcontabil);
          IF ((prvalorresidualcontabil > 0) AND (wdepreciacaoperiodo > 0) AND (wvalorresidualcontabil <> wdepreciacaoperiodo)) THEN
            wvalorresidualcontabil = wdepreciacaoperiodo;

          IF (wvalorresidualcontabil > 0) THEN
            prvalorresidualcontabil = ABS(prvalorresidualcontabil - wvalorresidualcontabil);
        END

      IF (wvalorresidualcontabilmoeda > 0) THEN
        BEGIN
          wvalorresidualcontabilmoeda = ABS(wvalorresidualcontabilmoeda - prvalorresidualcontabilmoeda);
          IF ((prvalorresidualcontabilmoeda > 0) AND (wdepreciacaoperiodomoeda > 0) AND (wvalorresidualcontabilmoeda <> wdepreciacaoperiodomoeda)) THEN
            wvalorresidualcontabilmoeda = wdepreciacaoperiodomoeda;

          IF (wvalorresidualcontabilmoeda > 0) THEN
            prvalorresidualcontabilmoeda = ABS(prvalorresidualcontabilmoeda - wvalorresidualcontabilmoeda);
        END

      --alt:14761 - 16/06/2016 - Se tiver valor de deprecia??o acumulada (informado no cadastro da deprecia??o)
      --? feito um c?lculo da quantidade de meses j? depreciados e assim precisa retornar eles tamb?m. Pedro
      IF ((wdepreciacaoperiodo > 0) OR (wvaldepacumubem > 0)) THEN
        BEGIN
          IF ((wtaxaaux > 0) AND (wtaxaaux <> prtaxadepreciacaoanual)) THEN
            wmesesdepreciadosaux = wmesesdepreciadosaux + ABS(wmesesdepreciadosaux - prmesesdepreciados);

          IF ((wmesesdepreciados > 0) AND ((prmesesdepreciados = 0) OR (wmesesdepreciados > prmesesdepreciados))) THEN --alt:13784 - 12/04/2016 - Quando trocada a taxa de deprecia??o n?o estava levando os meses depreciados corretamente. Pedro
            prmesesdepreciados = wmesesdepreciados;
          --alt:9013 - Colocada essa valida??o para n?o continuar depreciando depois do total de meses da deprecia??o, isso acontecia quando tinha deprecia??o di?ria. Pedro
          ELSE IF (prmesesdepreciados <> prtotalmesesdepreciacao) THEN
            prmesesdepreciados = prmesesdepreciados + 1;
        END
      --#Alt:5105
      /*if (wvalorbaixa > 0) then
        begin
          wvalorbaixa = ABS(wvalorbaixa - prvalorbaixa);
          if (wvalorbaixa > 0) then
            prvalorbaixa = prvalorbaixa + wvalorbaixa;
        end*/

      IF (wdepreciacaobaixamoeda > 0) THEN
        BEGIN
          wdepreciacaobaixamoeda = ABS(wdepreciacaobaixamoeda - prdepreciacaobaixamoeda);
          IF (wdepreciacaobaixamoeda > 0) THEN
            prdepreciacaobaixamoeda = prdepreciacaobaixamoeda + wdepreciacaobaixamoeda;
        END

      IF (wvalorbaixareal > 0) THEN
        BEGIN
          wvalorbaixareal = ABS(wvalorbaixareal - prvalorbaixareal);
          IF (wvalorbaixareal > 0) THEN
            prvalorbaixareal = prvalorbaixareal + wvalorbaixareal;
        END

      IF (wvaloraquisicaomoeda > 0) THEN
        BEGIN
          wvaloraquisicaomoeda = ABS(wvaloraquisicaomoeda - prvaloraquisicaomoeda);
          IF (wvaloraquisicaomoeda > 0) THEN
            prvaloraquisicaomoeda = ABS(prvaloraquisicaomoeda - wvaloraquisicaomoeda);
        END

      IF (prdatabaixa IS NOT NULL) THEN
        wdtbaixaaux = prdatabaixa;

      wtaxaant = wtaxaaux;
      wtaxaaux = prtaxadepreciacaoanual;
      wdtini   = addmonth(wdtini, 1);
      wdtfim   = addmonth(wdtini, 1)-1;
      wrefatu  = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  --alt:15196 - 09/11/2016 - Alterado para carregar a deprecia??o acumulada da vari?vel que est? somando o valor para cada per?odo. Pedro
  /*IF (wdepreciacaoperiodo > 0) THEN
    prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoperiodo;*/

  prdepreciacaoacumuladaanterior = wdepreciacaoacumulada;

  wtaxaaux = COALESCE(wtaxaaux,0);
  /* Final deprecia??o anteriores */

  wdtini  = prdatainicial;
  wmes    = CAST(SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano    = CAST(EXTRACT(YEAR FROM wdtini) AS INTEGER);--cast(substring(cast(wdtini as varchar(10)) from 1 for 4) as integer);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultdiames;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultdiames = EXTRACT(DAY FROM (wdtini - EXTRACT(DAY FROM wdtini) +
               32 - EXTRACT(DAY FROM wdtini - EXTRACT(DAY FROM wdtini) + 32)));
  wdtfim  = wmes||'-'||wultdiames||'-'||wano;
  IF (wdtfim > prdatafinal) THEN
    wdtfim = prdatafinal;
  wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim = CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER);

  prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior;

  --#alt:18204 - Adicionei a verifica??o da data da aquisi??o com a data final para n?o executar quando n?o pertencer ao per?odo de aquisi??o do bem. Ana - 28/04/2017
  WHILE ((wrefatu <= wreffim) AND (prdatafinal >= wdataaquisicao)) DO
    BEGIN
      /* A antiga rotina da deprecia??o estava pegando sempre o valor da moeda do m?s de aquisi??o, por isso
         fiz a busca do valor fora do while das refer?ncias, mas deixei como coment?rio caso seja feito
         para busca o valor da moeda conforme o m?s em que esta calculando
      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      if ((wvalormoeda is null) or (wvalormoeda = 0) or (position('UFIR',upper(wdescmoeda)) = 0))  then
        begin
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'0101';
          wrefmoedafim = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'1231';
    
          select max(tind.bdvalind) from tindval tind
                 where (tind.bdcodind = :wcodmoeda) and
                       (tind.bdrefind between :wrefmoedaini and :wrefmoedafim)
          into :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          if (wvalormoeda is null) then
            begin
              select first 1 tind.bdvalind from tindval tind
                     where tind.bdcodind = :wcodmoeda and
                     tind.bdrefind <= :wrefmoedaini
                     order by tind.bdrefind
              into :wvalormoeda;
            end
        end*/

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((COALESCE(prtaxadepreciacaoanual,0) = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        --#alt:16415 - Alterada a verifica??o do case, pois quando n?o havia nehuma contabiliza??o ele n?o levava o valor do bem. Ana - 05/12/2016
        --Faz o select com o First, pois um bem pode ter mais de uma deprecia??o cadastrada.
        --alt:14255 - 28/06/2016 - Adicionado case para verificar o tipo da contabiliza??o e ver de onde ir? buscar valor da aquisi??o. Pedro
        --SELECT FIRST 1 tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem,
        SELECT FIRST 1 tbem.bdcodorigbem, COALESCE(CASE WHEN ((tdep.BDCONTABILIZACAO = 0) OR (tdep.BDCONTABILIZACAO IS NULL) ) THEN tbem.BDVALAQUIBEM ELSE tdep.BDVALAQUISOC END, 0),
               tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem, tbem.bddepmesbaixabem,
               tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, COALESCE(tdep.bdvaldepacumubem,0),tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :wtaxaaux,         :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,     :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre, :wnumdias,        :wdepdiadata;

      --alt:13784 - 12/04/2016 - Se tiver trocado de taxa de deprecia??o, precisa levar os meses j? depreciados com a taxa anterior para o c?lculo da pr?xima. Pedro
      IF ((wtaxaant <> 0) AND (wtaxaant <> wtaxaaux)) THEN
        BEGIN
          wmesesdepreciadosoutrataxa = prmesesdepreciados;
          --alt:13784 - 12/04/2016 - Se estiver marcado para detalhar por taxa de deprecia??o, precisa retornar aqui a taxa. Pedro
          IF (prdetalhartaxadep = 1) THEN
            BEGIN
              prmesesdepreciar = prtotalmesesdepreciacao - prmesesdepreciados;
              prsomardepreciacao = 0; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
              SUSPEND;
            END
        END

      --alt:15793 - 22/09/2016 - Se tiver informa??o de deprecia??o em outra taxa ou valor acumulado, n?o ? o primeiro m?s a depreciar,
      --ent?o precisa mudar o valor desta vari?vel, pois estava calculando incorretamente a deprecia??o acumulada atual nestes casos. Pedro
      wFirst = IIF((wvaldepacumubem = 0) AND (wmesesdepreciadosoutrataxa = 0) AND (wFirst = 'TRUE'), 'TRUE', 'FALSE');

      --#alt:16929 - Quando h? um valor de deprecia??o acumulada cadastrado deve ser substituido pelo valor da deprecia??o acumulada anterior ao per?odo. Ana - 01/02/2017
      wdatainimes = SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                    SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
      wdatainicialcalculo = SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                            SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

      wdiasdepreciados = DATEDIFF(DAY,:wdatainicialcalculo,:wdatainimes);

      IF ((wdiasdepreciados < 30) AND (wdepreciacaoacumuladaanterior > 0) AND ((wdiasdepreciados > -1) OR (prdepreciacaoacumuladaanterior <> wdepreciacaoacumuladaanterior)) )THEN
        prdepreciacaoacumuladaanterior = wvaldepacumubem;
      --#alt:16929. fim

      SELECT prdepreciacaoperiodo, prdepreciacaoperiodomoeda, prcorrecaomonetariadepreciacao,
             prvalorresidualcontabil, prvalorresidualcontabilmoeda, prtotalmesesdepreciacao,
             prmesesdepreciados, prmesesdepreciar, prtaxadepreciacaoanual, prdatataxadepreciacao, prvalorbaixa,
             prdepreciacaobaixamoeda, prvalorbaixareal, prvalormoeda, prdatabaixa, prvaloraquisicaomoeda, prvalorcorrigidoanteriormoeda,
             prvaloraquisicaooriginal, prctadebitodepre, prvalordepreciacaodiariafim, prvalorcorrigidoanterior,
             prvalorcorrigidoatual, prdepreciacaoacumuladaanterior, prdepreciacaoacumuladaatualmoed, prdepreciacaoacumuladaatual, prcompensacaobaixaperanterior
      FROM sp_cons_calc_dep_correcao(:prcodemp, :prcodbem, :wdtini, :wdtfim, :prtipo, :prcontabilizacao,:wvalormoeda,:wpossuibaixa,:wcodbemoriginal,
                                     :prvaloraquisicaooriginal,:wtaxaaux,:wdataaquisicao,:wdataorigaquisicao,:wdepdia,:wdepmensal,
                                     :wdepmesbaixa,:wdatainiciocalc,:wdatafimcalc,:wdataultimoitemdep,:wvaldepacumubem,:prctadebitodepre,:wnumdias,
                                     :wdepdiadata, :wvalorbaixabem, :wmesesdepreciadosoutrataxa, :prdepreciacaoacumuladaatual)
      INTO   :wdepreciacaoperiodo, :wdepreciacaoperiodomoeda, :wcorrecaomonetariadepreciacao,
             :wvalorresidualcontabil, :wvalorresidualcontabilmoeda, :prtotalmesesdepreciacao,
             :wmesesdepreciados, :prmesesdepreciar, :prtaxadepreciacaoanual, :prdatataxadepreciacao, :wvalorbaixa, 
             :wdepreciacaobaixamoeda, :wvalorbaixareal, :prvalormoeda, :prdatabaixa, :wvaloraquisicaomoeda, :wvalorcorrigidoanteriormoeda, 
             :prvaloraquisicaooriginal, :prctadebitodepre, :prvalordepreciacaodiariafim, :wvalorcorrigidoanterior,
             :wvalorcorrigidoatual, :wdepreciacaoacumuladaanterior, :wdepreciacaoacumuladaatualmoed, :wdepreciacaoacumuladaatual, :prcompensacaobaixaperanterior;

      --#alt:16929 - Alterada verifica??o para substituir o valor da deprecia??o acumuludada anterior.
      -- Quando h? uma deprecia??o acumulada anterior cadastrada na taxa de deprecia??o, ent?o esta deve ser substituida. Ana - 31/01/2017
      --#Alt:5105 -> Acrescentado a vari?vel wfirst
      IF ((prdepreciacaoacumuladaanterior = 0)  AND (wdepreciacaoacumuladaanterior > 0) AND (wvaldepacumubem <> 0) /*AND (wfirst = 'TRUE')*/) THEN
        BEGIN
          wdepreciacaoacumuladaanterior = ABS(wdepreciacaoacumuladaanterior - prdepreciacaoacumuladaanterior);
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoacumuladaanterior;

          IF (wfirst = 'TRUE') THEN
          prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior;
        END
      wfirst = 'FALSE';

      IF (((wtaxaaux = prtaxadepreciacaoanual) OR (wtaxaaux = 0)) AND (prdepreciacaoacumuladaatualmoed = 0)) THEN
        BEGIN
          wdepreciacaoacumuladaatualmoed = ABS(wdepreciacaoacumuladaatualmoed - wdepreciacaoperiodomoeda);
          IF (wdepreciacaoacumuladaatualmoed > 0) THEN
            prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoacumuladaatualmoed;
        END

      IF ((wvalorcorrigidoanterior > 0) AND (prvalorcorrigidoanterior = 0)) THEN
        prvalorcorrigidoanterior = wvalorcorrigidoanterior;

      IF ((wvalorcorrigidoanteriormoeda > 0) AND (prvalorcorrigidoanteriormoeda = 0)) THEN
        prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;

      prdepreciacaoperiodo            = prdepreciacaoperiodo + COALESCE(wdepreciacaoperiodo,0);
      prdepreciacaoperiodomoeda       = prdepreciacaoperiodomoeda + COALESCE(wdepreciacaoperiodomoeda,0);
      prcorrecaomonetariadepreciacao  = prcorrecaomonetariadepreciacao + COALESCE(wcorrecaomonetariadepreciacao,0);

      --alt:14761 - 20/06/2016 - Quando h? baixa, pode n?o haver deprecia??o no per?odo, ent?o estava sendo calculado incorretamente. Pedro
      --alt:14624 - 14/06/2016 - Aparentemente estava somando novamente a deprecia??o do per?odo porque vinha
      --errado do sp_cons_calc_dep_correcao, por?m agora vem certo e estava somando valor de um m?s a mais. Pedro
      --prdepreciacaoacumuladaatual     = prdepreciacaoacumuladaatual + COALESCE(wdepreciacaoperiodo,0);
      --prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + COALESCE(wdepreciacaoperiodomoeda,0);
      --prdepreciacaoacumuladaatual     = prdepreciacaoacumuladaanterior + COALESCE(wdepreciacaoperiodo,0);
      --prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatual / COALESCE(wvalormoeda,0);

      --#alt:18200 - Comentado pois foram feitas altera??es na sp_cons_calc_dep_correcao que n?o h? mais necessidade de fazer esta verifica??o. Ana - 04/05/2017
      --alt:16006 - 03/11/2016 - S? deve carregar o saldo anterior no caso de ter baixa e n?o depreciar neste m?s, caso contrario, se estiver calculando mais de um m?s de uma vez, o saldo anterior vem incorreto. Pedro
      /*if ((wdepmesbaixa <> 'TRUE') and (wvalorbaixa > 0)) then
        prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;  */
      --alt:14624 - Fim

      --#alt:16852 - Quando n?o tiver uma taxa cadastrada ent?o deve levar o valor correto do valo residual que ? o valor original do bem - o total de baixas. Ana - 01/02/2017
      IF (prtotalmesesdepreciacao = 0) THEN
        prvalorresidualcontabil = wvalorresidualcontabil;
      ELSE
      IF (wvalorresidualcontabil > 0) THEN
        BEGIN
          wvalorresidualcontabil = ABS(wvalorresidualcontabil - prvalorresidualcontabil);
          --alt:16006 - 23/11/2016 - Corrigido para trazer o valor residual considerando quando houver baixa. Pedro
          --IF ((prvalorresidualcontabil > 0) AND (wdepreciacaoperiodo > 0) AND (wvalorresidualcontabil <> wdepreciacaoperiodo)) THEN
          --  wvalorresidualcontabil = wdepreciacaoperiodo;

          IF (wvalorresidualcontabil > 0) THEN
            prvalorresidualcontabil = ABS(prvalorresidualcontabil - wvalorresidualcontabil);
        END

      --#alt:16852 - Quando o valor da aquisi??o for o mesmo do valor residual o valor residual moeda ja vem correto da sp. Ana - 10/02/2017
      IF (prvaloraquisicaooriginal = prvalorresidualcontabil) THEN
        prvalorresidualcontabilmoeda = wvalorresidualcontabilmoeda;
      ELSE
      IF (wvalorresidualcontabilmoeda > 0) THEN
        BEGIN
          wvalorresidualcontabilmoeda = ABS(wvalorresidualcontabilmoeda - prvalorresidualcontabilmoeda);
          --alt:16006 - 23/11/2016 - Corrigido para trazer o valor residual considerando quando houver baixa. Pedro
          --IF ((prvalorresidualcontabilmoeda > 0) AND (wdepreciacaoperiodomoeda > 0) AND (wvalorresidualcontabilmoeda <> wdepreciacaoperiodomoeda)) THEN
          --  wvalorresidualcontabilmoeda = wdepreciacaoperiodomoeda;

          IF (wvalorresidualcontabilmoeda > 0) THEN
            prvalorresidualcontabilmoeda = ABS(prvalorresidualcontabilmoeda - wvalorresidualcontabilmoeda);
        END

      --alt:14761 - 20/06/2016 - Se tiver baixa no per?odo tamb?m precisa retornar os meses depreciados. Pedro
      --alt:14761 - 16/06/2016 - Se tiver valor de deprecia??o acumulada (informado no cadastro da deprecia??o)
      --? feito um c?lculo da quantidade de meses j? depreciados e assim precisa retornar eles tamb?m. Pedro
      IF ((wdepreciacaoperiodo > 0) OR (wvaldepacumubem > 0) OR (wvalorbaixa > 0)) THEN
        BEGIN
          IF ((wtaxaaux > 0) AND (wtaxaaux <> prtaxadepreciacaoanual)) THEN
            wmesesdepreciadosaux = wmesesdepreciadosaux + ABS(wmesesdepreciadosaux - prmesesdepreciados);

          IF ((wmesesdepreciados > 0) AND ((prmesesdepreciados = 0) OR (wmesesdepreciados > prmesesdepreciados))) THEN --alt:13784 - 12/04/2016 - Quando trocada a taxa de deprecia??o n?o estava levando os meses depreciados corretamente. Pedro
            prmesesdepreciados = wmesesdepreciados;
          --alt:9013 - Comentado pois essa valida??o n?o faz sentido quando ? deprecia??o di?ria. Pedro
          /*else
            if (not prmesesdepreciados = prtotalmesesdepreciacao) then
               prmesesdepreciados = prmesesdepreciados + 1; */
        END

      IF (wvalorbaixa > 0) THEN
        BEGIN
          --#alt:18200 - Comentado pois desta forma estava calculando o valor da baixa incorretamente. Ana - 04/05/2017
          --wvalorbaixa = ABS(wvalorbaixa - prvalorbaixa);
          IF (wvalorbaixa > 0) THEN
            prvalorbaixa = prvalorbaixa + wvalorbaixa;
        END

      IF (wdepreciacaobaixamoeda > 0) THEN
        BEGIN
          wdepreciacaobaixamoeda = ABS(wdepreciacaobaixamoeda - prdepreciacaobaixamoeda);
          IF (wdepreciacaobaixamoeda > 0) THEN
            prdepreciacaobaixamoeda = prdepreciacaobaixamoeda + wdepreciacaobaixamoeda;
        END

      IF (wvalorbaixareal > 0) THEN
        BEGIN
          wvalorbaixareal = ABS(wvalorbaixareal - prvalorbaixareal);
          IF (wvalorbaixareal > 0) THEN
            prvalorbaixareal = prvalorbaixareal + wvalorbaixareal;
        END

      IF (wvaloraquisicaomoeda > 0) THEN
        BEGIN
          wvaloraquisicaomoeda = ABS(wvaloraquisicaomoeda - prvaloraquisicaomoeda);
          IF (wvaloraquisicaomoeda > 0) THEN
            prvaloraquisicaomoeda = ABS(prvaloraquisicaomoeda - wvaloraquisicaomoeda);
        END

      IF (wvalorcorrigidoatual > 0) THEN
        BEGIN
          --#alt:18200 - O valor ja vem correto da sp_cons_calc_dep_correcao com as novas altera??es. Ana - 02/05/2017
          prvalorcorrigidoatual = wvalorcorrigidoatual;
          /*wvalorcorrigidoatual = ABS(wvalorcorrigidoatual - prvalorcorrigidoatual);
          IF (wvalorcorrigidoatual > 0) THEN
            prvalorcorrigidoatual = ABS(prvalorcorrigidoatual - wvalorcorrigidoatual);*/
          --#alt:18200. fim
        END

      --#alt:19501 - Foi feito o tratamento na sp de corre??o para quando o bem estiver totalmente baixado e n?o for o m?s da baixa total, ent?o todos os saldos devem ser zerados. Ana - 22/09/2017
      IF ((wdepreciacaoperiodo = 0) AND (wdepreciacaoacumuladaatual = 0) AND (prdepreciacaoacumuladaanterior <> 0) AND (prvalorbaixa = 0) ) THEN
        BEGIN
          prdepreciacaoacumuladaanterior = 0;
          prdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * wvalormoeda);
          --se n?o tiver baixa no per?odo da consulta, ent?o o bem ja foi totalmente baixado. Com isso o saldo anterior, valor residual e valor residual moeda devem ir zerados
          IF (wpossuibaixa = 'FALSE') THEN
            BEGIN
              prdepreciacaoacumuladaatual  = 0;
              prvalorresidualcontabil      = 0;
              prvalorresidualcontabilmoeda = 0;
            END
        END
      ELSE
        IF ((prdepreciacaoacumuladaatual = 0) OR (wdepreciacaoacumuladaatual <> 0)) THEN
        BEGIN
          --antes o valor de retorno da sp era setado direto na vari?vel de retorno, mas n?o deve substituir sempre
          prdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual;
        END
      --#alt:19501. fim

      IF (prdatabaixa IS NOT NULL) THEN
        BEGIN
          wdtbaixaaux = prdatabaixa;
          --#alt:19501 - Atribui ? vari?vel o valor true quando possuir alguma baixa no per?odo. Colocando como true n?o interfere na sp da corre??o, pois la dentro ? refeita esta verifica??o. Ana - 22/09/2017'
          wpossuibaixa = 'TRUE';
        END

      wtaxaant = wtaxaaux;
      wtaxaaux = COALESCE(prtaxadepreciacaoanual,0);
      wdtini   = addmonth(wdtini, 1);
      wdtfim   = addmonth(wdtini, 1)-1;
      IF (wdtfim > prdatafinal) THEN
        wdtfim = prdatafinal;
      wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  --#alt:18200 - Alterada forma de c?lculo do valor corrigido atual (valor corrigido anterior + corre??o do per?odo - valor de baixas do per?odo). Ana - 02/05/2017
  prvalorcorrigidoatual = (prvalorcorrigidoanterior + prcorrecaoperiodo - prvalorbaixa);

  --#alt:19501 - Se o valor corrigido atual for zero, ent?o o bem ja foi totalmente depreciado/baixado. Ana - 22/09/2017
  IF (prvalorcorrigidoatual = 0) THEN
    BEGIN
      prcorrecaomonetariadepreciacao = 0;
      prvalorresidualcontabil        = 0;
      prvalorresidualcontabilmoeda   = 0;
    END

  prtotalmesesdepreciacao = prtotalmesesdepreciacao + wmesesdepreciadosaux;
  --alt:11609 - 21/10/2015 - Corrigido, estava retornando o valor incorreto para o meses a depreciar. H? um outro c?lculo 
  --que ? feito na vari?vel wmesesdepreciados que n?o estava sendo propagado por pegar o valor do prmesesdepreciados. Pedro
  prmesesdepreciar        = prtotalmesesdepreciacao - prmesesdepreciados; --alt:13978 - 06/04/2016 - Voltado como era antes, corrigido o tratamento dos campos. Pedro
  --prmesesdepreciar        = prtotalmesesdepreciacao - wmesesdepreciados;

  --#alt:16929 - Estava trazendo a quantidade de meses depreciados maior que o total de meses de deprecia??o e os meses a depreciar negativo. Ana - 01/02/2017
  IF (prmesesdepreciados > prtotalmesesdepreciacao) THEN
    BEGIN
      prmesesdepreciados = prtotalmesesdepreciacao;
      prmesesdepreciar   = 0;
    END

  --#alt:16852 - Quando n?o tiver uma taxa cadastrada ent?o deve levar o valor correto do valor residual. Quando o valor residual for 0 o residual moeda tamb?m deve ser. Ana - 08/02/2017
  IF (((prtotalmesesdepreciacao = prmesesdepreciados) AND (prtotalmesesdepreciacao > 0)) OR (prvalorresidualcontabil = 0)) THEN
    BEGIN
      prcorrecaomonetariadepreciacao = 0;
      prvalorresidualcontabil        = 0;
      prvalorresidualcontabilmoeda   = 0;
    END

  --#alt:17098 - Com um per?odo maior do que a data da baixa estava retornando null, ent?o se teve alguma baixa durante o per?odo selecionado deve retornar essa data. Ana - 19/05/2017
  IF ((prdatabaixa IS NULL) AND (wdtbaixaaux IS NOT NULL))THEN
    prdatabaixa = wdtbaixaaux;

  --alt:9581 - Joga o valor para a vari?vel de retorno, antes no ?ltimo m?s em alguns casos n?o retornava nada. Pedro
  --prmesesdepreciados = wmesesdepreciados; --alt:13978 - 06/04/2016 - Agora o retorno est? correto acima, e se jogar o valor aqui, mata outro tratamento acima. Pedro

  --#Alt:5105
  IF (prvaloraquisicaooriginal = wvalorbaixabem) THEN
    BEGIN
      prvalorresidualcontabil      = 0;
      prvalorresidualcontabilmoeda = 0;

      IF ((wdepmesbaixa = 'TRUE') AND
          (wreffim > CAST((SUBSTRING(wdtbaixaaux FROM 1 FOR 4)) || (SUBSTRING(wdtbaixaaux FROM 6 FOR 2)) AS INTEGER))) THEN
        BEGIN
          prvalorcorrigidoanterior        = 0;
          prcorrecaoperiodo               = 0;
          prvalorcorrigidoatual           = 0;
          prvalorbaixa                    = 0;
          prdepreciacaoacumuladaanterior  = 0;
          prdepreciacaoperiodo            = 0;
          prdepreciacaoperiodomoeda       = 0;
          prdepreciacaoacumuladaatual     = 0;
          prdepreciacaoacumuladaatualmoed = 0;
          prcorrecaomonetariadepreciacao  = 0;
          prtotalmesesdepreciacao         = 0;
          prmesesdepreciados              = 0;
          prmesesdepreciar                = 0;
        END
    END

  prsomardepreciacao = 1; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
  SUSPEND;
END
^

/* Restore proc. body: SP_CONS_CALC_DEP_CORRECAO */
ALTER PROCEDURE SP_CONS_CALC_DEP_CORRECAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER,
PRVLRMOEDA NUMERIC(15,6),
PRPOSSUIBAIXA VARCHAR(5),
PRCODBEMORIGINAL INTEGER,
PRVALORAQUISICAO NUMERIC(15,6),
PRTAXADEPANUAL NUMERIC(6,6),
PRDATAAQUISICAO DATE,
PRDATAORIGAQUISICAO DATE,
PRDEPDIA VARCHAR(5),
PRDEPMENSAL VARCHAR(5),
PRDEPMESBAIXA VARCHAR(5),
PRDATAINICIOCALC DATE,
PRDATAFIMCALC DATE,
PRDATAULTIMOITEMDEP DATE,
PRVALDEPACUMUBEM NUMERIC(15,6),
PRCTADEBDEPRE INTEGER,
PRNUMDIAS INTEGER,
PRDEPDIADATA INTEGER,
PRVALORBAIXABEM NUMERIC(15,6),
PRMESESDEPRECIADOSOUTRATAXA INTEGER,
PRVALORACUMULADOANTERIOR NUMERIC(15,6))
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,6),
PRCORRECAOPERIODO NUMERIC(15,6),
PRVALORCORRIGIDOATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6),
PRDEPRECIACAOPERIODO NUMERIC(15,6),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6),
PRVALORRESIDUALCONTABIL NUMERIC(15,6),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,6),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,6),
PRVALORBAIXAREAL NUMERIC(15,6),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,6),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,6),
PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOPERIODO DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED DOUBLE PRECISION;
DECLARE VARIABLE WVALORRESIDUALCONTABIL DOUBLE PRECISION;
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WDIASDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WVALORAQUISICAO DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOAUX DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOORIGINAL DOUBLE PRECISION;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAATUAL DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALORBAIXA DOUBLE PRECISION;
DECLARE VARIABLE WVALORBAIXAAUX DOUBLE PRECISION;
DECLARE VARIABLE WVALORBAIXAPER DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPDIASADEPRECIAR INTEGER;
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WTOTALMESESDOPERIODO INTEGER;
DECLARE VARIABLE WVALORDEPRECIACAOMENSAL DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPRECIACAODIARIA DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPRECIACAODIARIABAIXA DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDIFERENCAMESES INTEGER;
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WVALDEPACUMUBEM DOUBLE PRECISION;
DECLARE VARIABLE WMESESDEPACUMUBEM INTEGER;
DECLARE VARIABLE WDATAOFICIALINICIOLCALCULO DATE;
DECLARE VARIABLE WDATAINICIALINICIOCALCULO DATE;
DECLARE VARIABLE WULTIMODIADOMES SMALLINT;
DECLARE VARIABLE WDIA SMALLINT;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WDEPDIADATA INTEGER;
DECLARE VARIABLE WDATAINICIALOFICIAL DATE;
DECLARE VARIABLE WDEPDIAFINAL VARCHAR(5);
DECLARE VARIABLE WDATATOTALMESESULTIMODIA DATE;
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATATOTALMESESDEPDIA DATE;
DECLARE VARIABLE WVALORCORRIGIDOANTERIORMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WVERIFICAMESINTEIRO INTEGER;
DECLARE VARIABLE WDIASDEPDIARIA DOUBLE PRECISION;
DECLARE VARIABLE WMESESDEPDIARIA DOUBLE PRECISION;
DECLARE VARIABLE WDATAINICIOCALCAUX DATE;
BEGIN
  /*Stored procedure para calcular a deprecia??o dos bens*/
  -- Inicializa par?metros
  PRVALORCORRIGIDOANTERIOR        = 0;
  PRCORRECAOPERIODO               = 0;
  PRVALORCORRIGIDOATUAL           = 0;
  PRDEPRECIACAOACUMULADAANTERIOR  = 0;
  PRDEPRECIACAOPERIODO            = 0;
  PRDEPRECIACAOPERIODOMOEDA       = 0;
  PRDEPRECIACAOACUMULADAATUAL     = 0;
  PRDEPRECIACAOACUMULADAATUALMOED = 0;
  PRCORRECAOMONETARIADEPRECIACAO  = 0;
  PRVALORRESIDUALCONTABIL         = 0;
  PRVALORRESIDUALCONTABILMOEDA    = 0;
  PRTOTALMESESDEPRECIACAO         = 0;
  PRMESESDEPRECIADOS              = 0;
  PRMESESDEPRECIAR                = 0;
  PRTAXADEPRECIACAOANUAL          = 0;
  PRDATATAXADEPRECIACAO           = NULL;
  PRVALORBAIXA                    = 0;
  PRDEPRECIACAOBAIXAMOEDA         = 0;
  PRVALORBAIXAREAL                = 0;
  PRVALORMOEDA                    = 0;
  PRDATABAIXA                     = NULL;
  PRVALORAQUISICAOMOEDA           = 0;
  PRVALORCORRIGIDOANTERIORMOEDA   = 0;
  PRVALORAQUISICAOORIGINAL        = 0;
  PRCTADEBITODEPRE                = NULL;
  PRVALORDEPRECIACAODIARIAFIM     = 0;

  -- Inicializa vari?veis
  wdatainicialoficial            = prdatainicial;
  wdepdiafinal                   = 'FALSE';
  wnumdias                       = 0;
  wdepdiadata                    = 0;
  wultimodiadomes                = 0;
  wdepdiasadepreciar             = 0;
  wvalordepreciacaodiaria        = 0;
  wvalordepreciacaodiariabaixa   = 0;
  wvaloraquisicaomoeda           = 0;
  wvalorcorrigidoanterior        = 0;
  wdepreciacaoacumuladaanterior  = 0;
  wdepreciacaoperiodo            = 0;
  wdepreciacaoperiodomoeda       = 0;
  wdepreciacaoacumuladaatual     = 0;
  wdepreciacaoacumuladaatualmoed = 0;
  wvalorresidualcontabil         = 0;
  wvalorresidualcontabilmoeda    = 0;
  wtotalmesesdepreciacao         = 0;
  wmesesdepreciados              = 0;
  wdiasdepreciados               = 0;
  wmesesdepreciar                = 0;
  wvaloraquisicao                = 0;
  wvaloraquisicaoaux             = 0;
  wvaloraquisicaooriginal       = 0;
  wdataaquisicao                 = NULL;
  wdatainiciocalc                = NULL;
  wdatafimcalc                   = NULL;
  wdataatual                     = :prdatafinal;
  wdatatotalmeses                = NULL;
  wdatatotalmesesdepdia          = NULL;
  wdatatotalmesesultimodia       = NULL;
  wdataultimoitemdep             = NULL;
  wvalorbaixa                    = 0;
  wvalorbaixaaux                 = 0;
  wvalorbaixaper                 = 0;
  wvaldepacumubem                = 0;
  wmesesdepacumubem              = 0;
  wdataoficialiniciolcalculo     = NULL;
  wdatainicialiniciocalculo      = NULL;
  --alt:16494 - 25/11/2016 - Inicializar a vari?vel, ficava null quando calculava um per?odo antes do in?cio
  --da deprecia??o, assim os meses que deveriam depreciar concatenava com null e ficava sempre null. Pedro
  prvaloracumuladoanterior       = COALESCE(prvaloracumuladoanterior, 0);

  -- Para melhorar o desempenho da rotina esse select foi jogado na Stored Procedure SP_CONS_CALC_DEP para ser chamada apenas quando
  -- for necess?ria. As informa??es do select est?o sendo passadas por par?metro
  /*select tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem,
         tbem.bddepmesbaixabem, tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, tdep.bdvaldepacumubem,tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
  from empresas_tbem tbem
  left outer join empresas_tdepreciacao tdep on ((tbem.bdcodemp = tdep.bdcodemp) and (tbem.bdcodbem = tdep.bdcodbem) and
                                                 (tdep.bdcontabilizacao = :prcontabilizacao) and
                                                 (Cast((substring(tdep.bddatinicalcbem from 1 for 4)) || (substring(tdep.bddatinicalcbem from 6 for 2)) as integer) <=
                                                  Cast((substring(:prdatainicial from 1 for 4)) || (substring(:prdatainicial from 6 for 2)) as integer)) and
                                                 ((Cast((substring(tdep.bddatfimcalcbem from 1 for 4)) || (substring(tdep.bddatfimcalcbem from 6 for 2)) as integer) >=
                                                   Cast((substring(:prdatafinal from 1 for 4)) || (substring(:prdatafinal from 6 for 2)) as integer)) or (tdep.bddatfimcalcbem is null)))
  where (tbem.bdcodemp = :prcodemp) and
        (tbem.bdcodbem = :prcodbem)
  into :wcodbemoriginal, :wvaloraquisicao,    :prtaxadepreciacaoanual,
       :wdataaquisicao,  :wdataorigaquisicao, :wdepdia,            :wdepmensal, : wdepmesbaixa,
       :wdatainiciocalc, :wdatafimcalc,       :wdataultimoitemdep, :wvaldepacumubem, :prctadebitodepre, :wnumdias, :wdepdiadata;*/
  --wcodbemoriginal        = prcodbemoriginal;
  wvaloraquisicao        = prvaloraquisicao;
  wvaloraquisicaooriginal= wvaloraquisicao;
  prtaxadepreciacaoanual = prtaxadepanual;
  wdataaquisicao         = prdataaquisicao;
  wdataorigaquisicao     = prdataorigaquisicao;
  wdepdia                = prdepdia;
  wdepmensal             = prdepmensal;
  wdepmesbaixa           = prdepmesbaixa;
  wdatainiciocalc        = prdatainiciocalc;
  wdatafimcalc           = prdatafimcalc;
  wdataultimoitemdep     = prdataultimoitemdep;
  wvaldepacumubem        = prvaldepacumubem;
  prctadebitodepre       = prctadebdepre;
  wnumdias               = prnumdias;
  wdepdiadata            = prdepdiadata;
  wdepreciacaoacumuladaatual = prvaloracumuladoanterior;

  IF (wvaloraquisicao IS NULL) THEN
     BEGIN
       EXCEPTION ex_date;
       SUSPEND;
       EXIT;
     END

   IF (prdatainicial > wdatafimcalc) THEN
     EXIT;

  --alt:16006 - 03/11/2016 - Implementado aqui o c?lculo da baixa de todos os per?odos. Pedro
  --Processo para calcular os meses anteriores ao per?odo informado, pois posso ter v?rias deprecia??es cadastradas
  SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  AND   (tbai.BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
  INTO :wvalorbaixa;
  IF (wvalorbaixa > 0) THEN
    prpossuibaixa = 'TRUE';

  --#alt:85169. Deve fazer os outros c?lculos. Ana - 20/06/2018
  --Tipo 2 somente baixas
  /*IF ((prtipo = 2) AND (wvalorbaixa = 0)) THEN
    EXIT;*/
  --alt:16006 - Fim

  prvaloraquisicaooriginal = wvaloraquisicao;
  /*#Alt:5105. Conforme visto com o Celso quando o bem tem alguma baixa parcial o sistema calcula a depreci??o desde o in?cio levando em conta
  a baixa, e n?o apenas no m?s da baixa pra frente.*/
  --wvalorbaixa = 0;
  --wvalorbaixa = prvalorbaixabem; --alt:16006 - Calcula aqui o valor da baixa. Pedro
  IF (prpossuibaixa = 'TRUE') THEN
    BEGIN
      FOR SELECT bddatbai,COALESCE(SUM(bdvalbai),0) AS TotalBaixa FROM empresas_tbai
          WHERE (bdcodemp = :prcodemp) AND (bdcodbem = :prcodbem) AND (BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
          AND   (bddatbai BETWEEN :prdatainicial AND :prdatafinal) GROUP BY bddatbai
          INTO :wdatabaixa,:wvalorbaixaaux DO
        BEGIN
          --#Alt:5105
          --wvalorbaixa = wvalorbaixa + wvalorbaixaaux;
          wvalorbaixaper = wvalorbaixaper + wvalorbaixaaux;
        END
    END
  wvaloraquisicao = (wvaloraquisicao - wvalorbaixa);

  --alt:8005 - Foi removida esta valida??o porque n?o faz sentido e fazia com que n?o funcionasse corretamente em alguns casos. Pedro
  IF ((UPPER(wdepmesbaixa) = 'TRUE') /*and (wvalorbaixa >= wvaloraquisicao)*/) THEN
    BEGIN
      --alt:8005 - Foi removido porque n?o faz sentido setar um ano igual ao outro sendo que vai comparar os dois depois, isso fazia com que n?o funcionasse corretamente em alguns casos. Pedro
      --prdatafinal = wdatabaixa;

      --alt:8005 - Estava ocorrendo um erro no m?s da baixa, por isso foi adicionada a valida??o do "wdatabaixa is null".
      --Mas isso gerou outro problema agora e aparentemente o problema que acontecia antes n?o ocorreu mais, ent?o retirei. Pedro
      IF ((CAST((SUBSTRING(wdatabaixa FROM 1 FOR 4)) || (SUBSTRING(wdatabaixa FROM 6 FOR 2)) AS INTEGER) <=
          CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER))) THEN
        wdepmesbaixa = 'TRUE';
      ELSE
        wdepmesbaixa = 'FALSE';
    END
  ELSE
    wdepmesbaixa = 'FALSE';

  --alt:9013 - Foi colocado aqui o c?lculo do valor corrigido atual, pois precisava ser antes de juntar novamente o valor da baixa ao valor da aquisi??o. Pedro
  -- C?LCULO DE DEPRECIA??O
  prcorrecaoperiodo     = 0;

  --#alt:18200. Desta forma que estava retornando o valor n?o estava correta. Ana - 02/05/2017
  --#alt:16852 - Adicionada verifica??o para retornar o valor da baixa do per?odo quando tiver taxa cadastrada, pois estava calculando errado o valor residual. Ana - 01/02/2017
  /*if (prtaxadepanual <> 0) then
    prvalorcorrigidoatual = wvalorbaixaper;
  else
    prvalorcorrigidoatual = wvalorbaixa;*/

  --alt:9581 - Foi alterado para jogar devolta apenas a baixa do per?odo, n?o a baixa de todos os per?odos,
  --pois quando tinha mais de uma baixa e estava marcada a op??o calcular deprecia??o do m?s da baixa ele trazia o valor original para a deprecia??o do m?s,
  --sendo que deveria ser o valor original menos baixas que tenham ocorrido em per?odo anterior. Pedro
  IF ((UPPER(wdepmesbaixa) = 'TRUE') /*and (wdatabaixa is null)*/) THEN
    --wvaloraquisicao = (wvaloraquisicao + wvalorbaixa);
    wvaloraquisicao = (wvaloraquisicao + wvalorbaixaper);

  --alt:9581 - Implementado aqui, pois se cair no exit precisa retornar a quantidade de meses depreciados. Pedro
  IF (wdatainiciocalc IS NOT NULL) THEN
    wdataoficialiniciolcalculo = wdatainiciocalc;
  ELSE
    wdataoficialiniciolcalculo =  wdataaquisicao;

  -- Meses j? depreciados
  wmesesdepreciados = DATEDIFF(MONTH,:wdataoficialiniciolcalculo,:wdataatual);
  IF (wmesesdepreciados < 0) THEN
    wmesesdepreciados = 0;

  --#alt:16929 - Adicionada verifica??o para atribuir o valor do campo cadastrado na depreci??o acumulada, pois estava ignorando este campo e fazendo os calculos errados. Ana - 31/01/2017
  wdatainicialoficial = SUBSTRING(CAST(prdatainicial AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                        SUBSTRING(CAST(prdatainicial AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
  wdatainicialiniciocalculo = SUBSTRING(CAST(wdataoficialiniciolcalculo AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdataoficialiniciolcalculo AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

  wdiasdepreciados = DATEDIFF(DAY,:wdatainicialiniciocalculo,:wdatainicialoficial);
  IF ((wvaldepacumubem <> 0) AND ((wdiasdepreciados < 30) AND ((wvaldepacumubem <> prdepreciacaoacumuladaanterior) OR (wdiasdepreciados > -1)))) THEN
    wdepreciacaoacumuladaatual = wVALDEPACUMUBEM;
  wdatainicialoficial = prdatainicial;
  --#alt:16929. fim

  --alt:13784 - 12/04/2016 - Implementado para contar corretamente no caso de ter duas taxas de deprecia??o distintas. Pedro
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) /*>*/=
      CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER)) THEN
    wmesesdepreciados = wmesesdepreciados + 1;

  IF (prmesesdepreciadosoutrataxa > 0) THEN --alt:13784 - 12/04/2016 - Se j? tiver depreciado algum m?s com a taxa anterior, precisa somar esses meses tamb?m. Pedro
    wmesesdepreciados = wmesesdepreciados + prmesesdepreciadosoutrataxa;
  --alt:13784 - Fim

  prmesesdepreciados = wmesesdepreciados;
  --alt:9581 - Fim

  IF ((((wvaloraquisicao IS NULL) OR (wvaloraquisicao <= 0))) AND (UPPER(wdepmesbaixa) = 'FALSE')) THEN
     BEGIN
       --alt:14624 - 27/05/2016 - Se tiver baixa no per?odo, precisa calcular o valor depreciado at? ent?o. Pedro
       --alt:14761 - 20/06/2016 - Adicionados par?metros remanescentes. Pedro
       --alt:15375 - 12/08/2016 - Adicionada verifica??o do valor da aquisi??o, este processo ? executado no cadastro de deprecia??o
       --para verificar se h? valor depreciado anterior a ele, e como n?o possui valor da aquisi??o ainda, ocorre erro. Pedro
       ------- if ((wvaloraquisicao is not null) and (wvaloraquisicao > 0)) then  **** Essa regra estava dando problema. Foi comentado porque n?o conseguiram explicar a raz?o dela (Solicita??o.: 15605)
       --#alt:15259 - Quando o valor vinha zerado gerava um erro. Ana - 16/09/2016
       IF ( prtaxadepreciacaoanual <> 0) THEN
         BEGIN
           wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
           wvalordepreciacaomensal = (prvaloraquisicao / wtotalmesesdepreciacao);
         END

       --#alt:19501 - Se o bem ja foi totalmente baixado ent?o n?o deve possuir deprecia??o acumulada anterior e nem deprecia??o no per?odo, quando consultado em um per?odo ap?s a baixa total. Ana - 21/09/2017
       IF ((wvalorbaixa >= wvaloraquisicaooriginal) AND (wvalorbaixa <> wvalorbaixaper) AND (wvalorbaixaper = 0)) THEN
         BEGIN
           prdepreciacaoacumuladaanterior = 0;
           wdepreciacaoacumuladaatual = wvaloraquisicao;
           wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual;
         END
       ELSE
         BEGIN
           IF ((wvalordepreciacaodiaria > 0) AND (wdatainicialoficial <= :wdataaquisicao))  THEN
             BEGIN
               --alt:16006 - 03/11/2016 - Alterado para carregar o valor acumulado depreciado de uma vari?vel que calcula m?s a m?s, pois quando na aquisi??o utilizava a deprecia??o di?ria, nos meses seguintes desconsiderava este valor. Pedro
               --wdepreciacaoacumuladaatual     = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wmesesdepreciados);
               wdepreciacaoacumuladaatual     = (wvalordepreciacaodiaria + wvalordepreciacaomensal + wdepreciacaoacumuladaatual);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
             END
           ELSE
             BEGIN
               --alt:16006 - 03/11/2016 - Alterado para carregar o valor acumulado depreciado de uma vari?vel que calcula m?s a m?s, pois quando na aquisi??o utilizava a deprecia??o di?ria, nos meses seguintes desconsiderava este valor. Pedro
               --wdepreciacaoacumuladaatual     = (wvalordepreciacaomensal * wmesesdepreciados);
               wdepreciacaoacumuladaatual     = (wvalordepreciacaomensal + wdepreciacaoacumuladaatual);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
             END
    
           --#Alt:5105
           IF (wvalorbaixaper > 0) THEN
             BEGIN
               prdatabaixa  = wdatabaixa;
               prvalorbaixa = wvalorbaixaper;
               wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual - wvalordepreciacaomensal);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
               prdepreciacaoacumuladaanterior = wdepreciacaoacumuladaatual;
    
               --#Alt:16327 (In?cio) - Precisa ser setado o valor corrigido anterior mesmo que o valor do bem j? tenha baixado totalmente. E o
               --valor ? jogado para uma vari?vel local do tipo Double Precision e depois para a de sa?da,
               --pois pode gerar um erro de "Aritmethic Overflow" por calcular um valor grande demais.
               wvalorcorrigidoanterior  = (wvaloraquisicao + wvalorbaixaper);
               prvalorcorrigidoanterior = wvalorcorrigidoanterior;
    
               wvalorcorrigidoanteriormoeda  = (wvaloraquisicao + wvalorbaixaper) / prvlrmoeda;
               prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;
               --#Alt:16327 (Fim)
             END
           ELSE
             prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaatual - wvalordepreciacaomensal;
         END

       prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
       prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
       prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
       --alt:14624 - Fim
       --alt:14761 - Fim
       prcompensacaobaixaperanterior = wdepreciacaoacumuladaatual; --alt:16006 - 24/11/2016 - Tratado para retornar o valor da deprecia??o acumulada para quando tem baixa total. Pedro

       --alt:15196 - 24/11/2016 - Adapta??o para zerar o valor residual da deprecia??o. Pedro
       IF ((prdepreciacaoacumuladaanterior + wtotalmesesdepreciacao) > wvaloraquisicao) THEN
         BEGIN
           IF (prdepreciacaoacumuladaanterior < wvaloraquisicao) THEN
             BEGIN
               wtotalmesesdepreciacao = wvaloraquisicao - prdepreciacaoacumuladaanterior;
               prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior + wtotalmesesdepreciacao;
             END
           ELSE
             BEGIN
               wtotalmesesdepreciacao = 0;
               --#alt:19501 - N?o deve assumir o valor da aquisi??o, pois mesmo que o bem ja tenha sido totalmente baixado ainda h? como depreciar o valor acumulado anterior. Ana - 21/09/2017
               --prdepreciacaoacumuladaatual = wvaloraquisicao;
             END
    
           prdepreciacaoperiodomoeda = wtotalmesesdepreciacao * prvlrmoeda;
           prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatual * prvlrmoeda;
           prdepreciacaoperiodo = wtotalmesesdepreciacao;
         END

       SUSPEND;
       EXIT;
     END

  IF (prtipo = 2) THEN
    BEGIN
      --#alt:85169. Ana - 20/06/2018
      wvaloraquisicaoaux       = wvaloraquisicao;
      if ((wvalorbaixaper > 0) and (wvalorbaixa > 0)) then
        begin
          wvaloraquisicao          = wvalorbaixa;
          --prvaloraquisicaooriginal = wvalorbaixa;
        end
      --#alt:85169. fim
    END

  --alt:9013 - Foi retirado daqui e colocado mais acima, pois quando chegava aqui o valor estava incorreto, baseado no valor original da aquisi??o, desconsiderando a baixa. Pedro
  -- C?LCULO DE DEPRECIA??O
  /*prcorrecaoperiodo     = 0;
  prvalorcorrigidoatual = wvaloraquisicao;*/

  -- Deprecia??o di?ria (In?cio)
  --#alt:19501 - Alterada verifica??o da vari?vel "wNumDias". Ana - 24/10/2017
  --#alt:18200 - N?o estava fazendo a deprecia??o di?ria quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
  --alt:15196 - 24/11/2016 - Adicionada valida??o do "wNumDias", caso esteja selecionado para iniciar a deprecia??o no
  --dia seguinte ? aquisi??o, ter? um dia a menos para depreciar, e n?o ser? mais deprecia??o mensal nesta regra. Pedro
  --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
  --IF ((UPPER(wdepdia) = 'TRUE' ) AND ((SUBSTRING(wdatainiciocalc FROM 9 FOR 2)) = '01')) THEN
  IF ((UPPER(wdepdia) = 'TRUE') AND (wnumdias <= 2) AND
      (((EXTRACT(DAY FROM wdatainiciocalc) = 1) AND (wdatainiciocalc BETWEEN prdatainicial AND prdatafinal)) OR
       ((wdatabaixa BETWEEN prdatainicial AND prdatafinal) AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0)))) THEN
    wdepdia = 'FALSE';

  IF (UPPER(wdepdia) = 'TRUE') THEN
    BEGIN
      --#alt:18200 - Adicionei a verifica??o da diferen?a de meses da baixa para a aquisi??o do bem, pois n?o estava fazendo a deprecia??o di?ria corretamente
      --             quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
      --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
      IF ((wdatabaixa BETWEEN prdatainicial AND prdatafinal) AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0)) THEN
        BEGIN
          --alt:16006 - 03/11/2016 - Se n?o for uma baixa total, ent?o deve dividir o m?s em duas partes para calcular a deprecia??o sobre o valor do bem antes e depois da baixa. Pedro
          IF (wvaloraquisicao <= 0) THEN
            wdepdiasadepreciar = EXTRACT(DAY FROM wdatabaixa);
          ELSE
            wdepdiasadepreciar = EXTRACT(DAY FROM wdatabaixa) -1;
        END
      ELSE
        BEGIN
          -- Total de meses para a deprecia??o
          IF (prtaxadepreciacaoanual >= 0.1) THEN
            wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);

          --#alt:19501 - N?o estava considerando os dias a depreciar quando tem deprecia??o acumulada informada. Ana - 24/10/2017
          IF ((wvaldepacumubem <> 0) AND (wtotalmesesdepreciacao <> 0)) THEN
            BEGIN
              wmesesdepdiaria = (wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
              wverificamesinteiro = (TRUNC(wmesesdepdiaria));
              wdiasdepdiaria = (wmesesdepdiaria - wverificamesinteiro);
              IF (wdiasdepdiaria > 0) THEN
                BEGIN
                  --#alt:21342 - Quando a quantidade de dias depreciados for igual a 0.01 significa que h? um valor de depreci??o di?ria mas n?o fecha em um dia completo.
                  --             para isso truncamos o valor em 0.04 que j? equivale a um dia para conseguir fazer os calculos. Ana - 09/11/2017
                  IF (wdiasdepdiaria < 0.04) THEN
                    wdiasdepdiaria = 0.04;

                  wmes = (ABS((TRUNC((((wmesesdepdiaria)/12) - TRUNC((wmesesdepdiaria)/12)) * 12)-12)+1));
                  wano = (EXTRACT(YEAR FROM wdatainiciocalc));
                  wano = (wano - TRUNC(wverificamesinteiro/12));

                  --#alt:21342 - Tenho que considerar a quantidade de dia de cada m?s e n?o deixar fixo 30 dias. Ana - 13/11/2017
                  SELECT ULTDIA FROM ULTIMO_DIA_MES(:wmes, :wano)
                  INTO :wUltimoDiaDoMes;
                  IF (wUltimoDiaDoMes > 0) THEN
                    wdepdiasadepreciar = (TRUNC(wdiasdepdiaria * wUltimoDiaDoMes));

                  --#alt:21342 - Adicionei a verifica??o dos dias para n?o ocorrer erro na conver??o. Ana - 09/11/2017
                  IF ((wdepdiasadepreciar > 0) AND (wano > 0) AND (wmes > 0) )THEN
                    wdatainiciocalcaux = (CAST(wano AS VARCHAR(4)) ||'-'|| CAST(wmes AS VARCHAR(2)) ||'-'|| CAST(wdepdiasadepreciar AS VARCHAR(2)));
                END
            END
          ELSE
            BEGIN
          wdepdiasadepreciar = EXTRACT(DAY FROM wdatainiciocalc);
              wdatainiciocalcaux = wdatainiciocalc;
            END

          -- C?lculo que retorna o ?ltimo dia do m?s
          --alt:18200 - 22/05/2017 - Corrigido, j? reduz um dia a mais quando ? pra depreciar apenas no dia seguinte. Pedro
          --#alt:18200 - Quando for dia 31 deve considerar como 30 dias e depreciar apenas um dia. Ana - 19/05/2017
          IF (wnumdias = 2) THEN
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatainiciocalcaux - EXTRACT(DAY FROM wdatainiciocalcaux) +
                                                32 - EXTRACT(DAY FROM wdatainiciocalcaux - EXTRACT(DAY FROM wdatainiciocalcaux) + 32)));
          ELSE
            wUltimoDiaDoMes = 30;

          --alt:8005 - Adicionado um dia a mais, pois sempre faltava um dia no c?lculo di?rio. Pedro
          --IF (wnumdias = 2) THEN
          IF (wvaldepacumubem = 0) THEN
            wdepdiasadepreciar = (wultimodiadomes + 1) - wdepdiasadepreciar;
          ELSE
            BEGIN
              --#alt:18204 - Quando o mes tinha 31 dias estava desconciderando o ultimo dia para depreciar. Ana - 28/04/2017
              /*IF (wultimodiadomes = 31) THEN
                wdepdiasadepreciar = (32) - wdepdiasadepreciar;
              ELSE*/
                wdepdiasadepreciar = (30 + 1) - wdepdiasadepreciar;
            END
          --alt:8005 - Fim
          -- Caso a op??o Dia seguinte a aquisi??o esteja selecionada preciso diminuir um dia no
          -- n?mero de dias a depreciar, pois a wdepdiasadepreciar veio calculada conforme
          -- a data de aquisi??o
          IF (wdepdiadata = 2) THEN
            wdepdiasadepreciar = wdepdiasadepreciar - 1;
          IF (wdepdiasadepreciar < 0) THEN
            wdepdiasadepreciar = 0;
        END
      --alt:13156 - Fim
    END
  -- Deprecia??o di?ria (Fim)

  -- Total de meses para a deprecia??o
  IF (prtaxadepreciacaoanual >= 0.1) THEN
    wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
  ELSE
    BEGIN
      --#Alt:16327 - Tamb?m precisamos setar o valor corrigido anterior quando o bem n?o possui taxa de deprecia??o
      wvalorcorrigidoanterior  = (wvaloraquisicao + wvalorbaixaper);
      prvalorcorrigidoanterior = wvalorcorrigidoanterior;

      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / prvlrmoeda;
      --wvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / prvlrmoeda; #Alt:16327 - Alterado a vari?vel "wvalorbaixa" para a "wvalorbaixaper"
      wvalorcorrigidoanteriormoeda  = (wvaloraquisicao + wvalorbaixaper) / prvlrmoeda;
      prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;

      prvalorresidualcontabil       = wvaloraquisicao;

      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvalorresidualcontabilmoeda  = wvaloraquisicao / prvlrmoeda;
      wvalorresidualcontabilmoeda = wvaloraquisicao / prvlrmoeda;
      prvalorresidualcontabilmoeda = wvalorresidualcontabilmoeda;
      
      prdatataxadepreciacao         = wdataultimoitemdep;
      --#Alt:5105
      --prvalorbaixa                  = wvalorbaixa;
      prvalorbaixa                  = wvalorbaixaper;
      prvalorbaixareal              = wvalorbaixa;
      prvalormoeda                  = prvlrmoeda;
      prdatabaixa                   = wdatabaixa;
      
      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvaloraquisicaomoeda         = (wvaloraquisicao / prvlrmoeda);
      wvaloraquisicaomoeda = (wvaloraquisicao / prvlrmoeda);
      prvaloraquisicaomoeda = wvaloraquisicaomoeda;
    
      SUSPEND;
      EXIT;
    END

  IF (wdatainiciocalc IS NOT NULL) THEN
    wdataoficialiniciolcalculo = wdatainiciocalc;
  ELSE
    wdataoficialiniciolcalculo =  wdataaquisicao;

  IF (wvaloraquisicao = 0) THEN
     EXIT;

  -- Joga para vari?vel o n?mero de meses que j? foi depreciado em outro sistema
  IF (prmesesdepreciadosoutrataxa > 0) THEN --alt:13784 - 12/04/2016 - Se j? tiver meses depreciados anteriormente com outras taxas, precisa buscar esses meses. Pedro
    wmesesdepacumubem = prmesesdepreciadosoutrataxa;
  ELSE IF (wvaldepacumubem > 0) THEN
    --#alt:16911 - Alterada formula para o calculo dos meses de deprecia??o acumulada. Ana - 26/01/2016
    --wmesesdepacumubem = (wvaldepacumubem / ( wvaloraquisicao / wtotalmesesdepreciacao ));
    wmesesdepacumubem = (wvaldepacumubem / ( wvaloraquisicaooriginal / wtotalmesesdepreciacao ));

  --wmesesdepacumubem= 24311;
  wdatatotalmeses       = addmonth(wdataoficialiniciolcalculo, wtotalmesesdepreciacao-wmesesdepacumubem);
  wdatatotalmesesdepdia = addmonth(wdatatotalmeses, 1);
  wdatatotalmeses       = SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                          SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
  -- Transforma no primeiro dia do m?s
  wdataaquisicao = SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                   SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

  wdiferencameses = DATEDIFF(MONTH,:wdatatotalmeses,:wdataatual);
  IF (wdiferencameses < 0) THEN
    wdiferencameses = 0;
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >=
      CAST((SUBSTRING(wdataaquisicao FROM 1 FOR 4)) || (SUBSTRING(wdataaquisicao FROM 6 FOR 2)) AS INTEGER)) THEN
    wdiferencameses = wdiferencameses + 1;

  IF (wdiferencameses-1 > 0) THEN
    BEGIN
     IF (wdepmensal = 'FALSE') THEN
       BEGIN
         wdataatual = addmonth(:wdatatotalmeses,1);
         wmes       = CAST(SUBSTRING(CAST(wdataatual AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
         wano       = CAST(SUBSTRING(CAST(wdataatual AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
         wdataatual = wmes||'-01-'||wano;
       END
     ELSE
       wdataatual = wdatatotalmeses;
    END

  IF ((wdepmensal = 'FALSE') AND
      (CAST(EXTRACT(YEAR FROM :prdatainicial) || EXTRACT(MONTH FROM :prdatainicial) AS INTEGER) = CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
    BEGIN
      prdatafinal = addmonth(:prdatafinal,-1);
      wmes       = CAST(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
      wano       = CAST(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
      prdatafinal = wmes||'-01-'||wano;
    END

  -- Se for relatorio de baixas, a data atual devera ser o do mes da baixa.
  --if ((prtipo = 2) or (wdatabaixa is not null)) then
  IF ((prtipo = 2) AND (wdatabaixa IS NOT NULL)) THEN
    BEGIN
      wdataatual  = wdatabaixa;
      prdatafinal = wdatabaixa;
    END

   IF ((wdatafimcalc IS NOT NULL) AND (wdatafimcalc < prdatafinal)) THEN
     BEGIN
       wdataatual  = wdatafimcalc;
       prdatafinal = wdatafimcalc;
     END

  -- Meses j? depreciados
  wmesesdepreciados = DATEDIFF(MONTH,:wdataoficialiniciolcalculo,:wdataatual);
  IF (wmesesdepreciados < 0) THEN
    wmesesdepreciados = 0;


  --#alt:19501 - Devo considerar a deprecia??o di?ria no m?s da aquisi??o, que n?o s?o considerados como m?s cheio e por isso est?o informados nas casas ap?s
  --             a v?rgula. Esta deprecia??o di?ria era desconsiderada para os c?lculos. Ana - 18/10/2017
  IF (wdepdia = 'TRUE') THEN
    BEGIN
  wverificamesinteiro = TRUNC(wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
      wdiasdepdiaria = ((wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao)) - wverificamesinteiro);
    END
  ELSE
    BEGIN
      wverificamesinteiro = TRUNC(wdepreciacaoacumuladaatual/(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
      wdiasdepdiaria = ((wdepreciacaoacumuladaatual /(wvaloraquisicaooriginal / wtotalmesesdepreciacao)) - wverificamesinteiro);
    END

  --#alt:19501 - N?o deve considerar um m?s a mais na deprecia??o di?ria. E verifico o par?metro, pois a vari?vel sofre altera??o. Ana - 23/10/2017
  IF (prdepdia = 'FALSE') THEN
    BEGIN
      IF ((wdepmensal = 'TRUE') AND (wvaldepacumubem <> 0) AND (wdiasdepdiaria > 0)) THEN
    wmesesdepreciados = wmesesdepreciados + 1;
  ELSE
  --#alt:19501. Apenas somando este m?s altera bastante os c?culos da deprecia??o. Para somar este m?s s? em situa??es bem espec?ficas. Ana - 18/10/2017
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (((CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >
           CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER))) OR
     ((CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) =
       CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER)) AND
          ((wvaldepacumubem <> 0) OR (wdepmensal = 'TRUE'))) ) THEN
    wmesesdepreciados = wmesesdepreciados + 1;
    END

  --alt:14761 - 16/06/2016 - Retirada valida??o do wvaldepacumubem, sen?o no m?s inicial sem deprecia??o nele e com valor depreciado anteriormente cadastrado, estava retornando um m?s a mais como depreciado. Pedro
  --alt:14624 - 06/06/2016 - Precisa verificar tamb?m se o campo "wvaldepacumubem" est? nulo; estava incorreta a condi??o da data > ou = (o m?s retorna sem o zero, ex: 20158, assim n?o atendia a condi??o). Pedro
  --alt:13784 - 12/04/2016 - S? deve descontar um m?s se a data inicial for de m?s igual ou posterior a data de aquisi??o, n?o levando em considera??o apenas se h? valor j? depreciado. Pedro
  --IF ((wdepmensal = 'FALSE') OR (wvaldepacumubem > 0)) THEN
  --if ((wdepmensal = 'FALSE') AND (wvaldepacumubem = 0) and
  --   (CAST(EXTRACT(YEAR FROM :prdatainicial) || EXTRACT(MONTH FROM :prdatainicial) AS INTEGER) >= CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
  --if ((wdepmensal = 'FALSE') and (coalesce(wvaldepacumubem, 0) = 0) and
  IF ((wdepmensal = 'FALSE') AND
     ((EXTRACT(YEAR FROM :prdatainicial) > EXTRACT(YEAR FROM wdataorigaquisicao)) OR
      ((EXTRACT(YEAR FROM :prdatainicial) = EXTRACT(YEAR FROM wdataorigaquisicao)) AND (EXTRACT(MONTH FROM :prdatainicial) >= EXTRACT(MONTH FROM wdataorigaquisicao))))) THEN
    wmesesdepreciados = wmesesdepreciados - 1;

  --alt:13784 - 12/04/2016 - Se j? tiver depreciado meses com outra taxa, deve somar esse per?odo. Pedro
  IF (prmesesdepreciadosoutrataxa > 0) THEN
    wmesesdepreciados = wmesesdepreciados + prmesesdepreciadosoutrataxa;

  -- Adiciona no total de meses depreciados o valor j? depreciado de outro sistema
  IF ((wvaldepacumubem > 0) AND (wmesesdepreciados >=0)) THEN
     --#alt:18200 - Alterado para pegar o valor original da aquisi??o e n?o o valor ja corrigido. Ana - 03/05/2017
     --wmesesdepreciados = wmesesdepreciados + (wvaldepacumubem / (wvaloraquisicao / wtotalmesesdepreciacao));
     wmesesdepreciados = wmesesdepreciados + (wvaldepacumubem / (wvaloraquisicaooriginal / wtotalmesesdepreciacao));

  --#alt:19501 - Antes os c?lculos da deprecia??o do per?odo estavam incorretos quando o bem possuia baixa parcial, ent?o o total de meses depreciados sempre foi suficiente. Por?m, com
  --             estas altera??es, a quantidade de meses depreciados pode ser com um m?s a mais para fazer o c?lculo de compensa??o de baixa do per?odo anterior corretamente. Ana - 19/10/2017
  IF (((wmesesdepreciados > (wtotalmesesdepreciacao + 1)) AND (wdepmesbaixa = 'FALSE')) OR
      ((wmesesdepreciados > (wtotalmesesdepreciacao))     AND (wdepmesbaixa = 'TRUE')) ) THEN
     wmesesdepreciados = wtotalmesesdepreciacao;

  --#alt:19501 - Quando o bem possui deprecia??o no m?s da aquisi??o e deprecia??o di?ria, e for no m?s da aquisi??o, n?o vai considerar a deprecia??o deste m?s da aquisi??o.
  --             Essa deprecia??o ocorrer? no final do per?odo. Ana - 23/10/2017
  -- Se os meses decreciados for menor que zero, significa que foi informado uma data inferior a data de aquisicao do bem
  /*IF (wmesesdepreciados <= 0) THEN
    BEGIN
      SUSPEND;
      EXIT;
    END*/

  --#alt:19501 - Adicionada a atribui??o aqui, pois preciso dela para controle da vari?vel wdepdiafinal. Ana - 17/10/2017
  -- Meses ? depreciar
  wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);

  -- Total de meses da diferen?a do periodo de deprecia??o
  wmes = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultimodiadomes;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultimodiadomes = EXTRACT(DAY FROM (wdatatotalmesesdepdia - EXTRACT(DAY FROM wdatatotalmesesdepdia) +
                                      32 - EXTRACT(DAY FROM wdatatotalmesesdepdia - EXTRACT(DAY FROM wdatatotalmesesdepdia) + 32)));
  wdatatotalmesesultimodia = wmes||'-'||wultimodiadomes||'-'||wano;
  IF ((:prdatafinal > wdatatotalmesesultimodia) AND (wdepdia = 'TRUE')) THEN
    BEGIN
      -- Caso seja o ?ltimo m?s para depreciar
      IF (wmesesdepreciar = 0) THEN
        wdepdiafinal = 'TRUE';

      wdatatotalmesesultimodia = addmonth(wdatatotalmesesultimodia, 1);
      wdatatotalmesesultimodia = SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                                 SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
    END
  ELSE
    BEGIN
      --alt:8005 - Foi adicionada excess?o "else" e esta valida??o porque se tiver terminado a quantidade de dias a depreciar deve calcular o final da deprecia??o (os restos). Pedro
      IF (wmesesdepreciar = 0) THEN
        wdepdiafinal = 'TRUE';
    END

  IF (:prdatafinal > wdatatotalmeses) THEN
     prdatafinal = wdatatotalmeses;

  IF (:prdatainicial < :wdataoficialiniciolcalculo) THEN
      prdatainicial = wdataoficialiniciolcalculo;

  wtotalmesesdoperiodo = DATEDIFF(MONTH,:prdatainicial,:prdatafinal);
  IF (wtotalmesesdoperiodo < 0) THEN
    wtotalmesesdoperiodo = 0;
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
      CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER)) THEN
    wtotalmesesdoperiodo = wtotalmesesdoperiodo + 1;

  --#alt:18204 - Quando a data for igual a data origem de aquisi??o ent?o n?o deve ser calculado. Ana - 28/04/2017
  IF ((wvaldepacumubem > 0) AND (prdatainicial </*=*/ wdataorigaquisicao)) THEN
    wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;

  --#alt:6151. - Carlos Mello(08/11/2013)
  IF (((wtotalmesesdoperiodo > 0) AND
       ((CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) >
         CAST((SUBSTRING(wdatatotalmeses FROM 1 FOR 4)) || (SUBSTRING(wdatatotalmeses FROM 6 FOR 2)) AS INTEGER)) OR
        ((wdepmensal = 'TRUE') AND
         (CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
          CAST((SUBSTRING(wdatatotalmeses FROM 1 FOR 4)) || (SUBSTRING(wdatatotalmeses FROM 6 FOR 2)) AS INTEGER))))) OR
      (wtotalmesesdoperiodo < 0) ) THEN
    wtotalmesesdoperiodo = 0;

  --#alt:19501 - Movi essa atribui??o para cima, pois h? verifica??es com esta vari?vel. Ana - 17/10/2017
  -- Meses ? depreciar
  --wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);
  wvaloraquisicaomoeda = wvaloraquisicao / prvlrmoeda;
  -- Deprecia??o do per?odo
  --wvalordepreciacaomensal = (wvaloraquisicaomoeda / wtotalmesesdepreciacao); --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro

  --#alt:85169. O valor da aquisi??o deve ser o original para calcular a deprecia??o correta e n?o influenciar nos outro valores. Ana- 20/06/2018
  --wvalordepreciacaomensal = (wvaloraquisicao / wtotalmesesdepreciacao);
  IF (prtipo = 2) THEN
    wvalordepreciacaomensal = (wvaloraquisicaoaux / wtotalmesesdepreciacao);
  ELSE
    wvalordepreciacaomensal = (wvaloraquisicao / wtotalmesesdepreciacao);

  --#alt:19501 - Quando tenho deprecia??o acumulada anterior cadastrada devo considerar os meses pertinentes a essa deprecia??o, independente da deprecia??o di?ria. Ana - 17/10/2017
  IF ((wdepdia = 'TRUE') /*AND ((wvaldepacumubem = 0) AND (wvaldepacumubem = wdepreciacaoacumuladaatual))*/) THEN
    BEGIN
      -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
      wmesesdepreciar      = wmesesdepreciar + 1;
      wmesesdepreciados    = wmesesdepreciados - 1;
      wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;
    END

  --alt:15196 - 09/11/2016 - Se depreciou no m?s da aquisi??o, ir? terminar a deprecia??o um m?s antes. Pedro
  IF (wdepmensal = 'TRUE') THEN
    wdatatotalmeses = AddMonth(wdatatotalmeses, -1);

  IF (wdepdiasadepreciar > 0) THEN
    BEGIN
      --#alt:5105. - Carlos Mello(27/11/2013)
      IF (wnumdias = 2) THEN
        BEGIN
          -- C?lculo que retorna o ?ltimo dia do m?s
          --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
          IF (wdatabaixa BETWEEN prdatainicial AND prdatafinal) THEN
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) +
                                                32 - EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32)));
          ELSE
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatainiciocalc - EXTRACT(DAY FROM wdatainiciocalc) +
                                                32 - EXTRACT(DAY FROM wdatainiciocalc - EXTRACT(DAY FROM wdatainiciocalc) + 32)));

          --alt:13156 - Fim
          --alt:16006 - 03/11/2016 - Alterado para dividir o valor da daprecia??o antes e depois da baixa, no caso da baixa parcial. Pedro
          --wvalordepreciacaodiaria  = (wvalordepreciacaomensal * prvlrmoeda) / wultimodiadomes * wdepdiasadepreciar;
          wvalordepreciacaodiaria = (prvaloraquisicaooriginal / wtotalmesesdepreciacao) / wultimodiadomes * wdepdiasadepreciar;
          wvalordepreciacaodiariabaixa = (wvalordepreciacaomensal / wultimodiadomes) * (wultimodiadomes - wdepdiasadepreciar);
          wDia = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32 -
                                   EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32))) - EXTRACT(DAY FROM wdatainiciocalc);
          prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados -1 + (CAST(wdepdiasadepreciar + wDia AS FLOAT) / wUltimoDiaDoMes));
        END
      ELSE
        BEGIN
          --alt:16006 - 03/11/2016 - Alterado para dividir o valor da daprecia??o antes e depois da baixa, no caso da baixa parcial. Pedro
          --wvalordepreciacaodiaria  = (wvalordepreciacaomensal * prvlrmoeda) / 30 * wdepdiasadepreciar;
          wvalordepreciacaodiaria = (prvaloraquisicaooriginal / wtotalmesesdepreciacao) / 30 * wdepdiasadepreciar;
          wvalordepreciacaodiariabaixa = (wvalordepreciacaomensal / 30) * (30 - wdepdiasadepreciar);
          wDia = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32 -
                                   EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32))) - EXTRACT(DAY FROM wdatainiciocalc);
          prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados -1 + (CAST(wdepdiasadepreciar + wDia AS FLOAT) / 30));
        END
      --alt:16006 - Fim

      --alt:15196 - 09/11/2016 - Esta nova vari?vel calcula corretamente o valor a ser compensado no final da deprecia??o. Pedro
      --prvalordepreciacaodiariafim = (wvalordepreciacaomensal * prvlrmoeda) - wvalordepreciacaodiaria;
      prvalordepreciacaodiariafim = wvalordepreciacaodiariabaixa;
    END
  ELSE
    --#alt:19501 - Adicionei o valor pertinente a deprecia??o di?ria no m?s da aquisi??o. Ana - 24/10/2017
    --alt:15196 - 09/11/2016 - Calcula o valor a ser compensado ap?s a baixa para bens SEM deprecia??o di?ria. Pedro
    prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * ((wmesesdepreciados + wdiasdepdiaria) - IIF(wdepmesbaixa = 'TRUE', 0, 1));

  --#alt:18200 - Adicionei a verifica??o da diferen?a de meses da baixa para a aquisi??o do bem, pois n?o estava fazendo a deprecia??o di?ria corretamente
  --             quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
  --alt:16006 - 03/11/2016 - Separado o c?lculo para per?odo com baixa do per?odo depreciado em outro sistema,
  --pois precisa utilizar o valor da deprecia??o acumulada do c?lculo m?s a m?s, caso contr?rio, caso o primeiro
  --m?s tenha sido depreciado diariamente, estava desconsiderando este valor para os meses seguintes. Pedro
  --alt:13156 - 17/02/2016 - Na baixa tamb?m deve descontar o valor proporcional ao n?mero de dias, se o par?metro estiver marcado. Pedro
  IF ((wdatabaixa BETWEEN prdatainicial AND prdatafinal)  AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0))THEN
    BEGIN
      wdepreciacaoperiodo = (wvalordepreciacaodiaria + wvalordepreciacaodiariabaixa) + (wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  --#alt:19501 - Quando for deprecia??o di?ria e tiver valor de deprecia??o acumulada anterior informada, deve ignorar qualquer c?lculo feito anteriormente. Ana - 17/10/2017
  ELSE IF ((wdatainicialoficial <= :wdataaquisicao) AND
          (((wdepdia = 'TRUE') AND (wvaldepacumubem = 0) OR ((wdepdia = 'FALSE') AND (wvaldepacumubem <> 0))) AND
          (wvaldepacumubem = wdepreciacaoacumuladaatual))) THEN
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo) / prvlrmoeda;
      wdepreciacaoperiodo      = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  ELSE
  IF (wdepdia = 'TRUE') THEN
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo +1) * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * (wtotalmesesdoperiodo+1));
      wdepreciacaoperiodo      = wvalordepreciacaomensal * (wtotalmesesdoperiodo +1);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  ELSE
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodo      = wvalordepreciacaomensal * wtotalmesesdoperiodo;
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END

  --#alt:19501 - Quando ? informado um valor de deprecia??o acumulada anterior, deve ignorar o qualquer calculo feito anteriormente(deprecia??o diaria) e permanecer com o valor informado. Ana - 17/10/2017
  IF ((prvaloracumuladoanterior = 0) AND (wvaldepacumubem <> 0) AND (wvaldepacumubem = wdepreciacaoacumuladaatual)) THEN
    BEGIN
      wdepreciacaoacumuladaatual    = (wdepreciacaoperiodo + wdepreciacaoacumuladaatual);
      wdepreciacaoacumuladaanterior = (wvaldepacumubem);
    END
  ELSE
   IF ((wvalordepreciacaodiaria > 0) AND (wdatainicialoficial <= :wdataaquisicao))  THEN
     BEGIN
       --alt:16006 - 03/11/2016 - Utiliza o valor da deprecia??o acumulado na vari?vel. Pedro
       --wdepreciacaoacumuladaatual    = (wvalordepreciacaomensal * wmesesdepreciados);
       wdepreciacaoacumuladaatual    = (wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * prvlrmoeda);
       wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
     END
   ELSE
     BEGIN
       --alt:16006 - 03/11/2016 - Utiliza o valor da deprecia??o acumulado na vari?vel. Pedro
       --wdepreciacaoacumuladaatual = (wvalordepreciacaomensal * wmesesdepreciados);
       --wdepreciacaoacumuladaatual = (wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * prvlrmoeda);
       wdepreciacaoacumuladaatual = wdepreciacaoperiodo + wdepreciacaoacumuladaatual;
      
       IF (wvalordepreciacaodiaria > 0) THEN
         wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
       ELSE
         BEGIN
          --#alt:19501 - Na deprecia??o di?ria devo considerar um m?s a mais no total de meses do per?odo. Ana - 25/10/2017 
           --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
           --alt:9013 - Dividido em duas partes porque calculando tudo de uma s? vez estava ocorrendo um over flow. Pedro
           --wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda;
          IF (wdepdia = 'TRUE') THEN
            wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * (wtotalmesesdoperiodo +1);
          ELSE
           wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * wtotalmesesdoperiodo;
           wdepreciacaoacumuladaanterior = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;
           --wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual -  (wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda));
           --alt:9013 - Fim
         END
     END

  --#alt:18200 - N?o precisa fazer esta verifica??o, pois o valor corrigido anterior sempre deve ser em rela??o ao valor da aquisi??o. Ana - 02/05/2017
  --IF (wdepreciacaoacumuladaanterior > 0) THEN
  wvalorcorrigidoanterior = wvaloraquisicao;

  IF (wdepreciacaoacumuladaanterior < 0) THEN
    wdepreciacaoacumuladaanterior = 0;

  --#alt:18200 - S? vai considerar a compensa??o da baixa do per?odo anterior se tiver deprecia??o acumulada anterior ou se o m?s da baixa n?o for o mesmo da aquisi??o.
  --             Deve ser o valor da aquisi??o original pois o valor da aquisi??o ? diminuido conforme os valores das baixas. Ana - 04/05/2017
  --alt:16006 - 03/11/2016 - Caso esteja deprecia??o diariamente e seja um m?s com baixa, deduz o valor dos meses anteriores que foram depreciados calculando valor inteiro do bem (sem baixa). Pedro
  --IF ((wvalorbaixaper > 0) AND (wvalorbaixa < wvaloraquisicao)) THEN
  IF ((wvalorbaixaper > 0) AND (wvalorbaixa < wvaloraquisicaooriginal) AND ((wdepreciacaoacumuladaanterior <> 0) OR (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0))) THEN
    wdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual - prcompensacaobaixaperanterior;
  ELSE IF (wvalorbaixa = wvaloraquisicao) THEN
    prcompensacaobaixaperanterior = wdepreciacaoacumuladaatual;

  --alt:15196 - 09/11/2016 - Agora o valor da deprecia??o mensal vem sem a moeda, ent?o precisa converter. Pedro
  --wdepreciacaoacumuladaatualmoed = ((wvalordepreciacaodiaria / prvlrmoeda) + wvalordepreciacaomensal * wmesesdepreciados);
  wdepreciacaoacumuladaatualmoed = (wvalordepreciacaodiaria + (wvalordepreciacaomensal * wmesesdepreciados)) / prvlrmoeda;
  wdepreciacaobaixamoeda         = (wvalorbaixa / wtotalmesesdepreciacao);
  wdepreciacaobaixamoeda         = (wdepreciacaobaixamoeda / prvlrmoeda);

  IF (prtipo = 2) THEN
    BEGIN
      prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
      prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior / prvlrmoeda);
    END
  ELSE
    BEGIN
      --#alt:18200 - N?o estava calculando certo. Atribuia o valor da aquisi??o menos todas as baixas e somava todas as baixas aqui novamente, mas s? deve somar as baixas que ja foram efetuadas. Ana - 02/05/2017
      /*prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + wvalorbaixa);
      prvalorcorrigidoanteriormoeda = ((wvalorcorrigidoanterior + wvalorbaixa) / prvlrmoeda);  */
      prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + (wvalorbaixaper));
      prvalorcorrigidoanteriormoeda = ((wvalorcorrigidoanterior + (wvalorbaixaper)) / prvlrmoeda);

      --#alt:19501 - Quando ? deprecia??o no mes da baixa, n?o deve considerar os valores de baixa no per?odo para c?lculo do valor corrigido anterior(Estes valores ja est?o inclusos). Ana - 16/10/2017
      --#alt:18200 - Apenas se o valor for maior deve substituir. Ana - 02/05/2017
      IF ((prvalorcorrigidoanterior >/*=*/ prvaloraquisicaooriginal) OR (UPPER(wdepmesbaixa) = 'TRUE') ) THEN
        BEGIN
          prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
          prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior / prvlrmoeda);
        END
    END

  --#alt:19501 - O calculo deve ser em cima do valor corrigido atual e n?o do valor da aquisi??o, quando possuir valor. Ana - 16/10/2017
  IF (prvalorcorrigidoanterior > 0) THEN
    wvalorresidualcontabil         = (((prvalorcorrigidoanterior + prcorrecaoperiodo) - wvalorbaixaper) - wdepreciacaoacumuladaatual);
  ELSE
    wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
  wvalorresidualcontabilmoeda    = (wvalorresidualcontabil / prvlrmoeda);
  --#alt:19501. fim

  IF ((wdepdia = 'TRUE') AND (wdepdiafinal = 'TRUE')) THEN
    BEGIN
      --alt:8005 - Alterado para n?o entrar aqui caso as datas sejam iguais, pois se entrar aqui ele mata a deprecia??o di?ria. Pedro
      --if (wdatainicialoficial <= :wdataaquisicao) then
      IF (wdatainicialoficial < :wdataaquisicao) THEN
        BEGIN
          --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
          --wdepreciacaoperiodo            = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
          --wdepreciacaoperiodomoeda       = (((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) / prvlrmoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
          wdepreciacaoperiodo            = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
          wdepreciacaoperiodomoeda       = wdepreciacaoperiodo / prvlrmoeda;
          wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim);
          wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual / prvlrmoeda);
          wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          wvalorresidualcontabilmoeda    = 0;
          wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
        END
      ELSE
        --#alt:19501 - Se o bem ja foi totalmente depreciado, n?o deve mais executar esta parte. Estava retornando a deprecia??o errada. Ana - 25/10/2017
       IF ((CAST(wvalorcorrigidoanterior AS NUMERIC(15,0)) <> CAST(wdepreciacaoacumuladaatual AS NUMERIC(15,0))) AND
            (CAST(wvalorcorrigidoanterior AS NUMERIC(15,1)) <> CAST(wdepreciacaoacumuladaatual AS NUMERIC(15,1))) OR
           ((wmesesdepreciados + 1) < wtotalmesesdepreciacao)) THEN
        BEGIN
          wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);
          wmes                     = CAST(SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano                     = CAST(SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          wdatatotalmesesultimodia = wmes||'-01-'||wano;

          --alt:14256 - 14/07/2016 - Alterada valida??o, n?o estava trazendo o valor da deprecia??o di?ria nos meses subsequentes ao t?rmino da deprecia??o. Pedro
          --alt:9013 - Retirado pois estava trazendo depreciacao anterior a mais do que devia quando usava deprecia??o di?ria. Pedro
          --IF (wdatatotalmesesultimodia BETWEEN PRDATAINICIAL AND PRDATAFINAL) THEN
          IF (wdatatotalmesesultimodia <= prdatainicial) THEN
             wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim);

          wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual / prvlrmoeda);

          wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          --#alt:16852 - Comentado pois n?o h? necessidade de zerar e estava fazendo com que o valor fosse errado. Ana - 10/02/2017
          --wvalorresidualcontabilmoeda = 0;

          IF (wdatainicialoficial <> :wdatatotalmesesultimodia) THEN
            BEGIN
              wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
              wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaanterior / prvlrmoeda);
            END

          wdepreciacaoperiodo = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;

          IF (wdepreciacaoperiodo <= 0) THEN
            wdepreciacaoperiodomoeda = 0;
          ELSE
            wdepreciacaoperiodomoeda = ((wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior) / prvlrmoeda);
        END

      --alt:9013 - Retirado pois sempre trazia um m?s a mais de deprecia??o quando ? di?ria. Pedro
      /*wmesesdepreciados = wmesesdepreciados + 1;
      wmesesdepreciar   = 0;*/
    END

  --#alt:18200 - Alterada forma de c?lculo do valor corrigido atual (valor corrigido anterior + corre??o do per?odo - valor de baixas do per?odo). Ana - 02/05/2017
  --prvalorcorrigidoatual = (prvalorcorrigidoanterior + prcorrecaoperiodo - wvalorbaixaper);

  --alt:15196 - 24/11/2016 - Adapta??o para zerar o valor residual da deprecia??o. Pedro
  IF ((wdepreciacaoacumuladaanterior + wdepreciacaoperiodo) > wvaloraquisicao) THEN
    BEGIN
      IF (wdepreciacaoacumuladaanterior < wvaloraquisicao) THEN
        BEGIN
          wdepreciacaoperiodo = wvaloraquisicao - wdepreciacaoacumuladaanterior;
          wdepreciacaoacumuladaatual = wdepreciacaoacumuladaanterior + wdepreciacaoperiodo;
        END

      wdepreciacaoperiodomoeda = wdepreciacaoperiodo * prvlrmoeda;
      wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual * prvlrmoeda;
    END

  IF ((wdepdia = 'TRUE')) THEN
    BEGIN
      -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
      wmesesdepreciar      = wmesesdepreciar - 1;
      wmesesdepreciados    = wmesesdepreciados + 1;
      wtotalmesesdoperiodo = wtotalmesesdoperiodo +1;
    END

  prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;
  prdepreciacaoperiodo            = wdepreciacaoperiodo;
  prdepreciacaoperiodomoeda       = wdepreciacaoperiodomoeda;
  prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
  prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
  prcorrecaomonetariadepreciacao  = 0;
  prvalorresidualcontabil         = wvalorresidualcontabil;
  prvalorresidualcontabilmoeda    = wvalorresidualcontabilmoeda;
  prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
  prmesesdepreciados              = wmesesdepreciados;
  prmesesdepreciar                = wmesesdepreciar;
  prdatataxadepreciacao           = wdataultimoitemdep;
  --#Alt:5105
  --prvalorbaixa                    = wvalorbaixa;
  prvalorbaixa                    = wvalorbaixaper;
  prdepreciacaobaixamoeda         = wdepreciacaobaixamoeda;
  prvalorbaixareal                = wvalorbaixa;
  prvalormoeda                    = prvlrmoeda;
  prdatabaixa                     = wdatabaixa;
  prvaloraquisicaomoeda           = wvaloraquisicaomoeda;

  SUSPEND;
END
^

/* Restore proc. body: SP_CONS_CALC_INTERMITENTE */
ALTER PROCEDURE SP_CONS_CALC_INTERMITENTE(PRCODEMP INTEGER = null,
PRCODCOL INTEGER = null,
PRCODCONTRATO INTEGER = null,
PRDATAINICIAL DATE = null,
PRDATAFINAL DATE = null)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRGCOL VARCHAR(13),
BDCODCONTTI INTEGER,
BDDESCCONTRATOTI VARCHAR(2000),
BDDATACONVTI DATE,
BDHORACONVTI TIME,
BDDATAINISERVTI DATE,
BDDATAFIMSERVTI DATE,
BDDATAPAGTI DATE,
BDLIQUIDO NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDDATAPGTOFN DATE,
BDFGTSFN NUMERIC(18,6),
BDFGTS13FN NUMERIC(18,6),
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(18,6),
BDREFAUXVFN NUMERIC(18,6),
BDVALVFN NUMERIC(18,6),
BDVALIFN NUMERIC(18,6),
BDDESCVER VARCHAR(40),
BDTIPOCODVER INTEGER,
BDORDEMVER INTEGER)
 AS
declare variable WSQL varchar(10000);
declare variable WWHERE varchar(500);
declare variable WSQL2 varchar(5000);
declare variable WWHERE2 varchar(500);
begin
    --<Local aonde deve ser zerado as vari?veis>--
    wSQL   = ' ';
    wWhere = ' ';

    /**************************************************************************/
    /*                      In?cio da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL = wSQL ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL = wSQL ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    --<Contrato>--
    wSQL = wSQL ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAPAGTI,'           || ASCII_CHAR(13);
    --<C?lculo>--
    wSQL = wSQL ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDATAPGTOFN,'                  || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFVFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALIFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDTIPOCODVER,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDORDEMVER'                    || ASCII_CHAR(13);
    wSQL = wSQL ||' FROM (SELECT'                             || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDCODCONTTI,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDLIQUIDO,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDBINSSFN,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDDATAPGTOFN,'       || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTSFN,'           || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTS13FN,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODEMP,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODCOL,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODVER,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDDESCVER,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDORDEMVER,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_DESCVERB.BDTIPOCODVER,'     || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFFN,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFVFN,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFAUXVFN,'    || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALVFN,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALIFN'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       FROM VRHF_EMP_TFOLHAINT XF_CALCULO' || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VRHF_EMP_TVERBAINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP    = XLF_VERBASCALC.BDCODEMP AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCOL    = XLF_VERBASCALC.BDCODCOL AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCONTTI = XLF_VERBASCALC.BDCODCONTTI AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDREFFN     = XLF_VERBASCALC.BDREFFN)'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB      ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'         || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB  ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'        || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    if (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere = wWhere || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

            wWhere = wWhere || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END

    IF (wWhere <> '') THEN
        BEGIN
            wWhere = ' WHERE ' || ASCII_CHAR(13) || wWhere;
        END

    wSQL = wSQL || wWhere || ASCII_CHAR(13);

    wSQL = wSQL || ') F_CALC ' || ASCII_CHAR(13);
    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL = wSQL ||'           JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP)'           || ASCII_CHAR(13);
    wSQL = wSQL ||'           JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP)'               || ASCII_CHAR(13);
    wSQL = wSQL ||'           JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP     AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL     AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI)'    || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          J_CONTRATO_INT.BDCODCOL = LF_REFCOL.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLCAD.BDREFCOL)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLDOC2.BDREFCOL)'           || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wWhere = ' ';
    if ((prDataInicial is not null) AND ( prDataFinal is not null)) THEN
        BEGIN
            wWhere = wWhere || 'J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN' || prDataInicial || ' AND ' || prDataFinal;
        END



    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/

    --<Local aonde deve ser zerado as vari?veis>--
    wSQL2   = ' ';
    wWhere2 = ' ';

    /**************************************************************************/
    /*                      In?cio da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL2 = wSQL2 ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL2 = wSQL2 ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    --<Contrato>--
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAPAGTI,'           || ASCII_CHAR(13);
    --<C?lculo>--
    wSQL2 = wSQL2 ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDATAPGTOFN,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFVFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALIFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDTIPOCODVER,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDORDEMVER'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||' FROM (SELECT'                                             || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'        XF_CALCULO.BDCODCONTTI,'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'SUM(XF_CALCULO.BDLIQUIDO) AS BDLIQUIDO,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDBINSSFT) AS BDBINSSFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPGTOFT AS BDDATAPGTOFN,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTSFT) AS BDFGTSFN,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTS13FT) AS BDFGTS13FN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'                         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'                        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR AS BDREFFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDREFVFT) AS BDREFVFN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFAUXVFT AS BDREFAUXVFN,'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALVFT) AS BDVALVFN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALIFT) AS BDVALIFN'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       FROM VRHF_EMP_TFOLHATOMINT XF_CALCULO'              || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VRHF_EMP_TVERBATOMINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP     = XLF_VERBASCALC.BDCODEMP AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCOL     = XLF_VERBASCALC.BDCODCOL AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCONTTI  = XLF_VERBASCALC.BDCODCONTTI AND'  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDREFTOMADOR = XLF_VERBASCALC.BDREFTOMADOR AND' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDORDEM      = XLF_VERBASCALC.BDORDEM)'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB         ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB     ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'          || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    if (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

             wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END

    IF (wWhere2 <> '') THEN
        BEGIN
            wWhere2 = ' WHERE ' || ASCII_CHAR(13) || wWhere2;
        END

    wSQL2 = wSQL2 || wWhere2 || ASCII_CHAR(13);

    wSQL2 = wSQL2 ||'       GROUP BY'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDCODCONTTI,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPGTOFT,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR,'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFAUXVFT'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||') F_CALC'                                   || ASCII_CHAR(13);

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL2 = wSQL2 ||'           JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP)'               || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI)'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          J_CONTRATO_INT.BDCODCOL = LF_REFCOL.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLCAD.BDREFCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLDOC2.BDREFCOL)'           || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wWhere2 = ' ';
    if ((prDataInicial is not null) AND ( prDataFinal is not null)) THEN
        BEGIN
            wWhere2 = wWhere2 || 'J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN' || prDataInicial || ' AND ' || prDataFinal;
        END



    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/
    
    wSQL = wSQL    || ASCII_CHAR(13) ||
           'UNION' || ASCII_CHAR(13) ||
           wSQL2;

    /*Seta a compet?ncia para o banco*/
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(201806);

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDNOMEMP,
        :BDCNPJEMP,
        :BDLOGREMP,
        :BDENDEMP,
        :BDNUMEMP,
        :BDCODCID,
        :BDNOMCID,
        :BDNOMCOL,
        :BDCPFCOL,
        :BDPISCOL,
        :BDRGCOL,
        :BDCODCONTTI,
        :BDDESCCONTRATOTI,
        :BDDATACONVTI,
        :BDHORACONVTI,
        :BDDATAINISERVTI,
        :BDDATAFIMSERVTI,
        :BDDATAPAGTI,
        :BDLIQUIDO,
        :BDBINSSFN,
        :BDDATAPGTOFN,
        :BDFGTSFN,
        :BDFGTS13FN,
        :BDCODCOL,
        :BDCODVER,
        :BDREFFN,
        :BDREFVFN,
        :BDREFAUXVFN,
        :BDVALVFN,
        :BDVALIFN,
        :BDDESCVER,
        :BDTIPOCODVER,
        :BDORDEMVER
    DO
        SUSPEND;
end
^

/* Restore proc. body: SP_CONS_FERIAS_PER_AQUIS_ESCALA */
ALTER PROCEDURE SP_CONS_FERIAS_PER_AQUIS_ESCALA(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PRPRIDIA DATE,
PRULTDIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDABONOFE NUMERIC(18,6),
BDQTDGOZOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDNOMEMP VARCHAR(100),
BDNOMCOL VARCHAR(70),
BDSALDOFINALSINDFE NUMERIC(18,6),
BDFERIADOSFE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WEMPRESA INTEGER;
DECLARE VARIABLE WCOLABORADOR INTEGER;
DECLARE VARIABLE WPERAQUIS DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WINIPERAQUISFE DATE;
DECLARE VARIABLE WCODFE INTEGER;
DECLARE VARIABLE WINIPERGOZOFE DATE;
DECLARE VARIABLE WFIMPERAQUISFE DATE;
DECLARE VARIABLE WFIMPERGOZOFE DATE;
DECLARE VARIABLE WDATAPAGFE DATE;
DECLARE VARIABLE WQTDGOZOFE NUMERIC(18,6);
DECLARE VARIABLE WQTDABONOFE NUMERIC(18,6);
DECLARE VARIABLE WSALDOINIFE NUMERIC(15,6);
DECLARE VARIABLE WSALDOFIMFE NUMERIC(15,6);
DECLARE VARIABLE WBASEIRFE NUMERIC(15,6);
DECLARE VARIABLE WALIQIRFE NUMERIC(15,6);
DECLARE VARIABLE WVALORIRFE NUMERIC(15,6);
DECLARE VARIABLE WBASEINSSFE NUMERIC(15,6);
DECLARE VARIABLE WALIQINSSFE NUMERIC(15,6);
DECLARE VARIABLE WVALORINSSFE NUMERIC(15,6);
DECLARE VARIABLE WDEPFE NUMERIC(15,6);
DECLARE VARIABLE WSALBASEFE NUMERIC(15,6);
DECLARE VARIABLE WSALBASEHEFE NUMERIC(15,6);
DECLARE VARIABLE WDATABAIXAFE DATE;
DECLARE VARIABLE WCOLETIVASFE VARCHAR(5);
DECLARE VARIABLE WREFPAGABOFE INTEGER;
DECLARE VARIABLE WFALTASFE NUMERIC(15,6);
DECLARE VARIABLE WNOMEMP DM_BDNOMEMP;
DECLARE VARIABLE WNOMCOL DM_BDNOMCOL;
DECLARE VARIABLE WSALDOFINALSINDFE NUMERIC(18,6);
DECLARE VARIABLE WFERIADOSFE INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref,  NULL, NULL);

  wsql = 'select FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE, FER.BDINIPERGOZOFE, FER.BDFIMPERAQUISFE, '||
                'FER.BDFIMPERGOZOFE, FER.BDDATAPAGFE, FER.BDQTDGOZOFE, FER.BDQTDABONOFE, FER.BDSALDOINIFE, '||
                'FER.BDSALDOFIMFE, FER.BDBASEIRFE, FER.BDALIQIRFE, FER.BDVALORIRFE, FER.BDBASEINSSFE, FER.BDALIQINSSFE, '||
                'FER.BDVALORINSSFE, FER.BDDEPFE, FER.BDSALBASEFE, FER.BDSALBASEHEFE, FER.BDDATABAIXAFE, FER.BDCOLETIVASFE, '||
                'FER.BDREFPAGABOFE, FER.BDFALTASFE, EMP.BDNOMEMP, COLCAD.BDNOMCOL, FER.BDSALDOFINALSINDFE, FER.BDFERIADOSFE ';

  wsql = wsql || 'from VRH_EMP_TFERIAS FER '||
                 'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
                    'on (EMP.BDCODEMP = FER.BDCODEMP) '||
                 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD '||
                    'on (COLCAD.BDCODEMP = FER.BDCODEMP and COLCAD.BDCODCOL = FER.BDCODCOL) ';

  wwhere = 'coalesce(coalesce(fer.BDDATAPAGFE,fer.BDINIPERGOZOFE),'||
           'cast(case when ((fer.bdrefpagabofe is null) or (fer.bdrefpagabofe = 0)) '||
           'then null else substring(cast(fer.bdrefpagabofe as varchar(6)) from 5 for 2)||'||
           ''''||'/01/'||''''||
           '||substring(cast(fer.bdrefpagabofe as varchar(6)) from 1 for 4) end as date))';

  wwhere = ' where '||wwhere||' <= '''||prultdia||''' ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wwhere;

  wsql = wsql||' order by FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE';

  wEmpresa = 0;
  wColaborador = 0;
  FOR EXECUTE STATEMENT wsql
  INTO :WCODEMP, :WCODCOL, :WINIPERAQUISFE, :WCODFE, :WINIPERGOZOFE, :WFIMPERAQUISFE,
       :WFIMPERGOZOFE, :WDATAPAGFE, :WQTDGOZOFE, :WQTDABONOFE, :WSALDOINIFE,
       :WSALDOFIMFE, :WBASEIRFE, :WALIQIRFE, :WVALORIRFE, :WBASEINSSFE, :WALIQINSSFE,
       :WVALORINSSFE, :WDEPFE, :WSALBASEFE, :WSALBASEHEFE, :WDATABAIXAFE, :WCOLETIVASFE,
       :WREFPAGABOFE, :WFALTASFE, :WNOMEMP, :WNOMCOL, :WSALDOFINALSINDFE, :WFERIADOSFE DO
    BEGIN

      IF ((wEmpresa <> WCODEMP) OR (wColaborador <> WCODCOL) OR (wPerAquis <> WINIPERAQUISFE)) THEN
        BEGIN
          IF (wEmpresa <> 0) THEN
            SUSPEND;

          wEmpresa = WCODEMP;
          wColaborador = WCODCOL;
          wPerAquis = WINIPERAQUISFE;
          BDQTDGOZOFE = 0;
          BDQTDABONOFE = 0;
          BDSALDOINIFE = 0;
        END

      BDCODEMP = WCODEMP;
      BDCODCOL = WCODCOL;
      BDINIPERAQUISFE = WINIPERAQUISFE;
      BDCODFE = WCODFE;
      BDINIPERGOZOFE = WINIPERGOZOFE;
      BDFIMPERAQUISFE = WFIMPERAQUISFE;
      BDFIMPERGOZOFE = WFIMPERGOZOFE;
      BDDATAPAGFE = NULL;     --WDATAPAGFE;
      BDQTDGOZOFE = COALESCE(BDQTDGOZOFE, 0) + COALESCE(WQTDGOZOFE, 0);
      BDQTDABONOFE = COALESCE(BDQTDABONOFE, 0) + COALESCE(WQTDABONOFE, 0);

      IF (WCODFE = 1) THEN
        BDSALDOINIFE = WSALDOINIFE;

      BDSALDOFIMFE = WSALDOFIMFE;
      BDBASEIRFE = WBASEIRFE;
      BDALIQIRFE = WALIQIRFE;
      BDVALORIRFE = WVALORIRFE;
      BDBASEINSSFE = WBASEINSSFE;
      BDALIQINSSFE = WALIQINSSFE;
      BDVALORINSSFE = WVALORINSSFE;
      BDDEPFE = WDEPFE;
      BDSALBASEFE = WSALBASEFE;
      BDSALBASEHEFE = WSALBASEHEFE;
      BDDATABAIXAFE = WDATABAIXAFE;
      BDCOLETIVASFE = WCOLETIVASFE;
      BDREFPAGABOFE = WREFPAGABOFE;
      BDFALTASFE = WFALTASFE;
      BDNOMEMP = WNOMEMP;
      BDNOMCOL = WNOMCOL;
      BDSALDOFINALSINDFE = wsaldofinalsindfe;
      BDFERIADOSFE = wferiadosfe;
    END

  SUSPEND;

END
^

/* Restore proc. body: SP_CONSULTA_COL_POR_REF */
ALTER PROCEDURE SP_CONSULTA_COL_POR_REF(PREMP INTEGER,
PRCOL INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDREFCOL INTEGER)
 AS
BEGIN
   IF (prrefmicro IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);


       SELECT MAX(Y.BDREFCOL)
       FROM VRH_EMP_TCOLCON_REF Y
       WHERE Y.BDCODEMP = :premp AND
             Y.BDCODCOL = :prcol AND
             CAST(Y.BDREFCOL AS VARCHAR(6)) <=
                (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                 FROM rdb$database
                )
       GROUP BY Y.BDCODEMP, Y.bdcodcol

  INTO
    :BDREFCOL;


  IF ((BDREFCOL IS NULL) OR (BDREFCOL = 0)) THEN
    BEGIN
      SELECT FIRST 1 Y.BDREFCOL
      FROM VRH_EMP_TCOLCON_REF Y
      WHERE Y.BDCODEMP = :premp AND
            Y.BDCODCOL = :prcol
      ORDER BY y.bdrefcol
      INTO
        :BDREFCOL;
    END

  SUSPEND;
END
^

/* Restore proc. body: SP_CONSULTA_EMP_POR_REF */
ALTER PROCEDURE SP_CONSULTA_EMP_POR_REF(PREMP INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER)
 AS
DECLARE VARIABLE wref INTEGER;
BEGIN
   IF (prrefmicro IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

   SELECT Y.BDCODEMP, MAX(Y.BDREFEMP)
          FROM TEMPRESAS_REF Y
          WHERE Y.BDCODEMP = :PREMP AND
                CAST(Y.BDREFEMP AS VARCHAR(6)) <=
                   (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                    FROM rdb$database
                   )
          GROUP BY Y.BDCODEMP
  INTO
    :BDCODEMP,
    :BDREFEMP;


  IF ((BDREFEMP IS NULL) OR (BDREFEMP = 0)) THEN
    BEGIN
      SELECT FIRST 1 Y.BDCODEMP, Y.BDREFEMP
      FROM TEMPRESAS_REF Y
      WHERE Y.BDCODEMP = :PREMP
      ORDER BY y.bdrefemp
      INTO
        :BDCODEMP,
        :BDREFEMP;
    END

  SUSPEND;
END
^

/* Restore proc. body: SP_CONSULTA_TERCEIRO */
ALTER PROCEDURE SP_CONSULTA_TERCEIRO(PRCODTER INTEGER,
PRREF INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER DM_BDENDERECO,
BDNUMTER VARCHAR(10),
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER VARCHAR(60),
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDORGAOPUBLICO VARCHAR(5),
BDCODTIPO INTEGER,
BDCODIBGE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

    wSql = ' select ';
    wSql = wSql || 'TER.BDCODTER, ';
    wSql = wSql || 'TER.BDCODPLAPADRAO, ';
    wSql = wSql || 'TER.BDCODTPLA, ';
    wSql = wSql || 'TER.BDCGCTER, ';
    wSql = wSql || 'TER.BDREFEMP, ';
    wSql = wSql || 'TER.BDAPELIDOTER, ';
    wSql = wSql || 'TER.BDNOMETER, ';
    wSql = wSql || 'TER.BDLOGRTER, ';
    wSql = wSql || 'TER.BDENDTER, ';
    wSql = wSql || 'TER.BDNUMTER, ';
    wSql = wSql || 'TER.BDCOMPTER, ';
    wSql = wSql || 'TER.BDCEPTER, ';
    wSql = wSql || 'TER.BDBAITER, ';
    wSql = wSql || 'TER.BDDDDTER, ';
    wSql = wSql || 'TER.BDFONETER, ';
    wSql = wSql || 'TER.BDFAXTER, ';
    wSql = wSql || 'TER.BDEMAILTER, ';
    wSql = wSql || 'TER.BDIETER, ';
    wSql = wSql || 'TER.BDDATACADTER, ';
    wSql = wSql || 'TER.BDIMTER, ';
    wSql = wSql || 'TER.BDPRURALTER, ';
    wSql = wSql || 'TER.BDENQSIMPLESFEDTER, ';
    wSql = wSql || 'TER.BDINSCSUFRAMATER, ';
    wSql = wSql || 'TER.BDCODGPS, ';
    wSql = wSql || 'TER.BDCODCID, ';
    wSql = wSql || 'TER.BDCODPAIS, ';
    wSql = wSql || 'TER.BDDESCPAIS, ';
    wSql = wSql || 'TER.BDDDDFAXTER, ';
    wSql = wSql || 'CID.BDCODUF, ';
    wSql = wSql || 'UF.BDSIGLAUF, ';
    wsql = wsql || 'CID.BDNOMCID,';
    wsql = wsql || 'TER.BDORGAOPUBLICO,';
    wsql = wsql || 'TER.BDCODTIPO,';
    wsql = wsql || 'CID.BDCODIBGE';
 
    wSql = wsql || ' FROM vw_tterceiro TER ';

    wSql = wsql || ' left outer join tcidade CID';
    wSql = wsql || ' on (TER.BDCODCID = CID.bdCODCID)';
    wSql = wsql || ' left outer join tuf UF';
    wSql = wsql || ' on (CID.BDCODUF = UF.bdCODUF)';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' TER.bdcodTER = '||prcodter;

  IF (prwhereTER IS NOT NULL AND prwhereTER <> '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereTER;
    END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TER.bdcodTER';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODTER,
    :BDCODPLAPADRAO,
    :BDCODTPLA,
    :BDCGCTER,
    :BDREFEMP,
    :BDAPELIDOTER,
    :BDNOMETER, 
    :BDLOGRTER, 
    :BDENDTER, 
    :BDNUMTER, 
    :BDCOMPTER,
    :BDCEPTER, 
    :BDBAITER, 
    :BDDDDTER, 
    :BDFONETER,
    :BDFAXTER,
    :BDEMAILTER,
    :BDIETER,
    :BDDATACADTER,
    :BDIMTER,
    :BDPRURALTER,
    :BDENQSIMPLESFEDTER,
    :BDINSCSUFRAMATER,
    :BDCODGPS,
    :BDCODCID,
    :BDCODPAIS,
    :bddescpais, 
    :BDDDDFAXTER,
    :BDCODUF,
    :BDSIGLAUF,
    :bdnomcid,
    :BDORGAOPUBLICO,
    :BDCODTIPO,
 :BDCODIBGE
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_CONSULTACLIENTES */
ALTER PROCEDURE SP_CONSULTACLIENTES(PRREFMICRO INTEGER,
PRCODCLI VARCHAR(10240),
PRCODSITCLI INTEGER)
 RETURNS(BDCODCLI INTEGER,
BDCODESC INTEGER,
BDCODPRESER INTEGER,
BDCODCLIMATRIZ INTEGER,
BDCNPJCLI VARCHAR(18),
BDDATAINIATIVCLI DATE,
BDDATAFIMATIVCLI DATE,
BDORGAOCLI VARCHAR(20),
BDNUMREGCLI VARCHAR(40),
BDNOMECARTORIO VARCHAR(100),
BDDATAREGCLI DATE,
BDLIVROREG VARCHAR(15),
BDFOLHAREG VARCHAR(15),
BDDOCAUXREG VARCHAR(18),
BDCODTIPOCLI INTEGER,
BDDATACADCLI DATE,
BDCODCID INTEGER,
BDCODCNAE INTEGER,
BDCODNATJUR INTEGER,
BDDESCPLASITFIN VARCHAR(50),
BDCODPLASITFIN INTEGER,
BDAPECLI DM_BDAPEMP,
BDNOMCLI DM_BDNOMEMP,
BDNOMREDUZCLI DM_BDNOMREDUZEMP,
BDCEPCLI VARCHAR(9),
BDLOGRCLI VARCHAR(15),
BDENDCLI DM_BDENDERECO,
BDNUMCLI INTEGER,
BDCOMPLCLI DM_BDCOMPENDERECO,
BDBAICLI DM_BDBAIRRO,
BDDDDCLI INTEGER,
BDFONECLI DM_BDTELEFONE,
BDDDDFAXCLI INTEGER,
BDFONEFAXCLI DM_BDTELEFONE,
BDDDDCELCLI INTEGER,
BDCELCLI DM_BDTELEFONE,
BDCXPCLI DM_CXPOSTAL,
BDIECLI VARCHAR(20),
BDIMCLI VARCHAR(20),
BDEMAILCLI DM_BDEMAIL,
BDCAPITALSOC DM_NUMERIC_15_2,
BDORGAOPUBLICO DM_BOOLEAN,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCCNAE VARCHAR(200),
BDDESCNAT VARCHAR(100),
BDNUMFUN INTEGER,
BDCODPLATRIB INTEGER,
BDINATIVO DM_BOOLEAN,
BDDESCPLATRIB VARCHAR(50),
BDCODIBGECID INTEGER,
BDCODFEDCID INTEGER,
BDCODSPEDPAIS INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'cli.BDCODCLI, cli.BDCODESC, cli.BDCODPRESER, cli.BDCODCLIMATRIZ, ';
  wSql = wSql||'cli.BDCNPJCLI, cli.BDDATAINIATIVCLI, cli.BDDATAFIMATIVCLI, ';
  wSql = wSql||'cli.BDORGAOCLI, cli.BDNUMREGCLI, cli.BDNOMECARTORIO, cli.BDDATAREGCLI, ';
  wSql = wSql||'cli.BDLIVROREG, cli.BDFOLHAREG, cli.BDDOCAUXREG, cli.BDCODTIPOCLI, cli.BDDATACADCLI, ';
  wSql = wSql||'refcli.BDCODCID, refcli.BDCODCNAE, refcli.BDCODNATJUR, ';
  wSql = wSql||'/*refcli.BDCODSITCLI,*/ refcli.BDAPECLI, refcli.BDNOMCLI, ';
  wSql = wSql||'refcli.BDNOMREDUZCLI, refcli.BDCEPCLI, refcli.BDLOGRCLI, ';
  wSql = wSql||'refcli.BDENDCLI, refcli.BDNUMCLI, refcli.BDCOMPLCLI, ';
  wSql = wSql||'refcli.BDBAICLI, refcli.BDDDDCLI, refcli.BDFONECLI, ';
  wSql = wSql||'refcli.BDDDDFAXCLI, refcli.BDFONEFAXCLI, refcli.BDDDDCELCLI, ';
  wSql = wSql||'refcli.BDCELCLI, refcli.BDCXPCLI,refcli.BDIECLI, refcli.BDIMCLI, ';
  wSql = wSql||'refcli.BDEMAILCLI, refcli.BDCAPITALSOC, refcli.BDORGAOPUBLICO, ';
  wSql = wSql||'/*refcli.BDDATAENTRADA, refcli.BDDATASAIDA,*/ refcli.bdnumfun, refcli.bdinativo, refcli.bdcodplatrib, ';
  wSql = wSql||'refcli.BDCODPLANOONLINE, refcli.BDCODPLAPADRAO, refcli.BDCODHIST, ';
  wSql = wsql||'cid.bdnomcid, uf.bdsiglauf, ';
  wSql = wSql||'/*sitcli.bddescsitcli,*/ cnae.BDDESCCNAE, natjur.bddescnat, tplatrib.bddescplatrib, ';
  wSql = wSql||'cid.bdcodibge bdcodibgecid, cid.bdcodfed bdcodfedcid, pais.bdcodsped bdcodspedpais, ';
  wSql = wSql||'refcli.BDCODPLASITFIN, plasit.BDDESCPLASITFIN ';
  wSql = wSql||' from VFIN_BASE_TCLIENTE cli ';
  wSql = wSql||' join vw_vfin_clientes_ref refcli on (refcli.bdcodcli = cli.bdcodcli) ';
  wSql = wSql||' left outer join tcidade cid on (cid.bdcodcid = refcli.bdcodcid)  ';
  wSql = wSql||' left outer join tpais pais on pais.bdcodpais = cid.bdcodpais ';
  wSql = wSql||' left outer join tuf uf on (uf.bdcoduf = cid.bdcoduf) ';
  /*wSql = wSql||' left outer join vfin_base_ttabsitcli sitcli on (sitcli.bdcodsitcli = refcli.bdcodsitcli) ';*/
  wSql = wSql||' left outer join VFIN_BASE_TPLANOSITFIN plasit on (plasit.bdcodplasitfin = refcli.bdcodplasitfin) ';
  wSql = wSql||' left outer join tcnae cnae on (cnae.bdcodcnae = refcli.bdcodcnae) ';
  wSql = wSql||' left outer join tnatjur natjur on (natjur.bdcodnatjur = refcli.bdcodnatjur) ';
  wSql = wSql||' left outer join VCT_PLANO_TRIBUTARIO tplatrib on (tplatrib.bdcodplatrib = refcli.bdcodplatrib) ';

  wwhere = '';

  IF ((prcodcli IS NOT NULL) AND (prcodcli <> '0') AND (prcodcli <> '')) THEN
     BEGIN
       SELECT POSITION('=', :prcodcli) FROM RDB$DATABASE INTO wpos;

       IF (wPos = 0) THEN
          SELECT POSITION(' in (', :prcodcli) FROM RDB$DATABASE INTO :wpos;

       IF (wPos = 0) THEN
          SELECT POSITION(' between ', :prcodcli) FROM RDB$DATABASE INTO :wpos;

       IF (wpos > 0) THEN
          wwhere = wwhere||' ('||prcodcli||') ';
       ELSE
          wwhere = wwhere||' cli.bdcodcli = '||prcodcli;
     END

  /*Comentado pois n?o existe mais o campo BDCODSITCLI na tabela de clientes*/
  /* filra situa??o do cliente*/
  /*if (PRCODSITCLI is not null and PRCODSITCLI <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wWhere = 'ref.bdCODSITCLI = '||prCODSITCLI;
     end*/

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By cli.BDCODCLI';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    /*BDCODSITCLI,*/
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    /*BDDATAENTRADA,
    BDDATASAIDA,*/
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDNOMCID,
    BDSIGLAUF,
    /*BDDESCSITCLI,*/
    BDDESCCNAE,
    BDDESCNAT,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODPLASITFIN,
    BDDESCPLASITFIN
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_CONSULTACLIENTES_SIS */
ALTER PROCEDURE SP_CONSULTACLIENTES_SIS(PRREFMICRO INTEGER,
PRCODCLI INTEGER,
PRCODSITCLI INTEGER)
 RETURNS(BDCODCLI INTEGER,
BDCODESC INTEGER,
BDCODPRESER INTEGER,
BDCODCLIMATRIZ INTEGER,
BDCNPJCLI VARCHAR(18),
BDDATAINIATIVCLI DATE,
BDDATAFIMATIVCLI DATE,
BDORGAOCLI VARCHAR(20),
BDNUMREGCLI VARCHAR(40),
BDNOMECARTORIO VARCHAR(100),
BDDATAREGCLI DATE,
BDLIVROREG VARCHAR(15),
BDFOLHAREG VARCHAR(15),
BDDOCAUXREG VARCHAR(18),
BDCODTIPOCLI INTEGER,
BDDATACADCLI DATE,
BDCODCID INTEGER,
BDCODCNAE INTEGER,
BDCODNATJUR INTEGER,
BDAPECLI DM_BDAPEMP,
BDNOMCLI DM_BDNOMEMP,
BDNOMREDUZCLI DM_BDNOMREDUZEMP,
BDCEPCLI VARCHAR(9),
BDLOGRCLI VARCHAR(15),
BDENDCLI DM_BDENDERECO,
BDNUMCLI INTEGER,
BDCOMPLCLI DM_BDCOMPENDERECO,
BDBAICLI DM_BDBAIRRO,
BDDDDCLI INTEGER,
BDFONECLI DM_BDTELEFONE,
BDDDDFAXCLI INTEGER,
BDFONEFAXCLI DM_BDTELEFONE,
BDDDDCELCLI INTEGER,
BDCELCLI DM_BDTELEFONE,
BDCXPCLI DM_CXPOSTAL,
BDIECLI VARCHAR(20),
BDIMCLI VARCHAR(20),
BDEMAILCLI DM_BDEMAIL,
BDCAPITALSOC DM_NUMERIC_15_2,
BDORGAOPUBLICO DM_BOOLEAN,
BDDATAENTRADA DATE,
BDDATASAIDA DATE,
BDCODCONT INTEGER,
BDCONTATO VARCHAR(60),
BDPROFISCONTATO VARCHAR(60),
BDDATANASCCON DATE,
BDCPFCON VARCHAR(18),
BDCODCIDETI INTEGER,
BDNOMENDETI DM_BDNOMEMP,
BDLOGRETI VARCHAR(15),
BDENDERECOETI DM_BDENDERECO,
BDNUMEROETI INTEGER,
BDCOMPLETI DM_BDCOMPENDERECO,
BDBAIRROETI DM_BDBAIRRO,
BDCEPETI VARCHAR(9),
BDCXPETI DM_CXPOSTAL,
BDNOMCIDETI VARCHAR(40),
BDSIGLAUFETI VARCHAR(2),
BDCODENQFED INTEGER,
BDCOMERCIO DM_BOOLEAN,
BDINDUSTRIA DM_BOOLEAN,
BDSERVICO DM_BOOLEAN,
BDANEXOIII DM_BOOLEAN,
BDANEXOIV DM_BOOLEAN,
BDANEXOV DM_BOOLEAN,
BDANEXOVI DM_BOOLEAN,
BDPERINSS DM_NUMERIC_7_4_ALIQ,
BDDEDINSSNF DM_BOOLEAN,
BDUSARPERISS INTEGER,
BDRETIR DM_BOOLEAN,
BDRETCSLL DM_BOOLEAN,
BDRETCOF DM_BOOLEAN,
BDRETPIS DM_BOOLEAN,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCSITCLI VARCHAR(100),
BDDESCCNAE VARCHAR(200),
BDDESCNAT VARCHAR(100),
BDNUMFUN INTEGER,
BDINATIVO DM_BOOLEAN,
BDCODPLATRIB INTEGER,
BDDESCPLATRIB VARCHAR(50),
BDCODIBGECID INTEGER,
BDCODFEDCID INTEGER,
BDCODSPEDPAIS INTEGER,
BDINCENTCULT DM_BOOLEAN,
BDCODIBGECIDETI INTEGER,
BDCODFEDCIDETI INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODSITESP INTEGER,
BDCODPLASITFIN INTEGER,
BDDESCPLASITFIN VARCHAR(50),
BDCODHIST INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'ref.BDCODCLI, ';
  wSql = wSql||'ref.BDCODESC, ';
  wSql = wSql||'ref.BDCODPRESER, ';
  wSql = wSql||'ref.BDCODCLIMATRIZ, ';
  wSql = wSql||'ref.BDCNPJCLI, ';
  wSql = wSql||'ref.BDDATAINIATIVCLI, ';
  wSql = wSql||'ref.BDDATAFIMATIVCLI, ';
  wSql = wSql||'ref.BDORGAOCLI, ';
  wSql = wSql||'ref.BDNUMREGCLI, ';
  wSql = wSql||'ref.BDNOMECARTORIO, ';
  wSql = wSql||'ref.BDDATAREGCLI, ';
  wSql = wSql||'ref.BDLIVROREG, ';
  wSql = wSql||'ref.BDFOLHAREG, ';
  wSql = wSql||'ref.BDDOCAUXREG, ';
  wSql = wSql||'ref.BDCODTIPOCLI, ';
  wSql = wSql||'ref.BDDATACADCLI, ';
  wSql = wSql||'ref.BDCODCID, ';
  wSql = wSql||'ref.BDCODCNAE, ';
  wSql = wSql||'ref.BDCODNATJUR, ';
  /*wSql = wSql||'ref.BDCODSITCLI, ';*/
  wSql = wSql||'ref.BDAPECLI, ';
  wSql = wSql||'ref.BDNOMCLI, ';
  wSql = wSql||'ref.BDNOMREDUZCLI, ';
  wSql = wSql||'ref.BDCEPCLI, ';
  wSql = wSql||'ref.BDLOGRCLI, ';
  wSql = wSql||'ref.BDENDCLI, ';
  wSql = wSql||'ref.BDNUMCLI, ';
  wSql = wSql||'ref.BDCOMPLCLI, ';
  wSql = wSql||'ref.BDBAICLI, ';
  wSql = wSql||'ref.BDDDDCLI, ';
  wSql = wSql||'ref.BDFONECLI, ';
  wSql = wSql||'ref.BDDDDFAXCLI, ';
  wSql = wSql||'ref.BDFONEFAXCLI, ';
  wSql = wSql||'ref.BDDDDCELCLI, ';
  wSql = wSql||'ref.BDCELCLI, ';
  wSql = wSql||'ref.BDCXPCLI, ';
  wSql = wSql||'ref.BDIECLI, ';
  wSql = wSql||'ref.BDIMCLI, ';
  wSql = wSql||'ref.BDEMAILCLI, ';
  wSql = wSql||'ref.BDCAPITALSOC, ';
  wSql = wSql||'ref.BDORGAOPUBLICO, ';
  /*wSql = wSql||'ref.BDDATAENTRADA, ';
  wSql = wSql||'ref.BDDATASAIDA, ';*/
  wSql = wSql||'ref.bdnomcid, ';
  wSql = wSql||'ref.bdsiglauf, ';
  /*wSql = wSql||'ref.bddescsitcli, ';*/
  wSql = wSql||'ref.bddesccnae, ';
  wSql = wSql||'ref.bddescnat, ';
  wSql = wSql||'ref.bdnumfun, ';
  wSql = wSql||'ref.bdinativo, ';
  wSql = wSql||'ref.bdcodplatrib, ';
  wSql = wSql||'ref.bddescplatrib, ';
  wSql = wSql||'ref.bdcodibgecid, ';
  wSql = wSql||'ref.bdcodfedcid, ';
  wSql = wSql||'ref.bdcodspedpais, ';
  wSql = wSql||'ref.BDCODPLANOONLINE, ';
  wSql = wSql||'ref.BDCODPLAPADRAO, ';
  wSql = wSql||'ref.BDCODHIST, ';
  wSql = wSql||'reftot.BDCODCONT, ';
  wSql = wSql||'reftot.BDCONTATO, ';
  wSql = wSql||'reftot.BDPROFISCONTATO, ';
  wSql = wSql||'reftot.BDDATANASCCON, ';
  wSql = wSql||'reftot.BDCPFCON, ';
  wSql = wSql||'reftot.BDCODCIDETI, ';
  wSql = wSql||'reftot.BDNOMENDETI, ';
  wSql = wSql||'reftot.BDLOGRETI, ';
  wSql = wSql||'reftot.BDENDERECOETI, ';
  wSql = wSql||'reftot.BDNUMEROETI, ';
  wSql = wSql||'reftot.BDCOMPLETI, ';
  wSql = wSql||'reftot.BDBAIRROETI, ';
  wSql = wSql||'reftot.BDCEPETI, ';
  wSql = wSql||'reftot.BDCXPETI, ';
  wSql = wSql||'reftot.BDNOMCIDETI, ';
  wSql = wSql||'reftot.BDSIGLAUFETI, ';
  wSql = wSql||'reftot.BDCODENQFED, ';
  wSql = wSql||'reftot.BDCOMERCIO, ';
  wSql = wSql||'reftot.BDINDUSTRIA, ';
  wSql = wSql||'reftot.BDSERVICO, ';
  wSql = wSql||'reftot.BDANEXOIII, ';
  wSql = wSql||'reftot.BDANEXOIV, ';
  wSql = wSql||'reftot.BDANEXOV, ';
  wSql = wSql||'reftot.BDANEXOVI, ';
  wSql = wSql||'reftot.BDPERINSS, ';
  wSql = wSql||'reftot.BDDEDINSSNF, ';
  wSql = wSql||'reftot.BDUSARPERISS, ';
  wSql = wSql||'reftot.BDRETIR, ';
  wSql = wSql||'reftot.BDRETCSLL, ';
  wSql = wSql||'reftot.BDRETCOF, ';
  wSql = wSql||'reftot.BDRETPIS, ';
  wSql = wSql||'reftot.BDINCENTCULT, ';
  wSql = wSql||'reftot.BDCODIBGECIDETI, ';
  wSql = wSql||'reftot.BDCODFEDCIDETI, ';
  wSql = wSql||'reftot.BDCODSITESP, ';
  wSql = wSql||'ref.BDCODPLASITFIN, ';
  wSql = wSql||'ref.BDDESCPLASITFIN ';


  WPAR = 'from sp_consultaclientes('||prrefmicro;
  IF (prcodcli IS NOT NULL AND prcodcli <> 0) THEN
    wpar = wpar||','||prcodcli||',';
  ELSE
    wpar = wpar||',null,';

  IF (PRCODSITCLI IS NULL) THEN
    wpar = wpar||'0) ref';
  ELSE
    wpar = wpar||PRCODSITCLI||') ref';

  wSql = wsql || wpar;

  wSql = wsql || ' left outer join VW_VFIN_BASE_TCLIENTE_REF_TOTAL reftot on (reftot.bdcodcli = ref.bdcodcli) ';

  wwhere = '';

  IF (prcodcli IS NOT NULL AND prcodcli <> 0) THEN
     wwhere = wwhere || ' ref.bdcodcli = '||prcodcli;

  /*Comentado pois n?o existe mais o campo BDCODSITCLI na tabela de clientes*/
  /* filra empresas inativas */
  /*IF (prcodsitcli IS NOT NULL AND prcodsitcli <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'ref.BDCODSITCLI) = '||prcodsitcli;
     END*/

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By ref.BDCODCLI';


  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    /*BDCODSITCLI,*/
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    /*BDDATAENTRADA,
    BDDATASAIDA,*/
    BDNOMCID,
    BDSIGLAUF,
    /*BDDESCSITCLI,*/
    BDDESCCNAE,
    BDDESCNAT,
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCONT,
    BDCONTATO,
    BDPROFISCONTATO,
    BDDATANASCCON,
    BDCPFCON,
    BDCODCIDETI,
    BDNOMENDETI,
    BDLOGRETI,
    BDENDERECOETI,
    BDNUMEROETI,
    BDCOMPLETI,
    BDBAIRROETI,
    BDCEPETI,
    BDCXPETI,
    BDNOMCIDETI,
    BDSIGLAUFETI,
    BDCODENQFED,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDPERINSS,
    BDDEDINSSNF,
    BDUSARPERISS,
    BDRETIR,
    BDRETCSLL,
    BDRETCOF,
    BDRETPIS,
    BDINCENTCULT,
    BDCODIBGECIDETI,
    BDCODFEDCIDETI,
    BDCODSITESP,
    BDCODPLASITFIN,
    BDDESCPLASITFIN
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_CONSULTADESPESAS */
ALTER PROCEDURE SP_CONSULTADESPESAS(PRREFDESP INTEGER,
PRCODDESP INTEGER)
 RETURNS(BDCODDESP INTEGER,
BDCLASSDESP DM_CLASSCONTAS,
BDDESCDESP VARCHAR(100),
BDSABDOMFER INTEGER,
BDDIAVENC INTEGER,
BDTIPODESP INTEGER,
BDVALORDESP DM_NUMERIC_15_2)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefdesp, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'desp.BDCODDESP, ';
  wSql = wSql||'desp.BDCLASSDESP, ';
  wSql = wSql||'desp.BDDESCDESP, ';
  wSql = wSql||'refdesp.BDSABDOMFER, ';
  wSql = wSql||'refdesp.BDDIAVENC, ';
  wSql = wSql||'desp.BDTIPODESP, ';
  wSql = wSql||'refdesp.BDVALORDESP ';
  wSql = wSql||'from VFIN_BASE_TDESPESA desp ';
  wSql = wsql||'left outer join VW_VFIN_BASE_TDESPESA_REF refdesp on (refdesp.bdcoddesp = desp.bdcoddesp) ';

  wwhere = '';

  IF (prcoddesp IS NOT NULL AND prcoddesp <> 0) THEN
     wwhere = wwhere || ' desp.bdcoddesp = '||prcoddesp;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By desp.BDCODDESP';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODDESP,
    BDCLASSDESP,
    BDDESCDESP,
    BDSABDOMFER,
    BDDIAVENC,
    BDTIPODESP,
    bdvalordesp
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_CONSULTAEMPRESAS_SEARCH */
ALTER PROCEDURE SP_CONSULTAEMPRESAS_SEARCH(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDAPEEMP VARCHAR(20),
BDIEEMP VARCHAR(20))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);


  wSql = ' select TEMP.BDCODEMP, TEMP.BDCNPJEMP, TREF.bdapeemp, '||
                 'tref.BDIEEMP '||
      ' from TEMPRESAS TEMP'||
      ' left outer join vw_tempresas_ref tref  on (tref.bdcodemp = temp.bdcodemp)';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' TEMP.bdcodemp = '||prcodemp;

  /* filra empresas inativas */
  IF (prinativas IS NOT NULL AND prinativas <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'UPPER(tref.BDSITEMP) = '''||'FALSE''';
     END


  /*
  for select BDCODUSU from sp_get_usuario
  into
    :wcodusu
  do

   filtra as empresas por usuario
  if (wcodusu is not null and wcodusu <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TEMP.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     end   */

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TEMP.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCNPJEMP,
    :BDAPEEMP,
    :BDIEEMP
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_CONSULTAEMPRESAS_SIS */
ALTER PROCEDURE SP_CONSULTAEMPRESAS_SIS(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDDATAINIATIVEMP DATE,
BDORGAOEMP VARCHAR(8),
BDDATAREGEMP DATE,
BDDATACONSTEMP DATE,
BDDESCCARTEMP VARCHAR(40),
BDDATAFIMATIVEMP DATE,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCODCENTROS INTEGER,
BDCODCID INTEGER,
BDCODCONT INTEGER,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDNOMREDUZEMP DM_BDNOMREDUZEMP,
BDAPEEMP DM_BDAPEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDFAXEMP DM_BDTELEFONE,
BDDDDCELULAREMP INTEGER,
BDCELULAREMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDLOGREMP VARCHAR(15),
BDIEEMP VARCHAR(20),
BDIMEMP VARCHAR(20),
BDSITEMP VARCHAR(5),
BDDDDFAXEMP INTEGER,
BDNOMCID VARCHAR(40),
BDCODUF INTEGER,
BDNOMECONT VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCUF VARCHAR(40),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODCONFATIVO INTEGER,
BDSUFRAMA VARCHAR(9),
BDCODACESSOSN VARCHAR(12),
BDPERFILSPED INTEGER,
BDATIVIDADESPED INTEGER,
BDCODCONFIPI INTEGER,
BDCODCONFIRLP INTEGER,
BDCODCONFDIMESC INTEGER,
BDCODPORTEEMP INTEGER,
BDCODAPUCON INTEGER,
BDCODESCCONT INTEGER,
BDCODREGAPU INTEGER,
BDCONTPRODEC VARCHAR(5),
BDNRPARPRODEC INTEGER,
BDLANBCICMSVALCONT VARCHAR(5),
BDLANBCICMSISEOUT INTEGER,
BDLANCLISAISER VARCHAR(5),
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDMOVSER VARCHAR(5),
BDPERCISS NUMERIC(15,6),
BDREDPERCISS NUMERIC(15,6),
BDMOVIRRF VARCHAR(5),
BDALIQIRRF NUMERIC(15,6),
BDISENTOIRRF NUMERIC(15,6),
BDEMPINATIVA VARCHAR(5),
BDEMPDIFPAPEL VARCHAR(5),
BDEMPBARREST VARCHAR(5),
BDVERIFICARNOTASJALAN INTEGER,
BDCODPLANOONLINE INTEGER,
BDLRISSSN NUMERIC(15,6),
BDCOMERCIO VARCHAR(5),
BDINDUSTRIA VARCHAR(5),
BDSERVICO VARCHAR(5),
BDANEXOIII VARCHAR(5),
BDANEXOIV VARCHAR(5),
BDANEXOV VARCHAR(5),
BDCODENQFED INTEGER,
BDSUBSTRIB INTEGER,
BDCODCONFDACON INTEGER,
BDCODCONFICMSSPED INTEGER,
BDCODCONFCIAP INTEGER,
BDREDBCICMSENT NUMERIC(15,6),
BDREDBCICMSSAI NUMERIC(15,6),
BDCODCONFDASN INTEGER,
BDRETPARPIS VARCHAR(5),
BDRETPARCOFINS VARCHAR(5),
BDRETPARCSLL VARCHAR(5),
BDRETPARIRRF VARCHAR(5),
BDRETPARISSQN VARCHAR(5),
BDRETPARINSS VARCHAR(5),
BDRETPARFUNRURAL VARCHAR(5),
BDTIPOAPURACAO INTEGER,
BDSOMFREBASEICMS VARCHAR(5),
BDSOMFREVLRCONTAB VARCHAR(5),
BDCODPLATROCA INTEGER,
BDCODPLACFOP INTEGER,
BDCODCONFBLOCOP INTEGER,
BDCREDPRESUMIDO VARCHAR(5),
BDTERMOACEITE VARCHAR(5),
BDANTECIPAIMPOSTO VARCHAR(5),
BDTIPODECLARANTEDMED INTEGER,
BDREGISTROANSDMED INTEGER,
BDNUMEROCNESDMED INTEGER,
BDDTOBRIGSPEDCONT DATE,
BDTIPOAPURACAORET INTEGER,
BDTIPOAPURACAORETIR INTEGER,
BDDTOBRIGSPEDICMS DATE,
BDCODCONTEF INTEGER,
BDLIVRO VARCHAR(15),
BDFOLHA VARCHAR(15),
BDNOMECARTORIO VARCHAR(100),
BDLANCAPARCELAAUTO VARCHAR(5),
BDCODIGOPLA INTEGER,
BDINDATIV INTEGER,
BDTRANMANUAL VARCHAR(5),
BDIMPORTARVALORESICMSSN DM_BOOLEAN,
BDDIFALIQ VARCHAR(5),
BDDIFALIQBASEEM INTEGER,
BDANEXOVI DM_BOOLEAN,
BDCODPLATRIB INTEGER,
BDCODPLAPADRAOREF INTEGER,
BDINDNATPJ INTEGER,
BDCODIBGE INTEGER,
BDFORMATRIBUTACAO INTEGER,
BDSOMAPISCOFVLRCONT DM_BOOLEAN,
BDSOMAIIVLRCONT DM_BOOLEAN,
BDMANTERPARCELAS DM_BOOLEAN,
BDCODPLANOINCONS INTEGER,
BDABRIRRATEIO DM_BOOLEAN,
BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
BDINTEGRANET DM_BOOLEAN,
BDSOMAIPIPROD DM_BOOLEAN,
BDSOMAICMSVLRCONT DM_BOOLEAN,
BDCODPLAE115 INTEGER,
BDDATACADEMP DATE,
BDCODCLATRI INTEGER,
BDDATAOBRIGREINF DATE,
BDSOMASTPROD DM_BOOLEAN,
BDCALCANTICMS VARCHAR(5),
BDCONSIPIBC VARCHAR(5),
BDIMPICMSST VARCHAR(5),
BDANEXOIII_2018 VARCHAR(5),
BDANEXOIV_2018 VARCHAR(5),
BDANEXOV_2018 VARCHAR(5),
BDSTATUSEMP INTEGER,
BDQTDBACKUPEMP INTEGER,
BDIMPORTARISS VARCHAR(5),
BDINCORPORADORAS DM_BOOLEAN)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);
    wSql = ' select ';
    wSql = wsql || 'Tref.BDCODEMP, ';
    wSql = wsql || 'tref.BDCODMATRIZ, ';
    wSql = wsql || 'tref.BDCNPJEMP, ';
    wSql = wsql || 'tref.BDDATAINIATIVEMP, ';
    wSql = wsql || 'tref.BDORGAOEMP, ';
    wSql = wsql || 'tref.BDDATAREGEMP, ';
    wSql = wsql || 'tref.BDDATACONSTEMP, ';  --alt:14844 - Adicionado campo BDDATACONSTEMP na consulta. Ana - 05/08/2016
    wSql = wsql || 'tref.BDDESCCARTEMP, ';
    wSql = wsql || 'tref.BDDATAFIMATIVEMP, ';
    wSql = wsql || 'tref.BDCODPLAPADRAO, ';
    wSql = wsql || 'tref.BDCODHIST, ';
    wSql = wsql || 'tref.BDCODCENTROS, ';
    wSql = wsql || 'tref.BDCODCID, ';
    wSql = wsql || 'tref.BDCODCONT, ';
    wSql = wsql || 'tref.BDCODNATJUR, ';
    wSql = wsql || 'tref.BDCODCNAE, ';
    wSql = wsql || 'tref.BDNOMEMP, ';
    wSql = wsql || 'tref.BDNOMREDUZEMP, ';
    wSql = wsql || 'tref.BDAPEEMP, ';
    wSql = wsql || 'tref.BDENDEMP, ';
    wSql = wsql || 'tref.BDNUMEMP, ';
    wSql = wsql || 'tref.BDBAIEMP, ';
    wSql = wsql || 'tref.BDCEPEMP, ';
    wSql = wsql || 'tref.BDDDDEMP, ';
    wSql = wsql || 'tref.BDFONEEMP, ';
    wSql = wsql || 'tref.BDFAXEMP, ';
    wSql = wsql || 'tref.BDDDDCELULAREMP, ';
    wSql = wsql || 'tref.BDCELULAREMP, ';
    wSql = wsql || 'tref.BDEMAILEMP, ';
    wSql = wsql || 'tref.BDCOMPLEMP, ';
    wSql = wsql || 'tref.BDLOGREMP, ';
    wSql = wsql || 'tref.BDIEEMP, ';
    wSql = wsql || 'tref.BDIMEMP, ';
    wSql = wsql || 'tref.BDSITEMP, ';
    wSql = wsql || 'tref.BDDDDFAXEMP, ';
    wSql = wsql || 'Tref.BDNOMCID, ';
    wSql = wsql || 'Tref.BDCODUF, ';
    wSql = wsql || 'Tref.BDNOMECONT, ';
    wSql = wsql || 'tref.BDSIGLAUF, ';
    wSql = wsql || 'tref.BDDESCUF, ';
    wSql = wsql || 'tref.BDTRANMANUAL, ';
    wSQL = wsql || 'tref.BDDATACADEMP, ';

    wSql = wsql || 'trefsis.bdretinss, ';
    wSql = wsql || 'trefsis.bdvlrmininss, ';
    wSql = wsql || 'trefsis.bdSUFRAMA, ';
    wSql = wsql || 'trefsis.bdcodacessosn, ';
    wSql = wsql || 'trefsis.bdperfilsped, ';
    wSql = wsql || 'trefsis.bdatividadesped, ';
    wSql = wsql || 'trefsis.BDCODCONFIPI, ';
    wSql = wsql || 'trefsis.BDCODCONFIRLP, ';
    wSql = wsql || 'trefsis.BDCODCONFDIMESC, ';
    wSql = wsql || 'trefsis.BDCODPORTEEMP, ';
    wSql = wsql || 'trefsis.BDCODAPUCON, ';
    wSql = wsql || 'trefsis.BDCODESCCONT, ';
    wSql = wsql || 'trefsis.BDCODREGAPU, ';
    wSql = wsql || 'trefsis.BDCONTPRODEC, ';
    wSql = wsql || 'trefsis.BDNRPARPRODEC, ';
    --wSql = wsql || 'trefsis.BDDIAVCTOEMPSC, ';
    wSql = wsql || 'trefsis.BDCODCONFATIVO, ';
    --harry 17-02-2011
    wSql = wsql || 'trefsis.BDLANBCICMSVALCONT, ';
    wSql = wsql || 'trefsis.BDLANBCICMSISEOUT, ';
    wSql = wsql || 'trefsis.BDLANCLISAISER, ';
    wSql = wsql || 'trefsis.BDLANPROENT, ';
    wSql = wsql || 'trefsis.BDLANPROSAI, ';
    wSql = wsql || 'trefsis.BDMOVSER, ';
    wSql = wsql || 'trefsis.BDPERCISS, ';
    wSql = wsql || 'trefsis.BDREDPERCISS, ';
    wSql = wsql || 'trefsis.BDMOVIRRF, ';
    wSql = wsql || 'trefsis.BDALIQIRRF, ';
    wSql = wsql || 'trefsis.BDISENTOIRRF, ';
    wSql = wsql || 'trefsis.BDEMPINATIVA, ';
    wSql = wsql || 'trefsis.BDEMPDIFPAPEL, ';
    wSql = wsql || 'trefsis.BDEMPBARREST, ';
    wSql = wsql || 'trefsis.BDVERIFICARNOTASJALAN, ';

    wSql = wsql || 'tref.bdcodplanoonline, ';

    wSql = wsql || 'trefsis.bdlrisssn, ';
    wSql = wsql || 'trefsis.bdcomercio, ';
    wSql = wsql || 'trefsis.bdindustria, ';
    wSql = wsql || 'trefsis.bdservico, ';
    wSql = wsql || 'trefsis.bdanexoiii, ';
    wSql = wsql || 'trefsis.bdanexoiv, ';
    wSql = wsql || 'trefsis.bdanexov, ';
    wSql = wsql || 'enq.BDCODENQFED, ';
    wSql = wsql || 'case when (not (enq.BDFORMATRIBUTACAO is null)) then enq.BDFORMATRIBUTACAO else tref.BDFORMATRIBUTACAO end, ';
    wSql = wsql || 'TREFSIS.BDSUBSTRIB, ';
    wSql = wsql || 'TREFSIS.bdcodconfdacon, ';
    wSql = wsql || 'TREFSIS.bdcodconficmssped, ';
    wSql = wsql || 'TREFSIS.BDCODCONFCIAP, ';
    wSql = wsql || 'TREFSIS.BDREDBCICMSENT, ';
    wSql = wsql || 'TREFSIS.BDREDBCICMSSAI, ';
    wSql = wsql || 'TREFSIS.BDCODCONFDASN, ';

    wSql = wsql || 'TREFSIS.BDRETPARPIS, ';
    wSql = wsql || 'TREFSIS.BDRETPARCOFINS, ';
    wSql = wsql || 'TREFSIS.BDRETPARCSLL, ';
    wSql = wsql || 'TREFSIS.BDRETPARIRRF, ';
    wSql = wsql || 'TREFSIS.BDRETPARISSQN, ';
    wSql = wsql || 'TREFSIS.BDRETPARINSS, ';
    wSql = wsql || 'TREFSIS.BDRETPARFUNRURAL, ';
    wSql = wsql || 'TREFSIS.bdtipoapuracao, ';
    wSql = wsql || 'TREFSIS.BDSOMFREVLRCONTAB, ';
    wSql = wsql || 'TREFSIS.BDSOMFREBASEICMS, ';
    wSql = wsql || 'TREFSIS.BDCODPLATROCA, ';
    wSql = wsql || 'TREFSIS.bdcodplacfop, ';
    wSql = wsql || 'TREFSIS.bdcodconfblocop, ';
    wSql = wSql || 'TREFSIS.bdcredpresumido, ';
    wSql = wSql || 'TREFSIS.bdTERMOACEITE, '; --#Alt:84445 (04/06/2018) Patr?cio H. Lehn
    wSql = wSql || 'TREFSIS.bdantecipaimposto, ';
    wSql = wsql || 'TREFSIS.BDTIPODECLARANTEDMED, ';
    wSql = wsql || 'TREFSIS.BDREGISTROANSDMED, ';
    wSql = wsql || 'TREFSIS.BDNUMEROCNESDMED, ';
    wSql = wsql || 'TREFSIS.BDDTOBRIGSPEDCONT, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORET, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORETIR, ';
    wSql = wSql || 'TREFSIS.BDDTOBRIGSPEDICMS, ';
    wsql = wsql || 'TREF.BDCODCONTEF, ';
    wsql = wsql || 'TREF.BDLIVRO, ';
    wsql = wsql || 'TREF.BDFOLHA, ';
    wsql = wsql || 'TREF.BDNOMECARTORIO, ';
    wsql = wsql || 'TREFSIS.BDLANCAPARCELAAUTO, ';
    wsql = wsql || 'TREFSIS.BDCODIGOPLA, ';
    wSql = wsql || 'TREFSIS.BDINDATIV, ';
    wSql = wSql || 'parinteg.BDIMPORTARVALORESICMSSN, ';
    wSql = wSql || 'parinteg.BDDIFALIQ, ';
    wSql = wSql || 'parinteg.BDDIFALIQBASEEM, ';
    wSql = wSql || 'TREFSIS.BDANEXOVI, ';
    wsql = wsql || 'tref.bdcodplatrib, ';
    wSQL = wSQL || 'TREF.BDCODPLAPADRAOREF, '; --alt:11108 - Adicionado novo campo na tabela e na SP. Pedro
    wSql = wsql || 'TREFSIS.BDINDNATPJ, ';
    wSql = wsql || 'TREF.BDCODIBGE, '; --Sol: 11334 Patrick T. S? 03/07/2015. Traz o c?digo do IBGE para verificar o tipo de ISS da empresa
     /*
      Sol: 11439 Patrick T. S? 03/07/2015. Retorna campos para verificar
      se ? para somar ou n?o o imposto de importa??o(II). Parametros incluidos no cadastro de empresas.
    */
    wSql = wSql || 'parinteg.BDSOMAPISCOFVLRCONT, ';
    wSql = wSql || 'parinteg.BDSOMAIIVLRCONT, ';
    wsql = wsql || 'TREFSIS.BDMANTERPARCELAS, ';
    wsql = wsql || 'TREFSIS.BDCODPLANOINCONS, ';
    wSQL = wSQL || 'tref.BDABRIRRATEIO, '; --alt:13677 - 15/03/2016 - Adicionados par?metros. Pedro
    wSQL = wSQL || 'tref.BDNAOPERMITERATEIOGRUPO, '; --alt:13677 - 15/03/2016 - Adicionados par?metros. Pedro
    wSQL = wSQL || 'tref.BDINTEGRANET, '; --alt:14035 - Adicionado par?metro para o IntegraNet. Everton
    wSQL = wSQL || 'parinteg.BDSOMAIPIPROD, ';
    wSql = wSql || 'parinteg.BDSOMAICMSVLRCONT, ';
    wSql = wSql || 'parinteg.BDCODPLAE115, ';
    wSql = wSql || 'tesocial.BDCODCLATRI, ';
    wSql = wSql || 'tref.BDDATAOBRIGREINF, ';
    wSQL = wSQL || 'parinteg.BDSOMASTPROD, ';
    wSql = wSql || 'parinteg.BDCALCANTICMS, ';
    wSql = wSql || 'parinteg.BDCONSIPIBC, ';
    WSQL = WSQL || 'parinteg.BDIMPICMSST, ';
    wSql = wsql || 'trefsis.bdanexoiii_2018, ';
    wSql = wsql || 'trefsis.bdanexoiv_2018, ';
    wSql = wsql || 'trefsis.bdanexov_2018, ';
    wSQL = wsql || 'tref.BDSTATUSEMP, ';   --#Alt:16965 - Carlos Mello (06/10/2017)
    wSQL = wsql || 'tref.BDQTDBACKUPEMP, '; --#Alt:16965 - Carlos Mello (06/10/2017)
    wSql = wSql || 'parinteg.BDIMPORTARISS, ';
    wSql = wsql || 'tref.BDINCORPORADORAS ';
/*
       parger.BDLANBCICMSVALCONT,
       parger.BDLANBCICMSISEOUT,
       parger.BDLANCLISAISER,
       parger.BDLANPROENT,
       parger.BDLANPROSAI,
       parger.BDMOVSER,
       parger.BDPERCISS,
       parger.BDREDPERCISS,
       parger.BDMOVIRRF,
       parger.BDALIQIRRF,
       parger.BDISENTOIRRF,
       parger.BDEMPINATIVA,
       parger.BDEMPDIFPAPEL,
       parger.BDEMPBARREST,
       parger.BDVERIFICARNOTASJALAN
*/

  WPAR = 'from sp_consultaempresas('||prrefmicro;
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wpar = wpar||','||prcodemp||',';
  ELSE
    wpar = wpar||',null,';

  IF (prinativas IS NULL) THEN
    wpar = wpar||'0) tref';
  ELSE
    wpar = wpar||prinativas||') tref';

--  if (prinativas is null) then
--     wSql = wsql || ' from sp_consultaempresas('||prrefmicro||','||PRCODEMP||',0) tref';
--  else
--     wSql = wsql || ' from sp_consultaempresas('||prrefmicro||','||PRCODEMP||','||PRINATIVAS||') tref';

    wSql = wsql || wpar;

    wSql = wsql || ' left outer join vw_emp_ref_TOTAL TREFSIS on (TREFSIS.bdcodemp = tref.bdcodemp) ';
    wSql = wsql || ' left outer join VW_TENQFED Enq  on (Enq.bdcodemp = tref.bdcodemp) ';
    wSql = wSql || ' left outer join VW_VEF_BASE_TEMPPARINTEG parinteg on ( parinteg.bdCodEmp = tref.bdCodEmp ) and ( parinteg.bdRefEmp = trefsis.bdRefEmp ) ';
    wSql = wSql || ' left outer join VW_VRHF_BASE_TEMPESOCIAL tesocial on ( tesocial.bdcodemp = tref.bdcodemp) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' tref.bdcodemp = '||prcodemp;

  /* filra empresas inativas */
  IF (prinativas IS NOT NULL AND prinativas <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'UPPER(tref.BDSITEMP) = '''||'FALSE''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By tref.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODMATRIZ,
    :BDCNPJEMP,
    :BDDATAINIATIVEMP,
    :BDORGAOEMP,
    :BDDATAREGEMP,
    :BDDATACONSTEMP, --alt:14844 - Novo campo no cadastro de empresa. Ana - 05/08/2016
    :BDDESCCARTEMP,
    :BDDATAFIMATIVEMP,
    :BDCODPLAPADRAO,
    :BDCODHIST,
    :BDCODCENTROS,
    :BDCODCID,
    :BDCODCONT,
    :BDCODNATJUR,
    :BDCODCNAE,
    :BDNOMEMP,
    :BDNOMREDUZEMP,
    :BDAPEEMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDFAXEMP,
    :bddddcelularemp,
    :bdcelularemp,
    :BDEMAILEMP,
    :BDCOMPLEMP,
    :BDLOGREMP,
    :BDIEEMP,
    :BDIMEMP,
    :BDSITEMP,
    :BDDDDFAXEMP,
    :BDNOMCID,
    :BDCODUF,
    :BDNOMECONT,
    :BDSIGLAUF,
    :BDDESCUF,
    :BDTRANMANUAL,
    :BDDATACADEMP, 

    :bdretinss,
    :bdvlrmininss,
    :BDSUFRAMA,
    :bdcodacessosn,
    :bdperfilsped,
    :bdatividadesped,

    :BDCODCONFIPI,
    :BDCODCONFIRLP,
    :BDCODCONFDIMESC,
    :BDCODPORTEEMP,
    :BDCODAPUCON,
    :BDCODESCCONT ,
    :BDCODREGAPU ,
    :BDCONTPRODEC ,
    :BDNRPARPRODEC ,
    --:BDDIAVCTOEMPSC,
    :BDCODCONFATIVO,

    --harry 17-02-2011
    :bdlanbcicmsvalcont,
    :bdlanbcicmsiseout,
    :bdlanclisaiser,
    :bdlanproent,
    :bdlanprosai,
    :bdmovser,
    :bdperciss,
    :bdredperciss,
    :bdmovirrf,
    :bdaliqirrf ,
    :bdisentoirrf,
    :bdempinativa ,
    :bdempdifpapel,
    :bdempbarrest,
    :bdverificarnotasjalan,
    :bdcodplanoonline,
    :bdlrisssn,
    :bdcomercio,
    :bdindustria,
    :bdservico,
    :bdanexoiii,
    :bdanexoiv,
    :bdanexov,
    :BDCODENQFED,
    :BDFORMATRIBUTACAO,
    :BDSUBSTRIB,
    :bdcodconfdacon,
    :bdcodconficmssped,
    :BDCODCONFCIAP,
    :BDREDBCICMSENT,
    :BDREDBCICMSSAI,
    :BDCODCONFDASN,

    :BDRETPARPIS,
    :BDRETPARCOFINS,
    :BDRETPARCSLL,
    :BDRETPARIRRF,
    :BDRETPARISSQN,
    :BDRETPARINSS,
    :BDRETPARFUNRURAL,
    :bdtipoapuracao,
    :bdsomfrevlrcontab,
    :bdsomfrebaseicms,
    :bdcodplatroca,
    :bdcodplacfop,
    :bdcodconfblocop,
    :bdcredpresumido,
    :bdtermoaceite,
    :bdantecipaimposto,
    :BDTIPODECLARANTEDMED,
    :BDREGISTROANSDMED,
    :BDNUMEROCNESDMED,
    :BDDTOBRIGSPEDCONT,
    :BDTIPOAPURACAORET,
    :BDTIPOAPURACAORETIR,
    :BDDTOBRIGSPEDICMS,
    :BDCODCONTEF,
    :BDLIVRO,
    :BDFOLHA,
    :BDNOMECARTORIO,
    :BDLANCAPARCELAAUTO,
    :BDCODIGOPLA,
    :BDINDATIV,
    :BDIMPORTARVALORESICMSSN,
    :BDDIFALIQ,
    :BDDIFALIQBASEEM,
    :BDANEXOVI,
    :BDCODPLATRIB,
    :BDCODPLAPADRAOREF,
    :BDINDNATPJ,
    :BDCODIBGE,
    :BDSOMAPISCOFVLRCONT,
    :BDSOMAIIVLRCONT,
    :BDMANTERPARCELAS,
    :bdcodplanoincons,
    :BDABRIRRATEIO,
    :BDNAOPERMITERATEIOGRUPO,
    :BDINTEGRANET,
    :BDSOMAIPIPROD,
    :BDSOMAICMSVLRCONT,
    :BDCODPLAE115,
    :BDCODCLATRI,
    :BDDATAOBRIGREINF,
    :BDSOMASTPROD,
    :BDCALCANTICMS,
    :BDCONSIPIBC,
    :BDIMPICMSST,
    :BDANEXOIII_2018,
    :BDANEXOIV_2018,
    :BDANEXOV_2018,
    :BDSTATUSEMP,
    :BDQTDBACKUPEMP,
    :BDIMPORTARISS,
    :BDINCORPORADORAS
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_CONSULTASERVICOS */
ALTER PROCEDURE SP_CONSULTASERVICOS(PRREFSER INTEGER,
PRCODOBRSER INTEGER)
 RETURNS(BDCODOBRSER INTEGER,
BDCHAVE INTEGER,
BDCLASSIFICACAO VARCHAR(60),
BDDESCRICAO VARCHAR(100),
BDPERIODICIDADE INTEGER,
BDDIA INTEGER,
BDANTECIPAR VARCHAR(5),
BDVENCE INTEGER,
BDALERTA INTEGER,
BDCRIACAO DATE,
BDEXTINTO DATE,
BDSITEGOVERNO VARCHAR(255),
BDPREVHORAS VARCHAR(6),
BDTIPO SMALLINT,
BDPREVDIAS INTEGER,
BDCODSIS INTEGER,
BDMESVENCE INTEGER,
BDENTREGA INTEGER,
BDTEMPOESTIMADO INTEGER,
BDSABDOMFER INTEGER,
BDPERISS NUMERIC(15,4),
BDPERIRRF NUMERIC(15,4),
BDPERCSLL NUMERIC(15,4),
BDPERCOF NUMERIC(15,4),
BDPERPIS NUMERIC(15,4),
BDDEDISS VARCHAR(5),
BDDEDIRRF VARCHAR(5),
BDDEDCSLL VARCHAR(5),
BDDEDCOFINS VARCHAR(5),
BDDEDPIS VARCHAR(5),
BDTIPSERV INTEGER,
BDCALCINSS VARCHAR(5),
BDSOFREREAJ VARCHAR(5),
BDDESCONTO VARCHAR(5),
BDVALORPADRAO DM_NUMERIC_15_2,
BDCODCOBSERV INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefser, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'ser.BDCODOBRSER, ';
  wSql = wSql||'ser.BDCHAVE, ';
  wSql = wSql||'ser.BDCLASSIFICACAO, ';
  wSql = wSql||'ser.BDDESCRICAO, ';
  wSql = wSql||'ser.BDPERIODICIDADE, ';
  wSql = wSql||'ser.BDDIA, ';
  wSql = wSql||'ser.BDANTECIPAR, ';
  wSql = wSql||'ser.BDVENCE, ';
  wSql = wSql||'ser.BDALERTA, ';
  wSql = wSql||'ser.BDCRIACAO, ';
  wSql = wSql||'ser.BDEXTINTO, ';
  wSql = wSql||'ser.BDSITEGOVERNO, ';
  wSql = wSql||'ser.BDPREVHORAS, ';
  wSql = wSql||'ser.BDTIPO, ';
  wSql = wSql||'ser.BDPREVDIAS, ';
  wSql = wSql||'ser.BDCODSIS, ';
  wSql = wSql||'ser.BDMESVENCE, ';
  wSql = wSql||'ser.BDENTREGA, ';
  wSql = wSql||'ser.BDTEMPOESTIMADO, ';
  wSql = wSql||'ser.BDSABDOMFER, ';
  wSql = wSql||'ser.BDPERISS, ';
  wSql = wSql||'ser.BDPERIRRF, ';
  wSql = wSql||'ser.BDPERCSLL, ';
  wSql = wSql||'ser.BDPERCOF, ';
  wSql = wSql||'ser.BDPERPIS, ';
  wSql = wSql||'ser.BDDEDISS, ';
  wSql = wSql||'ser.BDDEDIRRF, ';
  wSql = wSql||'ser.BDDEDCSLL, ';
  wSql = wSql||'ser.BDDEDCOFINS, ';
  wSql = wSql||'ser.BDDEDPIS, ';
  wSql = wSql||'ser.BDTIPSERV, ';
  wSql = wSql||'ser.BDCALCINSS, ';
  wSql = wSql||'ser.BDSOFREREAJ, ';
  wSql = wSql||'ser.BDDESCONTO, ';
  wSql = wSql||'refser.BDVALORPADRAO, ';
  wSql = wSql||'ser.BDCODCOBSERV ';
  wSql = wSql||'from VCT_BASE_SERVICO ser ';
  wSql = wsql||'left outer join VW_VCT_BASE_SERVICO_REF refser on (refser.bdcodobrser = ser.bdcodobrser) ';

  wwhere = '';

  IF (prcodobrser IS NOT NULL AND prcodobrser <> 0) THEN
     wwhere = wwhere || ' ser.bdcodobrser = '||prcodobrser;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By ser.BDCODOBRSER';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODOBRSER,
    BDCHAVE,
    BDCLASSIFICACAO,
    BDDESCRICAO,
    BDPERIODICIDADE,
    BDDIA,
    BDANTECIPAR,
    BDVENCE,
    BDALERTA,
    BDCRIACAO,
    BDEXTINTO,
    BDSITEGOVERNO,
    BDPREVHORAS,
    BDTIPO,
    BDPREVDIAS,
    BDCODSIS,
    BDMESVENCE,
    BDENTREGA,
    BDTEMPOESTIMADO,
    BDSABDOMFER,
    BDPERISS,
    BDPERIRRF,
    BDPERCSLL,
    BDPERCOF,
    BDPERPIS,
    BDDEDISS,
    BDDEDIRRF,
    BDDEDCSLL,
    BDDEDCOFINS,
    BDDEDPIS,
    BDTIPSERV,
    BDCALCINSS,
    BDSOFREREAJ,
    BDDESCONTO,
    BDVALORPADRAO,
    BDCODCOBSERV
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_CRIA_DADOSCALC_BAIXA */
ALTER PROCEDURE SP_CRIA_DADOSCALC_BAIXA AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WLIQUIDO NUMERIC(18,6);
DECLARE VARIABLE WREFCOMP INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WDATAAUX DATE;
BEGIN
  /* Procedure Text */
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdcodemp IS NOT NULL;

  /* 1 - Terceiros */
  FOR SELECT bdcodemp,bdcodter,bdcodserv,bdliquido FROM vrhf_base_calc_terc
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp, wcodcol, wreferencia,NULL,1,NULL,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 2 - 13? salario */
  FOR SELECT bdcodemp,bdcodcol,bdref13,bdliquido FROM vrhf_emp_t13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,2,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 3 -  ad 13? */
  FOR SELECT bdcodemp,bdcodcol,bdrefa13,bdliquido FROM vrhf_emp_ta13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,3,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 4 -  ad sal */
  FOR SELECT bdcodemp,bdcodcol,BDDATAAD,bdliquido FROM vrhf_emp_tadsal
   INTO
     :wcodemp,
     :wcodcol,
     :wdata,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,4,NULL,wdata,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 5 -  c 13? */
  FOR SELECT bdcodemp,bdcodcol,bdrefc13,bdref13,bdliquido FROM vrhf_emp_tc13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wrefcomp,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,5,wreferencia,NULL,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 6 - folha normal*/
  FOR SELECT bdcodemp,bdcodcol,bdreffn,bdliquido FROM vrhf_emp_tfolhanormal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,6,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 7 - folha normal tomador */
  FOR SELECT bdcodemp,bdcodcol,bdreftomador,bdliquido FROM vrhf_emp_tfolhatomador
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,7,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 8 -  fc */
  FOR SELECT bdcodemp,bdcodcol,bdreffn,bdrefcomp,bdliquido,bddatapagfc FROM vrhf_emp_tfolhacomp
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wrefcomp,
     :wliquido,
     :wdata
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,8,wreferencia,wdata,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 9 -  fct */
  FOR SELECT x.bdcodemp,x.bdcodcol,x.bdreftomador,x.bdliquido,x.bdrefcomp,x.bddatapagfc FROM vrhf_emp_tfoltomcomp x
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido,
     :wrefcomp,
     :wdata
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,9,wreferencia,wdata,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 10 -  f?rias */
  FOR SELECT x.bdcodemp,x.bdcodcol,x.bdliquido,x.bdiniperaquisfe,x.bdcodfe,x.bdiniperaquisfe,x.bdrefpagabofe FROM VRH_EMP_TFERIAS x
   INTO
     :wcodemp,
     :wcodcol,
     :wliquido,
     :wdata,
     :wreferencia,
     :wdataaux,
     :wrefcomp
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,10,NULL,NULL,NULL,wdata,wreferencia,wliquido,wdataaux,wrefcomp);
  END
END
^

/* Restore proc. body: SP_EXP_SEFIP */
ALTER PROCEDURE SP_EXP_SEFIP(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRDATARECFGTS DATE,
PRDATARECINSS DATE,
PRTIPOFOLHA INTEGER,
PRMODALIDADE VARCHAR(1),
PRINDRECFGST VARCHAR(1),
PRINDRECINSS VARCHAR(1))
 RETURNS(BDARQ INTEGER,
BDREG VARCHAR(360),
BDORDEM VARCHAR(70),
BDINC VARCHAR(32000),
BDCONTADOR INTEGER,
BDCODREC INTEGER,
BDMODALIDADE VARCHAR(1))
 AS
DECLARE VARIABLE windrecinss VARCHAR(1);
DECLARE VARIABLE windrecfgts VARCHAR(1);
DECLARE VARIABLE wmodalidade VARCHAR(1);
DECLARE VARIABLE wsqlcalc VARCHAR(32000);
DECLARE VARIABLE wparsqlcalc VARCHAR(32000);
DECLARE VARIABLE wsqlemp VARCHAR(32000);
DECLARE VARIABLE wempatu INTEGER;
DECLARE VARIABLE wcodrecatu INTEGER;
DECLARE VARIABLE wcodrecsqlatu INTEGER;
DECLARE VARIABLE wwhereemp VARCHAR(32000);
BEGIN
  /* Procedure Text */
  /* prtipoFolha
     0 = normal
     1 = folha complementar
     2 = 13 sal
  */
  wmodalidade = prmodalidade;

  windrecfgts = prindrecfgst;
  windrecinss = prindrecinss;

  IF (windrecfgts IS NULL) THEN
     windrecfgts = '1';

  IF (windrecinss IS NULL) THEN
     windrecinss  = '1';

  IF (prtipofolha IS NULL) THEN
     prtipofolha = 0;

  rdb$set_context('USER_TRANSACTION', 'W_TIPOFOLHA', :prtipofolha);

  rdb$set_context('USER_TRANSACTION', 'W_MODALIDADE', :wmodalidade);

  rdb$set_context('USER_TRANSACTION', 'W_INDRECFGTS', :windrecfgts);
  rdb$set_context('USER_TRANSACTION', 'W_INDRECINSS', :windrecinss);

  IF (prdatarecfgts IS NOT NULL) THEN
     rdb$set_context('USER_TRANSACTION', 'W_DATARECFGTS', :prdatarecfgts );

  IF (prdatarecinss IS NOT NULL) THEN
     rdb$set_context('USER_TRANSACTION', 'W_DATARECINSS', :prdatarecinss);

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  rdb$set_context('USER_TRANSACTION', 'W_ANOMESPAG', :pranomespag);

  WPARSQLCALC = '';

  wsqlemp = 'select colcon.bdcodemp,case when colcon.bdcodsefipemp is null then 115 else colcon.bdcodsefipemp end from VW_VRHF_BASE_TEMPSEFIP colcon ';
  IF (prcodemp IS NOT NULL) THEN
     wsqlemp = wsqlemp||' where '||prcodemp;

  wsqlemp = wsqlemp||' order by colcon.bdcodsefipemp, colcon.bdcodemp';

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  IF (prtipofolha IS NULL) THEN
     prtipofolha = 0;

  wcodrecsqlatu = -1;
  wwhereemp = '';
  FOR EXECUTE STATEMENT wsqlemp
  INTO
    : wempatu,
    : wcodrecatu
  DO
    BEGIN
      IF ((wcodrecatu IS NULL) OR (wcodrecatu = 0) ) THEN
         wcodrecatu = 115;

      IF ((wcodrecatu = wcodrecsqlatu) OR (wcodrecsqlatu = -1)) THEN
         BEGIN
           wcodrecsqlatu = wcodrecatu;
           IF (CHAR_LENGTH(wwhereemp)>0) THEN
              wwhereemp = wwhereemp||',';
           wwhereemp = wwhereemp||CAST(wempatu AS VARCHAR(10));
         END
      ELSE
         BEGIN
           WPARSQLCALC = ''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';
           wsqlcalc = 'select bdarq,bdreg,bdinc,bdordem,bdcontador,bdcodrec,bdmodalidade from sp_exp_sefip_codrec(';
           wparsqlcalc = wparsqlcalc||',';
           IF (prcodcol IS NULL) THEN
              wparsqlcalc = wparsqlcalc||'null';
           ELSE
              wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
           wparsqlcalc = wparsqlcalc||','||CAST(wcodrecsqlatu AS VARCHAR(10));

           wsqlcalc = wsqlcalc||wparsqlcalc||')';

           FOR EXECUTE STATEMENT wsqlcalc
           INTO
             : bdarq,
             : bdreg,
             : bdinc,
             : bdordem,
             : bdcontador,
             : bdcodrec,
             : bdmodalidade
           DO
             SUSPEND;

           /*proximo sql*/
           wcodrecsqlatu = wcodrecatu;
           wwhereemp = CAST(wempatu AS VARCHAR(10));
         END
    END

   WPARSQLCALC = ''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';

   wsqlcalc = 'select bdarq,bdreg,bdinc,bdordem,bdcontador,bdcodrec,bdmodalidade from sp_exp_sefip_codrec(';
   wparsqlcalc = wparsqlcalc||',';
   IF (prcodcol IS NULL) THEN
       wparsqlcalc = wparsqlcalc||'null';
   ELSE
       wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
   wparsqlcalc = wparsqlcalc||','||CAST(wcodrecsqlatu AS VARCHAR(10));

   wsqlcalc = wsqlcalc||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsqlcalc
   INTO
     : bdarq,
     : bdreg,
     : bdinc,
     : bdordem,
     : bdcontador,
     : bdcodrec,
     : bdmodalidade
   DO
     SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL,NULL,NULL);

  DELETE FROM VRHF_EXP_SEFIP;
END
^

/* Restore proc. body: SP_EXP_SEFIP_MOVIMENTACAO_COL */
ALTER PROCEDURE SP_EXP_SEFIP_MOVIMENTACAO_COL(PRREFINI INTEGER = 0,
PRREFFIM INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA DATE,
BDDATASTR VARCHAR(10),
BDMOTIVO VARCHAR(5),
BDINDFGTS INTEGER,
BDCODMFG INTEGER,
BDDATAFIM DATE,
BDINSSINTSIT DM_BOOLEAN)
 AS
DECLARE VARIABLE WOK INTEGER;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WSQLQ1 VARCHAR(3000);
DECLARE VARIABLE WSQLAUX VARCHAR(1000);
DECLARE VARIABLE WSQLAUX2 VARCHAR(1000);
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WCOL INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WDATASTR VARCHAR(10);
DECLARE VARIABLE WMOTIVO VARCHAR(5);
DECLARE VARIABLE WCODMFG INTEGER;
DECLARE VARIABLE WCODSIT INTEGER;
DECLARE VARIABLE WPROJECAO DATE;
DECLARE VARIABLE WDATAFIMSIT DATE;
DECLARE VARIABLE WCODSIT2 INTEGER;
DECLARE VARIABLE WINSSINTSIT VARCHAR(5);
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wcodemp;
  IF (wcodemp IS NULL) THEN
     wcodemp = 0;

  SELECT rdb$get_context('USER_TRANSACTION', 'W_COLSEFIP') FROM rdb$database INTO wcodcol;
  IF (wcodcol IS NULL) THEN
     wcodcol = 0;

  IF (COALESCE(prrefini, 0) > 0 AND COALESCE(prreffim, 0) > 0) THEN
     BEGIN
       wanomes = prrefini;
       wdataini = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
     
       wanomes = prreffim;
       wmes = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5) AS SMALLINT);
       wano = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
       SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;
     
       wdatafim = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/'||
                  waux||
                  '/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
     END
  ELSE
     BEGIN
  SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;
  IF (wanomes IS NULL) THEN
     wanomes = 99999;
     
  wmes = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;
     
  wdataini = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
  wdatafim = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/'||
             waux||
             '/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
     END

  /* entrada em situacao */
  wsql = ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,'||
         '        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,'||
         '        sit.bdcodsit, sit.bddatafimsit '||
         ' from vrh_emp_tsitcol sit '||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol) '||
         ' where (((sit.bddatainisefip - 1)  between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)) or '||
         '(sit.bddatafimsit between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)))';

  IF (wcodemp > 0) THEN
     wsql = wsql||' and sit.bdcodemp = '||wcodemp;

  IF (wcodcol > 0) THEN
     wsql = wsql||' and sit.bdcodcol = '||wcodcol;
    
  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit DO
    BEGIN
      wdata = wdata + 1;
      wsqlq1 = 'select '||
                 'STD2.BDCODMFGENT, '||
                 'mot.BDCODSEFMFG, '||
                 'STD2.BDINSSINTSIT '||
               'from ( '||
                 'select BDCODSIT, MAX(BDDATASTD) BDDATASTD '||
                 'from vrh_base_tprepsit_dia '||
                 'where BDCODSIT = '||wcodsit||' and BDDATASTD <= '''||wdata||''' '||
                 'group by BDCODSIT '||
               ') STD '||
               'join vrh_base_tprepsit_dia STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD) '||
               'join vrh_base_tmotfgts mot on (mot.bdcodmfg = STD2.BDCODMFGENT) ';

      wdata = wdata -1;
      FOR EXECUTE STATEMENT wsqlq1 INTO :wcodmfg,:wmotivo,:winssintsit DO
        BEGIN
          -- Deve incluir a movimentacao Q1
          IF (UPPER(wmotivo) = 'Q2') THEN
             BEGIN
               BDINDFGTS  = NULL;
               wsqlaux = 'select first 1 SIT.BDCODEMP, SIT.BDCODCOL, '||
                                 'case '||
                                   'when (SIT.BDDATAINISEFIP - 1) < COL.BDDATAADMCOL then COL.BDDATAADMCOL '||
                                   'else (SIT.BDDATAINISEFIP - 1) '||
                                 'end BDDATAINISEFIP, '||
                                 '(select X.BDDDMMAAAA '||
                                  'from DDMMAAAA(case '||
                                                  'when (SIT.BDDATAINISEFIP - 1) < COL.BDDATAADMCOL then COL.BDDATAADMCOL '||
                                                  'else (SIT.BDDATAINISEFIP - 1) '||
                                                'end) X) DATA, SIT.BDCODSIT, SIT.BDDATAFIMSIT '||
                          'from VRH_EMP_TSITCOL SIT '||
                          'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = SIT.BDCODEMP) and (COL.BDCODCOL = SIT.BDCODCOL) '||
                          'where SIT.BDDATAFIMSIT <= '''||wdata||''' and '||
                                'SIT.BDCODEMP = '||wemp||' and '||
                                'SIT.BDCODCOL = '||wcol||' and '||
                                'SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 7) <= SUBSTRING(CAST('''||wdata||''' AS VARCHAR(10)) FROM 1 FOR 7) '||
                          'order by SIT.BDDATAINISEFIP DESC ';

               FOR EXECUTE STATEMENT wsqlaux INTO :bdcodemp, :bdcodcol, :bddata, :bddatastr, :wcodsit2, :bddatafim DO
                 BEGIN
                   IF (SUBSTRING(CAST(bddatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bddatafim AS VARCHAR(10)) FROM 6 FOR 2) < prrefini) THEN
                      BEGIN
                        wsqlaux2 = 'select STD2.BDCODMFGENT, MOT.BDCODSEFMFG, STD2.BDINSSINTSIT '||
                                   'from (select BDCODSIT, max(BDDATASTD) BDDATASTD '||
                                         'from VRH_BASE_TPREPSIT_DIA '||
                                         'where BDCODSIT = '||wcodsit2||' and '||
                                               'BDDATASTD <= '''||bddata||''' '||
                                         'group by BDCODSIT) STD '||
                                   'join VRH_BASE_TPREPSIT_DIA STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD) '||
                                   'join VRH_BASE_TMOTFGTS MOT on (MOT.BDCODMFG = STD2.BDCODMFGENT) '||
                                   'where MOT.BDCODSEFMFG = ''Q1''';
                        FOR EXECUTE STATEMENT wsqlaux2 INTO :bdcodmfg, :bdmotivo, :winssintsit DO
                          SUSPEND;
                      END
                 END
             END

          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = NULL;
          BDINSSINTSIT = winssintsit;
          SUSPEND;
        END
    END


  wsql = '';
    

  /* o mes todo em situacao */
  wsql = wsql||
         ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,'||
         '        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,'||
         '        sit.bdcodsit, sit.bddatafimsit '||
         ' from vrh_emp_tsitcol sit '||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol) '||
         ' where (sit.bddatainisefip - 1) < cast('||''''||wdataini||''''||' as date) and ((sit.bddatafimsit > cast('||''''||wdatafim||''''||' as date) or (sit.bddatafimsit is null))) ';

  IF (wcodemp > 0) THEN
     wsql = wsql||' and sit.bdcodemp = '||wcodemp;

  IF (wcodcol > 0) THEN
     wsql = wsql||' and sit.bdcodcol = '||wcodcol;
    
  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit DO
    BEGIN
      wdata = wdata + 1;
      wsqlq1 = 'select '||
                 'STD2.BDCODMFGENT, '||
                 'mot.BDCODSEFMFG, '||
                 'STD2.BDINSSINTSIT '||
               'from ( '||
                 'select BDCODSIT, MAX(BDDATASTD) BDDATASTD '||
                 'from vrh_base_tprepsit_dia '||
                 'where BDCODSIT = '||wcodsit||' and BDDATASTD <= '''||wdata||''' '||
                 'group by BDCODSIT '||
               ') STD '||
               'join vrh_base_tprepsit_dia STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD) '||
               'join vrh_base_tmotfgts mot on (mot.bdcodmfg = STD2.BDCODMFGENT) ';

      wdata = wdata -1;
      FOR EXECUTE STATEMENT wsqlq1 INTO :wcodmfg,:wmotivo,:winssintsit DO
        BEGIN
          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = NULL;
          BDINSSINTSIT = winssintsit;
          SUSPEND;
        END
    END


  wsql = '';
    

  /* saida de situacao */
  wsql = wsql||' select sit.bdcodemp,sit.bdcodcol,sit.bddatafimsit, (select x.bdddmmaaaa from ddmmaaaa(sit.bddatafimsit) x), sit.bdcodsit, sit.bddatafimsit '||
          ' from vrh_emp_tsitcol sit'||
          ' where sit.bddatafimsit between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

   IF (wcodemp > 0) THEN
      wsql = wsql||' and sit.bdcodemp = '||wcodemp;

   IF (wcodcol > 0) THEN
      wsql = wsql||' and sit.bdcodcol = '||wcodcol;

  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit DO
    BEGIN
      wdata = wdata + 1;
      wsqlq1 = 'select '||
                 'STD2.BDCODMFGENT, '||
                 'mot.BDCODSEFMFG, '||
                 'STD2.BDINSSINTSIT '||
               'from ( '||
                 'select BDCODSIT, MAX(BDDATASTD) BDDATASTD '||
                 'from vrh_base_tprepsit_dia '||
                 'where BDCODSIT = '||wcodsit||' and BDDATASTD <= '''||wdata||''' '||
                 'group by BDCODSIT '||
               ') STD '||
               'join vrh_base_tprepsit_dia STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD) '||
               'join vrh_base_tmotfgts mot on (mot.bdcodmfg = STD2.BDCODMFGSAI) ';

      wdata = wdata -1;
      FOR EXECUTE STATEMENT wsqlq1 INTO :wcodmfg,:wmotivo,:winssintsit DO
        BEGIN
          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = wdatafimsit;
          BDINSSINTSIT = winssintsit;
          SUSPEND;
        END
    END


  wsql = '';

  BDDATAFIM = NULL;

  /* rescisao */
  wsql = wsql||'SELECT res.bdcodemp,res.bdcodcol,res.bddatarescisao, (SELECT x.bdddmmaaaa FROM ddmmaaaa(res.bddatarescisao) x) Data,'||
         '       mot.bdcodsefmfg CodMovi, pres.bdgrrfpres, mot.BDCODMFG, res.bdprojecaoaviso '||
         ' FROM vrh_emp_trescisao res, vrh_base_tprepresc pres, VRH_BASE_TMOTFGTS mot'||
         ' where (pres.bdcodpres = res.bdcodpres)'||
         ' and (pres.bdcodmfg = mot.bdcodmfg)'||
--         ' FROM vrh_emp_trescisao res'||
--         ' INNER JOIN vrh_base_tprepresc pres ON (pres.bdcodpres = res.bdcodpres)'||
--         ' INNER JOIN VRH_BASE_TMOTFGTS mot ON (pres.bdcodmfg = mot.bdcodmfg)'||
--         ' where res.bddatarescisao between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)'||
         ' and ((res.bddatarescisao between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)) or '||
         ' (res.bdprojecaoaviso between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date))) ';

   IF (wcodemp > 0) THEN
      wsql = wsql||' and res.bdcodemp = '||wcodemp;

   IF (wcodcol > 0) THEN
      wsql = wsql||' and res.bdcodcol = '||wcodcol;


  wsql = wsql||' union all ';

  /* transferencia de entrada */
  wsql = wsql||'select tra.bdcodempdest,tra.bdcodcoldest,tra.bddatatrf, (select x.bdddmmaaaa from ddmmaaaa(tra.bddatatrf) x), '||''''||'N3'||''''||' CodMovi, null indfgts, mot.BDCODMFG, CAST(null as DATE) bdprojecaoaviso '||
               ' from vrh_emp_ttranscol tra, vrh_base_tprepRESc ptra, VRH_BASE_TMOTFGTS mot '||
               ' where  (ptra.bdcodpres = tra.bdcodptran)'||
               ' and (ptra.bdcodmfgent = mot.bdcodmfg)'||
--         '       from vrh_emp_ttranscol tra'||
--         ' inner join vrh_base_tpreptran ptra on (ptra.bdcodptran = tra.bdcodptran)'||
--         ' inner join VRH_BASE_TMOTFGTS mot on (ptra.bdcodmfg = mot.bdcodmfg)'||
--         ' where tra.bddatatrf between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)'||
         ' and tra.bddatatrf between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

  IF (wcodemp > 0) THEN
     wsql = wsql||' and tra.bdcodempdest = '||wcodemp;

  IF (wcodcol > 0) THEN
     wsql = wsql||' and tra.bdcodcoldest = '||wcodcol;

--  wsql = wsql||' union ';

  /* transferencia de saida */ /* vai estar na rescisao */
/*  wsql = wsql||'select tra.bddatatrf, (select x.bdddmmaaaa from ddmmaaaa(tra.bddatatrf) x), mot.bdcodsefmfg CodMovi, null indfgts'||
         '       from vrh_emp_ttranscol tra'||
         ' inner join vrh_base_tpreptran ptra on (ptra.bdcodptran = tra.bdcodptran)'||
         ' inner join VRH_BASE_TMOTFGTS mot on (ptra.bdcodmfg = mot.bdcodmfg)'||
         ' where tra.bddatatrf between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)'||
         ' and tra.bdcodempdest = '||wcodemp||
         ' and tra.bdcodcoldest = '||wcodcol;*/

  FOR EXECUTE STATEMENT wsql INTO
      : bdcodemp,
      : bdcodcol,
      : bddata,
      : bddatastr,
      : bdmotivo,
      : bdindfgts,
      : bdcodmfg,
      : wprojecao
    DO
  BEGIN
    wok = 1;

    IF (wprojecao IS NOT NULL) THEN
       BEGIN
         IF (wprojecao >= CAST(wdataini AS DATE) AND wprojecao <= CAST(wdatafim AS DATE) AND bddata < CAST(wdataini AS DATE)) THEN
            BEGIN
              bddata    = wprojecao;
              bddatastr = SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
                          SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                          SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 1 FOR 4);
            END
       END


    IF ((bdmotivo = 'Q2') AND (bddata <= wdataini)) THEN
       BEGIN
         -- Se movimentacao Q2 for iniciada em mes diferente ou no primeira dia do mes atual precisa buscar a ultima situacao Q1 existente para o colaborador
         SUSPEND;

         wsqlq1 = ' select first 1 sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,'||
                  '        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,'||
                  '        mot.bdcodsefmfg codmovi, null indfgts, mot.bdcodmfg, sit.bddatafimsit '||
                  ' from vrh_emp_tsitcol sit, vrh_base_tprepsit psit, vrh_base_tmotfgts mot, vrh_emp_tcolcon col '||
                  ' where (psit.bdcodsit = sit.bdcodsit) and (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol) and '||
                  '       (psit.bdcodmfgent = mot.bdcodmfg) and upper(mot.bdcodsefmfg) = '||''''||'Q1'||''''||
                  ' and (sit.bddatainisefip - 1) < cast('||''''||bddata||''''||' as date) ';
         wsqlq1 = wsqlq1||' and sit.bdcodemp = '||bdcodemp;
         wsqlq1 = wsqlq1||' and sit.bdcodcol = '||bdcodcol;
         wsqlq1 = wsqlq1||' order by bddatainisefip desc ';

         FOR EXECUTE STATEMENT wsqlq1 INTO : bdcodemp, : bdcodcol, : bddata, : bddatastr, : bdmotivo, : bdindfgts, : bdcodmfg, :bddatafim, :bdinssintsit DO
           SUSPEND;

         wok = 0;
       END

    IF (wok = 1) THEN
      SUSPEND;
  END
END
^

/* Restore proc. body: SP_EXPORTA_BLOCOC_CONTRIBUICOES */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_CONTRIBUICOES(PRCODEMP VARCHAR(500),
PRCODPLAPADRAOREF INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100))
 AS
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WARQUIVOEMP VARCHAR(100);
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  PRCODEMP = PRCODEMP||',';
  WHILE (CHAR_LENGTH(:PRCODEMP) > 0) DO
    BEGIN
      wEmpAtu = TRIM(SUBSTRING(:PRCODEMP FROM 1 FOR POSITION(',', :PRCODEMP)-1));

      /*Cria arquivo da empresa que vai ser exportada*/
      wArquivoEmp = REPLACE(:PRARQUIVO, '.tmp', '_e='||:wEmpAtu||'.tmp');
      NEWFILE(:wArquivoEmp);

      /*SA?DA*/
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(:wEmpAtu, :PRCODPLAPADRAOREF, :PRDTINI, :PRDTFIM, :wArquivoEmp);

      PRCODEMP = SUBSTRING(:PRCODEMP FROM POSITION(',', :PRCODEMP)+1 FOR CHAR_LENGTH(:PRCODEMP));

      /*****************************************************************************
       *                           EXPORTANDO ARQUIVO                              *
       ****************************************************************************/
    
      OPENARQ(:wArquivoEmp);
    
      FOR SELECT E.BDLINHA
          FROM TEXPORTACAO_SPED E
          WHERE E.BDID = :wArquivoEmp
          ORDER BY E.BDCHAVEREG
          INTO :wLinha
      DO
        BEGIN
          WRITELNOA(:wLinha);
        END
    
      CLOSEARQ(:wArquivoEmp);
    END
END
^

/* Restore proc. body: SP_EXPORTA_BLOCOC_SAI_REG300 */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI_REG300(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRPERFIL INTEGER)
 AS
BEGIN

  /*****************************************************************************
   *                                   C300                                    *
   ****************************************************************************/

/* INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
   SELECT :PRAQUIVO BDID,
          LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C300',
          'C300' BDREG,
          ('|C300'|| --REG
          '|'||MOD.BDMODELOSTR|| --COD_MOD
          '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(M.BDSERIE, ''))|| -- SER
          '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(M.BDSUBSERIE, '|', ''))|| --SUB_SER
          '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(M.BDNUMDOCINI, ''))|| --NUM_DOC_INI
          '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(M.BDNUMDOCFIM, ''))|| --NUM_DOC_FIN
          '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_DOC
          '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C350.BDVLRTOTPIS, 0.00), '.', ','))|| --VL_PIS
          '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C350.BDVLRTOTCOFINS, 0.00), '.', ','))|| --VL_COFINS
          '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(C350.BDCODCTA, ''))|| --COD_CTA
          '|') BDLINHA, IIF(((M.BDMODELO = 65) OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER
   FROM (
         SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB
         FROM (
               SELECT M.BDCODEMP, M.BDCHAVE
               FROM VEF_EMP_TMOVsai M
               WHERE M.BDCODEMP = :PRCODEMP
               AND M.BDMODELO IN (2)
               AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              ) MOV
         LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
        ) SAI
   LEFT OUTER JOIN (
                    SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRDESC, 0)) BDVLRDESC, SUM(COALESCE(P.BDVLRPIS, 0)) BDVLRPIS, SUM(COALESCE(P.BDVLRCOFINS, 0)) BDVLRCOFINS, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM
                    FROM VEF_EMP_TMOVPROSAI P
                    WHERE P.BDCODEMP = :PRCODEMP
                    GROUP BY P.BDCODEMP, P.BDCHAVE
                    ) PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
   JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE)
   LEFT OUTER JOIN VEF_EMP_TC300350SAI C350 ON(C350.BDCODEMP = M.BDCODEMP AND C350.BDCHAVE = M.BDCHAVE)
   JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)  */


  /*****************************************************************************
   *                                   C350                                    *
   ****************************************************************************/

   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
   SELECT :PRARQUIVO BDID,
         LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C300.C350.'||LPAD(GETORDEMSEQUENCIAL(SAI.BDCHAVE), 10, '0'),
         'C350' BDREG,
         ('|C350'|| --REG
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(M.BDSERIE, ''))|| -- SER
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(M.BDSUBSERIE, '|', ''))|| --SUB_SER
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(M.BDNUMDOCINI, ''))|| --NUM_DOC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_DOC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(CHAR_LENGTH(COALESCE(TERCOL.BDCGCTER, '')) = 18, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4, TERCOL.BDCODTER, TERCOL.BDCGCTER, '', '')), ''))|| --CNPJ_COL
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ','))||    --VL_MERC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(PRO.BDVLRITEM, '.', ','))|| --VL_DOC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00), '.', ','))|| --VL_DESC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C350.BDVLRTOTPIS, 0.00), '.', ','))|| --VL_PIS
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C350.BDVLRTOTCOFINS, 0.00), '.', ','))|| --VL_COFINS
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(C350.BDCODCTA, ''))|| --COD_CTA
         '|') BDLINHA, IIF(((M.BDMODELO = 2) OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER
   FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVsai M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (2)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) SAI
   LEFT OUTER JOIN VEF_EMP_TC300350SAI C350 ON (C350.BDCODEMP = SAI.BDCODEMP AND C350.BDCHAVE = SAI.BDCHAVE)
   LEFT OUTER JOIN (
                    SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRDESC, 0)) BDVLRDESC, SUM(COALESCE(P.BDVLRPIS, 0)) BDVLRPIS, SUM(COALESCE(P.BDVLRCOFINS, 0)) BDVLRCOFINS, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM
                    FROM VEF_EMP_TMOVPROSAI P
                    WHERE P.BDCODEMP = :PRCODEMP
                    GROUP BY P.BDCODEMP, P.BDCHAVE
                  ) PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
   JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE)
   LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERCOL ON (TERCOL.BDCODTER = M.BDCODTER);

   /*****************************************************************************
   *                                   C370                                    *
   ****************************************************************************/
   SETORDEMSEQUENCIAL(0);
   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
   SELECT :PRARQUIVO BDID,
          LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C300.C370.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
          'C370' BDREG,
          ('|C370'|| --REG
          '|'||GETORDEMSEQUENCIAL(PRO.BDCHAVE)|| --NUM_ITEM
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                    IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                    COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 3)), '.', ',')|| --QTD
          '|'||COALESCE(IIF(((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')), UN.BDAPEUNIMED, UN.BDAPEUNIMED), '')|| --UNID
          '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
          '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
          '|') BDLINHA, PRO.BDCODPROD
   FROM (
         SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
         FROM (
               SELECT MOV.BDCODEMP, MOV.BDCHAVE
               FROM (
                     SELECT M.BDCODEMP, M.BDCHAVE
                     FROM VEF_EMP_TMOVSAI M
                     WHERE M.BDCODEMP = :PRCODEMP
                     AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                     AND M.BDMODELO IN (2)
                     AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                    ) MOV
              ) SAI
         JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
        ) SAI
   JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
   LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD)
   LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
   LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)
   JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE);


  /*****************************************************************************
   *                                   C390                                    *
   ****************************************************************************/
   SETORDEMSEQUENCIAL(0);
   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
   SELECT :PRARQUIVO BDID,
         LPAD(C390.BDCODEMP, 6, '0')||'.1.'||LPAD(C390.BDCHAVE, 10, '0')||'.C300.C390.'||LPAD(GETORDEMSEQUENCIAL(C390.BDCHAVE), 10, '0'),
         'C390' BDREG,
         ('|C390'|| --REG
         '|'||COALESCE(C390.BDCSTICMS, '')|| --CST_ICMS
         '|'||COALESCE(C390.BDCODNAT, '')|| --CFOP
         '|'||REPLACE(CAST(COALESCE(C390.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
         '|'||REPLACE(COALESCE(IIF(C390.BDMODELO = 2, (COALESCE(C390.BDVLRITEM + C390.BDVLRDESPACESSORIA + C390.BDVLRFRETE, 0) - COALESCE(C390.BDVLRDESC, 0)),
                                                      (IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C390.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C390.BDVLRTOT + (C390.BDVALORNOTA - TOT.BDVLRDIF)), C390.BDVLRTOT))), 0.00), '.', ',')|| --VL_OPR
         '|'||REPLACE(COALESCE(C390.BDBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
         '|'||REPLACE(COALESCE(C390.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
         '|'||REPLACE(COALESCE(IIF(C390.BDMODELO = 2, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C390.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C390.BDVLRTOT + (C390.BDVALORNOTA - TOT.BDVLRDIF)), C390.BDVLRTOT)), C390.BDREDBCICMS, C390.BDBCICMS, C390.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
         '|'||COALESCE(C390.BDOBSERVACAO, '')|| --COD_OBS
         '|') BDLINHA
   FROM (
         SELECT MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, MOV.BDCODNAT, MOV.BDALIQICMS, SAI.BDMODELO, MOV.BDVLRITEM,
                MOV.BDVLRDESC, MOV.BDVLRFRETE, MOV.BDVLRDESPACESSORIA, MOV.BDVLRIPI, MOV.BDVLRST, MOV.BDBCICMS, MOV.BDOBSERVACAO,
                MOV.BDVLRICMS, MOV.BDBCST, MOV.BDREDBCICMS, SAI.BDVALORNOTA,
                (COALESCE(MOV.BDVLRFRETE, 0) + COALESCE(MOV.BDVLRITEM, 0) +
                 COALESCE(MOV.BDVLRDESPACESSORIA, 0) + COALESCE(MOV.BDVLRIPI, 0) +
                 COALESCE(MOV.BDVLRST, 0) - COALESCE(MOV.BDVLRDESC, 0)) BDVLRTOT
         FROM (
               SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDOBSERVACAO,
                      COALESCE(PRO.BDCODCSTICMS, 0) BDCODCSTICMS,
                      COALESCE(MOV.BDCODNAT, 0) BDCODNAT,
                      CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS,
                      SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                      SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                      SUM(COALESCE(PRO.BDVLRFRETE, 0)) BDVLRFRETE,
                      SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) BDVLRDESPACESSORIA,
                      SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI,
                      SUM(COALESCE(PRO.BDVLRST, 0)) BDVLRST,
                      SUM(COALESCE(PRO.BDBCST, 0)) BDBCST,
                      SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS,
                      SUM(COALESCE(PRO.BDVLRICMS, 0)) BDVLRICMS,
                      SUM(COALESCE(PRO.BDREDBCICMS, 0)) BDREDBCICMS
               FROM (
                     SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT, I.BDOBSERVACAO
                     FROM VEF_EMP_TMOVSAI M
                     JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                     WHERE M.BDCODEMP = :PRCODEMP
                     AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                     AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                     AND M.BDMODELO IN (2)
                    ) MOV
               JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
               GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS, MOV.BDOBSERVACAO
              ) MOV
         JOIN VEF_EMP_TMOVSAI SAI ON(SAI.BDCODEMP = MOV.BDCODEMP AND SAI.BDCHAVE = MOV.BDCHAVE)
         LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
        ) C390
  LEFT OUTER JOIN (
                   SELECT C390_TOT.BDCODEMP, C390_TOT.BDCHAVE, SUM(C390_TOT.BDVLRDIF) BDVLRDIF, COUNT(C390_TOT.BDCHAVE) BDORDEMMAX
                   FROM (
                         SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                                ((SUM(COALESCE(PRO.BDVLRITEM, 0)) +
                                  SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) +
                                  SUM(COALESCE(PRO.BDVLRIPI, 0)) +
                                  SUM(COALESCE(PRO.BDVLRST, 0)) +
                                  SUM(COALESCE(PRO.BDVLRFRETE, 0))) -
                                  SUM(COALESCE(PRO.BDVLRDESC, 0))
                                 ) BDVLRDIF     
                         FROM (
                               SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                               FROM VEF_EMP_TMOVSAI M
                               JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                               WHERE M.BDCODEMP = :PRCODEMP
                               AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                               AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                               AND M.BDMODELO IN (2)
                              ) MOV
                         JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
                        ) C390_TOT
                   GROUP BY C390_TOT.BDCODEMP, C390_TOT.BDCHAVE
                  ) TOT ON(TOT.BDCODEMP = C390.BDCODEMP AND TOT.BDCHAVE = C390.BDCHAVE);

END
^

/* Restore proc. body: SP_EXPORTA_BLOCOC_SAI_SPEDCONTR */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(PRCODEMP INTEGER,
PRCODPLAPADRAOREF INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100))
 AS
/*DECLARE VARIABLE WCNPJEMP VARCHAR(18);*/
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WMIN INTEGER;
DECLARE VARIABLE WMAX INTEGER;
DECLARE VARIABLE WCHAVEREG VARCHAR(80);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WALIQPIS NUMERIC(15,6);
DECLARE VARIABLE WALIQCOFINS NUMERIC(15,6);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
BEGIN
  --Pega da matriz
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));  
  
  SELECT FIRST 1 SPED.BDINCTRIB, SPED.BDCODCRIT
  FROM (
        SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ
        FROM vw_tempresas_ref tbem
        JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP)
        WHERE TBEM.BDCODEMP = :PRCODEMP
        GROUP BY BDCODMATRIZ
       ) EMP
  JOIN VW_INT_SPEDPISCOFINS_REF SPED ON(SPED.BDCODEMP = EMP.BDCODMATRIZ AND SPED.BDREFERENCIA <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')))
  ORDER BY SPED.BDREFERENCIA DESC
  INTO :wIncTrib, :wCodCrit;

  IF (NOT((:wIncTrib = 1) AND (:wCodCrit IN(1, 2)))) THEN
    BEGIN
      /*****************************************************************************
       *                                   C860                                    *
       ****************************************************************************/
      /*Salva os n?meros de documento menores e maiores por data de emissao e modelo na DLL, na hora de montar o registro busca os dados na DLL*/
      FREEANDNIL_C800(0);
      FOR SELECT S.BDDATAEMISSAO, MIN(S.BDNUMDOCINI) BDMIN, MAX(S.BDNUMDOCINI) BDMAX
          FROM VEF_EMP_TMOVSAI S
          WHERE S.BDCODEMP = :PRCODEMP
          AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
          AND S.BDMODELO = 59
          AND S.BDCODSITNF NOT IN(2, 3, 4, 5)
          GROUP BY S.BDDATAEMISSAO, S.BDMODELO
          INTO :wData, :wMin, :wMax
      DO
        BEGIN
          SETNUMDOC_C800(:wData, 59, :wMin, :wMax);
        END
    
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO, 'C860.'||(MOV.BDCODEMP||'_'||COALESCE(MOV.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO),
             'C860' BDREG,
             '|C860|59'||
             '|'||COALESCE(MOV.BDNRSERIE, '')|| --NR_SAT
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||MOV.BDNUMDOCINI|| --DOC_INI
             '|'||MOV.BDNUMDOCFIM|| --DOC_FIM
             '|'
      FROM (
            SELECT M.BDCODEMP, M.BDDATAEMISSAO,
                   GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) BDNUMDOCINI,
                   GETNUMDOC_C800_MAX(M.BDDATAEMISSAO, 59) BDNUMDOCFIM,
                   EQ.BDNRSERIE
            FROM VEF_EMP_TMOVSAI M
            LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = M.BDCODEMP AND EQ.BDCODEQUIPSAT = M.BDCODEQUIPSAT)
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND M.BDMODELO = 59
            AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
            GROUP BY M.BDCODEMP, M.BDDATAEMISSAO, BDNUMDOCINI, BDNUMDOCFIM, EQ.BDNRSERIE
           ) MOV;
    
      /*****************************************************************************
       *                                   C870                                    *
       ****************************************************************************/
      /*Grava os dados cfop, al?quota pis, al?quota cofins na DLL*/
      FOR SELECT 'C860.'||(MOV.BDCODEMP||'_'||COALESCE(EQ.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||MOV.BDNUMDOCINI||'_'||COALESCE(PRO.BDCODPROD, '')||'_'||LPAD(COALESCE(PIS.BDCSTPIS, ''), 3, '0')||'_'||LPAD(COALESCE(COF.BDCSTCOF, ''), 3, '0')||'_'||LPAD(COALESCE(PRO.BDCODPLAPADRAO, ''), 9, '0')||'_'||LPAD(COALESCE(PRO.BDCODTPLA, ''), 9, '0')) BDCHAVEREG,
                 MOV.BDCODNAT, PRO.BDALIQPIS, PRO.BDALIQCOFINS, MOV.BDCHAVE, MOV.BDORDEM
          FROM (
                SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODEQUIPSAT,
                       SAI.BDDATAEMISSAO, I.BDCODNAT, SAI.BDNUMDOCINI
                FROM (
                      SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEQUIPSAT,
                             MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI
                      FROM (
                            SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODEQUIPSAT, M.BDDATAEMISSAO,
                                   (SELECT GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) FROM RDB$DATABASE) BDNUMDOCINI
                            FROM VEF_EMP_TMOVSAI M
                            WHERE M.BDCODEMP = :PRCODEMP
                            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                            AND M.BDMODELO = 59
                            AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                           ) MOV
                     ) SAI
                JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
               ) MOV
          LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = MOV.BDCODEMP AND EQ.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT)
          LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
          LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
          LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
          INTO :wChaveReg, :wCodNat, :wAliqPIS, :wAliqCofins, :wChave, :wOrdem
      DO
        BEGIN
          SET_C870(:wChaveReg, :wAliqPIS, :wAliqCofins, :wCodNat, :wChave, :wOrdem);
        END

      DELETE FROM TMP_TOL_VEF_EMP_TMOVSAI;
    
      INSERT INTO TMP_TOL_VEF_EMP_TMOVSAI(BDCHAVESAI, BDORDEM, BDCHAVE, BDCODEMP)
      SELECT T.BDCHAVESAI, T.BDORDEM, MIN(T.BDCHAVE) BDCHAVE, T.BDCODEMP
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDMODELO = 59
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
           ) S
      JOIN TOL_VEF_EMP_TMOVSAI T ON(T.BDCODEMP = S.BDCODEMP AND T.BDCHAVESAI = S.BDCHAVE)
      GROUP BY T.BDCHAVESAI, T.BDORDEM, T.BDCODEMP;

      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCHAVE, BDCODEMP)
      SELECT :PRARQUIVO, MOV.BDCHAVEREG,
             'C870' BDREG,
             '|C870'||
             '|'||COALESCE(IIF(COALESCE(PRO_VINC.BDCODSAIDA, '') = '', PRO_VINC.BDCODPROD, PRO_VINC.BDCODSAIDA), '')|| --COD_ITEM
             '|'||COALESCE(SUBSTRING(GETCFOP_C870(MOV.BDCHAVEREG) FROM 1 FOR 4), '')|| --CFOP
             '|'||REPLACE(MOV.BDVLRITEM, '.', ',')|| --VL_ITEM
             '|'||REPLACE(MOV.BDVLRDESC, '.', ',')|| --VL_DESC
             '|'||COALESCE(LPAD(MOV.BDCSTPIS, 2, '0'), '')|| --CST_PIS
             '|'||REPLACE(MOV.BDBCPIS, '.', ',')|| --VL_BC_PIS
             '|'||COALESCE(REPLACE(CAST(IIF(MOV.BDALIQPIS = '', '0', MOV.BDALIQPIS) AS NUMERIC(8, 4)), '.', ','), '')|| --ALIQ_PIS
             '|'||REPLACE(MOV.BDVLRPIS, '.', ',')|| --VL_PIS
             '|'||COALESCE(LPAD(MOV.BDCSTCOF, 2, '0'), '')|| --CST_COFINS
             '|'||REPLACE(MOV.BDBCCOFINS, '.', ',')|| --VL_BC_COFINS
             '|'||COALESCE(REPLACE(CAST(IIF(MOV.BDALIQCOFINS = '', '0', MOV.BDALIQCOFINS) AS NUMERIC(8, 4)), '.', ','), '')|| --ALIQ_COFINS
             '|'||REPLACE(MOV.BDVLRCOFINS, '.', ',')|| --VL_COFINS
             '|'||COALESCE(COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON), '')|| --COD_CTA
             '|', PRO_VINC.BDCODPROD, COALESCE(ccl.bdcodtpla,cclrat.bdcodtpla) bdcredito, (SELECT BDDATA FROM SP_PARSE_DATE(LAN.BDDATA, 'YYYY')) bdanocredito,
                  COALESCE(MOV.bdcodplapadrao, lan.bdcodplapadrao) bdcodplapadrao, COALESCE(cclep.BDCODTPLAREF, ccderatp.BDCODTPLAREF) bdcreditoref,
                  COALESCE(cclep.BDCODPLAPADRAOREF, ccderatp.BDCODPLAPADRAOREF) bdcreditoplapadraoref, COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON,
                  MOV.BDCHAVE, MOV.BDCODEMP
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, MOV.BDCODPROD, MOV.BDCSTPIS, MOV.BDCSTCOF, MOV.BDCODPLAPADRAO, MOV.BDCODTPLA,
                   GETCHAVE_C870(MOV.BDCHAVEREG) BDCHAVE, GETORDEM_C870(MOV.BDCHAVEREG) BDORDEM, MOV.BDCHAVEREG, MOV.BDVLRITEM, MOV.BDVLRDESC, MOV.BDBCPIS, MOV.BDVLRPIS,
                   MOV.BDBCCOFINS, MOV.BDVLRCOFINS, GETALIQPIS_C870(MOV.BDCHAVEREG) BDALIQPIS, GETALIQCOFINS_C870(MOV.BDCHAVEREG) BDALIQCOFINS
            FROM (
                  SELECT MOV.BDCODEMP, EQ.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, PRO.BDCODPROD, PIS.BDCSTPIS, COF.BDCSTCOF, PRO.BDCODPLAPADRAO, PRO.BDCODTPLA,
                         ('C860.'||MOV.BDCODEMP||'_'||COALESCE(EQ.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||MOV.BDNUMDOCINI||'_'||COALESCE(PRO.BDCODPROD, '')||'_'||LPAD(COALESCE(PIS.BDCSTPIS, ''), 3, '0')||'_'||LPAD(COALESCE(COF.BDCSTCOF, ''), 3, '0')||'_'||LPAD(COALESCE(PRO.BDCODPLAPADRAO, ''), 9, '0')||'_'||LPAD(COALESCE(PRO.BDCODTPLA, ''), 9, '0')) BDCHAVEREG,
                         SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                         SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                         SUM(COALESCE(PRO.BDBCPIS, 0)) BDBCPIS,
                         SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPIS,
                         SUM(COALESCE(PRO.BDBCCOFINS, 0)) BDBCCOFINS,
                         SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINS
                  FROM (
                        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODEQUIPSAT,
                               SAI.BDDATAEMISSAO, SAI.BDNUMDOCINI
                        FROM (
                              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEQUIPSAT,
                                     MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI
                              FROM (
                                     SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODEQUIPSAT, M.BDDATAEMISSAO,
                                           (SELECT GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) FROM RDB$DATABASE) BDNUMDOCINI
                                    FROM VEF_EMP_TMOVSAI M
                                    WHERE M.BDCODEMP = :PRCODEMP
                                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                                    AND M.BDMODELO = 59
                                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                                   ) MOV
                             ) SAI
                        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                       ) MOV
                  LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = MOV.BDCODEMP AND EQ.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT)
                  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                  LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
                  LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
                  GROUP BY MOV.BDCODEMP, EQ.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, PRO.BDCODPROD, PIS.BDCSTPIS, COF.BDCSTCOF, PRO.BDCODPLAPADRAO, PRO.BDCODTPLA
                 ) MOV
           ) MOV
      JOIN TCADPRO_VINC PRO_VINC ON(PRO_VINC.BDCODEMP = MOV.BDCODEMP AND PRO_VINC.BDCODPROD = MOV.BDCODPROD)
      LEFT OUTER JOIN TMP_TOL_VEF_EMP_TMOVSAI TOL ON(TOL.BDCHAVESAI = MOV.BDCHAVE AND TOL.BDORDEM = MOV.BDORDEM)
      LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.BDCODEMP = tol.bdcodemp AND lan.bdchave = tol.BDCHAVE)
      LEFT OUTER JOIN planos_tpla ccl ON (COALESCE(MOV.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) = ccl.bdcodplapadrao AND COALESCE(MOV.bdcodtpla, lan.bdcredito) = ccl.bdcodtpla)
      LEFT OUTER JOIN PLANOS_TPLA_ECF ccle ON (ccle.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                               AND ccle.bdano = (SELECT FIRST 1 BDANO
                                                                 FROM PLANOS_TPLA_ECF
                                                                 WHERE CAST(BDANO || '01' AS INTEGER) <= lan.bdreferencia
                                                                 AND BDCODTPLAREF IS NOT NULL
                                                                 AND CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                 AND CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                 AND CCLE.BDCODTPLA = BDCODTPLA
                                                                 ORDER BY BDANO DESC
                                                                )
                                               AND ccle.bdcodplapadrao = ccl.bdcodplapadrao AND ccle.bdcodtpla = ccl.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cclep ON (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF AND ccle.BDCODTPLAREF = cclep.BDCODTPLAREF)
     LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat ON (tolrat.bdcodemp = mov.bdcodemp AND tolrat.bdchavelan = mov.bdchave AND tolrat.bdordem = mov.bdordem)
     LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.BDCODEMP = tolrat.bdcodemp AND lanrat.bdchave = tolrat.BDCHAVE)
     LEFT OUTER JOIN planos_tpla cclrat ON (lanrat.BDCODPLAPADRAO = cclrat.bdcodplapadrao AND lanrat.bdcredito = cclrat.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON (CCDERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                                 CCDERAT.bdano =(SELECT FIRST 1 BDANO 
                                                                 FROM PLANOS_TPLA_ECF 
                                                                 WHERE CAST(BDANO || '01' AS INTEGER) <= lanrat.bdreferencia AND 
                                                                   BDCODTPLAREF IS NOT NULL AND 
                                                                   CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                                   CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                                   CCDERAT.BDCODTPLA = BDCODTPLA 
                                                                 ORDER BY BDANO DESC
                                                                ) AND
                                                 ccderat.bdcodplapadrao = cclrat.bdcodplapadrao AND ccderat.bdcodtpla = cclrat.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO ccderatp ON (ccderat.BDCODPLAPADRAOref = ccderatp.BDCODPLAPADRAOREF AND ccderat.BDCODTPLAREF = ccderatp.BDCODTPLAREF);

      /*****************************************************************************
       *                                   C890                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO, MOV.BDCHAVEREG,
             'C890' BDREG,
             '|C890'||
             '|'||COALESCE(MOV.BDNUMPROC, '')|| --NUM_PROC
             '|'||COALESCE(MOV.BDINDORIG, '')||  --IND_PROC
             '|'
      FROM (
            SELECT ('C860.'||MOV.BDCODEMP||'_'||COALESCE(MOV.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||'99999999_'||'99999999_'||'999_'||'999_999999999_999999999.C890.'||C890.BDNUMPROC||'_'||IND.BDINDORIG) BDCHAVEREG,
                   C890.BDNUMPROC, IND.BDINDORIG
            FROM (
                  SELECT M.BDCODEMP, M.BDDATAEMISSAO,
                         GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) BDNUMDOCINI,
                         GETNUMDOC_C800_MAX(M.BDDATAEMISSAO, 59) BDNUMDOCFIM,
                         EQ.BDNRSERIE,
                         EQ.BDCODEQUIPSAT
                  FROM VEF_EMP_TMOVSAI M
                  LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = M.BDCODEMP AND EQ.BDCODEQUIPSAT = M.BDCODEQUIPSAT)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDMODELO = 59
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                  GROUP BY M.BDCODEMP, M.BDDATAEMISSAO, M.BDCODEQUIPSAT, BDNUMDOCINI, BDNUMDOCFIM, EQ.BDNRSERIE, EQ.BDCODEQUIPSAT
                 ) MOV
            JOIN VEF_EMP_TPROCREFC890 C890 ON (C890.BDCODEMP = MOV.BDCODEMP AND C890.BDCHAVE = (SELECT FIRST 1 C.BDCHAVE
                                                                                                FROM VEF_EMP_TPROCREFC890 C
                                                                                                WHERE c.BDCODEMP = mov.BDCODEMP
                                                                                                AND c.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT
                                                                                                AND c.BDDTINIVIG <= mov.BDDATAEMISSAO
                                                                                                AND ((c.BDDTFINVIG IS NULL) OR (c.BDDTFINVIG >= mov.BDDATAEMISSAO))
                                                                                                ORDER BY C.BDDTINIVIG))
            LEFT OUTER JOIN VEF_BASE_TTABINDORIG IND ON (IND.BDORDEMINDORIG = C890.BDORDEMINDORIG)
           ) MOV;

      /*Destruindo a lista da DLL*/
--      FREEANDNIL_C800(0);
      DELETE FROM TMP_TOL_VEF_EMP_TMOVSAI;
    END
END
^

/* Restore proc. body: SP_EXPORTA_ISS_CURITIBA */
ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRTIPOLANC INTEGER,
PRRETIFICADORA INTEGER,
PRARQUIVO VARCHAR(100))
 AS
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200 CHARACTER SET UTF8;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- REGISTRO HEADER ? ?H?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, r.bdCODEMP, 1, '000000',                                   -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                      OBSERVA??ES
--SELECT :prARQUIVO, r.bdCODEMP, 1, r.bdCODEMP,                                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                      OBSERVA??ES
         'H'||                                                                  -- H.01     1 -   1  Caracter(1)   C?digo do registro ?H?                                                         Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                  (COALESCE(r.bdIMEMP,''))), 10, '0')||         -- H.02     2 -  11  Num?rico(10)  N?mero da Inscri??o Municipal do Declarante                                    Formato: 9999999999 Exemplo: 65985-1 No arquivo ficar?: 0000659851 Campo N?o Obrigat?rio.
         LPAD(IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,'')))) >= 14,
                  (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,''))),
                  ''), 14, '0')||                                               -- H.03    12 -  25  Num?rico(14)  N?mero do CNPJ do Declarante no caso de pessoa jur?dica                        Formato: 99999999999999 Campo Obrigat?rio quando o campo H.02 ou H.04 n?o for preenchido
         LPAD(IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,'')))) < 14,
                  (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,''))),
                  ''), 11, '0')||                                               -- H.04    26 -  36  Num?rico(11)  N?mero do CPF do Declarante no caso de pessoa f?sica                           Obs.: Se o campo H.02 ou H.03 n?o for informado, ent?o este campo ser? obrigat?rio Formato: 99999999999
         RPAD(COALESCE(r.bdNOMEMP,''), 100, ' ')||                              -- H.05    37 - 136  Caracter(100) Nome/Raz?o Social do Declarante                                                Campo Obrigat?rio.
         'N'||                                                                  -- H.06   137 - 137  Caracter(1)   Tipo do Arquivo enviado para a Prefeitura, podendo ser: N ? normal, T ? Teste  Campo Obrigat?rio.
         SUBSTRING(:prREFERENCIA FROM 5 FOR 2)||                                -- H.07   138 - 139  Num?rico (2)  M?s de refer?ncia dos documentos declarados                                    Campo Obrigat?rio.
         SUBSTRING(:prREFERENCIA FROM 1 FOR 4)||                                -- H.08   140 - 143  Num?rico(4)   Ano de refer?ncia dos documentos declarados                                    Campo Obrigat?rio.
         RPAD('', 252, ' ')||                                                   -- H.09   144 - 395  Caracter(252) Brancos ? reservado para futuro                                                Campo Obrigat?rio.
         '.'                                                                    -- H.10   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                      Campo obrigat?rio que indica o final do registro.
  FROM VW_EMPRESAS_REF_ATUAL r
  WHERE r.bdCODEMP = :prCODEMP;

  -- REGISTRO DOCUMENTOS EMITIDOS CANCELADOS ? ?C?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, s.bdCODEMP, 2, LPAD(COALESCE((SELECT COUNT(*)              -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                        OBSERVA??ES
                                                   FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, s.bdCODEMP, 2, s.bdCODEMP||'.'||s.bdCHAVE,                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                        OBSERVA??ES
         'C'||                                                                  -- C.01     1 -   1  Caracter(1)   C?digo do registro ?C?                           Campo Obrigat?rio
         COALESCE((SUBSTRING(s.bdDATACANC FROM 9 FOR 2)||
                   SUBSTRING(s.bdDATACANC FROM 6 FOR 2)||
                   SUBSTRING(s.bdDATACANC FROM 1 FOR 4)),'00000000')||          -- C.02     2 -   9  Num?rico(8)   Data do cancelamento  da nota fiscal emitida.    Campo Obrigat?rio Formato: DDMMAAAAA
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCINI,'') FROM 1 FOR 8), 8, '0')||     -- C.03    10 -  17  Num?rico(8)   N?mero da nota fiscal inicial cancelada          Campo Obrigat?rio
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCFIM,'') FROM 1 FOR 8), 8, '0')||     -- C.04    18 -  25  Num?rico(8)   N?mero da nota fiscal final cancelada            Dever? ser informado somente quando houver um agrupamento de notas canceladas.
         RPAD(SUBSTRING(COALESCE(s.bdSERIE,'') FROM 1 FOR 3), 3, ' ')||         -- C.05    26 -  28  Caracter(3)   S?rie da Nota Fiscal cancelada                   Campo Obrigat?rio
         RPAD('', 361, ' ')||                                                   -- C.06    29 - 389  Caracter(361) Reservado para futuro
         LPAD(COALESCE((SELECT COUNT(*)
                        FROM TEXPORTACAO_ISS_CURITIBA),1), 6, '0')||            -- C.07   390 - 395  Num?rico(6)   N?mero seq?encial do registro dentro do arquivo. Campo Obrigat?rio.
         '.'                                                                    -- C.08   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                        Campo obrigat?rio que indica o final do registro.
  FROM VEF_EMP_TMOVSER s
  WHERE s.bdCODEMP = :prCODEMP
    AND s.bdTIPLAN = 0 -- Apenas servi?os Emitidos
    AND s.bdCODSITNF IN (2,3,4,5) -- Notas canceladas
    AND s.bdDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM;

  -- REGISTRO DOCUMENTOS EMITIDOS DECLARADOS ? ?E?
  IF (:prTIPOLANC IN (0,1)) THEN -- 0 = Ambos (emitidos/recebidos) / 1 = Somente emitidos
    EXECUTE PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (:prCODEMP, :prREFERENCIA, :prDTINI, :prDTFIM, :prTIPOLANC, :prRETIFICADORA, :prARQUIVO, 0);

  -- REGISTRO DOCUMENTOS RECEBIDOS DECLARADOS ? ?R?
  IF (:prTIPOLANC IN (0,2)) THEN -- 0 = Ambos (emitidos/recebidos) / 2 = Somente recebidos
    EXECUTE PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (:prCODEMP, :prREFERENCIA, :prDTINI, :prDTFIM, :prTIPOLANC, :prRETIFICADORA, :prARQUIVO, 1);

  -- REGISTRO HEADER ? ?T?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, c.bdCODEMP, 5, LPAD(COALESCE((SELECT COUNT(*)              -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                                                                        OBSERVA??ES
                                                   FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, c.bdCODEMP, 5, c.bdCODEMP,                                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                                                                        OBSERVA??ES
         'T'||                                                                  -- T.01     1 -   1  Caracter(1)   C?digo do registro ?T?                                                                                                           Campo Obrigat?rio
         LPAD(COUNT(*)+1, 8, '0')||                                             -- T.02     2 -   9  Num?rico(8)   Quantidade total de registros do arquivo, incluindo o header (H) e trailler (T)                                                  Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLREMIT,0)))), 15, '0')||        -- T.03    10 -  24  Num?rico(15)  Valor Total dos Documentos emitidos  pelo Prestador de Servi?os. Soma de todos os valores descritos nos campos E.11              Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRDEDEMIT,0)))), 15, '0')||     -- T.04    25 -  39  Num?rico(15)  Valor Total das Dedu??es dos Documentos emitidos pelo Prestador de Servi?os. Soma de todos os valores descritos nos campos E.12  Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRRECEB,0)))), 15, '0')||       -- T.05    40 -  54  Num?rico(15)  Valor Total dos Documentos recebidos  pelo tomador de Servi?os. Soma de todos os valores descritos nos campos R.11               Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRDEDRECEB,0)))), 15, '0')||    -- T.06    55 -  69  Num?rico(15)  Valor Total das Dedu??es dos Documentos recebidos  pelo tomador de Servi?os. Soma de todos os valores descritos nos campos R.12  Campo Obrigat?rio
         RPAD('', 326, ' ')||                                                   -- T.07    70 - 395  Caracter(326) Brancos ? reservado para futuro
         '.'                                                                    -- T.08   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                                                                        Campo obrigat?rio que indica o final do registro.
  FROM TEXPORTACAO_ISS_CURITIBA c
  WHERE c.bdCODEMP = :prCODEMP
  GROUP BY c.bdCODEMP;

  -- Exporta arquivo...
  OPENARQ(:prARQUIVO);

  FOR
    SELECT e.bdLINHA
    FROM TEXPORTACAO_ISS_CURITIBA E
    WHERE e.bdID = :prARQUIVO
    ORDER BY e.bdORDEMREG, e.bdORDEM
    INTO :wLINHA
  DO
    BEGIN
      WRITELNOA(:WLINHA);
    END

  CLOSEARQ(:prARQUIVO);

  DELETE FROM TEXPORTACAO_ISS_CURITIBA;

END
^

/* Restore proc. body: SP_FERIADO_EMPRESA */
ALTER PROCEDURE SP_FERIADO_EMPRESA(PRCODEMP INTEGER,
PRDATA DATE,
PRREFERENCIA INTEGER = 0,
PRSINDICATO INTEGER = 0)
 RETURNS(BDFERIADO VARCHAR(5))
 AS
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WCIDFER INTEGER;
DECLARE VARIABLE WUFFER INTEGER;
DECLARE VARIABLE WSINDFER INTEGER;
DECLARE VARIABLE WRETURN VARCHAR(5);
BEGIN
  IF ((prreferencia IS NULL) OR (prreferencia = 0)) THEN
     wref = CAST((SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     wref = prreferencia;

  wcodcid = NULL;
  wcoduf  = NULL;
  EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
  SELECT EMP.BDCODCID, CID.BDCODUF FROM VW_TEMPRESAS_REF EMP LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) WHERE EMP.BDCODEMP = :prcodemp INTO :wcodcid,:wcoduf;
  wreturn = 'FALSE';
  FOR SELECT BDCODSINTRAB,BDCODCID,BDCODUF FROM sp_tferiados(:wref, :wref) WHERE BDDATAFER = :prdata INTO :wsindfer,:wcidfer,wuffer DO
    BEGIN
      IF (wsindfer IS NULL AND wcidfer IS NULL AND wuffer IS NULL) THEN  -- Feriado nacional
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wcidfer IS NOT NULL AND wcodcid IS NOT NULL AND wcidfer = wcodcid) THEN  -- Feriado municipal
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wcidfer IS NULL AND wcoduf IS NOT NULL AND wuffer = wcoduf) THEN  -- Feriado estadual
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wsindfer IS NOT NULL AND prsindicato IS NOT NULL AND wsindfer = prsindicato) THEN  -- Feriado sindical
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
    END

  bdferiado = wreturn;
  SUSPEND;
END
^

/* Restore proc. body: SP_FICHA_REGISTROS_SALARIOS */
ALTER PROCEDURE SP_FICHA_REGISTROS_SALARIOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRREF INTEGER,
PRRETORNAVAZIO INTEGER,
PRTRAZERSALINI INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDSALINICOL NUMERIC(18,6),
BDDATACOL DATE,
BDSALBASECOL NUMERIC(18,6),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODTFUC INTEGER,
BDCODSHE INTEGER,
BDDESCSHE VARCHAR(50),
BDSALBASEANT NUMERIC(18,6))
 AS
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATAADMCOL date;
declare variable WSALINICOL numeric(18,6);
declare variable WDATACOL date;
declare variable WSALBASECOL numeric(18,6);
declare variable WCODMAS integer;
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(30000);
declare variable WCONT integer;
declare variable WDESCMAS varchar(50);
declare variable WCODTFUC integer;
declare variable WCODSHE integer;
declare variable WTIPOCOL integer;
declare variable WDESCSHE varchar(50);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WWHERE varchar(500);
BEGIN
  BDSALBASEANT = 0;

  IF (PRRETORNAVAZIO = 1) THEN
     BEGIN
       EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);
       WSQL = ' select BDCODEMP, BDCODCOL, BDTIPOCOL from VW_VRHF_EMP_TCOL_CALC COL ';

       -- 14269 - Marcelo B. M. - 23/06/2016: Ajustado para aceitar mais de uma empresa e/ou colaborador
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
             WSQL = WSQL || ' where '||prcodemp;
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' and '||PRCODCOL;
          END
       ELSE
          BEGIN
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' where '||PRCODCOL;
          END

       FOR EXECUTE STATEMENT wsql INTO
         WCODEMP,
         WCODCOL,
         WTIPOCOL
       DO
       BEGIN
         --Sol. 17643 - Bruno L. R. - 01/08/2017
         IF (WTIPOCOL = 4) THEN
            BEGIN
              WSQL2 = 'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, SHE.BDSALSHE bdsalinicol, SHE.BDDATASHE BDDATACOL, SHE.BDSALSHE BDSALBASECOL, SHE.bdcodshe bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe,  CAST(null as varchar(50)) BDDESCSHE  ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_SHE SHE on (SHE.bdcodemp = COL.bdcodemp and SHE.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = SHE.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = SHE.bdcodemp and VINCDIA.bdcodcol = SHE.bdcodcol and VINCDIA.BDDATACOL = SHE.BDDATASHE) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              WSQL2 = WSQL2 || ' union select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, '||
                      ' HIST.BDSALBASEHAUMHE,  HIST.bdcodshe bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = col.bdcodemp and VINCDIA.bdcodcol = col.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUMHE) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              /*
              WCAMPOSSHE = ' HIST.BDSALBASEANTHAUMHE bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, HIST.BDSALBASEHAUMHE BDSALBASECOL, HIST.bdcodmas, MAUMSAL.BDDESCMAS,'||
                           ' VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE ';
              WJOINSHE = ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) '||
                         ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = HIST.bdcodmas) '||
                         ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WCAMPODATA = 'HIST.BDDATAHAUMHE';      */
            END
          ELSE
            BEGIN
              WSQL2 = 'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, CALC.BDDATACOL, CALC.BDSALBASECOL, CALC.bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOLCON_CALCDIA CALC on (CALC.bdcodemp = COL.bdcodemp and CALC.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = CALC.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = CALC.bdcodemp and VINCDIA.bdcodcol = CALC.bdcodcol and VINCDIA.BDDATACOL = CALC.BDDATACOL) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              WSQL2 = WSQL2 || ' union select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUM BDDATACOL, HIST.BDSALBASEHAUM, '||
                      ' HIST.bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUM HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = COL.bdcodemp and VINCDIA.bdcodcol = COL.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUM) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;
            END
         --Sol. 17643 - Bruno L. R. - 01/08/2017

           wempatu = 0;
           wcolatu = 0;

           WCONT = 0;
           FOR EXECUTE STATEMENT WSQL2 INTO
             WCODEMP,
             WCODCOL,
             WDATAADMCOL,
             WSALINICOL,
             WDATACOL,
             WSALBASECOL,
             WCODMAS,
             WDESCMAS,
             WCODTFUC,
             WCODSHE,
             WDESCSHE
           DO
           BEGIN
             IF (wcont = 0) THEN
                BEGIN
                   BDCODEMP = WCODEMP;
                   BDCODCOL = WCODCOL;
                   BDDATAADMCOL = WDATAADMCOL;
                   IF (WSALINICOL IS NULL) THEN
                      BDSALINICOL = 0;
                   ELSE
                      BDSALINICOL = WSALINICOL;
                   BDDATACOL = WDATACOL;
                   BDSALBASEANT = NULL;   --Sol. 17798 - Bruno L. R. - 05/04/2017
                   BDSALBASECOL = WSALBASECOL;

                   IF ((WDATACOL = WDATAADMCOL) OR (BDSALBASEANT IS NULL)) THEN   --Sol. 18509 - Bruno L. R. - 26/07/2017
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admiss?o';

                        --IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                          -- BDSALBASECOL = BDSALINICOL;

                       -- IF (BDSALBASECOL IS NOT NULL) THEN
                         --  BDSALINICOL = BDSALBASECOL;
                      END
                   ELSE
                     BEGIN
                       BDCODMAS = WCODMAS;
                       BDDESCMAS = WDESCMAS;
                     END

                   IF (BDDATACOL IS NULL) THEN
                      BDDATACOL = BDDATAADMCOL;

                   IF (BDSALBASEANT = BDSALINICOL) THEN
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admiss?o';
                        BDDATACOL = WDATAADMCOL;
                      END

                   BDCODSHE = WCODSHE;
                   BDDESCSHE = WDESCSHE;
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL = BDSALINICOL) AND (WTIPOCOL = 4))) THEN
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL <> BDSALINICOL) OR (BDSALBASECOL IS NULL))) THEN
                   IF ((PRTRAZERSALINI = 1) AND (BDSALINICOL <> 0)) THEN
                      begin
                        if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                           begin
                             wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                      ' and BDREFCOL <= '||prref||
                                      ' order by BDREFCOL DESC';
                             execute statement wwhere into :BDNOMCOL;
           
                             wempatu = wcodemp;
                             wcolatu = wcolatu;
                           end

                        SUSPEND;
                      end
                END
             ELSE
                BEGIN
                --  IF ((BDCODEMP <> WCODEMP) OR (BDCODCOL <> WCODCOL) OR (BDSALBASECOL <> WSALBASECOL) OR (BDCODMAS <> WCODMAS)) THEN   --Sol. 18509 - Bruno L. R. - 03/07/2017
                 -- BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        BDDATAADMCOL = WDATAADMCOL;
                        IF (WSALINICOL IS NULL) THEN
                           BDSALINICOL = 0;
                        ELSE
                           BDSALINICOL = WSALINICOL;
                        BDDATACOL = WDATACOL;
                        BDSALBASEANT = BDSALBASECOL;     --Sol. 17798 - Bruno L. R. - 04/04/2017
                        BDSALBASECOL = WSALBASECOL;

                       IF ((WDATACOL = WDATAADMCOL) OR (BDSALBASEANT IS NULL)) THEN    --Sol. 18509 - Bruno L. R. - 10/07/2017
                          BEGIN
                            BDCODMAS = 0;
                            BDDESCMAS = 'Admiss?o';

                         --   IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                           --    BDSALBASECOL = BDSALINICOL;
                          END
                       ELSE
                         BEGIN
                           BDCODMAS = WCODMAS;
                           BDDESCMAS = WDESCMAS;
                         END

                        BDCODTFUC = WCODTFUC;
                        BDCODSHE = WCODSHE;
                        BDDESCSHE = WDESCSHE;

                        IF (BDDATACOL IS NULL) THEN
                           BDDATACOL = BDDATAADMCOL;

                        IF (BDSALBASEANT = BDSALINICOL) THEN
                           BEGIN
                             BDCODMAS = 0;
                             BDDESCMAS = 'Admiss?o';
                       --      BDDATACOL = WDATAADMCOL;
                           END

                        IF (BDSALBASEANT <> BDSALBASECOL) THEN
                           BEGIN
                             BDCODMAS = WCODMAS;
                             BDDESCMAS = WDESCMAS;
                           END

                       IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND ((BDSALBASECOL <> BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR
                          ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN
                          begin
                            if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                               begin
                                 wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                          ' and BDREFCOL <= '||prref||
                                          ' order by BDREFCOL DESC';
                                 execute statement wwhere into :BDNOMCOL;
               
                                 wempatu = wcodemp;
                                 wcolatu = wcolatu;
                               end

                            SUSPEND;
                          end
                   --  END
                END
    
             WCONT = 1;
           END
       END
     END
   ELSE
     SUSPEND;
END
^

/* Restore proc. body: SP_FUNCOES_PLANO_EMP */
ALTER PROCEDURE SP_FUNCOES_PLANO_EMP(PRCODEMP INTEGER,
PRCODPLAFUC INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODCBO INTEGER,
BDDESCCBO VARCHAR(150),
BDDESCTFUC VARCHAR(40),
BDCODCBOTSIN INTEGER,
BDDESCFUNCDET VARCHAR(100),
BDINATIVA VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FUC.BDCODTFUC, '||
                'FUC.bdcodplafuc, '||
                'FUC.BDCODCBO, '||
                'FUC.BDCODCBOTSIN, '||
                'case when (CBO.BDDESCCBOTSIN <> '''||''||''') and (CBO.BDDESCCBOTSIN is not null) then CBO.BDDESCCBOTSIN else CBOO.BDDESCCBO end BDDESCCBO, '||
                'FUC.BDDESCTFUC, '||
                'FUC.BDDESCFUNCDET, '||
                'FUC.BDINATIVA '||
         'from VRH_FUNCOES_TFUC FUC '||
         'left outer join VRH_BASE_TCBO CBOO on (CBOO.BDCODCBO = FUC.BDCODCBO) '||
         'left outer join VRH_BASE_CBO_TSIN CBO '||
           'on (CBO.BDCODCBO = FUC.BDCODCBO and CBO.BDCODCBOTSIN = FUC.BDCODCBOTSIN) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> 0) THEN
     BEGIN
       wsql = wsql||'join VW_EMPRESAS_REF_ATUAL Y '||
                      'on (Y.BDCODEMP = '||prcodemp||' and Y.BDCODPLAFUC = FUC.BDCODPLAFUC) '||
                    'where Y.BDCODEMP = '||prcodemp;
     END
  ELSE
     BEGIN
       IF (PRCODPLAFUC IS NOT NULL AND PRCODPLAFUC <> 0) THEN
          wsql = wsql||'where FUC.BDCODPLAFUC = '||PRCODPLAFUC;
     END

  FOR EXECUTE STATEMENT wSql
    INTO
      :BDCODTFUC,
      :BDCODPLAFUC,
      :BDCODCBO,
      :BDCODCBOTSIN,
      :BDDESCCBO,
      :BDDESCTFUC,
      :BDDESCFUNCDET,
      :BDINATIVA
    DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_GERAR_INCON_TCADPRO */
ALTER PROCEDURE SP_GERAR_INCON_TCADPRO(PRSESSAO INTEGER,
PRCODEMP INTEGER,
PRCODPLANOINCO INTEGER,
PRREF INTEGER,
PRIDTERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOUNIMED INTEGER;
DECLARE VARIABLE WNCMINVALIDO DM_BOOLEAN;
DECLARE VARIABLE WISINDUSTRIA DM_BOOLEAN;
DECLARE VARIABLE WNCMPADRAO INTEGER;
DECLARE VARIABLE WCODUNIMEDPADRAO INTEGER;
DECLARE VARIABLE WAPEUNIMEDPADRAO VARCHAR(5);
BEGIN
  DELETE FROM VEF_INCON_TCADPRO WHERE BDSESSAO = :PRSESSAO;

  SELECT I.BDPRODNCMVAZIO, I.BDNCMPROD, I.BDCODUNIMED
  FROM VEF_BASE_TACOESINCONS I
  WHERE I.BDCODPLANOINCONS = :PRCODPLANOINCO
  INTO :wNcmInvalido, :wNcmPadrao, :wCodUnimedPadrao;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREF);
  /*Faz esse select pra ver se a empresa n?o ? industria*/
  SELECT IIF(((a.bdcodconficmssped > 0) AND (a.BDATIVIDADESPED = 0) AND (a.bddtobrigspedcont IS NOT NULL) AND (a.BDINDATIV = 1)), 'TRUE', 'FALSE') BDISINDUSTRIA
  FROM VW_VEF_BASE_TEMPPARFED a
  WHERE a.bdcodemp = :PRCODEMP
  INTO :wIsIndustria;

  /*Transforma ncm's inv?lidas para vazio*/
  IF (:wNcmInvalido = 'TRUE') THEN
    BEGIN
      /*Verifica se a empresa n?o ? Ind?stria, industria deve ter ncm v?lido, sen?o tiver ? inconsistente*/
      IF (:wIsIndustria = 'FALSE') THEN
        BEGIN
          /*Altera na tabela TMP*/
          UPDATE TMP_TCADPRO P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );

          /*Altera na tabela TEMP*/
          UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );
        END
    END

  /*Muda as ncm's inv?lidas para ncm padr?o, se a empresa for ind?stria principalmente(obrigat?rio)*/
  IF ((:wNcmPadrao IS NOT NULL) OR (:wNcmPadrao > 0)) THEN
    BEGIN
      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se j? alterou, n?o vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se j? alterou, n?o vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );
    END

  /*Se tiver uma unidade de medida padr?o, coloca ela nos produtos que n?o tem unidade de medida*/
  IF ((:wCodUnimedPadrao IS NOT NULL) OR (:wCodUnimedPadrao > 0)) THEN
    BEGIN
      /*Busca apelido, apenas para mostrar na grid*/
      SELECT U.BDAPEUNIMED FROM TUNIDADEMEDIDA U WHERE U.BDCODUNIMED = :wCodUnimedPadrao INTO :wApeUnimedPadrao;

      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDCODUNIMED IS NULL) OR (P.BDCODUNIMED = 0))
      AND P.BDCODUNIMED <> :wCodUnimedPadrao; /*Se j? alterou, n?o vai alterar denovo*/

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDALTCODUNIMED = :wCodUnimedPadrao, P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0))
      AND P.BDALTCODUNIMED <> :wCodUnimedPadrao;
    END

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TUNIDADEMEDIDA_TEMP'
  INTO :wSessaoUniMed;

  /*49 - C?digo de unidade de medida n?o cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 49 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TUNIDADEMEDIDA U ON(U.BDCODUNIMED = P.BDALTCODUNIMED)
  LEFT OUTER JOIN TMP_TUNIDADEMEDIDA_TEMP T ON(T.BDEDITCHAVE = P.BDALTCODUNIMED AND T.BDSESSAO = :wSessaoUniMed)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDALTCODUNIMED IS NOT NULL) AND (P.BDALTCODUNIMED > 0))
  AND (U.BDCODUNIMED IS NULL) AND (T.BDCODUNIMED IS NULL);

  /*77 - O campo Unidade de medida n?o pode ficar em branco caso a empresa tenha Sped!*/
  IF (:wIsIndustria = 'TRUE') THEN
    BEGIN
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 77 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/  
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0));

      /*50 - C?digo de NCM n?o cadastrado*/
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/  
      AND ((P.BDNCMPROD IS NULL) OR ((P.BDNCMPROD IS NOT NULL) AND (N.BDNCMPROD IS NULL)));
    END

  /*50 - C?digo de NCM n?o cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
  WHERE P.BDSESSAO = :PRSESSAO
--  AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/
  AND P.BDNCMPROD IS NOT NULL
  AND N.BDNCMPROD IS NULL;

  /*73 - Situa??o como N?o relacionado(Est? inconsistencia n?o aparece para o usu?rio, ? somente para o controle de commit's)*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 73 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDSITUACAO IS NULL) OR (P.BDSITUACAO = 0));

  /*63 - Descri??o do produto n?o pode estar vazia*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 63 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDDESCPROD IS NULL) OR (P.BDDESCPROD = ''));

  /*62 - Apelido do produto n?o pode estar vazio*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 62 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDAPEPROD IS NULL) OR (P.BDAPEPROD = ''));

  /*118 - NCM n?o possui o c?digo de exce??o.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 118 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TCODEXTIPI EX ON(EX.BDNCMPROD = P.BDNCMPROD AND EX.BDCODTIPI = P.BDCODTIPI)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDCODTIPI IS NOT NULL) AND (P.BDCODTIPI > 0))
  AND EX.BDCODTIPI IS NULL;
END
^

/* Restore proc. body: SP_GET_CODPARTICIPANTEEXP */
ALTER PROCEDURE SP_GET_CODPARTICIPANTEEXP(PRTIPOEXPCODPART INTEGER,
PRCODTER INTEGER,
PRCGCTER VARCHAR(18),
PRIETER VARCHAR(20),
PRCODIGOARQUIVO VARCHAR(60))
 RETURNS(BDRETORNO VARCHAR(60))
 AS
DECLARE VARIABLE WI INTEGER;
BEGIN

  IF (:PRTIPOEXPCODPART = 0) THEN
    BDRETORNO = :PRCODTER;
  ELSE
  IF (:PRTIPOEXPCODPART = 1) THEN
    BEGIN
      SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:PRIETER) INTO :PRIETER;
      SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:PRCGCTER) INTO :PRCGCTER;

      PRIETER = TRIM(COALESCE(:PRIETER, ''));
      PRCGCTER = TRIM(COALESCE(:PRCGCTER, ''));

      BDRETORNO = :PRCGCTER;

      wI = 0;
      WHILE (wI <= 9) DO
        BEGIN
          IF (:PRCGCTER = LPAD('', CHAR_LENGTH(:PRCGCTER), wI)) THEN
            BEGIN
              BDRETORNO = '';
              BREAK;
            END
          wI = wI + 1;
        END

      IF (:PRIETER <> '') THEN
        BDRETORNO = :BDRETORNO || '_' || :PRIETER;
    END
  ELSE
  IF (:PRTIPOEXPCODPART = 3) THEN
    BDRETORNO = :PRCODIGOARQUIVO;
  ELSE
    BEGIN
      SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:PRCGCTER) INTO :PRCGCTER;
      PRCGCTER = TRIM(COALESCE(:PRCGCTER, ''));

      BDRETORNO = :PRCGCTER;

      wI = 0;
      WHILE (wI <= 9) DO
        BEGIN
          IF (:PRCGCTER = LPAD('', CHAR_LENGTH(:PRCGCTER), wI)) THEN
            BEGIN
              BDRETORNO = '';
              BREAK;
            END
          wI = wI + 1;
        END
    END

  IF (:BDRETORNO = '') THEN
    BDRETORNO = :PRCODTER;

  BDRETORNO = TRIM(COALESCE(BDRETORNO, ''));

  SUSPEND;
END
^

/* Restore proc. body: SP_GET_EVT_FILA_ESOCIAL */
ALTER PROCEDURE SP_GET_EVT_FILA_ESOCIAL(PRCODEMP INTEGER,
PREXCLUSAO INTEGER)
 RETURNS(BDCODIGO INTEGER,
BDCODEMP INTEGER,
BDCHAVE VARCHAR(50),
BDXML BLOB,
BDCODTIPO INTEGER,
BDSTATUS INTEGER,
BDDATAEVENTO DATE,
BDMOTIVO VARCHAR(100),
BDGRUPO INTEGER,
BDDATAININAOPERIOD DATE,
BDDATAINITABELA DATE,
BDDATAINIPERIOD DATE,
BDDATAINISST DATE)
 AS
declare variable WCODTIPO integer;
begin
  if (PREXCLUSAO = 0) then
  begin
    WCODTIPO = 0;
    for select first 40 EVT.BDCODIGO, EVT.BDCODEMP, EVT.BDCHAVE, EVT.BDXML, EVT.BDCODTIPO, EVT.BDSTATUS,
                        EVT.BDDATAEVENTO, EVT.BDMOTIVO, TP.BDGRUPO, FAS.BDDATAININAOPERIOD, FAS.BDDATAINITABELA,
                        FAS.BDDATAINIPERIOD, FAS.BDDATAINISST
        from VRH_ESOCIAL_TARQUIVO EVT
        left outer join VRH_ESOCIAL_TTIPO_ARQ TP on TP.BDCODTIPO = EVT.BDCODTIPO
        left outer join TEMPRESAS EMP on EVT.BDCODEMP = EMP.BDCODEMP
        left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.BDCODEMP = EMP.BDCODEMP
        left outer join VRH_EMP_TCOLCON COL on COL.BDCODEMP = EVT.BDCODEMP and COL.BDCODCOL = EVT.BDCODCOL
        where (EVT.BDCODTIPO <> 38) and
              ((EMP.BDCODEMP = :PRCODEMP) or (EMP.BDCODMATRIZ = :PRCODEMP and
              coalesce(EMP.BDSITUACAOESOCIAL, 0) = 1)) and
              ((EVT.BDCODTIPO = 1 and
              EVT.BDREFARQ = (select min(BDREFARQ)
                              from VRH_ESOCIAL_TARQUIVO EVTREF
                              where EVTREF.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                    EVTREF.BDCODTIPO = 1)) or (not exists(select first 1 *
                                                                          from VRH_ESOCIAL_TARQUIVO EVT1000
                                                                          where EVT1000.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                                EVT1000.BDCODTIPO = 1 and
                                                                                EVT1000.BDSTATUS <> 2 and
                                                                                EVT1000.BDREFARQ = (select min(BDREFARQ)
                                                                                                    from VRH_ESOCIAL_TARQUIVO EVTREF
                                                                                                    where EVTREF.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                                                          EVTREF.BDCODTIPO = 1)))) and
              ((TP.BDGRUPO = 1) or (TP.BDGRUPO in (2, 3) and
              not exists(select first 1 *
                         from VRH_ESOCIAL_TARQUIVO EVTORD
                         left outer join VRH_EMP_TCOLCON COLORD on COLORD.BDCODEMP = EVTORD.BDCODEMP and COLORD.BDCODCOL = EVTORD.BDCODCOL
                         where EVTORD.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                               COLORD.BDCPFCOL = COL.BDCPFCOL and
                               EVTORD.BDDATAEVENTO < EVT.BDDATAEVENTO and
                               EVTORD.BDSTATUS not in (2, 5, 6, 7)) and
              ((EVT.BDCODTIPO not in (11, 15, 16)) or (not exists(select *
                                                                  from VRH_ESOCIAL_TARQUIVO EVTESTAB
                                                                  where EVTESTAB.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                        EVTESTAB.BDCODTIPO = 2 and
                                                                        EVTESTAB.BDSTATUS not in (2, 5, 6, 7)))) and
              ((EVT.BDCODTIPO not in (11, 14, 34, 37)) or (not exists(select *
                                                                      from VRH_ESOCIAL_TARQUIVO EVTRUB
                                                                      where EVTRUB.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                            EVTRUB.BDCODTIPO = 3 and
                                                                            EVTRUB.BDSTATUS not in (2, 5, 6, 7)))) and
              ((EVT.BDCODTIPO not in (11, 34, 37)) or (not exists(select *
                                                                  from VRH_ESOCIAL_TARQUIVO EVTLOT
                                                                  where EVTLOT.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                        EVTLOT.BDCODTIPO = 4 and
                                                                        EVTLOT.BDSTATUS not in (2, 5, 6, 7)))) and
              ((EVT.BDCODTIPO not in (24, 26, 35, 36)) or (not exists(select *
                                                                      from VRH_ESOCIAL_TARQUIVO EVTCARGO
                                                                      where EVTCARGO.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                            EVTCARGO.BDCODTIPO = 5 and
                                                                            EVTCARGO.BDSTATUS not in (2, 5, 6, 7)))) and
              ((EVT.BDCODTIPO not in (24, 26)) or (not exists(select *
                                                              from VRH_ESOCIAL_TARQUIVO EVTHOR
                                                              where EVTHOR.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                    EVTHOR.BDCODTIPO = 7 and
                                                                    EVTHOR.BDSTATUS not in (2, 5, 6, 7)))) and
              ((EVT.BDCODTIPO not in (11, 15, 16)) or (not exists(select *
                                                                  from VRH_ESOCIAL_TARQUIVO EVTPROC
                                                                  where EVTPROC.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                        EVTPROC.BDCODTIPO = 9 and
                                                                        EVTPROC.BDSTATUS not in (2, 5, 6, 7)))) and
              ((EVT.BDCODTIPO not in (20)) or (not exists(select *
                                                          from VRH_ESOCIAL_TARQUIVO EVTPER
                                                          left outer join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                          where EVTPER.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                TPPER.BDGRUPO = 3 and
                                                                TPPER.BDCODTIPO not in (19, 20) and
                                                                EVTPER.BDSTATUS not in (2, 5, 6, 7)))) and
              ((EVT.BDCODTIPO not in (14)) or (not exists(select *
                                                          from VRH_ESOCIAL_TARQUIVO EVTPER
                                                          left outer join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                          where EVTPER.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                                                                EVTPER.BDCODCOL = EVT.BDCODCOL and
                                                                TPPER.BDCODTIPO = 11 and
                                                                EVTPER.BDSTATUS not in (2, 5, 6, 7)))))) and
              EVT.BDSTATUS in (0, 3)
        order by TP.BDGRUPO, TP.BDCODTIPO
        into :BDCODIGO, :BDCODEMP, :BDCHAVE, :BDXML, :BDCODTIPO, :BDSTATUS, :BDDATAEVENTO, :BDMOTIVO, :BDGRUPO,
             :BDDATAININAOPERIOD, :BDDATAINITABELA, :BDDATAINIPERIOD, :BDDATAINISST
    do
    begin
      if ((BDGRUPO = 1) and
          (WCODTIPO = 0)) then
        WCODTIPO = BDCODTIPO;

      if ((WCODTIPO = 0) or (WCODTIPO = BDCODTIPO)) then
        suspend;
    end
  end
  else
  begin
    for select first 40 EVT.BDCODIGO, EVT.BDCODEMP, EVT.BDCHAVE, EVT.BDXML, EVT.BDCODTIPO, EVT.BDSTATUS,
                        EVT.BDDATAEVENTO, EVT.BDMOTIVO, TP.BDGRUPO, FAS.BDDATAININAOPERIOD, FAS.BDDATAINITABELA,
                        FAS.BDDATAINIPERIOD, FAS.BDDATAINISST
        from VRH_ESOCIAL_TARQUIVO EVT
        left outer join VRH_ESOCIAL_TTIPO_ARQ TP on TP.BDCODTIPO = EVT.BDEVENTOEXCLUSAO
        left outer join TEMPRESAS EMP on EVT.BDCODEMP = EMP.BDCODEMP
        left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.BDCODEMP = EMP.BDCODEMP
        left outer join VRH_EMP_TCOLCON COL on COL.BDCODEMP = EVT.BDCODEMP and COL.BDCODCOL = EVT.BDCODCOL
        where (EVT.BDCODTIPO = 38) and
              ((EMP.BDCODEMP = :PRCODEMP) or (EMP.BDCODMATRIZ = :PRCODEMP and
              coalesce(EMP.BDSITUACAOESOCIAL, 0) = 1)) and
              (TP.BDGRUPO in (2, 3) and
              not exists(select first 1 *
                         from VRH_ESOCIAL_TARQUIVO EVTORD
                         left outer join VRH_EMP_TCOLCON COLORD on COLORD.BDCODEMP = EVTORD.BDCODEMP and COLORD.BDCODCOL = EVTORD.BDCODCOL
                         where EVTORD.BDCODEMP in (EMP.BDCODMATRIZ, EMP.BDCODEMP) and
                               COLORD.BDCPFCOL = COL.BDCPFCOL and
                               EVTORD.BDDATAEVENTO > EVT.BDDATAEVENTO and
                               EVTORD.BDSTATUS not in (-1, 2, 5, 6, 7))) and
              EVT.BDSTATUS in (0, 3)
        into :BDCODIGO, :BDCODEMP, :BDCHAVE, :BDXML, :BDCODTIPO, :BDSTATUS, :BDDATAEVENTO, :BDMOTIVO, :BDGRUPO,
             :BDDATAININAOPERIOD, :BDDATAINITABELA, :BDDATAINIPERIOD, :BDDATAINISST
    do
      suspend;
  end
end
^

/* Restore proc. body: SP_IMPOSTO_EMPRESA */
ALTER PROCEDURE SP_IMPOSTO_EMPRESA(PRCODEMP INTEGER,
PRCODSIS INTEGER,
PRTIPORETENCAO INTEGER,
PRREF INTEGER,
PRQTD INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER,
BDCODSIS INTEGER)
 AS
DECLARE VARIABLE WPRIDIA DATE;
DECLARE VARIABLE WULTDIA DATE;
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select ';

  EXECUTE PROCEDURE sp_seta_competencia(:prref,NULL,NULL);

  IF (prqtd IS NOT NULL AND prqtd <> 0) THEN
     wsql = wsql||'first '||prqtd||' ';

  wsql = wsql|| 'BDCODEMP, '||
                'BDREFEMP, '||
                'BDREFFIMIMP, '||
                'BDCODIMP, '||
                'BDDESCIMP, '||
                'BDDATACRIACAO, '||
                'BDDATAEXTINTO, '||
                'BDCOMPETENCIA, '||
                'BDDOCARRECADACAO, '||
                'BDPERAPURACAO, '||
                'BDDIAVENCTO, '||
                'BDANTECIPA, '||
                'BDMESVENCTO, '||
                'BDJUROSDIA, '||
                'BDVLRJUROS, '||
                'BDJUROSDIAMES, '||
                'BDMULTADIA, '||
                'BDVLRMULTA, '||
                'BDMULTADIAMES, '||
                'BDVLRMAXMULTA, '||
                'COALESCE(BDALIQIMPOSTO, 0.0) BDALIQIMPOSTO, '||
                'BDLIMITEISENCAO, '||
                'BDTIPORETENCAO, '||
                'BDCODREC, '||
                'BDCODIND, '||
                'BDRETBCCALCULOIMP, '||
                'BDDESCREC, '||
                'BDTIPOIMPOSTO, '||
                'BDCODSIS ';
  wsql = wsql||'from VW_TEMPRESAIMPOSTOREF ';


  wwhere = '';

  IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
       wpridia = CAST((SUBSTRING(prref FROM 5 FOR 2)||'-01-'||SUBSTRING(prref FROM 1 FOR 4)) AS DATE);
       wultdia = wpridia - EXTRACT(DAY FROM wpridia) + 32 - EXTRACT(DAY FROM wpridia - EXTRACT(DAY FROM wpridia) + 32);

       wwhere = wwhere||'BDREFEMP <= '||prref||' ';

       wwhere = wwhere||' and (';

       wwhere = wwhere||'(BDDATACRIACAO is null) or (BDDATACRIACAO <= '''||wpridia||''') and ';
       wwhere = wwhere||'(BDDATAEXTINTO is null) or (BDDATAEXTINTO > '''||wultdia||''')';

       wwhere = wwhere||') ';
     END

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdcodemp = '||prcodemp;
     END

  IF (prcodsis IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdcodsis = '||prcodsis;
     END

  IF (prtiporetencao IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdtiporetencao = '||prtiporetencao;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFEMP,
    :BDREFFIMIMP,
    :BDCODIMP,
    :BDDESCIMP,
    :BDDATACRIACAO,
    :BDDATAEXTINTO,
    :BDCOMPETENCIA,
    :BDDOCARRECADACAO,
    :BDPERAPURACAO,
    :BDDIAVENCTO,
    :BDANTECIPA,
    :BDMESVENCTO,
    :BDJUROSDIA,
    :BDVLRJUROS,
    :BDJUROSDIAMES,
    :BDMULTADIA,
    :BDVLRMULTA,
    :BDMULTADIAMES,
    :BDVLRMAXMULTA,
    :BDALIQIMPOSTO,
    :BDLIMITEISENCAO,
    :BDTIPORETENCAO,
    :BDCODREC,
    :BDCODIND,
    :BDRETBCCALCULOIMP,
    :BDDESCREC,
    :BDTIPOIMPOSTO,
    :BDCODSIS
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_NOME_TERCEIRO */
ALTER PROCEDURE SP_NOME_TERCEIRO(PRREF INTEGER,
PRTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDNOME VARCHAR(200))
 AS
BEGIN
  /* Procedure Text */
  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  bdcodter = prter;

  SELECT ter.bdnome FROM vw_tterceiro_simples ter WHERE ter.bdcodter = :prter INTO bdnome;

  SUSPEND;
END
^

/* Restore proc. body: SP_PBM */
ALTER PROCEDURE SP_PBM(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDEMP INTEGER,
BDREF INTEGER,
BDOK INTEGER)
 AS
BEGIN
  /* Procedure Text */
  /* BDOK */
  bdemp = premp;
  bdref = prref;

  EXECUTE PROCEDURE sp_seta_competencia(prref);
  bdok = 0;

  FOR SELECT COALESCE(BDCODCONFBLOCOP,0) FROM VW_VEF_BASE_TEMPPARGER WHERE bdcodemp = :premp INTO bdok DO
    BEGIN
    END

  IF (bdok <> 0) THEN
     bdok = 1;

  SUSPEND;
END
^

/* Restore proc. body: SP_PERC_GORJETA */
ALTER PROCEDURE SP_PERC_GORJETA(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(2000),
PRREF INTEGER)
 RETURNS(BDREFCOL VARCHAR(10),
BDPERCGORJ NUMERIC(18,6),
BDNOMCOL VARCHAR(200),
BDCODCOL INTEGER,
BDCODEMP INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WNOMCOL VARCHAR(200);
DECLARE VARIABLE WPERCGORJ NUMERIC(18,6);
DECLARE VARIABLE WREFCOL INTEGER;
DECLARE VARIABLE WSQL VARCHAR(20000);
DECLARE VARIABLE WSQL2 VARCHAR(20000);
DECLARE VARIABLE WCOUNT INTEGER;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);

  WSQL = ' select BDCODEMP, BDCODCOL from VW_VRHF_EMP_TCOL_CALC COL ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       WSQL = WSQL || ' where '||prcodemp;
       IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
          WSQL = WSQL || ' and '||PRCODCOL;
     END
  ELSE
     BEGIN
       IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
          WSQL = WSQL || ' where '||PRCODCOL;
     END

  FOR EXECUTE STATEMENT WSQL INTO
    WCODEMP,
    WCODCOL
  DO
  BEGIN
    WCOUNT = 0;
    WSQL2 = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDNOMCOL, CALC.BDPERCGORJ, CALC.BDREFCOL '||
                'from VW_VRH_EMP_TCOLCON_CAD COL '||
                'left outer join VRHF_EMP_TCOL_CALC CALC on (CALC.BDCODEMP = COL.BDCODEMP and CALC.BDCODCOL = COL.BDCODCOL) '||
                'where CALC.BDPERCGORJ is not null and COL.BDCODEMP='||WCODEMP||' and COL.BDCODCOL='||WCODCOL||' '||
                'order by COL.BDCODEMP, COL.BDCODCOL, CALC.BDREFCOL ';

    FOR EXECUTE STATEMENT WSQL2 INTO
      WCODEMP,
      WCODCOL,
      WNOMCOL,
      WPERCGORJ,
      WREFCOL
    DO
      BEGIN
        IF (WCOUNT = 0) THEN
           BEGIN
             BDCODEMP = WCODEMP;
             BDCODCOL = WCODCOL;
             BDNOMCOL = WNOMCOL;
             BDPERCGORJ = WPERCGORJ;
             BDREFCOL = SUBSTRING(WREFCOL FROM 5 FOR 2)||'/'||SUBSTRING(WREFCOL FROM 1 FOR 4);
             SUSPEND;
           END
        ELSE
           BEGIN
             IF (BDPERCGORJ <> WPERCGORJ) THEN
                BEGIN
                  BDCODEMP = WCODEMP;
                  BDCODCOL = WCODCOL;
                  BDNOMCOL = WNOMCOL;
                  BDPERCGORJ = WPERCGORJ;
                  BDREFCOL = SUBSTRING(WREFCOL FROM 5 FOR 2)||'/'||SUBSTRING(WREFCOL FROM 1 FOR 4);
                  SUSPEND;
                END
           END

        WCOUNT = WCOUNT + 1;
      END
  END
END
^

/* Restore proc. body: SP_PRAZO_EXPERIENCIA_SITUACAO */
ALTER PROCEDURE SP_PRAZO_EXPERIENCIA_SITUACAO(PRCODEMP VARCHAR(30000),
PRCODCOL VARCHAR(30000),
PRDIASPRAZO1COL INTEGER,
PRDIASPRAZO2COL INTEGER,
PRCODSIT INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE)
 AS
DECLARE VARIABLE WWHERE VARCHAR(200);
DECLARE VARIABLE WDATAINISIT DATE;
DECLARE VARIABLE WDATAADMCOL DATE;
DECLARE VARIABLE WDATAULTIMASAIDAAFASTAMENTO DATE;
DECLARE VARIABLE WDATAINICIOPRAZO DATE;
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDIASPRAZO1COL INTEGER;
DECLARE VARIABLE WDIASPRAZO2COL INTEGER;
DECLARE VARIABLE WQDEDIASRESTANTES INTEGER;
DECLARE VARIABLE WQDEDIASAFASTADO INTEGER;
DECLARE VARIABLE WDIASSIT INTEGER;
DECLARE VARIABLE WCONTINUAR CHAR(1);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WMESCOMZERO VARCHAR(2);
DECLARE VARIABLE WSQL2 VARCHAR(1000);
DECLARE VARIABLE WSQL3 VARCHAR(1000);
DECLARE VARIABLE WCOUNTSITUACAO INTEGER;
DECLARE VARIABLE WSQL4 VARCHAR(1000);
DECLARE VARIABLE WINIDATAULTSIT DATE;
DECLARE VARIABLE WFIMDATAPRISIT DATE;
DECLARE VARIABLE WQDIASENTRESIT INTEGER;
DECLARE VARIABLE WPRORROGACONTRATO VARCHAR(5);
DECLARE VARIABLE WCODSIT INTEGER;
DECLARE VARIABLE WCOUNTPRORROGA INTEGER;
DECLARE VARIABLE WDATAINIPRISIT DATE;
DECLARE VARIABLE WCOUNTQTDDIAS INTEGER;
DECLARE VARIABLE WQTDDIAS INTEGER;
BEGIN
--    prcodemp = trim(prcodemp);
--    prcodcol = trim(prcodcol);
--    prdiasprazo2col = coalesce(prdiasprazo2col, 0);

  /*
     Essa primeira parte verifica somente os colaboradores que estao ou estiveram em situacao dentro do periodo de experiencia
   */

  wsql = 'select ADM.BDCODEMP, ADM.BDCODCOL, COL2.BDDATAADMCOL, ';

  IF (prdiasprazo1col IS NOT NULL ) THEN
     wsql = wsql||:prdiasprazo1col||' ';
  ELSE
     wsql = wsql||'coalesce(ADM.BDDIASPRAZO1COL, 0) ';

  wsql = wsql||' bdprazo1, ';

  IF (prdiasprazo2col IS NOT NULL ) THEN
     wsql = wsql||:prdiasprazo2col||' ';
  ELSE
     wsql = wsql||'coalesce(ADM.BDDIASPRAZO2COL, 0) ';

  wsql = wsql||' bdprazo2 ';

  wsql = wsql||
         'from ('||
            'select BDCODEMP, BDCODCOL, BDDIASPRAZO1COL, BDDIASPRAZO2COL, BDDATAFIMPRAZO1COL, BDDATAFIMPRAZO2COL from VRH_EMP_TCOL_ADM ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' where '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and ';
       ELSE
          wsql = wsql||' where ';

       wsql = wsql||prcodcol;
     END

  wsql = wsql||
         ') ADM '||
         'join VRH_EMP_TCOLCON COL2 on (COL2.BDCODEMP = ADM.BDCODEMP and COL2.BDCODCOL = ADM.BDCODCOL) '||
         'join vrh_emp_tsitcol sit on (sit.bdcodemp = adm.bdcodemp and sit.bdcodcol = adm.bdcodcol) '||
         'join vrh_base_tprepsit psit on (psit.bdcodsit = sit.bdcodsit and UPPER(psit.bdprorrogacontrato) = '''||'TRUE'||''') '||
         'where ((adm.bddiasprazo1col > 0 and sit.bddatainisit <= adm.bddatafimprazo1col) or (adm.bddiasprazo2col > 0 and sit.bddatainisit <= adm.bddatafimprazo2col)) ';

  wsql = wSql||' group by ADM.BDCODEMP, ADM.BDCODCOL, COL2.BDDATAADMCOL,bdprazo1,bdprazo2';

  wcountprorroga = 0; -- Sol 19715 - Marcelo B. M. - 25/08/2017
  wcountqtddias = 0;  -- Sol 18917 - Marcelo B. M. - 28/08/2017

    FOR EXECUTE STATEMENT WSQL INTO
        :bdcodemp, :bdcodcol, :wdataadmcol, :wdiasprazo1col, :wdiasprazo2col
    DO
        BEGIN
            wdiasprazo1col = wdiasprazo1col - 1;
            wqdediasrestantes = wdiasprazo1col;
            bddatafimprazo1col = NULL;
            bddatafimprazo2col = NULL;

            wcontinuar = 'S';
            IF (wdiasprazo1col > 0) THEN
                BEGIN
                    wdatainicioprazo = wdataadmcol;
        
                    WHILE (wcontinuar = 'S') DO
                        BEGIN
                            wqdediasafastado = 0;
                            bddatafimprazo1col = wdatainicioprazo + wdiasprazo1col;
        
        
                            wsql2 = 'select sit.BDDATAINISIT, coalesce(sit.BDDIASSIT, 0) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                        ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo1col||''')';

                            -- Sol 18917 - Se tem duas situacoes dentro do periodo de experiencia, considera os dias entre o fim de uma e o comeco de outra como trabalhados
                            wsql3 = 'select count(sit.BDDATAINISIT) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                    ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo1col||''')';

                            wqdiasentresit = 0;

                            IF (wsql3 IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                            BEGIN
                            FOR EXECUTE STATEMENT wsql3 INTO
                                :wcountsituacao
                            DO
                                BEGIN
                                  IF (wcountsituacao = 2) THEN
                                     BEGIN
                                       wsql4 = 'select max(sit.BDDATAINISIT), min(sit.BDDATAFIMSIT) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                               ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo1col||''')';

                                       IF (wsql4 IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                                       BEGIN
                                       FOR EXECUTE STATEMENT wsql4 INTO
                                           :winidataultsit, :wfimdataprisit
                                       DO
                                           wqdiasentresit = TRUNC(winidataultsit - wfimdataprisit) - 1;
                                       END
                                     END
                                END
                            END
                            -- Sol 18917 - Fim

                            wcontinuar = 'N';

                            IF (wsql2 IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                            BEGIN
                            FOR EXECUTE STATEMENT wsql2 INTO
                                :wdatainisit, :wdiassit
                            DO
                                BEGIN
                                    wcontinuar = 'S';
        
                                    IF (wdiassit > 0) THEN
                                        wqdediasafastado = wqdediasafastado + wdiassit;
                                    ELSE
                                        BEGIN
                                            wmes = CAST(SUBSTRING(CAST(wdatainisit AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
                                            wano = CAST(SUBSTRING(CAST(wdatainisit AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
                                            SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;
                                            SELECT str FROM strzero(:wmes,  2) INTO :wmescomzero;
                                            wqdediasafastado = wqdediasafastado + (CAST(:wmescomzero||'/'||:wdia||'/'||:wano AS DATE) - wdatainisit) + 1;
                                        END
                
                                    wqdediasrestantes = wqdediasrestantes - TRUNC(wdatainisit - wdatainicioprazo) + COALESCE(wqdiasentresit,0); -- Sol 18917 - Somando os dias entre as situacoes
                                    wdataultimasaidaafastamento = wdatainisit + wqdediasafastado;

                                    wqdiasentresit = 0; -- Sol 18917 - Deve somar somente uma vez
                                END
                           END
        
                           wdatainicioprazo = wdataultimasaidaafastamento;
                           wdiasprazo1col = wqdediasrestantes;
        
                        END
        
        -- Encontra os afastamenstos do primeiro prazo, encontra os afastamentos do prazo prorrogado prorroga o prazo 2 encontra os afastamentos do prazo 2 prorrogado

                    IF (wdiasprazo2col > 0) THEN
                        BEGIN
                            bddatafimprazo2col = bddatafimprazo1col;
                            wqdediasrestantes = wdiasprazo2col;
                            wdatainicioprazo = bddatafimprazo2col;
                            wcontinuar = 'S';
                            WHILE (wcontinuar = 'S') DO
                                BEGIN
                                    wqdediasafastado = 0;
                                    bddatafimprazo2col = wdatainicioprazo + wdiasprazo2col;
        
                                    wsql = 'select sit.BDDATAINISIT, coalesce(sit.BDDIASSIT, 0) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                                ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo2col||''')';
                                    
                                    wcontinuar = 'N';

                                    IF (wsql IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                                    BEGIN
                                    FOR EXECUTE STATEMENT wsql INTO
                                        :wdatainisit, :wdiassit
                                    DO
                                        BEGIN
                                            wcontinuar = 'S';

                                            -- Sol 19715 - Caso a situacao tenha o parametro 'prorroga contrato de experiencia' desmarcado, nao deve somar os dias
                                            IF (prcodsit <> 0) THEN
                                                BEGIN
                                                    wsql3 = 'select first 1 BDPRORROGACONTRATO from VRH_BASE_TPREPSIT_DIA where BDCODSIT = '||:prcodsit||' order by BDDATASTD desc';

                                                    IF (wsql3 IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                                                    BEGIN
                                                    FOR EXECUTE STATEMENT wsql3 INTO
                                                        :wprorrogacontrato
                                                    DO
                                                        BEGIN
                                                            IF (wprorrogacontrato = 'FALSE') THEN
                                                                wcontinuar = 'N';

                                                            -- Sol 19715 - Marcelo B. M. - 25/08/2017 - Se penultima situacao prorroga deve somar esses dias
                                                            wsql4 = 'select first 1 SIT1.BDCODSIT from VRH_EMP_TSITCOL SIT1 where SIT1.BDCODEMP = '||:bdcodemp||' and SIT1.BDCODCOL = '||:bdcodcol||
                                                                    ' and SIT1.BDDATAINISIT <> (select first 1 SIT2.BDDATAINISIT from VRH_EMP_TSITCOL SIT2 where SIT2.BDCODEMP = '||:bdcodemp||' and SIT2.BDCODCOL = '||:bdcodcol||
                                                                    ' order by SIT2.BDDATAINISIT desc) order by SIT1.BDDATAINISIT desc';

                                                            IF (wsql4 IS NOT NULL) THEN
                                                                EXECUTE STATEMENT wsql4 INTO :wcodsit;

                                                            wsql3 = 'select first 1 BDPRORROGACONTRATO from VRH_BASE_TPREPSIT_DIA where BDCODSIT = '||:wcodsit||' order by BDDATASTD desc';

                                                            IF (wsql3 IS NOT NULL) THEN
                                                            BEGIN
                                                            FOR EXECUTE STATEMENT wsql3 INTO
                                                                :wprorrogacontrato
                                                            DO
                                                                BEGIN
                                                                    IF (wprorrogacontrato = 'TRUE') THEN
                                                                        BEGIN
                                                                            wcountprorroga = wcountprorroga + 1;

                                                                            IF (wcountprorroga = 1) THEN -- Sol 19715 - Marcelo B. M. - 25/08/2017 - Soma os dias da penultima situacao apenas uma vez
                                                                                wcontinuar = 'S';
                                                        END
                                                    END
                                                END
                                                        END
                                                    END
                                                END
                                            -- Sol 19715 - Fim
                
                                            IF (wdiassit > 0) THEN
                                                wqdediasafastado = wqdediasafastado + wdiassit;
                                            ELSE
                                                BEGIN
                                                    wmes = CAST(SUBSTRING(CAST(wdatainisit AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
                                                    wano = CAST(SUBSTRING(CAST(wdatainisit AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
                                                    SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;
                                                    SELECT str FROM strzero(:wmes,  2) INTO :wmescomzero;
                                                    wqdediasafastado = wqdediasafastado + (CAST(:wmescomzero||'/'||:wdia||'/'||:wano AS DATE) - wdatainisit) + 1;
                                                END
                        
                                            -- Sol 18917 - Marcelo B. M. - 28/08/2017 - Deve considerar os dias entre o fim do prazo da experiencia e o comeco da primeira situacao
                                            wsql3 = 'select count(sit.BDDATAINISIT) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                                    ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo2col||''')';
--
                                            IF (wsql3 IS NOT NULL) THEN
                                            BEGIN
                                                FOR EXECUTE STATEMENT wsql3 INTO
                                                    :wcountsituacao
                                                DO
                                                    BEGIN
                                                        IF (wcountsituacao = 2) THEN
                                                            BEGIN
                                                                wsql4 = 'select max(sit.BDDATAINISIT), min(sit.BDDATAFIMSIT) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                                                        ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo2col||''')';

                                                            IF (wsql4 IS NOT NULL) THEN
                                                                BEGIN
                                                                    FOR EXECUTE STATEMENT wsql4 INTO
                                                                        :winidataultsit, :wfimdataprisit
                                                                    DO
                                                                        wqdiasentresit = TRUNC(winidataultsit - wfimdataprisit) - 1;
                                                                END
                                                            END
                                                    END
                                            END
                                            -- Sol 18917 - Fim

                                            -- Sol 18917 - Marcelo B. M. - 28/08/2017
                                            IF (COALESCE(wcountsituacao,0) = 2) THEN
                                                BEGIN
                                                    wsql3 = 'select min(bddatainisit) from vrh_emp_tsitcol where bdcodemp = '||:bdcodemp||' and bdcodcol = '||:bdcodcol||';';

                                                    IF (wsql3 IS NOT NULL) THEN
                                                    BEGIN
                                                        FOR EXECUTE STATEMENT wsql3 INTO
                                                            :wdatainiprisit
                                                        DO
                                                            BEGIN
                                                                wcountqtddias = wcountqtddias + 1;
                                                                wqtddias = COALESCE(TRUNC(wdatainiprisit - wdatainicioprazo),0);

                                                                IF ((wcountqtddias > 1) OR (wqtddias < 0))  THEN
                                                                    wqtddias = 0;
                                                            END
                                                    END
                                                END
                                            -- Sol 18917 - Marcelo B. M. - 28/08/2017 - Fim

                                            wqdediasrestantes = wqdediasrestantes - TRUNC(wdatainisit - wdatainicioprazo) + COALESCE(wqdiasentresit,0) + COALESCE(wqtddias,0);
                                            wdataultimasaidaafastamento = wdatainisit + wqdediasafastado;
                        
                                            wqdiasentresit = 0;
                                            wqdediasafastado = 0;
                                        END
                                    END

                                   wdatainicioprazo = wdataultimasaidaafastamento;
                                   wdiasprazo2col = wqdediasrestantes;
                
                                END
        
                        END

                    SUSPEND;
                END
            ELSE
                SUSPEND;

        END

END
^

/* Restore proc. body: SP_REL_CONSULTA_CONFIGURAVEL2 */
ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL2 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDCODPLANO INTEGER,
BDCODQUADRO INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDLINHA INTEGER,
BDTITULOS VARCHAR(640))
 AS
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wcolunaatual INTEGER;
DECLARE VARIABLE wmes CHAR(2);
DECLARE VARIABLE wano CHAR(4);
DECLARE VARIABLE windice INTEGER;
DECLARE VARIABLE wnumcolunas INTEGER;
DECLARE VARIABLE wnumlinhas INTEGER;
DECLARE VARIABLE wlinhaatual INTEGER;
DECLARE VARIABLE wdescricao VARCHAR(80);
BEGIN
  /*
    #6566:
    modifica??o para aceitar mais de 8 colunas no relat?rio
  */
  bdcol01 = NULL;
  bdcol02 = NULL;
  bdcol03 = NULL;
  bdcol04 = NULL;
  bdcol05 = NULL;
  bdcol06 = NULL;
  bdcol07 = NULL;
  bdcol08 = NULL;
  bdtitulos = '';

  FOR SELECT c.bdcodmatriz,c.bdcodemp,c.bdcodplaconsconf,c.bdcodqplaconsconf,
             c.bdref,COUNT(c.bdordem) AS "BDNUMCOLUNAS"
      FROM vef_rel_cons_anual_conf c
      INNER JOIN tempresas e ON e.bdcodemp = c.bdcodemp
      GROUP BY bdcodmatriz, c.bdcodemp, c.bdcodplaconsconf, c.bdcodqplaconsconf, c.bdref
      ORDER BY bdcodmatriz, c.bdcodemp, c.bdcodplaconsconf, c.bdcodqplaconsconf, c.bdref
  INTO
    :bdcodmatriz,
    :bdcodemp,
    :bdcodplano,
    :bdcodquadro,
    :bdref, 
    :wnumcolunas
  DO
    BEGIN
      wano = SUBSTRING(:bdref FROM 1 FOR 4);
      wmes = SUBSTRING(:bdref FROM 5 FOR 2);
      SELECT FIRST 1 bdanomes FROM sp_retorna_mesano_extenso(:wmes, :wano,  '/') INTO :bdmesextenso;

      --N?mero de linhas para cada quadro (n?mero de formulas no quadro / 8) arredondado para cima
      wNumLinhas = CEIL((CAST(:wnumcolunas AS NUMERIC(15,2))/CAST(8 AS NUMERIC(15,2))));
      wColunaAtual = 1;
      wIndice = 0;
      wLinhaAtual = 0;

      WHILE (:wLinhaAtual < wNumLinhas) DO
        BEGIN                                                   --TCONFCONSFORM.BDDESCRICAO ? um varchar(80), garante que vai ter no m?ximo 80 caracteres a descri??o
          FOR SELECT FIRST 8 SKIP (:wLinhaAtual * 8) f.bdvalor, LEFT(f.bddescricao, 80) AS "BDDESCRICAO"
              FROM vef_rel_cons_anual_conf f
              WHERE f.bdcodmatriz       = :bdcodmatriz AND
                    f.bdcodemp          = :bdcodemp AND
                    f.bdcodplaconsconf  = :bdcodplano AND
                    f.bdcodqplaconsconf = :bdcodquadro AND
                    f.bdref             = :bdref
              ORDER BY f.bdordem
          INTO
            :wvalor,
            :wdescricao
          DO
            BEGIN
              wIndice = :wIndice + 1;
    
              IF (:wColunaAtual = 1) THEN
                bdcol01 = :wvalor;
              ELSE IF (:wColunaAtual = 2) THEN
                bdcol02 = :wvalor;
              ELSE IF (:wColunaAtual = 3) THEN
                bdcol03 = :wvalor;
              ELSE IF (:wColunaAtual = 4) THEN
                bdcol04 = :wvalor;
              ELSE IF (:wColunaAtual = 5) THEN
                bdcol05 = :wvalor;
              ELSE IF (:wColunaAtual = 6) THEN
                bdcol06 = :wvalor;
              ELSE IF (:wColunaAtual = 7) THEN
                bdcol07 = :wvalor;
              ELSE IF (:wColunaAtual = 8) THEN
                bdcol08 = :wvalor;

              bdtitulos = :bdtitulos || LPAD(:wdescricao, 80);

              IF ((MOD(:wColunaAtual, 8) = 0) OR (:wIndice = :wnumcolunas)) THEN
                BEGIN
                  bdlinha = :wlinhaatual;
                  bdtitulos = RPAD(:bdtitulos, 640);
                  SUSPEND;
    
                  wColunaAtual = 1;
                  bdcol01 = NULL;
                  bdcol02 = NULL;
                  bdcol03 = NULL;
                  bdcol04 = NULL;
                  bdcol05 = NULL;
                  bdcol06 = NULL;
                  bdcol07 = NULL;
                  bdcol08 = NULL;
                  bdtitulos = '';
                END
              ELSE
                wColunaAtual = :wColunaAtual + 1;
            END
          wLinhaAtual = :wLinhaAtual + 1;
        END
    END
END
^

/* Restore proc. body: SP_REL_RESUMO_IMPOSTOS */
ALTER PROCEDURE SP_REL_RESUMO_IMPOSTOS(PRCODEMP VARCHAR(10000),
PRCODIMP VARCHAR(10000),
PRCODSIS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRDTVCTOINI DATE,
PRDTVCTOFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(200),
BDCODREC INTEGER,
BDCODSIS INTEGER,
BDCODPERIODO INTEGER,
BDDESCPERIODO VARCHAR(40),
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDMESEXTENSO VARCHAR(20),
BDQUOTA INTEGER,
BDCODCOL INTEGER,
BDCODEMPCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDPERIODO DATE,
BDNUMREFDOC VARCHAR(20),
BDDATAVCTO DATE,
BDVALOR NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDJUROS NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDOBS BLOB,
BDORDEMCOMPL INTEGER,
BDBASEIMP NUMERIC(15,6),
BDALIQIMP NUMERIC(15,6),
BDVLRIMPORIGINAL NUMERIC(15,6),
BDVLRACUMULO NUMERIC(15,6),
BDVLRMULTAJUROS NUMERIC(15,6),
BDVLROUTENTIDADE NUMERIC(15,6),
BDTIPOIMPOSTO INTEGER,
BDCOMPENSACAO NUMERIC(15,6),
BDVLRACUOUTENT NUMERIC(15,6),
BDREFPAG INTEGER,
BDDTPGTO DATE)
 AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WMES CHAR(10);
DECLARE VARIABLE WANO CHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wSql = 'select DARF.BDCODEMP, ';
  wSql = wSql || 'DARF.BDCODIMP, ';
  wSql = wSql || 'IMP.BDDESCIMP, ';
  wSql = wSql || 'IMP.BDCODREC, ';
  wSql = wSql || 'IMP.BDCODSIS, ';
  wSql = wSql || 'DARF.BDCODPERIODO, ';
  wSql = wSql || 'periodo.bddescricao, ';
  wSql = wSql || 'DARF.BDREFERENCIA, ';
  wSql = wSql || 'DARF.BDQUOTA, ';
  wSql = wSql || 'DARF.BDDATAVCTO , ';

  wSql = wSql || 'DARF.BDBASEIMP , ';
  wSql = wSql || 'DARF.BDALIQIMP , ';
  wSql = wSql || 'DARF.BDVLRIMPORIGINAL , ';
  wSql = wSql || 'DARF.BDVALOR , ';
  wSql = wSql || 'DARF.BDMULTA , ';
  wSql = wSql || 'DARF.BDJUROS , ';
  wSql = wSql || 'DARF.BDTOTAL , ';
  wSql = wSql || 'DARF.BDOBS , ';
  wSql = wSql || 'DARF.BDORDEMCOMPL , ';
  wSql = wSql || 'DARF.BDVLRMULTAJUROS , ';
  wSql = wSql || 'DARF.BDVLROUTENTIDADE, ';
  wSql = wSql || 'DARF.BDORDEM, ';
  wSql = wSql || 'DARF.BDCHAVEDARF ';

  wsql = wsql || 'from tdarfpadrao DARF , timposto IMP , ttiposperiodo periodo, VW_EMPRESAS_REF_ATUAL emp ';

  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wWhere||PRCODEMP||' ';

  IF ((prcodimp IS NOT NULL) OR (prcodimp > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||prcodimp||' ';
     END

  IF ((prcodsis IS NOT NULL) OR (prcodsis > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||prcodsis||' ';
     END

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.BDREFERENCIA >= '||prrefini||' ';
     END

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.BDREFERENCIA <= '||prreffin||' ';
     END

  IF (prdtvctoini IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.bddatavcto >= '||''''||prdtvctoini||'''';
     END

  IF (prdtvctofim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.bddatavcto <= '||''''||prdtvctofim||'''';
     END

  IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

  wwhere = wwhere||' and (imp.bdcodimp = darf.bdcodimp) and (emp.bdcodemp = darf.bdcodemp) and (darf.bdcodperiodo = periodo.bdcodperiodo)';

  wgroupby = '';
  worderby = 'order by DARF.BDCODIMP, DARF.BDORDEM, DARF.bdreferencia, DARF.BDCODPERIODO';

  wsql = wsql||wwhere||wgroupby||worderby;

  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodemp,
      :BDCODIMP,
      :BDDESCIMP,
      :bdcodrec,
      :bdcodsis,
      :BDCODPERIODO,
      :bddescperiodo,
      :BDREFERENCIA,
      :BDQUOTA,
      :BDDATAVCTO ,
      :BDBASEIMP ,
      :BDALIQIMP ,
      :BDVLRIMPORIGINAL ,
      :BDVALOR ,
      :BDMULTA ,
      :BDJUROS ,
      :BDTOTAL ,
      :BDOBS ,
      :BDORDEMCOMPL ,
      :BDVLRMULTAJUROS ,
      :BDVLROUTENTIDADE,
      :BDORDEM,
      :BDCHAVEDARF  DO
      BEGIN


    wano = SUBSTRING(bdreferencia FROM 1 FOR 4);
    wmes = SUBSTRING(bdreferencia FROM 5 FOR 2);

    IF (wmes = '01') THEN
       bdmesextenso =  'Janeiro / ' || wano;
    IF (wmes = '02') THEN
       bdmesextenso =  'Fevereiro / ' || wano;
    IF (wmes = '03') THEN
       bdmesextenso =  'Mar?o / ' || wano;
    IF (wmes = '04') THEN
       bdmesextenso =  'Abril / ' || wano;
    IF (wmes = '05') THEN
       bdmesextenso =  'Maio / ' || wano;
    IF (wmes = '06') THEN
       bdmesextenso =  'Junho / ' || wano;
    IF (wmes = '07') THEN
       bdmesextenso =  'Julho / ' || wano;
    IF (wmes = '08') THEN
       bdmesextenso =  'Agosto / ' || wano;
    IF (wmes = '09') THEN
       bdmesextenso =  'Setembro / ' || wano;
    IF (wmes = '10') THEN
       bdmesextenso =  'Outubro / ' || wano;
    IF (wmes = '11') THEN
       bdmesextenso =  'Novembro / ' || wano;
    IF (wmes = '12') THEN
       bdmesextenso =  'Dezembro / ' || wano;


        SELECT MAX(pgto.bddatapgto) FROM tdarfgerpgto pgto
               WHERE (PGTO.bdcodemp = :bdcodemp AND PGTO.BDCHAVEDARF = :BDCHAVEDARF) INTO :BDDTPGTO;

        SUSPEND;
      END
END
^

/* Restore proc. body: SP_RELDEMRECDESP */
ALTER PROCEDURE SP_RELDEMRECDESP(PRCODESC VARCHAR(500),
PRTIPODEM INTEGER,
PRDATAINICIAL VARCHAR(10),
PRDATAFINAL VARCHAR(10),
PRCHAVECTABAN VARCHAR(500),
PRCODOBRSER VARCHAR(10240),
PRCODDESP VARCHAR(10240),
PRNIVEL INTEGER,
PRTIPORECDESP INTEGER,
PRDEMLANCREEMBOLSO DM_BOOLEAN)
 RETURNS(BDCODSERDESP INTEGER,
BDCLASSIFICACAO VARCHAR(60),
BDDESCRICAO VARCHAR(100),
BDTIPO INTEGER,
BDPERIODO01 VARCHAR(12),
BDVLRPERIODO01 NUMERIC(15,2),
BDPERIODO02 VARCHAR(12),
BDVLRPERIODO02 NUMERIC(15,2),
BDPERIODO03 VARCHAR(12),
BDVLRPERIODO03 NUMERIC(15,2),
BDPERIODO04 VARCHAR(12),
BDVLRPERIODO04 NUMERIC(15,2),
BDPERIODO05 VARCHAR(12),
BDVLRPERIODO05 NUMERIC(15,2),
BDPERIODO06 VARCHAR(12),
BDVLRPERIODO06 NUMERIC(15,2),
BDPERIODO07 VARCHAR(12),
BDVLRPERIODO07 NUMERIC(15,2),
BDPERIODO08 VARCHAR(12),
BDVLRPERIODO08 NUMERIC(15,2),
BDPERIODO09 VARCHAR(12),
BDVLRPERIODO09 NUMERIC(15,2),
BDPERIODO10 VARCHAR(12),
BDVLRPERIODO10 NUMERIC(15,2),
BDPERIODO11 VARCHAR(12),
BDVLRPERIODO11 NUMERIC(15,2),
BDPERIODO12 VARCHAR(12),
BDVLRPERIODO12 NUMERIC(15,2),
BDVLRTOTPERIODO NUMERIC(15,2))
 AS
declare variable VULTDIAMES integer;
declare variable VPERIODOFINAL varchar(10);
declare variable VPERIODOINICIAL varchar(10);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSERDESP varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODSERDESP integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
begin
  vguardaserdesp = '';
  vclassaux = '';
  vcodserdespaux = 0;
  vsql = '';
  vsqlserdesp = '';
  vultdiames = 0;
  vnumperiodo = 0;
  vperiodoinicial = '';
  vperiodofinal = '';

  vperiodo01 = '';
  vvlrperiodo01 = 0;
  vperiodo02 = '';
  vvlrperiodo02 = 0;
  vperiodo03 = '';
  vvlrperiodo03 = 0;
  vperiodo04 = '';
  vvlrperiodo04 = 0;
  vperiodo05 = '';
  vvlrperiodo05 = 0;
  vperiodo06 = '';
  vvlrperiodo06 = 0;
  vperiodo07 = '';
  vvlrperiodo07 = 0;
  vperiodo08 = '';
  vvlrperiodo08 = 0;
  vperiodo09 = '';
  vvlrperiodo09 = 0;
  vperiodo10 = '';
  vvlrperiodo10 = 0;
  vperiodo11 = '';
  vvlrperiodo11 = 0;
  vperiodo12 = '';
  vvlrperiodo12 = 0;
  DELETE FROM TMP_DEMRECDESP_ANALITICAS;

  IF (prtiporecdesp = 0) THEN -- Servi?os
     BEGIN
       /* Antes de tudo, obter os servi?os selecionados de acordo com as op??es "t?tulos" e "anal?ticas".
       prnivel = 0: apenas a op??o "t?tulos" est? checada.
       prnivel = 1: apenas a op??o "anal?ticas" est? checada.
       prnivel = 2: ambas op??es est?o checadas. */

       IF (prnivel = 0) THEN
          BEGIN
            vsqlserdesp = 'select s.bdcodobrser, s.bdclassificacao, s.bddescricao, s.bdtipo ';
            vsqlserdesp = vsqlserdesp || 'from (';
            vsqlserdesp = vsqlserdesp || '       select bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
            vsqlserdesp = vsqlserdesp || '       from vct_base_servico ';

            IF (:prcodobrser <> '') THEN
                vsqlserdesp = vsqlserdesp || 'where bdcodobrser in ('||:prcodobrser||') ';

            vsqlserdesp = vsqlserdesp || '      ) ser ';
            vsqlserdesp = vsqlserdesp || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'') ';

            /* Se prnivel = 0 ent?o apenas a op??o "t?tulo" est? selecionada. Neste caso
            iremos trazer tamb?m as anal?ticas para que seja feito o c?lculo dos per?odos.
            Posteriormente apenas exibimos as t?tulos no relat?rio. */

            vsqlserdesp = vsqlserdesp || 'group by bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
            vsqlserdesp = vsqlserdesp || 'order by bdclassificacao ';
          END
       ELSE
         IF (prnivel = 1) THEN
            BEGIN
              /* Se apenas a op??o "anal?ticas" est? selecionada, ent?o basta
              trazer as pr?prias anal?ticas selecionadas. */
              vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
              vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
              vsqlserdesp = vsqlserdesp || 'where ser.bdtipo = 1';
      
              IF (:prcodobrser <> '') THEN
                 vsqlserdesp = vsqlserdesp || 'and ser.bdcodobrser in ('||:prcodobrser||') ';

              vsqlserdesp = vsqlserdesp || 'order by bdclassificacao ';
            END
         ELSE -- Ent?o possui t?tulos e anal?ticas selecionadas
           IF (prnivel = 2) THEN
              BEGIN
                if (prcodobrser = '') then
                   begin
                     vguardaserdesp = '';
                     vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                     vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
                     vsqlserdesp = vsqlserdesp || 'order by bdclassificacao';
                   end
                else
                   begin
                    /* Se t?tulos e anal?ticas foram selecionadas, dever? trazer as anal?ticas das t?tulos
                    que est?o selecionadas e tamb?m dever? trazer as t?tulos das anal?ticas que foram selecionadas.*/
        
                    -- Primeiramente pegar as t?tulos que foram selecionadas
                    vsql = 'select list(ser.bdcodobrser) from vct_base_servico ser ';
                    vsql = vsql || 'where ser.bdtipo = 0 ';
    
                    IF (:prcodobrser <> '') THEN
                       vsql = vsql || 'and ser.bdcodobrser in ('||:prcodobrser||') ';
                    EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
        
                    IF (vguardaserdesp IS NOT NULL) THEN
                       BEGIN
                         -- Em seguida, obter as anal?ticas destas t?tulos e guardar em vguardaservicos.
                         vsql = 'select s.bdcodobrser, s.bdclassificacao ';
                         vsql = vsql || 'from (';
                         vsql = vsql || '       select bdcodobrser, bdclassificacao, bddescricao ';
                         vsql = vsql || '       from vct_base_servico ';
                         vsql = vsql || '       where bdcodobrser in('||:vguardaserdesp||') ';
                         vsql = vsql || '      ) ser ';
                         vsql = vsql || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'')';
                  
                         vguardaserdesp = '';
        
                         FOR
                         EXECUTE STATEMENT :vsql
                         INTO
                         :vcodserdesp,
                         :vclassserdesp
                         DO
                         BEGIN
                           vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                         END
                       END
                    ELSE
                      vguardaserdesp = '';
    
    
                    -- Obtendo somente as anal?ticas selecionadas
                    vsql = 'select ser.bdcodobrser, ser.bdclassificacao ';
                    vsql = vsql || 'from (';
                    vsql = vsql || 'select bdcodobrser, bdclassificacao ';
                    vsql = vsql || 'from vct_base_servico ';
                    vsql = vsql || 'where bdtipo = 1 ';
    
                    IF (:prcodobrser <> '') THEN
                    vsql = vsql || 'and bdcodobrser in ('||:prcodobrser||') ';
    
                    vsql = vsql || ') ser ';
              
                    FOR
                    EXECUTE STATEMENT :vsql
                    INTO
                    :vcodserdesp,
                    :vclassserdesp
                    DO
                    BEGIN
                      vstop = 'FALSE';
                      vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                      vclassaux = :vclassserdesp;
          
                      /* A implementa??o abaixo vai removendo sempre o ?ltimo n?vel da classifica??o
                      para obter todas as t?tulos que compoem a anal?tica, e vai guardando o c?digo
                      de cada t?tulo na vari?vel vguardaserdesp. */
                      WHILE (UPPER(:vstop) = 'FALSE') DO
                        BEGIN
                          SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
    
                          IF (vposicaoponto > 0) THEN
                             BEGIN
                               SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classifica??o
                               SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a invers?o seria o ?ltimo ponto)
                               SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                               SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente

                               SELECT COALESCE(bdcodobrser,0) FROM vct_base_servico WHERE bdclassificacao = :vclassaux INTO :vcodserdespaux;
    
                               IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                  vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                             END
                          ELSE
                            BEGIN
                              vstop = 'TRUE';
                            END
                        END
                    END
                    vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
        
                    -- Por fim, junta todos os servi?os relacionados em um sql.
                    vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                    vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
                    vsqlserdesp = vsqlserdesp || 'where ser.bdcodobrser in ('||:vguardaserdesp||') ';
                    vsqlserdesp = vsqlserdesp || 'order by bdclassificacao';
                 end
              END


       -- Depois de ter obtido todos os servi?os, trazer apenas os que possuem rela??o com os lan?amentos financeiros.

       if (:vguardaserdesp <> '') then
          begin
             vguardaserdesp = '';
             vsql = 'select list(ser.bdcodobrser) from ('||:vsqlserdesp||') ser where ser.bdtipo = 1';
             EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
          end

       vsql = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bddesconto ';
       vsql = vsql || 'from vct_base_servico ser ';
       vsql = vsql || 'where exists ';
       vsql = vsql || ' (';
       vsql = vsql || '    select bdcodobrser from vfin_esc_tlancbancario lan ';
       vsql = vsql || '    where (lan.bdcodobrser = ser.bdcodobrser) ';
       vsql = vsql || '    and lan.bdtiposervdesp = 0 ';
       vsql = vsql || '    and lan.bdvalorlanc > 0 ';

       IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';

       IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

       if (Upper(:prdemlancreembolso) = 'FALSE') then
          begin
            vsql = vsql || 'and not exists (';
            vsql = vsql || '   select rec.* from VFIN_ESC_TRECFATURASERVICO rec ';
            vsql = vsql || '   inner join VFIN_ESC_TORIGEMSERFAT orig on (orig.bdcodcli = rec.bdcodcli and orig.bdcodesc = rec.bdcodesc and orig.bdchavefatura = rec.bdchavefatura and orig.bdordemser = rec.bdordemser) ';
            vsql = vsql || '   inner join VFIN_ESC_TSERVICOFIXO serfix on (serfix.bdcodcli = orig.bdcodcli and serfix.bdcodesc = orig.bdcodesc and serfix.bdchaveserfix = orig.bdchaveserfix ';
            vsql = vsql || '   and serfix.bdordemserfix = orig.bdordemserfix) ';
            vsql = vsql || '   inner join VFIN_ESC_TVINC_PAG_SERVIC vinc on (vinc.bdcodcli = serfix.bdcodcli and vinc.bdcodesc = serfix.bdcodesc and vinc.bdchaveserfix = serfix.bdchaveserfix and ';
            vsql = vsql || '   vinc.bdordemserfix = serfix.bdordemserfix) ';
            vsql = vsql || '   where rec.bdcodesc = lan.bdcodesc and ';
            vsql = vsql || '   rec.bdcodcli = lan.bdcodcli and ';
            vsql = vsql || '   rec.bdchavefatura = lan.bdchavefatura and ';
            vsql = vsql || '   rec.bdordemser = lan.bdordemser and ';
            vsql = vsql || '   rec.bdordemrecser = lan.bdordemrecser ';
            vsql = vsql || ')';
          end

       vsql = vsql || ' )';

       IF (:vguardaserdesp <> '') THEN
          vsql = vsql || 'and ser.bdcodobrser in ('||:vguardaserdesp||') ';

     END
  ELSE
    BEGIN -- Despesas
      IF (prnivel = 0) THEN -- Ent?o s? possui t?tulos selecionadas
         BEGIN
           vsqlserdesp = 'select d.bdcoddesp, d.bdclassdesp, d.bddescdesp, d.bdtipodesp ';
           vsqlserdesp = vsqlserdesp || 'from (';
           vsqlserdesp = vsqlserdesp || '       select bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
           vsqlserdesp = vsqlserdesp || '       from vfin_base_tdespesa ';

           IF (:prcoddesp <> '') THEN
              vsqlserdesp = vsqlserdesp || 'where bdcoddesp in ('||:prcoddesp||') ';

           vsqlserdesp = vsqlserdesp || '      ) desp ';
           vsqlserdesp = vsqlserdesp || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';

           /* Se prnivel = 0 ent?o apenas a op??o "t?tulo" est? selecionada. Neste caso
           iremos trazer tamb?m as anal?ticas para que seja feito o c?lculo dos per?odos.
           Posteriormente apenas exibimos as t?tulos no relat?rio. */

           vsqlserdesp = vsqlserdesp || 'group by bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
           vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
         END
      ELSE
        IF (prnivel = 1) THEN -- Ent?o s? possui anal?ticas selecionadas
           BEGIN
             /* Se apenas a op??o "anal?ticas" est? selecionada, ent?o basta
             trazer as pr?prias anal?ticas selecionadas. */
             vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
             vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
             vsqlserdesp = vsqlserdesp || 'where desp.bdtipodesp = 1 ';

             IF (:prcoddesp <> '') THEN
                vsqlserdesp = vsqlserdesp || 'and desp.bdcoddesp in ('||:prcoddesp||') ';

             vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
           END
        ELSE -- Ent?o possui t?tulos e anal?ticas selecionadas, e obrigatoriamente as duas op??es "t?tulos" e "anal?ticas" est?o checadas.
          IF (prnivel = 2) THEN
             BEGIN

                if (prcoddesp = '') then
                   begin
                     vguardaserdesp = '';
                     vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                     vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                     vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
                   end
                else
                   begin
                       /* Se t?tulos e anal?ticas foram selecionadas, dever? trazer as anal?ticas das t?tulos
                       que est?o selecionadas e tamb?m dever? trazer as t?tulos das anal?ticas que foram selecionadas.*/
            
                       -- Primeiramente pegar as t?tulos que foram selecionadas
                       vsql = 'select list(desp.bdcoddesp) from vfin_base_tdespesa desp ';
                       vsql = vsql || 'where desp.bdtipodesp = 0 ';
        
                       IF (:prcoddesp <> '') THEN
                          vsql = vsql || 'and desp.bdcoddesp in ('||:prcoddesp||')';
        
                       EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
              
                       IF (vguardaserdesp IS NOT NULL) THEN
                          BEGIN
                            -- Em seguida, obter as anal?ticas destas t?tulos e guardar em vguardaservicos.
                            vsql = 'select d.bdcoddesp, d.bdclassdesp ';
                            vsql = vsql || 'from (';
                            vsql = vsql || '       select bdcoddesp, bdclassdesp, bddescdesp ';
                            vsql = vsql || '       from vfin_base_tdespesa ';
                            vsql = vsql || '       where bdcoddesp in('||:vguardaserdesp||') ';
                            vsql = vsql || '      ) desp ';
                            vsql = vsql || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';
                   
                            vguardaserdesp = '';
                         
                            FOR
                            EXECUTE STATEMENT :vsql
                            INTO
                            :vcodserdesp,
                            :vclassserdesp
                            DO
                            BEGIN
                              vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                            END
                          END
                       ELSE
                         vguardaserdesp = '';
        
                       -- Obtendo somente as anal?ticas selecionadas
                       vsql = 'select desp.bdcoddesp, desp.bdclassdesp ';
                       vsql = vsql || 'from (';
                       vsql = vsql || 'select bdcoddesp, bdclassdesp ';
                       vsql = vsql || 'from vfin_base_tdespesa ';
                       vsql = vsql || 'where bdtipodesp = 1';
        
                       IF (:prcoddesp <> '') THEN
                          vsql = vsql || 'and bdcoddesp in ('||:prcoddesp||') ';
        
                       vsql = vsql || ') desp ';
            
                       FOR
                       EXECUTE STATEMENT :vsql
                       INTO
                       :vcodserdesp,
                       :vclassserdesp
                       DO
                       BEGIN
                         vstop = 'FALSE';
                         vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                         vclassaux = :vclassserdesp;
                  
                         /* A implementa??o abaixo vai removendo sempre o ?ltimo n?vel da classifica??o
                         para obter todas as t?tulos que compoem a anal?tica, e vai guardando o c?digo
                         de cada t?tulo na vari?vel vguardaserdesp. */
                         WHILE (UPPER(:vstop) = 'FALSE') DO
                           BEGIN
                             SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
                  
                             IF (vposicaoponto > 0) THEN
                                BEGIN
                                  SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classifica??o
                                  SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a invers?o seria o ?ltimo ponto)
                                  SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                                  SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente
                                  SELECT COALESCE(bdcoddesp,0) FROM vfin_base_tdespesa WHERE bdclassdesp = :vclassaux INTO :vcodserdespaux;
            
                                  IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                     vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                                END
                             ELSE
                               BEGIN
                                 vstop = 'TRUE';
                               END
                           END
                       END
        
                       vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
                
                       -- Por fim, junta todos os servi?os relacionados em um sql.
                       vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                       vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                       vsqlserdesp = vsqlserdesp || 'where desp.bdcoddesp in ('||:vguardaserdesp||') ';
                       vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
                end
             END



      -- Depois de ter obtido todos os servi?os, trazer apenas os que possuem rela??o com os lan?amentos financeiros.
      if (vguardaserdesp <> '') then
         begin
            vguardaserdesp = '';
            vsql = 'select list(desp.bdcoddesp) from ('||:vsqlserdesp||') desp where desp.bdtipodesp = 1';
            EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
         end

      vsql = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, (null) bddesconto ';
      vsql = vsql || 'from vfin_base_tdespesa desp ';
      vsql = vsql || 'where exists ';
      vsql = vsql || ' (';

      if (Upper(:prdemlancreembolso) = 'FALSE') then
         begin
           vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lan ';
           vsql = vsql || 'left outer join vfin_esc_tvinc_pag_servic vinc on (vinc.bdcodesc = lan.bdcodesc and vinc.BDCHAVECTAPAG = lan.bdchavectapag ';
           vsql = vsql || 'and vinc.bdordemdesp = lan.bdordemdesp) ';
           vsql = vsql || 'where (lan.bdcoddesp = desp.bdcoddesp) ';
           vsql = vsql || 'and lan.bdtiposervdesp = 1 ';
           vsql = vsql || 'and lan.bdvalorlanc > 0 ';
           vsql = vsql || 'and vinc.bdcodesc is null  ';
         end
      else
        begin
          vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lan ';
          vsql = vsql || 'where (lan.bdcoddesp = desp.bdcoddesp) ';
          vsql = vsql || 'and lan.bdtiposervdesp = 1 ';
          vsql = vsql || 'and lan.bdvalorlanc > 0 ';
        end

      if ((:prcodesc <> '') and (:prcodesc is not null)) then
         vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';

      IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||')';


      vsql = vsql || ' )';

      IF (:vguardaserdesp <> '') THEN
         vsql = vsql || 'and desp.bdcoddesp in ('||:vguardaserdesp||') ';
    END

  /* Adicionar todas as anal?ticas em uma tabela tempor?ria com os valores de seus per?odos */
  FOR
  EXECUTE STATEMENT :vsql
  INTO
  :vcodserdesp,
  :vclassserdesp,
  :vdescserdesp,
  :vDesconto
  DO
  BEGIN
    vstop = 'FALSE';
    vperiodoinicial = '';
    vperiodofinal = '';
    vnumperiodo = 0;
  
    WHILE (UPPER(vstop) = 'FALSE') DO
      BEGIN
        vnumperiodo = :vnumperiodo +1;
  
        IF (:prtipodem = 0) THEN -- Demonstrativo total
           BEGIN
             vperiodoinicial = :prdatainicial;
             vperiodofinal = :prdatafinal;

             SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
           END
        ELSE
          IF (:prtipodem = 1) THEN -- Demonstrativo mensal
             BEGIN
               IF (:vperiodoinicial = '') THEN
                  BEGIN
                    vperiodoinicial = prdatainicial;
                  END
               ELSE
                 BEGIN
                   -- Acrescentando um m?s ? data
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 1) INTO :vperiodoinicial;
                   vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                 END

                 -- Obtendo o ?ltimo dia do m?s
                 SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodoinicial FROM 1 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodoinicial FROM 7 FOR 4) AS INTEGER)) INTO :vultdiames;
                 vperiodofinal = SUBSTRING(:vperiodoinicial FROM 1 FOR 3)||:vultdiames||SUBSTRING(:vperiodoinicial FROM 6 FOR 5);


                 -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                    END
                 ELSE
                 IF (:vnumperiodo = 7) THEN
                    BEGIN
                      vperiodo07 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo07;
                    END
                 ELSE
                 IF (:vnumperiodo = 8) THEN
                    BEGIN
                      vperiodo08 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo08;
                    END
                 ELSE
                 IF (:vnumperiodo = 9) THEN
                    BEGIN
                      vperiodo09 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo09;
                    END
                 ELSE
                 IF (:vnumperiodo = 10) THEN
                    BEGIN
                      vperiodo10 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo10;
                    END
                 ELSE
                 IF (:vnumperiodo = 11) THEN
                    BEGIN
                      vperiodo11 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo11;
                    END
                 ELSE
                 IF (:vnumperiodo = 12) THEN
                    BEGIN
                      vperiodo12 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo12;
                    END
             END
          ELSE
            IF (:prtipodem = 2) THEN -- Demonstrativo bimestral
               BEGIN
                 IF (:vperiodoinicial = '') THEN
                    BEGIN
                      vperiodoinicial = :prdatainicial;
                    END
                 ELSE
                   BEGIN
                     -- Por ser bimestral, dever? acrescentar dois meses ? data
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 2) INTO :vperiodoinicial;
                     vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                   END

                 /* Acrescentando um m?s ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                 Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 28/02/2017 */
                 SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 1) INTO :vperiodofinal;
                 SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                 vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
  
                 -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = '1? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = '2? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = '3? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = '4? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = '5? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = '6? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                    END
               END
            ELSE
              IF (:prtipodem = 3) THEN -- Demonstrativo trimestral
                 BEGIN
                   IF (:vperiodoinicial = '') THEN
                       BEGIN
                         vperiodoinicial = :prdatainicial;
                       END
                   ELSE
                     BEGIN
                       -- Por ser trimestral, dever? acrescentar tr?s meses ? data
                       SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 3) INTO :vperiodoinicial;
                       vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                     END

                   /* Acrescentando tr?s meses ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                   Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 31/03/2017 */
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 2) INTO :vperiodofinal;
                   SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                   vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
                   -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                   IF (:vnumperiodo = 1) THEN
                      BEGIN
                        vperiodo01 = '1? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                      END
                   ELSE
                   IF (:vnumperiodo = 2) THEN
                      BEGIN
                        vperiodo02 = '2? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                      END
                   ELSE
                   IF (:vnumperiodo = 3) THEN
                      BEGIN
                        vperiodo03 = '3? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                      END
                   ELSE
                   IF (:vnumperiodo = 4) THEN
                      BEGIN
                        vperiodo04 = '4? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                      END
                 END
              ELSE
                IF (:prtipodem = 4) THEN -- Demonstrativo semestral
                   BEGIN
                     IF (:vperiodoinicial = '') THEN
                       BEGIN
                         vperiodoinicial = :prdatainicial;
                       END
                     ELSE
                       BEGIN
                         -- Por ser semestral, dever? acrescentar seis meses ? data
                         SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 6) INTO :vperiodoinicial;
                         vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                       END

                     /* Acrescentando cinco meses ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                     Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 30/06/2017 */
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 5) INTO :vperiodofinal;
                     SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                     vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
  
                     -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                     IF (:vnumperiodo = 1) THEN
                        BEGIN
                          vperiodo01 = '1? semestre';
                          SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                        END
                     ELSE
                     IF (:vnumperiodo = 2) THEN
                        BEGIN
                          vperiodo02 = '2? semestre';
                          SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                        END
                   END
                ELSE
                  BEGIN
                    IF (:prtipodem = 5) THEN -- Desmonstrativo anual
                       BEGIN
                         IF (:vperiodoinicial = '') THEN
                             BEGIN
                               vperiodoinicial = :prdatainicial;
                             END
                         ELSE
                           BEGIN
                             -- Por ser anual, dever? acrescentar um ano ? data
                             SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 12) INTO :vperiodoinicial;
                             vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                           END
                         -- O ?ltimo dia do ano sempre ser? 31/12/ + o ano que foi incrementado no vperiodoinicial
                         vperiodofinal = '12/31/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
             
                         -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                         IF (:vnumperiodo = 1) THEN
                            BEGIN
                              vperiodo01 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                            END
                         ELSE
                         IF (:vnumperiodo = 2) THEN
                            BEGIN
                              vperiodo02 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                            END
                         ELSE
                         IF (:vnumperiodo = 3) THEN
                            BEGIN
                              vperiodo03 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                            END
                         ELSE
                         IF (:vnumperiodo = 4) THEN
                            BEGIN
                              vperiodo04 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                            END
                         ELSE
                         IF (:vnumperiodo = 5) THEN
                            BEGIN
                              vperiodo05 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                            END
                         ELSE
                         IF (:vnumperiodo = 6) THEN
                            BEGIN
                              vperiodo06 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                            END
                         ELSE
                         IF (:vnumperiodo = 7) THEN
                            BEGIN
                              vperiodo07 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo07;
                            END
                         ELSE
                         IF (:vnumperiodo = 8) THEN
                            BEGIN
                              vperiodo08 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo08;
                            END
                         ELSE
                         IF (:vnumperiodo = 9) THEN
                            BEGIN
                              vperiodo09 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo09;
                            END
                         ELSE
                         IF (:vnumperiodo = 10) THEN
                            BEGIN
                              vperiodo10 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo10;
                            END
                         ELSE
                         IF (:vnumperiodo = 11) THEN
                            BEGIN
                              vperiodo11 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo11;
                            END
                         ELSE
                         IF (:vnumperiodo = 12) THEN
                            BEGIN
                              vperiodo12 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo12;
                            END
                       END
                  END

        IF (:vperiodofinal = :prdatafinal) THEN
           vstop = 'TRUE';
      END

      vvlrtotperiodo = :vvlrperiodo01 + :vvlrperiodo02 + :vvlrperiodo03 + :vvlrperiodo04 + :vvlrperiodo05 + :vvlrperiodo06 + :vvlrperiodo07 +
                       :vvlrperiodo08 + :vvlrperiodo09 + :vvlrperiodo10 + :vvlrperiodo11 + :vvlrperiodo12;

      if (Upper(:vdesconto) = 'TRUE') then
         begin
           vvlrtotperiodo = - :vvlrtotperiodo;
           vvlrperiodo01 = - :vvlrperiodo01;
           vvlrperiodo02 = - :vvlrperiodo02;
           vvlrperiodo03 = - :vvlrperiodo03;
           vvlrperiodo04 = - :vvlrperiodo04;
           vvlrperiodo05 = - :vvlrperiodo05;
           vvlrperiodo06 = - :vvlrperiodo06;
           vvlrperiodo07 = - :vvlrperiodo07;
           vvlrperiodo08 = - :vvlrperiodo08;
           vvlrperiodo09 = - :vvlrperiodo09;
           vvlrperiodo10 = - :vvlrperiodo10;
           vvlrperiodo11 = - :vvlrperiodo11;
           vvlrperiodo12 = - :vvlrperiodo12;
         end

      INSERT INTO TMP_DEMRECDESP_ANALITICAS (BDCODOBRSER, BDCLASSIFICACAO, BDPERIODO01, BDVLRPERIODO01, BDPERIODO02, BDVLRPERIODO02, BDPERIODO03, BDVLRPERIODO03,
      BDPERIODO04, BDVLRPERIODO04, BDPERIODO05, BDVLRPERIODO05, BDPERIODO06, BDVLRPERIODO06, BDPERIODO07, BDVLRPERIODO07, BDPERIODO08, BDVLRPERIODO08,
      BDPERIODO09, BDVLRPERIODO09, BDPERIODO10, BDVLRPERIODO10, BDPERIODO11, BDVLRPERIODO11, BDPERIODO12, BDVLRPERIODO12, BDVLRTOTPERIODO)
      VALUES (:vcodserdesp, :vclassserdesp, :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
      :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08, :vperiodo09, :vvlrperiodo09,
      :vperiodo10, :vvlrperiodo10, :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12, :vvlrtotperiodo);

   END

   FOR
   EXECUTE STATEMENT :vsqlserdesp
   INTO
   :vcodserdesp,
   :vclassserdesp,
   :vdescserdesp,
   :vtiposerdesp
   DO
   BEGIN
     bdcodserdesp = :vcodserdesp;
     bdclassificacao = :vclassserdesp;
     bddescricao = :vdescserdesp;
     bdtipo = :vtiposerdesp;
     bdvlrtotperiodo = 0;

     SELECT bdperiodo01, SUM(bdvlrperiodo01) bdvlrperiodo01, bdperiodo02, SUM(bdvlrperiodo02) bdvlrperiodo02, bdperiodo03, SUM(bdvlrperiodo03) bdvlrperiodo03,
     bdperiodo04, SUM(bdvlrperiodo04) bdvlrperiodo04, bdperiodo05, SUM(bdvlrperiodo05) bdvlrperiodo05, bdperiodo06, SUM(bdvlrperiodo06) bdvlrperiodo06,
     bdperiodo07, SUM(bdvlrperiodo07) bdvlrperiodo07, bdperiodo08, SUM(bdvlrperiodo08) bdvlrperiodo08, bdperiodo09, SUM(bdvlrperiodo09) bdvlrperiodo09,
     bdperiodo10, SUM(bdvlrperiodo10) bdvlrperiodo10, bdperiodo11, SUM(bdvlrperiodo11) bdvlrperiodo11, bdperiodo12, SUM(bdvlrperiodo12) bdvlrperiodo12,
     SUM(bdvlrtotperiodo) bdvlrtotperiodo
     FROM TMP_DEMRECDESP_ANALITICAS
     WHERE bdclassificacao LIKE :vclassserdesp||'%'
     GROUP BY bdperiodo01, bdperiodo02, bdperiodo03, bdperiodo04, bdperiodo05, bdperiodo06, bdperiodo07,
     bdperiodo08, bdperiodo09, bdperiodo10, bdperiodo11, bdperiodo12
     INTO :bdperiodo01, :bdvlrperiodo01, :bdperiodo02, :bdvlrperiodo02, :bdperiodo03, :bdvlrperiodo03, :bdperiodo04, :bdvlrperiodo04,
     :bdperiodo05, :bdvlrperiodo05, :bdperiodo06, :bdvlrperiodo06, :bdperiodo07, :bdvlrperiodo07, :bdperiodo08, :bdvlrperiodo08,
     :bdperiodo09, :bdvlrperiodo09, :bdperiodo10, :bdvlrperiodo10, :bdperiodo11, :bdvlrperiodo11, :bdperiodo12, :bdvlrperiodo12,
     :bdvlrtotperiodo;

     -- Servi?os de desconto vem negativos
     IF (:bdvlrtotperiodo <> 0) THEN
        BEGIN
          SUSPEND;
        END
   END

   DELETE FROM TMP_DEMRECDESP_ANALITICAS;
END
^

/* Restore proc. body: SP_RETORNA_SALDO_EMP */
ALTER PROCEDURE SP_RETORNA_SALDO_EMP(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(5000);
DECLARE VARIABLE wtemcc SMALLINT = 0;
DECLARE VARIABLE wtamanho INTEGER;
DECLARE VARIABLE wclassificacao VARCHAR(50);
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wdebito NUMERIC(15,2);
DECLARE VARIABLE wcredito NUMERIC(15,2);
DECLARE VARIABLE wlevel INTEGER;
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wvlr NUMERIC(15,2);
DECLARE VARIABLE wpermite INTEGER;
BEGIN
  codemp = prcodemp;
  SALDO_ANT_DEB = 0;
  SALDO_ANT_CRE = 0;
  saldo_anterior = 0;
  SALDO_DEB = 0;
  SALDO_CRE = 0;
  saldo_atual = 0;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and tpla.bdctalon like '''||wclassificacao||'%'' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROD = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_DEB do
     if (SALDO_DEB is null) then
        SALDO_DEB = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_DEB = SALDO_DEB + wvlr;
    END

--  exception ex_date;

  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROC = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_CRE do
     if (SALDO_CRE is null) then
        SALDO_CRE = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_CRE = SALDO_CRE + wvlr;
    END

  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';
/* #alt:6153 - gilberto - 09/08/2013 - retirado para sempre calcular zeramento no saldo anterior
  if (prignorazeramento = 1) then
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento
*/
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
     wsql = wsql||' and (TLAN.BDCODTERCEIROD = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_DEB do
     if (SALDO_ANT_DEB is null) then
        SALDO_ANT_DEB = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_ANT_DEB = SALDO_ANT_DEB + wvlr;
    END

  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';
/* #alt:6153 - gilberto - 09/08/2013 - retirado para sempre calcular zeramento no saldo anterior
  if (prignorazeramento = 1) then
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento
*/
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((BDCONCC is null) or (upper(bdconcc) = '|| '''FALSE'''||'))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROC = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_CRE do
     if (SALDO_ANT_CRE is null) then
        SALDO_ANT_CRE = 0; */
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_ANT_CRE = SALDO_ANT_CRE + wvlr;
    END

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;

  SUSPEND;
END
^

/* Restore proc. body: SP_RETORNA_SALDO_MATRIZFILIAL */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WCODEMPEFILIAL INTEGER;
DECLARE VARIABLE WSALDODEB NUMERIC(15,2);
DECLARE VARIABLE WSALDOCRE NUMERIC(15,2);
DECLARE VARIABLE WSALANTDEB NUMERIC(15,2);
DECLARE VARIABLE WSALANTCRE NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
BEGIN
  codemp = prcodemp;

  IF (prmatrizfiliais IS NULL) THEN
     prmatrizfiliais = prcodemp;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and tpla.bdctalon like '''||wclassificacao||'%'' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);



  -- retorna as empresas selecionadas
  wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||PRMATRIZFILIAIS||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  wsaldodeb = 0;
  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  wsaldocre = 0;
  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  wsalantdeb = 0;
  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  wsalantcre = 0;

  movimento = 0;

  FOR EXECUTE STATEMENT wsqlemp
              INTO :wcodempefilial DO
  BEGIN


  -- SALDO A D?BITO ____________________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsaldodeb do
  if (wsaldodeb is null) then
     wsaldodeb=0;*/
  wsaldodeb = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsaldodeb = wsaldodeb + wvlr;
    END
  saldo_deb = saldo_deb + wsaldodeb;

--  exception ex_date;

  -- SALDO A CR?DITO ___________________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN '; */
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsaldocre do
  if (wsaldocre is null) then
     wsaldocre=0;*/
  wsaldocre = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsaldocre = wsaldocre + wvlr;
    END
  saldo_cre = saldo_cre + wsaldocre;

  -- SALDO ANTERIOR A D?BITO _________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsalantdeb do
  if (wsalantdeb is null) then
     wsalantdeb=0;*/
  wsalantdeb = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsalantdeb = wsalantdeb + wvlr;
    END
  saldo_ant_deb = saldo_ant_deb + wsalantdeb;

  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';  */
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsalantcre do
  if (wsalantcre is null) then
     wsalantcre=0;*/
  wsalantcre = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsalantcre = wsalantcre + wvlr;
    END

  saldo_ant_cre = saldo_ant_cre + wsalantcre;

END /* matriz e filiais */

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;
  ELSE
    BEGIN
      movimento = saldo_atual - saldo_anterior;
    END

  SUSPEND;
END
^

/* Restore proc. body: SP_RETORNA_SALDO_MATRIZFILIAL_X */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL_X(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0,
PRCODTERCEIRO INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER,
CHAVELAN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WCODEMPEFILIAL INTEGER;
DECLARE VARIABLE WSALDODEB NUMERIC(15,2);
DECLARE VARIABLE WSALDOCRE NUMERIC(15,2);
DECLARE VARIABLE WSALANTDEB NUMERIC(15,2);
DECLARE VARIABLE WSALANTCRE NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WVLR_SALANT_DEB NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALATU_DEB NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALANT_CRE NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALATU_CRE NUMERIC(15,2);
DECLARE VARIABLE WCHAVELAN INTEGER;
DECLARE VARIABLE WDEBCRE INTEGER;
BEGIN
  codemp = prcodemp;
  IF (prmatrizfiliais IS NULL) THEN
     prmatrizfiliais = prcodemp;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||' and tpla.bdctalon starts with '''||wclassificacao||''' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- retorna as empresas selecionadas
  wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  --wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) '; --alt:13181 - N?o usa para nada este join. Pedro
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||PRMATRIZFILIAIS||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  wsaldodeb = 0;
  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  wsaldocre = 0;
  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  wsalantdeb = 0;
  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  wsalantcre = 0;
  movimento = 0;

  FOR EXECUTE STATEMENT wsqlemp
              INTO :wcodempefilial DO
  BEGIN

    --alt:11995 - 12/08/2015 - Somente ir? agruprar tudo se n?o estiver fazendo isso na integra??o do Cont?bil pro Lalur (na parte de gravar as chaves dos lan?amentos integrados). Pedro
    wSQL = '';
    IF ((PRINTCONTABILLALUR IS NULL) OR (PRINTCONTABILLALUR = 0))  THEN
      BEGIN
        wsql =        'select bddebcre, bdcodemp, bdfilial, bdtipolancfilial, null as BDCHAVE,';
        wsql = wsql|| '       sum(bdsalant_deb) as bdsalant_deb, sum(bdsalatu_deb) as bdsalatu_deb, ';
        wsql = wsql|| '       sum(bdsalant_cre) as bdsalant_cre, sum(bdsalatu_cre) as bdsalatu_cre  ';
    
        wsql = wsql|| ' from (';
      END
    --alt:11995 - Fim

    /*****D?bito***************************************************************************************************************************************************************************/

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| 'Select 1 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, TLAN.BDCHAVE, ';
    ELSE
      wsql = wsql|| 'Select 1 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, ';
    --alt:13181 - Fim

    --if ((prcc <> 0) and (not (prcc is null))) then
    --   SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP))
    --else
      --coalesce(sum(tlan.bdvalor),0) AS SOMA
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata < '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalant_deb, ';
    
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata >= '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalatu_deb, ';
        wsql = wsql|| '0 as bdsalant_cre, 0 as bdsalatu_cre ';
    
        wsql = wsql|| ' FROM VSUC_EMPRESAS_TLAN TLAN ';
    
    IF (wlevel > 1) THEN
       BEGIN
         wsql = wsql|| ' inner join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null)) ';
         IF (prrelcta IS NOT NULL) THEN
            wsql = wsql|| ' and (tpla.bdrelcta = '||prrelcta||')) ';
         ELSE
            wsql = wsql|| ' ) ';
       END
  
    wsql = wsql|| ' where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';

    --alt:11995 - 30/07/2015 - Quando for o processo de integra??o do cont?bil para o lalur n?o deve somar os lan?amentos j? integrados manualmente. Pedro
    IF (PRINTCONTABILLALUR = 1) THEN
       wsql = wsql||' and (not exists (select BDCHAVE from VLAL_VINCULO_CONTABIL_LALUR where BDCODEMPFILIAL = tlan.BDCODEMP and BDCHAVE = tlan.BDCHAVE))';
  
    IF (prcontabilizacao <> 99) THEN
       wsql = wsql|| ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

    IF (wlevel = 1) THEN
       wsql = wsql|| ' and (tlan.bddebito = '||prconta||') ';
    ELSE
       wsql = wsql|| ' and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

    --#Alt:19568. Inclu?do o filtro do participante
    IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
       wsql = wsql|| ' and (tlan.bdcodterceirod = '||prcodterceiro||') ';
    
    --alt:7728 - Estava comentado o ignorar zeramento, habilitei novamente porque estava gerando uma diferen?a de saldos. Pedro
    IF (prignorazeramento = 1) THEN
       wsql = wsql|| ' AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
    --alt:7728 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
       --  AND (TLCC.bdcodtpcc = 'prcc')
    
    IF (bdconciliados = 1) THEN
       wsql = wsql|| ' and (Upper(BDCONCD) = '''||'TRUE'||''') ';
    ELSE
    IF (bdconciliados = 2) THEN
       wsql = wsql|| ' and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null)) ';
  
    wsql = wsql|| ' and (tlan.bddata <= '''||wdatfin||''') ';

    --alt:11995 - Se estiver carregando as chaves de lan?amentos para a integra??o do Lalur, n?o pode carregar chaves de per?odos anteriores. Pedro
    IF (PRINTCONTABILLALUR = 1)  THEN
      wsql = wsql|| ' and (tlan.bddata >= '''||wdatini||''') ';

    --alt:9604 - Alterada regra do c?digo da empresa e c?digo da filial, pois antes ele n?o verificava o TipoLancFilial
    --e pegava registros que estavam lan?ado na filial ou na matriz que n?o deveriam trazer aqui. Pedro
    --wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
    wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL <> 1) or (bdfilial = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL = 1)) ';
  
    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, TLAN.BDCHAVE ';
    ELSE
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial ';
    --alt:13181 - Fim
    

    /******Cr?dito**************************************************************************************************************************************************************/
    wsql = wsql|| ' union all ';

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' Select 2 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, TLAN.BDCHAVE, 0 as bdsalant_deb, 0 as bdsalatu_deb, ';
    ELSE
      wsql = wsql|| 'Select 2 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, 0 as bdsalant_deb, 0 as bdsalatu_deb, ';
    --alt:13181 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
      --   SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP))
      --else
        --coalesce(sum(tlan.bdvalor),0) AS SOMA
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata < '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalant_cre, ';
    
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata >= '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalatu_cre ';
    
        wsql = wsql|| ' FROM VSUC_EMPRESAS_TLAN TLAN ';
    
    IF (wlevel > 1) THEN
       BEGIN
         wsql = wsql|| ' inner join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null)) ';
         IF (prrelcta IS NOT NULL) THEN
            wsql = wsql|| ' and (tpla.bdrelcta = '||prrelcta||')) ';
         ELSE
            wsql = wsql|| ' ) ';
       END
    
    wsql = wsql|| ' where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
    
    --alt:11995 - 30/07/2015 - Quando for o processo de integra??o do cont?bil para o lalur n?o deve somar os lan?amentos j? integrados manualmente. Pedro
    IF (printcontabillalur = 1) THEN
       wsql = wsql||' and (not exists (select BDCHAVE from VLAL_VINCULO_CONTABIL_LALUR where BDCODEMPFILIAL = tlan.BDCODEMP and BDCHAVE = tlan.BDCHAVE))';

    IF (prcontabilizacao <> 99) THEN
       wsql = wsql|| ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

    IF (wlevel = 1) THEN
       wsql = wsql|| ' and (tlan.bdcredito = '||prconta||') ';
    ELSE
       wsql = wsql|| ' and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

    --#Alt:19568. Inclu?do o filtro do participante
    IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
       wsql = wsql|| ' and (tlan.bdcodterceiroc = '||prcodterceiro||') ';
    
    --alt:7728 - Estava comentado o ignorar zeramento, habilitei novamente porque estava gerando uma diferen?a de saldos. Pedro
    IF (prignorazeramento = 1) THEN
       wsql = wsql|| ' AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
    --alt:7728 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
       --  AND (TLCC.bdcodtpcc = 'prcc')
    
    IF (bdconciliados = 1) THEN
       wsql = wsql|| ' and (Upper(BDCONCD) = '''||'TRUE'||''') ';
    ELSE
    IF (bdconciliados = 2) THEN
       wsql = wsql|| ' and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null)) ';
  
    wsql = wsql|| ' and (tlan.bddata <= '''||wdatfin||''') ';

    --alt:11995 - Se estiver carregando as chaves de lan?amentos para a integra??o do Lalur, n?o pode carregar chaves de per?odos anteriores. Pedro
    IF (PRINTCONTABILLALUR = 1)  THEN
      wsql = wsql|| ' and (tlan.bddata >= '''||wdatini||''') ';

    --alt:9604 - Alterada regra do c?digo da empresa e c?digo da filial, pois antes ele n?o verificava o TipoLancFilial
    --e pegava registros que estavam lan?ado na filial ou na matriz que n?o deveriam trazer aqui. Pedro
    --wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
    wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL <> 2) or (bdfilial = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL = 2)) ';
  

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, TLAN.BDCHAVE ';
    ELSE
       wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial ';
    --alt:13181 - Fim

  --alt:11995 - 12/08/2015 - Somente ir? agruprar tudo se n?o estiver fazendo isso na integra??o do Cont?bil pro Lalur (na parte de gravar as chaves dos lan?amentos integrados). Pedro
  IF ((PRINTCONTABILLALUR IS NULL) OR (PRINTCONTABILLALUR = 0))  THEN
    wsql = wsql|| ' ) group by bddebcre, bdcodemp, bdfilial, bdtipolancfilial ';

  wvlr_salant_deb = 0;
  wvlr_salatu_deb = 0;
  wvlr_salant_cre = 0;
  wvlr_salatu_cre = 0;

  wsalantdeb = 0;
  wsaldodeb = 0;
  wsalantcre = 0;
  wsaldocre = 0;

  FOR EXECUTE STATEMENT wSQL INTO :wdebcre, :wcodemp,:wfilial,:wtipolancfilial, :CHAVELAN, :wvlr_salant_deb, :wvlr_salatu_deb, :wvlr_salant_cre, :wvlr_salatu_cre DO
    BEGIN
      IF (wvlr_salant_deb IS NULL) THEN
         wvlr_salant_deb = 0;

      IF (wvlr_salatu_deb IS NULL) THEN
         wvlr_salatu_deb = 0;

      IF (wvlr_salant_cre IS NULL) THEN
         wvlr_salant_cre = 0;

      IF (wvlr_salatu_cre IS NULL) THEN
         wvlr_salatu_cre = 0;

      --alt:13903 - 29/03/2016 - N?o estava verificando a regra do "lan?ar a" quando era no cr?dito, estava fixo o d?bito. Pedro
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wdebcre,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          wsalantdeb = wsalantdeb + wvlr_salant_deb;
          wsaldodeb = wsaldodeb + wvlr_salatu_deb;
          wsalantcre = wsalantcre + wvlr_salant_cre;
          wsaldocre = wsaldocre + wvlr_salatu_cre;

          --alt:11995 - 12/08/2015 - Se estiver fazendo o processo de gravar as chaves integradas do Cont?bil pro Lalur deve retornar um lan?amento para cada registro. Pedro
          IF ((CHAVELAN > 0) AND (printcontabillalur = 1)) THEN
            BEGIN
              CODEMP = :wcodempefilial;
              SUSPEND;
            END
        END
    END

    saldo_deb = saldo_deb + wsaldodeb;
    saldo_ant_deb = saldo_ant_deb + wsalantdeb;
    saldo_cre = saldo_cre + wsaldocre;
    saldo_ant_cre = saldo_ant_cre + wsalantcre;

  END /* matriz e filiais */

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB - SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE - SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;
  ELSE
    BEGIN
      movimento = saldo_atual - saldo_anterior;
    END

  --alt:11995 - 12/08/2015 - S? retorna aqui se n?o estiver fazendo o processo de integra??o, para n?o duplicar registros. Pedro
  IF ((printcontabillalur = 0) OR (printcontabillalur IS NULL))  THEN
    SUSPEND;
END
^

/* Restore proc. body: SP_VALIDA_EXPORTACAO_SPED */
ALTER PROCEDURE SP_VALIDA_EXPORTACAO_SPED(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRBLOCO CHAR(4))
 AS
DECLARE VARIABLE WENTRADA INTEGER;
DECLARE VARIABLE WSAIDA INTEGER;
DECLARE VARIABLE WSQL VARCHAR(200);
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WQTDMAX INTEGER;
BEGIN
  wEntrada = 0;
  wSaida   = 1;
  PRBLOCO  = UPPER(:PRBLOCO);

  wSQL =          'SELECT COUNT(S.BDORDEMINCO) BDQTD ';
  wSQL = :wSQL || 'FROM TEXPORTACAO_SPED_INCO S ';
  wSQL = :wSQL || 'WHERE S.BDID = '''||:PRARQUIVO||''' ';
  wSQL = :wSQL || 'GROUP BY S.BDID';

  SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_LIM_INCO_EXPORTACAO') FROM RDB$DATABASE INTO :wQtdMax;
  SETORDEMSEQUENCIAL(0);  

  IF (:PRBLOCO = 'C100') THEN
    BEGIN
  /*****************************************************************************
   *                                   C113                                    *
   ****************************************************************************/
    
   IF (:PRDTINI > '12/31/2016') THEN
     BEGIN
       /*1 - Chave NFE inv?lida!*/
       INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
       SELECT :PRARQUIVO, C113.BDCHAVE, 1, :wEntrada, 'C113' /*Entrada*/
       FROM (
             SELECT MOVINF.BDCHAVE, MOVINF.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE(C113.BDCHAVENFE)) BDISVALID
             FROM (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                   FROM (
                         SELECT M.BDCODEMP, M.BDCHAVE
                         FROM VEF_EMP_TMOVENT M
                         WHERE M.BDCODEMP = :PRCODEMP
                         AND M.BDMODELO IN (1, 4, 55, 100)
                         AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                        ) MOV
                   JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  ) MOVINF                                                                                                                                            /*Modelos: 55, 57*/
             JOIN VEF_EMP_TMOVENTDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC AND C113.BDCODDOCFIS IN(30, 31))
            ) C113
       WHERE C113.BDISVALID = 'FALSE'
       UNION ALL
       SELECT :PRARQUIVO, C113.BDCHAVE, 1, :wSaida, 'C113' /*Sa?da*/
       FROM (
             SELECT MOVINF.BDCHAVE, MOVINF.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE(C113.BDCHAVENFE)) BDISVALID
             FROM (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                   FROM (
                         SELECT M.BDCODEMP, M.BDCHAVE
                         FROM VEF_EMP_TMOVSAI M
                         WHERE M.BDCODEMP = :PRCODEMP
                         AND M.BDMODELO IN (1, 4, 55, 100)
                         AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        ) MOV
                   JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  ) MOVINF                                                                                                                                            /*Modelos: 55, 57*/
             JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC AND C113.BDCODDOCFIS IN(30, 31))
            ) C113
       WHERE C113.BDISVALID = 'FALSE';
     END
      
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/
  /*2 - Produto sem vinculo com a empresa!*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODPROD, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, PRO.BDORDEMPRO, VINC.BDCODPROD, 2, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
       ) ENT
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')))
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, PRO.BDORDEMPRO, VINC.BDCODPROD, 2, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
       ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*3 - O valor total do desconto declarado no Registro C100 n?o confere com o somat?rio dos valores dos descontos declarados nos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, 3, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDORDEM
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) ENT
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
        GROUP BY ENT.BDCODEMP, ENT.BDCHAVE
       ) PRO
  JOIN VEF_EMP_TMOVENT LAN ON(LAN.BDCODEMP = PRO.BDCODEMP AND LAN.BDCHAVE = PRO.BDCHAVE)
  WHERE LAN.BDDESCONTONOTA <> PRO.BDVLRDESC
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, 3, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDORDEM
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) SAI
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
        GROUP BY SAI.BDCODEMP, SAI.BDCHAVE
       ) PRO
  JOIN VEF_EMP_TMOVSAI LAN ON(LAN.BDCODEMP = PRO.BDCODEMP AND LAN.BDCHAVE = PRO.BDCHAVE)
  WHERE LAN.BDDESCONTONOTA <> PRO.BDVLRDESC;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*4 - O valor declarado no campo Valor do PIS, no Registro C100, deve corresponder ? soma dos valores declarados no mesmo campo dos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 4, :wEntrada, 'C170' /*Entrada*/
  FROM (
        --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTPIS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPISPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTPIS <> PRO.BDVLRPISPROD
  UNION ALL
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 4, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTPIS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPISPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTPIS <> PRO.BDVLRPISPROD;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*5 - O valor declarado no campo Valor do Cofins, no Registro C100, deve corresponder ? soma dos valores declarados no mesmo campo dos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 5, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTCOFINS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINSPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTCOFINS <> PRO.BDVLRCOFINSPROD
  UNION ALL
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 5, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTCOFINS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINSPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTCOFINS <> PRO.BDVLRCOFINSPROD;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*6 - Quando o campo ALIQ_ICMS (Al?quota do ICMS) for preenchido com um valor maior que zero no Registro C170, os valores dos campos VL_BC_ICMS e VL_ICMS tamb?m devem ser maiores que zero.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 6, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 ((PRO.BDALIQICMS > 0) AND ((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) AND ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 6, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 ((PRO.BDALIQICMS > 0) AND ((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) AND ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*7 - O campo VL_BC_IPI (Valor da base de c?lculo do IPI) e/ou VL_IPI (Valor do IPI) est?(?o) inconsistente(s) no Registro C170. Observar: Os campos VL_BC_IPI e VL_IPI n?o devem ser maior que 0 (zero) quando a CST-IPI for diferente de: 00 e/ou 50.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 7, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI NOT IN(1, 8) AND ((PRO.BDBCIPI > 0) OR (PRO.BDVLRIPI > 0)))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 7, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI NOT IN(1, 8) AND ((PRO.BDBCIPI > 0) OR (PRO.BDVLRIPI > 0)));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*8 - Registro C170 se os dois ?ltimos d?gitos do C?digo da Situa??o Tribut?ria (CST_ICMS) forem diferentes de: 30, 40, 41,50 e/ou 60.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 8, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTICMS = 1 AND (((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) OR
                                                           ((PRO.BDALIQICMS IS NULL) OR (PRO.BDALIQICMS = 0)) OR
                                                           ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 8, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTICMS = 1 AND (((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) OR
                                                           ((PRO.BDALIQICMS IS NULL) OR (PRO.BDALIQICMS = 0)) OR
                                                           ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*9 - O campo Base de IPI/aliquota/valor do IPI deve ser maior que 0 (zero) se o Campo CST_IPI estiver preenchido com CST?s representativos de receitas tributadas ou opera??es com direito a cr?dito: 00 (Entrada) e/ou 50 (Sa?das).*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 9, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI IN (1, 8) AND (((PRO.BDBCIPI IS NULL) OR (PRO.BDBCIPI = 0)) OR
                                                                ((PRO.BDALIQIPI IS NULL) OR (PRO.BDALIQIPI = 0)) OR
                                                                ((PRO.BDVLRIPI IS NULL) OR (PRO.BDVLRIPI = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 9, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI IN (1, 8) AND (((PRO.BDBCIPI IS NULL) OR (PRO.BDBCIPI = 0)) OR
                                                                ((PRO.BDALIQIPI IS NULL) OR (PRO.BDALIQIPI = 0)) OR
                                                                ((PRO.BDVLRIPI IS NULL) OR (PRO.BDVLRIPI = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*10 - Itens declarados com CFOP de ativo imobilizado devem ser declarados com o tipo do item igual a 08.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 10, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 9
  AND C170.BDCODNAT IN(1406, 1551, 2406, 2551)
  UNION ALL
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 10, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 9
  AND C170.BDCODNAT IN(1406, 1551, 2406, 2551);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*11 - Itens declarados com CFOP de uso e consumo devem ser declarados com o tipo do item igual a 07.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 11, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 8
  AND C170.BDCODNAT IN(1407, 1556, 2407, 2556, 1653, 2653)
  UNION ALL
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 11, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 8
  AND C170.BDCODNAT IN(1407, 1556, 2407, 2556, 1653, 2653);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*12 - Deve ser informado se o C?digo da Situa??o Tribut?ria referente ao IPI (CST_IPI) for igual a: 01,02,03,04,05
    13 - Deve ser informado se o C?digo da Situa??o Tribut?ria referente ao IPI (CST_IPI) for igual a: 51,52,53,54,55*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 12, :wEntrada, 'C110' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND PRO.BDCODCSTIPI IN(2, 3, 4, 5, 6))
  LEFT OUTER JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 13, :wSaida, 'C110' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND PRO.BDCODCSTIPI IN(9, 10, 11, 12, 13))
  LEFT OUTER JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  WHERE INF.BDCHAVE IS NULL; /*N?o existe informa??o complementar para este lan?amento*/
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*14 - Normalmente deve ser informado se os dois ?ltimos d?gitos do C?digo da Situa??o Tribut?ria referente ao ICMS (CST_ICMS) forem iguais a:
         20, 30, 40, 41, 50, 51 e/ou 70. Consulte a legisla??o do seu estado sobre a obrigatoriedade.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 14, :wEntrada, 'C110' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) IN (20, 30, 40, 41, 50, 51, 70)
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 14, :wSaida, 'C110' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) IN (20, 30, 40, 41, 50, 51, 70);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*15 - Diverg?ncia entre CST e CFOP em opera??o sujeita ao regime de substitui??o tribut?ria no Registro C170. O CST deve possuir final 10,30,60 e 70 ou os c?digos 201,202,203 e 500.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 15, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDCODNAT
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE (((MOV.BDCODNAT >= 1401000) AND (MOV.BDCODNAT <= 1415000)) OR ((MOV.BDCODNAT >= 2401000) AND (MOV.BDCODNAT <= 2415000)))
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) NOT IN(10, 30, 60, 70)
  AND CST.BDCSTICMS NOT IN(201, 202, 203, 500);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
    
  /*16 - Diverg?ncia entre CST e CFOP em opera??o de compra de material para uso ou consumo. Para CFOP?s de compra de material para uso ou consumo (1.556 e 2.556), o CST deve ter os 2? e 3? d?gitos iguais a 90 ? outras.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 16, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE MOV.BDCODNAT IN(1556, 2556)
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) <> '90';
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*17 - Foram detectados CFOP(s) de energia el?trica, comunica??o/telecomunica??o e/ou transportes indevidamente declarado(s) no Registro C190.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 17, :wEntrada, 'C190' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO = 1
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND
                                       SUBSTRING(I.BDCODNAT FROM 1 FOR 4) IN(1207, 1153, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 2153, 2207, 2251, 2252, 2253, 2254, 2255, 2256, 2257,
                                                                             3207, 3251, 5153, 5207, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 6153, 6207, 6251, 6252, 6253, 6254,
                                                                             6255, 6256, 6257, 6258, 7207, 7251, 1205, 1301, 1302, 1303, 1304, 1305, 1306, 2205, 2301, 2302, 2303, 2304,
                                                                             2305, 2306, 3205, 3301, 5205, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 6205, 6301, 6302, 6303, 6304, 6305,
                                                                             6306, 6307, 7205, 7301, 1206, 1351, 1352, 1353, 1354, 1355, 1356, 1360, 1931, 1932, 2206, 2351, 2352, 2353,
                                                                             2354, 2355, 2356, 2931, 2932, 3206, 3351, 3352, 3353, 3354, 3355, 3356, 5206, 5351, 5352, 5353, 5354, 5355,
                                                                             5356, 5357, 5359, 5360, 5931, 5932, 6206, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6359, 6360, 7206, 7358))
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 17, :wSaida, 'C190' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO = 1
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND
                                       SUBSTRING(I.BDCODNAT FROM 1 FOR 4) IN(1207, 1153, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 2153, 2207, 2251, 2252, 2253, 2254, 2255, 2256, 2257,
                                                                             3207, 3251, 5153, 5207, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 6153, 6207, 6251, 6252, 6253, 6254,
                                                                             6255, 6256, 6257, 6258, 7207, 7251, 1205, 1301, 1302, 1303, 1304, 1305, 1306, 2205, 2301, 2302, 2303, 2304,
                                                                             2305, 2306, 3205, 3301, 5205, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 6205, 6301, 6302, 6303, 6304, 6305,
                                                                             6306, 6307, 7205, 7301, 1206, 1351, 1352, 1353, 1354, 1355, 1356, 1360, 1931, 1932, 2206, 2351, 2352, 2353,
                                                                             2354, 2355, 2356, 2931, 2932, 3206, 3351, 3352, 3353, 3354, 3355, 3356, 5206, 5351, 5352, 5353, 5354, 5355,
                                                                             5356, 5357, 5359, 5360, 5931, 5932, 6206, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6359, 6360, 7206, 7358))
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM);
    
  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  /*18 - Sem produto.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, MOV.BDCHAVE, 18, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVENT M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  WHERE PRO.BDORDEMPRO IS NULL
  UNION ALL
  SELECT :PRARQUIVO, MOV.BDCHAVE, 18, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVSAI M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  WHERE PRO.BDORDEMPRO IS NULL;
    
  /*19 - Com indicador de pagamento a prazo sem informa??o de parcelas.*/
  /*A partir dos produtos*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, MOV.BDCHAVE, 19, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE
        FROM VEF_EMP_TMOVENT M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO = 1
        AND M.BDCONDPGTO = 1 /*Prazo*/
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVENTPAR PAR ON(PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
  WHERE PAR.BDORDEMPAR IS NULL
  UNION ALL
  SELECT :PRARQUIVO, MOV.BDCHAVE, 19, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVSAI M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND M.BDCONDPGTO = 1 /*Prazo*/        
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON(PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
  WHERE PAR.BDORDEMPAR IS NULL;
    
  /*20 - Existe diferen?a entre base/valor de ICMS da nota e a base/valor de ICMS dos produtos.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 20, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = ENT.BDORDEM)
  WHERE ENT.BDBCICMS <> I.BDBASEICMS
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 20, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
  WHERE SAI.BDBCICMS <> I.BDBASEICMS;
    
  /*21 - Existe diferen?a entre base/valor de IPI da nota e a base/valor de IPI dos produtos.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 21, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = ENT.BDORDEM)
  WHERE ENT.BDBCIPI <> I.BDBASEIPI
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 21, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
  WHERE SAI.BDBCIPI <> I.BDBASEIPI;
    END
  ELSE
  IF (:PRBLOCO = 'D100') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
      SELECT :PRARQUIVO, MOV.BDCHAVE, 22, :wEntrada, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, COALESCE(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))), '') BDCHAVECTEREF
            FROM VEF_EMP_TMOVENT E
            JOIN VEF_EMP_TD100ENT D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE MOV.BDCHAVECTEREF <> ''
      UNION ALL
      SELECT :PRARQUIVO, MOV.BDCHAVE, 22, :wSaida, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, COALESCE(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))), '') BDCHAVECTEREF
            FROM VEF_EMP_TMOVSAI E
            JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE MOV.BDCHAVECTEREF <> '';
    END
END
^

/* Restore proc. body: SP_VRH_VAL_RAIS_FF_REF */
ALTER PROCEDURE SP_VRH_VAL_RAIS_FF_REF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
DECLARE VARIABLE WANOINI INTEGER;
DECLARE VARIABLE WANOFIM INTEGER;
BEGIN
  /* Procedure Text */
  wAnoIni = CAST(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wAnoFim = CAST(SUBSTRING(CAST(prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  IF ((premp IS NOT NULL) AND (premp <> '')) THEN
     BEGIN
       premp = UPPER(premp);
       IF (POSITION('TAB.BDCODEMP',premp) > 0) THEN
          BEGIN
            SELECT bdresult FROM strtran(:premp,'TAB.BDCODEMP','COL.BDCODEMP') INTO premp;
          END
     END

  WHILE (wAnoIni <= wAnoFim) DO
    BEGIN
      FOR SELECT BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade FROM SP_VRH_VAL_RAIS_FF(:premp,:prcol,:wanoini)
          INTO BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade DO

          IF ((bdref >= prrefini) AND (bdref <= prreffim)) THEN
             SUSPEND;

      wAnoIni = wanoini+ 1;
    END

END
^

/* Restore proc. body: SP_VRHF_DECLARACAO_DOMESTICO */
ALTER PROCEDURE SP_VRHF_DECLARACAO_DOMESTICO(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRANOBASE INTEGER,
PRTOMADOR INTEGER,
PRCODSIND INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRORDEM VARCHAR(50),
PRDATAEMISSAO VARCHAR(10),
PRSITUACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADM DATE,
BDDATARESCISAO DATE,
BDPIS VARCHAR(14),
BDCPF VARCHAR(14),
BDCOMPETENCIA INTEGER,
BDSALMIN NUMERIC(15,6),
BDBINSSN NUMERIC(15,6),
BDBINSSFE NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDREMUNERACAO NUMERIC(18,6),
BDINSSPATRONAL NUMERIC(15,6),
BDDIFERENCAINSS NUMERIC(15,6),
BDTOTALCONTRPATRONAL NUMERIC(15,6),
BDPARCELANAODEDUTIVEL NUMERIC(15,6),
BDINF VARCHAR(20),
BDORDEM VARCHAR(50),
BDDATAEMISSAO VARCHAR(10),
BDANOBASE INTEGER)
 AS
declare variable WULTDIA varchar(10);
declare variable WPRIDIA varchar(10);
declare variable WDIA varchar(10);
declare variable WMES varchar(10);
declare variable WORDEM varchar(50);
declare variable WPRIDIAEMISSAO varchar(10);
declare variable WULTDIAEMISSAO varchar(10);
declare variable WWHERE varchar(30000);
declare variable WSQLALIQ varchar(500);
declare variable WSQL varchar(30000);
declare variable WALIQINSS numeric(18,6);
declare variable WBASE numeric(18,6);
BEGIN
  wpridia = '01/01/'||pranobase;
  wultdia = '12/31/'||pranobase;

  wmes = SUBSTRING(:prdataemissao FROM 4 FOR 2);
  SELECT ultdia FROM ultimo_dia_mes(:wmes, :pranobase) INTO :wdia;
  wpridiaemissao = wmes||'/01/'||pranobase;
  wultdiaemissao = wmes||'/'||wdia||'/'||pranobase;

  wwhere = '';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       wwhere = ' where ' || prcodemp;

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wwhere = wwhere || ' and ' || prcodcol;
     END
  ELSE
     BEGIN
       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wwhere = ' where ' || prcodcol;
     END

  IF (prtomador > 0) THEN
     wordem = ', ORDEM ';
  ELSE
     wordem = ', null ';

  wsql = 'select distinct BDCODEMPRESA, BDCODCOLABORADOR, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOCREF.BDPISCOL, COL.BDCPFCOL, REF, ' ||
         'max(SALMIN.BDSALMIN) SALMIN, COALESCE(INSS, 0), COALESCE(INSSFE, 0), COALESCE(INSS13, 0), INF ' || wordem;

  IF (prtomador > 0) THEN
     wordem = ', NULL AS ORDEM ';
  ELSE
     wordem = '';

  wsql = wsql || 'from (select FN.BDCODEMP as BDCODEMPRESA, FN.BDCODCOL as BDCODCOLABORADOR, FN.BDREFFN as REF, ' ||
         'FN.BDBINSSFN as INSS, FN.BDBINSSFEFOLFN as INSSFE, FN.BDBINSS13FN as INSS13, '''' as INF ' || wordem || ' from VRHF_EMP_TFOLHANORMAL FN ' || wwhere;

  wsql = wsql || ' union all select FC.BDCODEMP as BDCODEMPRESA, FC.BDCODCOL as BDCODCOLABORADOR, FC.BDREFCOMP as REF, ' ||
            'FC.BDBINSSFC as INSS, FC.BDBINSSFEFOLFC as INSSFE, FC.BDBINSS13FC as INSS13, ''Fol. Compl.'' as INF' || wordem || ' from VRHF_EMP_TFOLHACOMP FC ' || wwhere;

  wsql = wsql || ' union all select F13SAL.BDCODEMP as BDCODEMPRESA, F13SAL.BDCODCOL as BDCODCOLABORADOR, F13SAL.BDREF13 as REF, ' ||
            'F13SAL.BDBASEINSS13 as INSS, 0 as INSSFE, 0 as INSS13, ''13? Sal.'' as INF' || wordem || ' from VRHF_EMP_T13SAL F13SAL ' || wwhere;

  IF (prtomador > 0) THEN
     wordem = ', FT.BDORDEM AS ORDEM ';

  wsql = wsql || ' union all select FT.BDCODEMP as BDCODEMPRESA, FT.BDCODCOL as BDCODCOLABORADOR, FT.BDREFTOMADOR as REF, ' ||
            'SUM(FT.BDBINSSFT) as INSS, SUM(FT.BDBINSSFEFOLFT) as INSSFE, SUM(FT.BDBINSS13FT) as INSS13, '''' as INF' || wordem || ' from VRHF_EMP_TFOLHATOMADOR FT ' || wwhere ||
            ' group by REF, BDCODEMPRESA, BDCODCOLABORADOR, INF';

  IF (prtomador > 0) THEN
     BEGIN
       wsql = wsql || ', FT.BDORDEM ';
       wordem = ', FTC.BDORDEM AS ORDEM ';
     END

  wsql = wsql || ' union all select FTC.BDCODEMP as BDCODEMPRESA, FTC.BDCODCOL as BDCODCOLABORADOR, FTC.bdreftomador as REF, ' ||
            'FTC.BDBINSSFC as INSS, FTC.BDBINSSFEFOLFC as INSSFE, FTC.BDBINSS13FC as INSS13, ''Fol. Compl'' as INF' || wordem || ' from VRHF_EMP_TFOLTOMCOMP FTC ' || wwhere;

  IF (prtomador > 0) THEN
     wordem = ', FER.BDORDEM AS ORDEM';

  wsql = wsql || ' union all select FER.BDCODEMP as BDCODEMPRESA, FER.BDCODCOL as BDCODCOLABORADOR, FER.BDREFINIFE as REF, ' ||
            'FER.BDBASEINSSFE as INSS, 0 as INSSFE, 0 as INSS13, ''F?rias'' as INF' || wordem || ' from VRH_EMP_TFERIAS FER ' || wwhere || ') ';

  wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = BDCODEMPRESA and COL.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRH_EMP_TCOLCON_DOC DOC on (DOC.BDCODEMP = COL.BDCODEMP and DOC.BDCODCOL = COL.BDCODCOL) ' ||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = BDCODEMPRESA and RESC.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRHF_TABELAS_TSALMIN SALMIN on (SALMIN.BDREFSM <= REF) ' ||
         'left outer join VRH_EMP_TCOLCON_VINC VINC on (VINC.BDCODEMP = BDCODEMPRESA and VINC.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRH_BASE_TCLASSE CLAS on (VINC.BDCODCLA = CLAS.BDCODCLA) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = BDCODEMPRESA and COLCAD.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = BDCODEMPRESA and DOCREF.BDCODCOL = BDCODCOLABORADOR) ';

  -- Filtros
  IF (prtomador > 0) THEN
     BEGIN
       wsql = wsql || 'left outer join VRHF_EMP_TPREPFN PREP on (prep.bdcodemp = bdcodempresa and prep.bdcodcol = bdcodcolaborador and prep.bdordem = ordem) ';
     END

  IF (prcodsind > 0) THEN
     wsql = wsql || 'left outer join VRH_EMP_TCOL_VINC VINC2 on (vinc2.bdcodemp = bdcodempresa and vinc2.bdcodcol = bdcodcolaborador) ';

  IF (prfuncao > 0) THEN
     wsql = wsql || 'left outer join VRH_EMP_TCOL_VINCDIA coldia on (coldia.bdcodemp = bdcodempresa and coldia.bdcodcol = bdcodcolaborador) ';

  IF (prsituacao = 0) THEN
     wSql = wSql || ' join SP_SOMENTE_ATIVOS(''' || wpridia || ''', ''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ';

  IF (prsituacao = 2) THEN
     wSql = wSql || ' join SP_SOMENTE_DEMITIDOS(''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 3) THEN
     wSql = wSql || ' join SP_SOMENTE_ADMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 4) THEN
     wSql = wSql || ' join SP_SOMENTE_DEMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 5) THEN
     wSql = wSql || ' join SP_ATIVOS_SEM_DEMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 6) THEN
     wSql = wSql || ' join SP_ATI_SEM_DEM_COM_TRANSF(''' || wpridia || ''',''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 7) THEN
     wSql = wSql || ' join SP_ATI_SEM_AFAST_MES_INT(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 8) THEN
     wSql = wSql || ' join SP_AFASTADOS_MES_INTEIRO(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  -- Where e filtros
  wwhere = ' where clas.bdgrupocla = 7 and SUBSTRING(CAST(REF AS VARCHAR(6)) FROM 1 FOR 4) = ' || pranobase;

  IF (prtomador > 0) THEN
     BEGIN
       wwhere = wwhere || ' and prep.bdcodtpcc = '||prtomador;
       wordem = ', ORDEM ';
     END
  ELSE
     wordem = '';

  IF (prcodsind > 0) THEN
     wwhere = wwhere||' and vinc2.bdcodsintrab = '||prcodsind;

  IF (prclasse > 0) THEN
     wwhere = wwhere||' and vinc.bdcodcla = '||prclasse;

  IF (prfuncao > 0) THEN
     wwhere = wwhere||' and coldia.bdcodtfuc = '||prfuncao;

  wsql = wsql || wwhere || ' group by BDCODEMPRESA, BDCODCOLABORADOR, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOCREF.BDPISCOL, COL.BDCPFCOL, REF, ' ||
         'INSS, INSSFE, INSS13, INF ' || wordem;

  IF (prordem IS NOT NULL AND prordem <> '') THEN
     BEGIN
       IF (PRORDEM = 'BDCODCOL') THEN
          wsql = wsql || 'ORDER BY BDCODEMPRESA, BDCODCOLABORADOR, REF, INF ';
       ELSE
          wsql = wsql || 'ORDER BY BDCODEMPRESA, COLCAD.BDNOMCOL, REF, INF ';
     END
  ELSE
     wsql = wsql || 'ORDER BY BDCODEMPRESA, REF, INF ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcodcol,
    :bdnomcol,
    :bddataadm,
    :bddatarescisao,
    :bdpis,
    :bdcpf,
    :bdcompetencia,
    :bdsalmin,
    :bdbinssn,
    :bdbinssfe,
    :bdbinss13,
    :bdinf,
    :bdordem
  DO
    BEGIN
      bdremuneracao = bdbinssn + bdbinssfe + bdbinss13;
      bddataemissao = prdataemissao;
      bdanobase = pranobase;
      bdtotalcontrpatronal  = bdremuneracao * 12 / 100;

      IF ((bdremuneracao - bdsalmin) > 0) THEN
         bdparcelanaodedutivel = (bdremuneracao - bdsalmin) * 12 / 100;
      ELSE
         bdparcelanaodedutivel = 0;

      wbase = 0;
      IF (bdbinssn IS NOT NULL AND bdbinssn > 0) THEN
         BEGIN
           wbase = bdbinssn;
           wsqlaliq = 'select fol.bdaliqinssfn from vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
                || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
         END
      ELSE
      IF (bdbinssfe IS NOT NULL AND bdbinssfe > 0) THEN
         BEGIN
           wbase = bdbinssfe;
           wsqlaliq = 'select fol.bdaliqinssfefolfn from vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
           || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
         END
      ELSE
      IF (bdbinss13 IS NOT NULL AND bdbinss13 > 0) THEN
        BEGIN
          wbase = bdbinss13;
          wsqlaliq = 'select fol.bdaliqinss13fn vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
          || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
        END
      ELSE
      -- N?o tem c?lculo nenhum
        wsqlaliq = '';

      IF (wsqlaliq IS NOT NULL AND wsqlaliq <> '') THEN
        BEGIN
          FOR EXECUTE STATEMENT wsqlaliq
          INTO
            :waliqinss
          DO
            BEGIN
              bdinsspatronal = wbase * waliqinss / 100;
            
              IF (bdremuneracao < bdsalmin) THEN
                 bddiferencainss = 0;
              ELSE
                 bddiferencainss = (bdremuneracao - bdsalmin) * waliqinss / 100;
            END
        END
      ELSE
        BEGIN
          bdinsspatronal = 0;
          bddiferencainss = 0;
        END

      SUSPEND;
    END
END
^

/* Restore proc. body: VSUC_SP_BALANCETE_MENSAL */
ALTER PROCEDURE VSUC_SP_BALANCETE_MENSAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDDATINI DATE,
BDDATFIN DATE,
BDAPECTA VARCHAR(20))
 AS
DECLARE VARIABLE WDATINI DATE;
DECLARE VARIABLE WDATFIN DATE;
BEGIN
  wdatini = prdatini;
  wdatfin = addmonth(wdatini, 1)-1;
  WHILE (wdatfin <= prdatfin) DO
    BEGIN
      bddatini = wdatini;
      bddatfin = wdatfin;
      FOR SELECT BDCODEMP, BDNOMEMP, BDCNPJEMP, BDCODMATRIZ, BDCODEMPFILIAL, BDCODPLAPADRAO,
                 BDCODCTA, BDCTALON, BDNOMCTA, BDTIPCTA, BDCODTPCC, BDNOMTPCC,
                 BDSALDO_ANTERIOR, BDSALDO_ANT_DEB, BDSALDO_ANT_CRE, BDSALDO_DEB,
                 BDSALDO_CRE, BDSALDO_ATUAL, BDGRPCTA, BDTPCCLON, BDMOVIMENTO,
                 BDFORMULA, BDRELCTA, BDCLANOM, BDAPECTA
          FROM vsuc_sp_retorna_balancete(:prcodemp, :wdatini, :wdatfin, :prindice, :prignora_zeramento, :prctaini, :prctafin, :prcodtpcc, :prrefemp, :prlansemcc, 0, :prnaomostracontacomp,
                                         :prconsolidada, :prdetalharctaparticipante, :PRAGRUPARPARTICIPANTEPORCNPJ, :prconcatenacodparticipante, :prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado, 0)
          INTO :BDCODEMP, :BDNOMEMP, :BDCNPJEMP, :BDCODMATRIZ, :BDCODEMPFILIAL, :BDCODPLAPADRAO,
               :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDCODTPCC, :BDNOMTPCC,
               :BDSALDO_ANTERIOR, :BDSALDO_ANT_DEB, :BDSALDO_ANT_CRE, :BDSALDO_DEB,
               :BDSALDO_CRE, :BDSALDO_ATUAL, :BDGRPCTA, :BDTPCCLON, :BDMOVIMENTO,
               :BDFORMULA, :BDRELCTA, :BDCLANOM, :BDAPECTA DO
          SUSPEND;

      wdatini = addmonth(wdatini, 1);
      wdatfin = addmonth(wdatini, 1)-1;
    END
END
^

/* Restore proc. body: VSUC_SP_BALANCO_PATRIMONIAL */
ALTER PROCEDURE VSUC_SP_BALANCO_PATRIMONIAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSEMCC INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSAL_ANT_DEB NUMERIC(15,2),
BDSAL_ANT_CRE NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDCODEMPFILIAL INTEGER,
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20),
BDPERTENCECONTA INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(4096);
DECLARE VARIABLE WSQLTCC VARCHAR(1024);
DECLARE VARIABLE WSEQCTA VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WCTALONATIVO VARCHAR(40);
DECLARE VARIABLE WCTALONPATLIQ VARCHAR(40);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
DECLARE VARIABLE WCODEMPATUAL INTEGER;
DECLARE VARIABLE WRELCONTA INTEGER;
BEGIN
  -- sql referente as empresas selecionadas
  wsqlemp = 'select bdcodemp, bdcodmatriz, bdcodplapadrao,  bdcodcentros from vw_empresas_ref_atual where bdcodemp in ('||prcodemp||') order by bdcodmatriz,  bdcodemp';
  -- laco das empresas selecionadas
  wdatahora = CURRENT_TIMESTAMP;

  FOR EXECUTE STATEMENT wsqlemp
      INTO :wcodemp, :bdcodmatriz, :wcodplapadrao, :wcodcentros DO
      BEGIN
        -- retorna a primeira conta do ativo
        SELECT FIRST 1 planos_tpla.bdcodtpla, planos_tpla.bdctalon FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
        AND planos_tpla.bdctalon = :prctalonini
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini, :wctalonativo;

        -- retorna a primeira conta do passivo a descoberto
        SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
        AND planos_tpla.bdctalon = :prctalonpas
        ORDER BY planos_tpla.bdctalon ASC INTO :wctalonpatliq;

        -- retorna a ultima conta do resto do plano
        wsql = 'select first 1 planos_tpla.bdcodtpla from planos_tpla ';
        wsql = wsql||'where planos_tpla.bdcodplapadrao = '||wcodplapadrao;
        wsql = wsql||' and substring(planos_tpla.bdctalon from 1 for '||strlen(prctalonfin)||') = '''||prctalonfin||'''';
        wsql = wsql||'order by planos_tpla.bdctalon desc';
        EXECUTE STATEMENT wsql INTO :wcodctafin;

        -- sql responsavel pela limpeza da tabela cache de saldos
--        delete from VSUC_EMPRESAS_TBALANCETE;
        DELETE FROM VSUC_EMPRESAS_TBALANCETE_3 WHERE bdcodemp <> 0;
-- gilberto - 20/03/2015 - ALT:#9178 - alterado para calcular cc com rotina "VSUC_SP_RETORNA_SALDO_CONTAS_XZ"
        IF ((prlistacc IS NULL) OR (TRIM(prlistacc) = '')) THEN
           BEGIN
             FOR SELECT tsal.codemp, tsal.codplapadrao, tsal.conta, tsal.classificacao, tsal.nomeconta, tsal.tipconta,
                        tsal.saldo_anterior, tsal.saldo_ant_deb, tsal.saldo_ant_cre, tsal.saldo_atual, tsal.saldo_deb, tsal.saldo_cre,
                        tref.bdnomemp, temp.bdcnpjemp, tsal.formula, tsal.participante, tsal.GRUPOCONTA, tsal.apecta, tsal.pertenceconta, tsal.relconta
                 FROM VSUC_SP_RETORNA_SALDO_CONTAS_X(:wcodemp, :wcodctaini, :wcodctafin, :prdatini, :prdatfin, :prindice, :prignzer, :bdcodtpcc, :wcodplapadrao,0,
                                                     :prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                 LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.codemp)
                 LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                 WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                        WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                        AND tempresas_ref.bdrefemp <= :prrefemp
                                        ORDER BY tempresas_ref.bdrefemp DESC) --and
                       --((tsal.relconta = 0) or (tsal.relconta is null)) -- RelConta -> 0 - Balan?o Patrimonial | 1 - Demonstra??o de Resultado
                 INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                      :bdsalant, :bdsal_ant_deb, :bdsal_ant_cre, :bdsalatu, :bdsaldo_deb, :bdsaldo_cre,
                      :bdnomemp, :bdcnpjemp, :bdformula, :wparticipante, :bdgrpcta, :bdapecta, :BDPERTENCECONTA, :wrelconta DO
             BEGIN
               -- Sol. #3208 - Bruno Borges 08/05/2012

               --alt:11586 - Precisa retornar zero pra quando vai imprimir sem CC e as linhas de espa?o entre t?tulos. Como Null estava dando problema na ordena??o. Pedro
               bdcodtpcc = 0;

               bdcodempfilial = bdcodemp;

               SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
               IF (wpos <> 0) THEN
                  BEGIN
                    IF (bdcodmatriz IS NULL) THEN
                       bdcodmatriz = bdcodemp;

                    bdcodemp = bdcodmatriz;

                    --bdcodmatriz = bdcodemp;
                    --if (bdcodmatriz is null) then
                    --   bdcodmatriz = bdcodemp;

                    --bdcodemp = bdcodmatriz;
                  END
               -- Fim
               -- sql para verificar se a conta atual e uma titulo geral
               bdsalmov = bdsalatu - bdsalant;

               IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonativo)) = wctalonativo) THEN
                  bdseqcta = 'ATIVO';
               ELSE
                 IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonpatliq)) = wctalonpatliq) THEN
                   bdseqcta = 'PASSIVO A DESCOBERTO';
                 ELSE
                 --alt:7876 - Verifica o grupo da conta para saber se deve exibir ou excluir. (o que tem o "DEL" ? deletado pelo Delphi). Pedro
                 IF ((wrelconta = 0) OR (wrelconta IS NULL)) THEN
                    bdseqcta = 'X';
                 ELSE
                    bdseqcta = 'DEL';

               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                 BEGIN
                   --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                   FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                       --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta, -- alt:#6647 - gilberto - 12/09/2013
                       FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                            :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                       -- Fim
                       INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                       BEGIN
                         IF (prconcatenacodparticipante = 1) THEN
                           BEGIN
                             wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                        -- 100 -> m?ximo de caracteres para nome da conta
                                        -- 003 -> qtd de caracteres " - ";
                             wpos     = ((100 - wpos) - 3);
                             bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                           END

                         bdsalmov = bdsalatu - bdsalant;
                         SUSPEND;
                       END
                 END
               ELSE
                 BEGIN
                   -- gilberto
                   IF ((NOT prconsolidada IS NULL) AND (prconsolidada <> 0)) THEN
                     SUSPEND;
                   ELSE
                     BEGIN
                       SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                       IF ((wfind IS NULL) OR (wfind = 0)) THEN
                         SUSPEND;
                       ELSE
                         IF (bdtipcta = 2) THEN
                           SUSPEND;
                     END
                 END
             END
           END
        ELSE
           BEGIN
             FOR SELECT tsal.bdcodemp, tsal.bdcodplapadrao, tsal.bdconta, tsal.bdclassificacao, tsal.bdnomeconta, tsal.bdtipconta,
                        tsal.bdsaldo_anterior, tsal.bdsaldo_ant_deb, tsal.bdsaldo_ant_cre, tsal.bdsaldo_atual, tsal.bdsaldo_deb, tsal.bdsaldo_cre,
                        tref.bdnomemp, temp.bdcnpjemp, tsal.bdformula, tsal.bdparticipante, tsal.bdGRUPOCONTA, tsal.bdapecta, tsal.bdpertenceconta, tsal.bdrelconta,
                        COALESCE(tsal.bdcodtpcc, 0), tsal.bdnomtpcc, tref.bdcodcentros
                 FROM vsuc_sp_retorna_saldo_contas_xz(:wcodemp, :wcodctaini, :wcodctafin, :prdatini, :prdatfin, :prindice, :prignzer, :prlistacc, :wcodplapadrao,:prsemcc,
                                                      0, :prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                 LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.bdcodemp)
                 LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                 WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                        WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                        AND tempresas_ref.bdrefemp <= :prrefemp
                                        ORDER BY tempresas_ref.bdrefemp DESC) --and
                       --((tsal.relconta = 0) or (tsal.relconta is null)) -- RelConta -> 0 - Balan?o Patrimonial | 1 - Demonstra??o de Resultado
                 INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                      :bdsalant, :bdsal_ant_deb, :bdsal_ant_cre, :bdsalatu, :bdsaldo_deb, :bdsaldo_cre,
                      :bdnomemp, :bdcnpjemp, :bdformula, :wparticipante, :bdgrpcta, :bdapecta, :BDPERTENCECONTA, :wrelconta, :bdcodtpcc, :bdnomtpcc, :bdcodcentros DO
             BEGIN
               -- Sol. #3208 - Bruno Borges 08/05/2012

               bdcodempfilial = bdcodemp;

               SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
               IF (wpos <> 0) THEN
                  BEGIN
                    IF (bdcodmatriz IS NULL) THEN
                       bdcodmatriz = bdcodemp;

                    bdcodemp = bdcodmatriz;

                    --bdcodmatriz = bdcodemp;
                    --if (bdcodmatriz is null) then
                    --   bdcodmatriz = bdcodemp;

                    --bdcodemp = bdcodmatriz;
                  END
               -- Fim
               -- sql para verificar se a conta atual e uma titulo geral
               bdsalmov = bdsalatu - bdsalant;

               IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonativo)) = wctalonativo) THEN
                  bdseqcta = 'ATIVO';
               ELSE
                 IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonpatliq)) = wctalonpatliq) THEN
                   bdseqcta = 'PASSIVO A DESCOBERTO';
                 ELSE
                 --alt:7876 - Verifica o grupo da conta para saber se deve exibir ou excluir. (o que tem o "DEL" ? deletado pelo Delphi). Pedro
                 IF ((wrelconta = 0) OR (wrelconta IS NULL)) THEN
                    bdseqcta = 'X';
                 ELSE
                    bdseqcta = 'DEL';

               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                 BEGIN
                   --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                   FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                       --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta, -- alt:#6647 - gilberto - 12/09/2013
                       FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                            :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                       -- Fim
                       INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                       BEGIN
                         IF (prconcatenacodparticipante = 1) THEN
                           BEGIN
                             wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                        -- 100 -> m?ximo de caracteres para nome da conta
                                        -- 003 -> qtd de caracteres " - ";
                             wpos     = ((100 - wpos) - 3);
                             bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                           END

                         bdsalmov = bdsalatu - bdsalant;
                         SUSPEND;
                       END
                 END
               ELSE
                 BEGIN
                   -- gilberto
                   IF ((NOT prconsolidada IS NULL) AND (prconsolidada <> 0)) THEN
                     SUSPEND;
                   ELSE
                     BEGIN
                       SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                       IF ((wfind IS NULL) OR (wfind = 0)) THEN
                         SUSPEND;
                       ELSE
                         IF (bdtipcta = 2) THEN
                           SUSPEND;
                     END
                 END
             END
           END
      END
END
^

/* Restore proc. body: VSUC_SP_LISTA_CTA_RAZAO_VIDEO */
ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO(PRCODEMP VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRDATINI DATE,
PRDATFIM DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRTIPORAZAO INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDNOMCTA VARCHAR(100),
BDCTALON VARCHAR(40),
BDCODPARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(3000);
DECLARE VARIABLE wsql2 VARCHAR(3000);
DECLARE VARIABLE wsqlemp VARCHAR(3000);
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wsaldo_deb NUMERIC(15,2);
DECLARE VARIABLE wsaldo_cre NUMERIC(15,2);
DECLARE VARIABLE wnomcta VARCHAR(100);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wsomavlr NUMERIC(15,2);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wparticipante INTEGER;
DECLARE VARIABLE wcodempaux INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wcodcta INTEGER;
DECLARE VARIABLE wtipocta INTEGER;
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wsomavlraux NUMERIC(15,2);
DECLARE VARIABLE wempprinc INTEGER;
BEGIN
  -- Foi aleterado a rotina para melhorar o desempenho
  /*wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao ';
  wsql = wsql||'from planos_tpla tpla ';
  wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao) ';
  wsql = wsql||'where ';
  wsql = wsql||'tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and ((tpla.bdcodtpla = tlan.bddebito) or (tpla.bdcodtpla = tlan.bdcredito)) ';
  wsql = wsql||'and (tlan.bddata between '''||prdatini||''' and '''||prdatfim||''') ';
  wsql = wsql||'and tpla.bdcodtpla in (select tcta.bdcodtpla from planos_tpla tcta ';
  wsql = wsql||'                       where (tcta.bdcodplapadrao = tlan.bdcodplapadrao) and ';
  wsql = wsql||'                       (tcta.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''') ';
  if (prTipoRazao = 1) then
    begin
      wsql = wsql||' and ((((bdconcd = ''TRUE'') and (not bddebito is null)) and (tpla.bdcodtpla = tlan.bddebito)) ';
      wsql = wsql||' or (((BDCONCC = ''TRUE'') and (not bdcredito is null))) and (tpla.bdcodtpla = tlan.bdcredito)) ';
    end
  else
    if (prTipoRazao = 2) then
      begin
        wsql = wsql||' and ((((bdconcd is null) and (not bddebito is null)) and (tpla.bdcodtpla = tlan.bddebito)) ';
        wsql = wsql||' or (((BDCONCC is null) and (not bdcredito is null))) and (tpla.bdcodtpla = tlan.bdcredito)) ';
      end
  wsql = wsql||'                       order by tcta.bdctalon)';*/
  wdatini = SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 1 FOR 4);

  IF (prctalonini = prctalonfim) THEN
    BEGIN
      wsql = '';
      wsql = 'select tpla.bdcodtpla, tpla.bdnomcta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao from planos_tpla tpla ';
      --#alt:5619 - gilberto - 13/08/2013 ______________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta > 0)) THEN
         wsql = wsql||' inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      ---------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||' where (tpla.bdcodplapadrao = '||prcodplapadrao||') and (tpla.bdctalon between '''||prctalonini||''' and  '''||prctalonfim||''' )';
      FOR EXECUTE STATEMENT wsql INTO :bdcodtpla,:bdnomcta,:bdctalon,:wparticipante,:wcodplapadrao DO
      BEGIN
        -- retorna as empresas selecionadas
        wsqlemp = 'select temp.bdcodemp from tempresas temp ';
        wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
        wsqlemp = wsqlemp||'order by temp.bdcodemp';
        -- executa o sql das empresas
        FOR EXECUTE STATEMENT wsqlemp INTO :wcodemp DO
        BEGIN
          wsomavlr = 0;
          wsql2    = '';
          --#alt:5837
          /*wsql2    = 'Select Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' (bdcodemp = '||wcodemp||') and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' ((bddebito = '||bdcodtpla||') or (bdcredito = '||bdcodtpla||'))';
          if (prTipoRazao = 1) then
            begin
              wsql2 = wsql2||' and ((((Upper(bdconcd) = ''TRUE'') and (not bddebito is null)) and (bddebito = '||bdcodtpla||')) ';
              wsql2 = wsql2||' or   (((Upper(bdconcc)  = ''TRUE'') and (not bdcredito is null)) and (bdcredito = '||bdcodtpla||'))) ';
            end
          else
            if (prTipoRazao = 2) then
              begin
                wsql2 = wsql2||' and (((((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) and (not bddebito is null)) and (bddebito = '||bdcodtpla||')) ';
                wsql2 = wsql2||' or   ((((Upper(bdconcc) = ''FALSE'') or (bdconcc is null)) and (not bdcredito is null)) and (bdcredito = '||bdcodtpla||'))) ';
              end */
          --D?bito
          wsql2    = 'Select bdcodemp,bdfilial,bdtipolancfilial,bddebito, 1 as bdtipcta, Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' ((bdcodemp = '||wcodemp||') or (bdfilial = '||wcodemp||')) and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' (bddebito = '||bdcodtpla||') ';
          --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
          IF (prcontabilizacao <> 99) THEN
            wsql2    = wsql2||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';
          IF (prTipoRazao = 1) THEN
            wsql2 = wsql2||' and (Upper(bdconcd) = ''TRUE'') ';
          ELSE
          IF (prTipoRazao = 2) THEN
            wsql2 = wsql2||' and ((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) ';
          wsql2 = wsql2||'Group By bdcodemp,bdfilial,bdtipolancfilial,bddebito ';

          wsql2 = wsql2||'union all ';
          --Cr?dito
          wsql2    = wsql2||'Select bdcodemp,bdfilial,bdtipolancfilial,bdcredito, 2 as bdtipcta, Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' ((bdcodemp = '||wcodemp||') or (bdfilial = '||wcodemp||')) and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' (bdcredito = '||bdcodtpla||') ';
          --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
          IF (prcontabilizacao <> 99) THEN
            wsql2    = wsql2||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';
          IF (prTipoRazao = 1) THEN
            wsql2 = wsql2||' and (Upper(bdconcc) = ''TRUE'') ';
          ELSE
          IF (prTipoRazao = 2) THEN
            wsql2 = wsql2||' and ((Upper(bdconcc) = ''FALSE'') or (bdconcd is null)) ';
          wsql2 = wsql2||'Group By bdcodemp,bdfilial,bdtipolancfilial,bdcredito ';
          --#alt:5837
          --execute statement wsql2 into :wsomavlr;
          FOR EXECUTE STATEMENT wsql2 INTO :wcodempaux,:wfilial,:wtipolancfilial,:wcodcta,:wtipocta,:wsomavlraux DO
            BEGIN
              SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipocta,:wcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
              IF (wpermite = 1) THEN
                wsomavlr = wsomavlr + wsomavlraux;
            END

          IF (wsomavlr > 0) THEN
            BEGIN
              -- Detalhado por participante
              IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN--#alt:6309
                BEGIN
                  FOR SELECT tctapar.bdnome, tctapar.bdclassificacao, tctapar.bdcodparticipante, tctapar.bdsaldo_deb, tctapar.bdsaldo_cre
                  --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,0,0,0, -- alt:#6647 - gilberto - 12/09/2013
                  FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,0,0,0,0,
                                                       :prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tctapar
                  INTO :wnomcta, :bdctalon, :bdcodparticipante,:wsaldo_deb,:wsaldo_cre  DO
                    BEGIN
                      IF ((wsaldo_deb <> 0) OR (wsaldo_cre <> 0))  THEN
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:bdcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 003 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              bdnomcta = bdcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                            END
                          SUSPEND;
                        END
                    END
                END
--              else
                SUSPEND;
            END
        END
      END
    END
  ELSE
    BEGIN
      wcodempaux = 0;
      wcodcta    = 0;

      wsql = '';
      --#alt:5837
      /*wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'(tlan.bdcodemp in ('||prcodemp||')) and ';
      wsql = wsql||'((tpla.bdcodtpla = tlan.bddebito) or (tpla.bdcodtpla = tlan.bdcredito)) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';*/
/*
      wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) and ';
      wsql = wsql||'(tpla.bdcodtpla = tlan.bddebito) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';
*/
      wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'       tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')) ';
      --#alt:5619 - gilberto - 13/08/2013 _____________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta <> 0)) THEN
         wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      --------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||'where ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';
      wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
         wsql = wsql||' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';
      wsql = wsql||' union all ';
/*
      wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 2 as bdtipolanc ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) and ';
      wsql = wsql||'(tpla.bdcodtpla = tlan.bdcredito) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';
*/
      wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'       tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')) ';
      --#alt:5619 - gilberto - 13/08/2013 _____________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta <> 0)) THEN
         wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      --------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||'where ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';
      wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql = wsql||' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';

      --Retorna a empresa principal
      SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
      IF (wpos = 0) THEN
        wempprinc = prcodemp;
      ELSE
        wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

      FOR EXECUTE STATEMENT wsql
      INTO :bdcodtpla,:bdnomcta,:bdctalon,:wparticipante,:wcodplapadrao,:wcodemp,:wfilial,:wtipolancfilial,:wtipocta DO
      BEGIN
        IF ((wcodemp <> wcodempaux) OR (bdcodtpla <> wcodcta)) THEN
          BEGIN
            -- Detalhado por participante
            IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN
              BEGIN
                FOR SELECT tctapar.bdnome, tctapar.bdclassificacao, tctapar.bdcodparticipante, tctapar.bdsaldo_deb, tctapar.bdsaldo_cre
                    --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla, -- alt:#6647 - gilberto - 12/09/2013
                    FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,
                                                         0,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tctapar
                INTO :wnomcta, :bdctalon, :bdcodparticipante,:wsaldo_deb,:wsaldo_cre  DO
                BEGIN
                  IF ((wsaldo_deb <> 0) OR (wsaldo_cre <> 0))  THEN
                    BEGIN
                      IF (prconcatenacodparticipante = 1) THEN
                        BEGIN
                          wpos     = CHARACTER_LENGTH(:bdcodparticipante);
                                     -- 100 -> m?ximo de caracteres para nome da conta
                                     -- 003 -> qtd de caracteres " - ";
                          wpos     = ((100 - wpos) - 3);
                          bdnomcta = bdcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                        END
                      SUSPEND;
                      wcodempaux = wcodemp;
                      wcodcta    = bdcodtpla;
                    END
                END
              END
            ELSE
              BEGIN
                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipocta,:wempprinc,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  SUSPEND;
                wcodempaux = wcodemp;
                wcodcta    = bdcodtpla;
              END
          END
      END
    END
END
^

/* Restore proc. body: VSUC_SP_MOVIMENTO_MENSAL */
ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRCC VARCHAR(5000),
PRANOINICIAL INTEGER,
PRANOFINAL INTEGER,
PRREFEMP INTEGER,
PRPARTICIPANTE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDDEB01 NUMERIC(15,2),
BDDEB02 NUMERIC(15,2),
BDDEB03 NUMERIC(15,2),
BDDEB04 NUMERIC(15,2),
BDDEB05 NUMERIC(15,2),
BDDEB06 NUMERIC(15,2),
BDDEB07 NUMERIC(15,2),
BDDEB08 NUMERIC(15,2),
BDDEB09 NUMERIC(15,2),
BDDEB10 NUMERIC(15,2),
BDDEB11 NUMERIC(15,2),
BDDEB12 NUMERIC(15,2),
BDCRE01 NUMERIC(15,2),
BDCRE02 NUMERIC(15,2),
BDCRE03 NUMERIC(15,2),
BDCRE04 NUMERIC(15,2),
BDCRE05 NUMERIC(15,2),
BDCRE06 NUMERIC(15,2),
BDCRE07 NUMERIC(15,2),
BDCRE08 NUMERIC(15,2),
BDCRE09 NUMERIC(15,2),
BDCRE10 NUMERIC(15,2),
BDCRE11 NUMERIC(15,2),
BDCRE12 NUMERIC(15,2),
BDMOV01 NUMERIC(15,2),
BDMOV02 NUMERIC(15,2),
BDMOV03 NUMERIC(15,2),
BDMOV04 NUMERIC(15,2),
BDMOV05 NUMERIC(15,2),
BDMOV06 NUMERIC(15,2),
BDMOV07 NUMERIC(15,2),
BDMOV08 NUMERIC(15,2),
BDMOV09 NUMERIC(15,2),
BDMOV10 NUMERIC(15,2),
BDMOV11 NUMERIC(15,2),
BDMOV12 NUMERIC(15,2),
BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2),
BDSALTOTDEB NUMERIC(15,2),
BDSALTOTCRE NUMERIC(15,2),
BDSALTOTMOV NUMERIC(15,2),
BDSALTOTATU NUMERIC(15,2),
BDANO INTEGER,
BDGRPCTA INTEGER,
BDDEBANT NUMERIC(15,2),
BDCREANT NUMERIC(15,2),
BDMOVANT NUMERIC(15,2),
BDSALANT NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WBDSALTOTDEB NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTCRE NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTMOV NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTATU NUMERIC(15,2);
DECLARE VARIABLE WBDDEBANT NUMERIC(15,2);
DECLARE VARIABLE WBDCREANT NUMERIC(15,2);
DECLARE VARIABLE WBDSALANT NUMERIC(15,2);
DECLARE VARIABLE WBDDEB01 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB02 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB03 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB04 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB05 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB06 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB07 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB08 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB09 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB10 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB11 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB12 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE01 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE02 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE03 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE04 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE05 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE06 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE07 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE08 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE09 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE10 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE11 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE12 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV01 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV02 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV03 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV04 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV05 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV06 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV07 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV08 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV09 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV10 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV11 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV12 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL01 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL02 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL03 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL04 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL05 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL06 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL07 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL08 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL09 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL10 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL11 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL12 NUMERIC(15,2);
BEGIN
  wcount = 0;
  WHILE (wcount <= pranofinal - pranoinicial) DO
    BEGIN
      BDANO = :pranoinicial + :wcount;
      --Precisa zerar o valores para n?o interferir nos valores dos pr?ximos anos
      bdsaltotdeb = 0;
      bdsaltotcre = 0;
      bdsaltotmov = 0;
      bdsaltotatu = 0;
      bddebant    = 0;
      bdcreant    = 0;
      bdmovant    = 0;
      bdsalant    = 0;

      bddeb01 = 0;
      bddeb02 = 0;
      bddeb03 = 0;
      bddeb04 = 0;
      bddeb05 = 0;
      bddeb06 = 0;
      bddeb07 = 0;
      bddeb08 = 0;
      bddeb09 = 0;
      bddeb10 = 0;
      bddeb11 = 0;
      bddeb12 = 0;

      bdcre01 = 0;
      bdcre02 = 0;
      bdcre03 = 0;
      bdcre04 = 0;
      bdcre05 = 0;
      bdcre06 = 0;
      bdcre07 = 0;
      bdcre08 = 0;
      bdcre09 = 0;
      bdcre10 = 0;
      bdcre11 = 0;
      bdcre12 = 0;

      --alt:9515 - Adicionado campo do movimento. Pedro
      bdmov01 = 0;
      bdmov02 = 0;
      bdmov03 = 0;
      bdmov04 = 0;
      bdmov05 = 0;
      bdmov06 = 0;
      bdmov07 = 0;
      bdmov08 = 0;
      bdmov09 = 0;
      bdmov10 = 0;
      bdmov11 = 0;
      bdmov12 = 0;

      bdsal01 = 0;
      bdsal02 = 0;
      bdsal03 = 0;
      bdsal04 = 0;
      bdsal05 = 0;
      bdsal06 = 0;
      bdsal07 = 0;
      bdsal08 = 0;
      bdsal09 = 0;
      bdsal10 = 0;
      bdsal11 = 0;
      bdsal12 = 0;

      wsql = 'select bdcodemp from tempresas where bdcodemp in ('||prcodemp||')';
      FOR EXECUTE STATEMENT wsql INTO :wcodemp DO
          BEGIN
            SELECT bdano, bdgrpcta, bdsaltotdeb, bdsaltotcre, bdsaltotmov, bdsaltotatu, bddebant, bdcreant, bdsalant,
                   bddeb01, bddeb02, bddeb03, bddeb04, bddeb05, bddeb06, bddeb07, bddeb08, bddeb09, bddeb10, bddeb11, bddeb12,
                   bdcre01, bdcre02, bdcre03, bdcre04, bdcre05, bdcre06, bdcre07, bdcre08, bdcre09, bdcre10, bdcre11, bdcre12,
                   bdmov01, bdmov02, bdmov03, bdmov04, bdmov05, bdmov06, bdmov07, bdmov08, bdmov09, bdmov10, bdmov11, bdmov12,
                   bdsal01, bdsal02, bdsal03, bdsal04, bdsal05, bdsal06, bdsal07, bdsal08, bdsal09, bdsal10, bdsal11, bdsal12
            FROM vsuc_sp_retorna_mov_mensal(:wcodemp, :prconta, :prcc, :bdano, :bdano, :prrefemp, :prparticipante, :prignorazeramento,:prcontabilizacao,:prmatrizfilialconsolidado)
            INTO :bdano, :bdgrpcta, :wbdsaltotdeb, :wbdsaltotcre, :wbdsaltotmov, :wbdsaltotatu, :wbddebant, :wbdcreant, :wbdsalant,
                 :wbddeb01, :wbddeb02, :wbddeb03, :wbddeb04, :wbddeb05, :wbddeb06, :wbddeb07, :wbddeb08, :wbddeb09, :wbddeb10, :wbddeb11, :wbddeb12,
                 :wbdcre01, :wbdcre02, :wbdcre03, :wbdcre04, :wbdcre05, :wbdcre06, :wbdcre07, :wbdcre08, :wbdcre09, :wbdcre10, :wbdcre11, :wbdcre12,
                 :wbdmov01, :wbdmov02, :wbdmov03, :wbdmov04, :wbdmov05, :wbdmov06, :wbdmov07, :wbdmov08, :wbdmov09, :wbdmov10, :wbdmov11, :wbdmov12,
                 :wbdsal01, :wbdsal02, :wbdsal03, :wbdsal04, :wbdsal05, :wbdsal06, :wbdsal07, :wbdsal08, :wbdsal09, :wbdsal10, :wbdsal11, :wbdsal12;

            bdsaltotdeb = COALESCE(bdsaltotdeb, 0) + COALESCE(wbdsaltotdeb, 0);
            bdsaltotcre = COALESCE(bdsaltotcre, 0) + COALESCE(wbdsaltotcre, 0);
            bdsaltotatu = COALESCE(bdsaltotatu, 0) + COALESCE(wbdsaltotatu, 0);
            bdsaltotmov = COALESCE(bdsaltotmov, 0) + COALESCE(wbdsaltotmov, 0);
            bddebant    = COALESCE(bddebant, 0) + COALESCE(wbddebant, 0);
            bdcreant    = COALESCE(bdcreant, 0) + COALESCE(wbdcreant, 0);
            bdsalant    = COALESCE(bdsalant, 0) + COALESCE(wbdsalant, 0);

            bddeb01 = COALESCE(bddeb01, 0) + COALESCE(wbddeb01, 0);
            bddeb02 = COALESCE(bddeb02, 0) + COALESCE(wbddeb02, 0);
            bddeb03 = COALESCE(bddeb03, 0) + COALESCE(wbddeb03, 0);
            bddeb04 = COALESCE(bddeb04, 0) + COALESCE(wbddeb04, 0);
            bddeb05 = COALESCE(bddeb05, 0) + COALESCE(wbddeb05, 0);
            bddeb06 = COALESCE(bddeb06, 0) + COALESCE(wbddeb06, 0);
            bddeb07 = COALESCE(bddeb07, 0) + COALESCE(wbddeb07, 0);
            bddeb08 = COALESCE(bddeb08, 0) + COALESCE(wbddeb08, 0);
            bddeb09 = COALESCE(bddeb09, 0) + COALESCE(wbddeb09, 0);
            bddeb10 = COALESCE(bddeb10, 0) + COALESCE(wbddeb10, 0);
            bddeb11 = COALESCE(bddeb11, 0) + COALESCE(wbddeb11, 0);
            bddeb12 = COALESCE(bddeb12, 0) + COALESCE(wbddeb12, 0);

            bdcre01 = COALESCE(bdcre01, 0) + COALESCE(wbdcre01, 0);
            bdcre02 = COALESCE(bdcre02, 0) + COALESCE(wbdcre02, 0);
            bdcre03 = COALESCE(bdcre03, 0) + COALESCE(wbdcre03, 0);
            bdcre04 = COALESCE(bdcre04, 0) + COALESCE(wbdcre04, 0);
            bdcre05 = COALESCE(bdcre05, 0) + COALESCE(wbdcre05, 0);
            bdcre06 = COALESCE(bdcre06, 0) + COALESCE(wbdcre06, 0);
            bdcre07 = COALESCE(bdcre07, 0) + COALESCE(wbdcre07, 0);
            bdcre08 = COALESCE(bdcre08, 0) + COALESCE(wbdcre08, 0);
            bdcre09 = COALESCE(bdcre09, 0) + COALESCE(wbdcre09, 0);
            bdcre10 = COALESCE(bdcre10, 0) + COALESCE(wbdcre10, 0);
            bdcre11 = COALESCE(bdcre11, 0) + COALESCE(wbdcre11, 0);
            bdcre12 = COALESCE(bdcre12, 0) + COALESCE(wbdcre12, 0);

            --alt:9515 - Adicionados campos do movimento. Pedro
            bdmov01 = COALESCE(bdmov01, 0) + COALESCE(wbdmov01, 0);
            bdmov02 = COALESCE(bdmov02, 0) + COALESCE(wbdmov02, 0);
            bdmov03 = COALESCE(bdmov03, 0) + COALESCE(wbdmov03, 0);
            bdmov04 = COALESCE(bdmov04, 0) + COALESCE(wbdmov04, 0);
            bdmov05 = COALESCE(bdmov05, 0) + COALESCE(wbdmov05, 0);
            bdmov06 = COALESCE(bdmov06, 0) + COALESCE(wbdmov06, 0);
            bdmov07 = COALESCE(bdmov07, 0) + COALESCE(wbdmov07, 0);
            bdmov08 = COALESCE(bdmov08, 0) + COALESCE(wbdmov08, 0);
            bdmov09 = COALESCE(bdmov09, 0) + COALESCE(wbdmov09, 0);
            bdmov10 = COALESCE(bdmov10, 0) + COALESCE(wbdmov10, 0);
            bdmov11 = COALESCE(bdmov11, 0) + COALESCE(wbdmov11, 0);
            bdmov12 = COALESCE(bdmov12, 0) + COALESCE(wbdmov12, 0);

            bdsal01 = COALESCE(bdsal01, 0) + COALESCE(wbdsal01, 0);
            bdsal02 = COALESCE(bdsal02, 0) + COALESCE(wbdsal02, 0);
            bdsal03 = COALESCE(bdsal03, 0) + COALESCE(wbdsal03, 0);
            bdsal04 = COALESCE(bdsal04, 0) + COALESCE(wbdsal04, 0);
            bdsal05 = COALESCE(bdsal05, 0) + COALESCE(wbdsal05, 0);
            bdsal06 = COALESCE(bdsal06, 0) + COALESCE(wbdsal06, 0);
            bdsal07 = COALESCE(bdsal07, 0) + COALESCE(wbdsal07, 0);
            bdsal08 = COALESCE(bdsal08, 0) + COALESCE(wbdsal08, 0);
            bdsal09 = COALESCE(bdsal09, 0) + COALESCE(wbdsal09, 0);
            bdsal10 = COALESCE(bdsal10, 0) + COALESCE(wbdsal10, 0);
            bdsal11 = COALESCE(bdsal11, 0) + COALESCE(wbdsal11, 0);
            bdsal12 = COALESCE(bdsal12, 0) + COALESCE(wbdsal12, 0);
          END

      wcount = wcount + 1;
      SUSPEND;
    END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_BALANCETE */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRORDEM INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDRE INTEGER = 0,
PRTODOPLANOCONTAS INTEGER = 0,
PRDETALHAREMPREENDIMENTO INTEGER = 0,
PRDETALHARUNIDIMOB INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDCODTER INTEGER,
BDAPECTA VARCHAR(20),
BDSALDO_ANTERIOR_DRE NUMERIC(15,2),
BDSALDO_ANT_DEB_DRE NUMERIC(15,2),
BDSALDO_ANT_CRE_DRE NUMERIC(15,2),
BDRAIZCNPJPARTICIPANTE VARCHAR(10),
BDRAIZCLASSIFICACAOCTA VARCHAR(40))
 AS
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WSALDO_ANT_DEB NUMERIC(15,2);
DECLARE VARIABLE WSALDO_DEB NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_CRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ATUAL NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCLANOM VARCHAR(140);
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WGRPCTA SMALLINT;
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
DECLARE VARIABLE WSALDO_ANTERIOR_DRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_DEB_DRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_CRE_DRE NUMERIC(15,2);
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCODTPCCANT INTEGER;
DECLARE VARIABLE WNOMTPCC VARCHAR(40);
DECLARE VARIABLE WTPCCLON VARCHAR(20);
declare variable WCODEMPREENDIMENTO integer;
declare variable WCODUNIDIMOB integer;
declare variable WDESCEMPREENDIMENTO varchar(500);
declare variable WDESCUNIDIMOB varchar(500);
declare variable WCADINCORP integer;
declare variable WRAIZCTASEMEMPREENDIMENTO varchar(40);
declare variable WRAIZCTASEMEMPREENDIMENTOANT varchar(40);
BEGIN
-- select * from VSUC_SP_RETORNA_BALANCETE('13,14', '01/01/2015', '12/31/2015', 0, 19, 35, '', 201204, 0, 0,1, 1, 0,'1,2,3,4') order by bdcodtpcc, bdctalon
  DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
  -- retorna as empresas selecionadas
  wsql = 'select case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  wpos = POSITION(',', :prcodemp);
  IF (wpos <> 0) THEN
     wsql = wsql||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsql = wsql||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsql = wsql||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsql = wsql||'       end bdcodemp, ';
  wsql = wsql||'       temp.bdcodemp bdcodempfilial, ';
  wsql = wsql||'       tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  wdatahora = CURRENT_TIMESTAMP;
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        bdcodter = 0;
        wcadincorp = 0;
        -- delete from vsuc_empresas_tbalancete where bdcodemp <> 0;
        -- verifica se existe centro de custo selecionado
        IF (prcodtpcc = '') THEN
           BEGIN
             bdcodtpcc = 0;
             bdnomtpcc = '';
             bdtpcclon = '';


             --#alt:11436 - Adiconado controle para o parametro de imprimir o plano de contas completo PRTODOPLANOCONTAS. Ana - 15/12/2016
             -- retorna todas as contas do plano de contas sem o centro de custo
             FOR SELECT tsalcta.conta, tsalcta.classificacao, tsalcta.nomeconta, tsalcta.tipconta, tsalcta.GRUPOCONTA,
                        tsalcta.saldo_ant_deb, tsalcta.saldo_ant_cre, tsalcta.saldo_deb,
                        tsalcta.saldo_cre, tsalcta.saldo_atual,
                        tsalcta.saldo_anterior, tsalcta.formula, tsalcta.relconta, tsalcta.clanom, tsalcta.participante, tsalcta.apecta,
                        tsalcta.saldo_ant_deb_dre, tsalcta.saldo_ant_cre_dre, tsalcta.saldo_anterior_dre
                 FROM vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prindice, :prignora_zeramento, 0, :bdcodplapadrao,:prlansemcc,
                                                     :prnaomostracontacomp,:prconsolidada,:prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,:prdre, :prtodoplanocontas) tsalcta
                 INTO :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta, :bdgrpcta,
                      :bdsaldo_ant_deb, :bdsaldo_ant_cre, :bdsaldo_deb, :bdsaldo_cre, :bdsaldo_atual,
                      :bdsaldo_anterior, :bdformula, :bdrelcta, :bdclanom, :wparticipante, :bdapecta,
                      :bdsaldo_ant_deb_dre, :bdsaldo_ant_cre_dre, :bdsaldo_anterior_dre DO
                 BEGIN
                   -- Detalhado por participante
                   IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                     BEGIN
--                       delete from vsuc_empresas_tbalancete_2 tbalan where tbalan.bdcodemp = :bdcodempfilial and tbalan.bddatahora = :wdatahora and tbalan.bdcodtpla = :bdcodcta;
                       --delete from vsuc_empresas_tbalancete_3 tbalan where tbalan.bdcodemp = :bdcodempfilial and tbalan.bdcodtpla = :bdcodcta;


                       FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_deb, tsalctapar.bdsaldo_ant_deb,
                                  tsalctapar.bdsaldo_cre, tsalctapar.bdsaldo_ant_cre, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdmovimento,
                                  tsalctapar.bdcodparticipante, tsalctapar.bdraizcnpjparticipante, tsalctapar.bdraizclassificacaocta
                           --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           --from vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           --                                     :prignora_zeramento,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tsalctapar
                           --alt:9167 - Adicionado par?metro para agrupar participantes por CNPJ. Pedro
                           FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                           INTO :bdnomcta, :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                :wcodparticipante, :bdraizcnpjparticipante, :bdraizclassificacaocta DO
                           BEGIN

                             bdcodter = :wcodparticipante;
                             bdclanom = SUBSTRING(bdctalon FROM 1 FOR strlen(bdctalon)-10)||' '||bdnomcta;
                             SUSPEND;
                           END

                     END
                   ELSE
                     BEGIN
                       --Detalhado por incorporadora
                       if ((prdetalharempreendimento = 1) or (prdetalharunidimob = 1)) then
                         BEGIN
                           wcadincorp = 0;
                           wnomcta = bdnomcta;
                           if (wctalonant is null) then
                             wctalonant = bdctalon;

                           FOR SELECT tsalctaincorp.bdclassificacao, tsalctaincorp.bdsaldo_deb, tsalctaincorp.bdsaldo_ant_deb, tsalctaincorp.bdsaldo_cre, tsalctaincorp.bdsaldo_ant_cre,
                                  tsalctaincorp.bdsaldo_atual, tsalctaincorp.bdsaldo_anterior, tsalctaincorp.bdmovimento, tsalctaincorp.bdcodempreendimento, tsalctaincorp.bdcodunidimob,
                                  tsalctaincorp.bddescempreendimento, tsalctaincorp.bddescunidimob, tsalctaincorp.bdraizclassificacaocta, tsalctaincorp.BDRAIZCTASEMEMPREENDIMENTO
                               FROM VSUC_SP_RETORNA_SALDOS_CTAINCOR(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                    0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :wctalonant, :bdtipcta, :wraizctasemempreendimentoant,
                                                                    :prdetalharempreendimento, :prdetalharunidimob) tsalctaincorp
                               INTO :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                    :wcodempreendimento, :wcodunidimob,:wdescempreendimento, :wdescunidimob, :bdraizclassificacaocta, :WRAIZCTASEMEMPREENDIMENTO DO
                               BEGIN
                                 if ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) then
                                   bdnomcta = bdnomcta||' ('||wdescempreendimento||')';

                                 if (wcodunidimob IS NOT NULL) then
                                   bdnomcta = bdnomcta||' ('||wdescunidimob||')';

                                 if (wraizctasemempreendimento IS NOT NULL) then
                                   wraizctasemempreendimentoant = wraizctasemempreendimento;

                             SUSPEND;

                                 wcadincorp = 1;
                                 bdnomcta = wnomcta;
                           END
                         END

                       bdcodter = 0;
                       bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                       --#Alt:19049
                       bdraizcnpjparticipante = '';
                       --#alt:20415. Ana - 22/09/2017
                       bdraizclassificacaocta = '';

                       --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
                       --#alt:11436 - Adicionada condi??o do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
                       --alt:7847 - Trocada a verifica??o, s? imprime se tiver movimento ou se estiver marcado para imprimir contas sem movimento. Pedro
                       --ALT:8067 - Adicionada exce??o para retornar contas t?tulo, mesmo zeradas, porque quando a anal?tica dela for uma f?rmula elas sempre retornar?o zeradas do banco. Pedro                       
                       IF ((wcadincorp = 0 ) and
                          ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                           (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                           (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                           (PRTODASASCONTAS = 1) OR (BDTIPCTA = 0) OR (bdformula <> '') OR (prtodoplanocontas = 1))) THEN
                           BEGIN
                             SUSPEND;
                           END

                     END

                     if (bdtipcta = 0) then
                       wctalonant = bdctalon;
                 END
           END
        ELSE
           BEGIN
             bdcodter = 0;
             -- retorna a conta longa da conta inicial
             SELECT tpla.bdctalon FROM planos_tpla tpla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :prctaini
             INTO :wctalonant;
             -- inicializa as variaveis
             bdsaldo_ant_cre = 0;
             bdsaldo_ant_deb = 0;
             bdsaldo_cre = 0;
             bdsaldo_deb = 0;
             bdsaldo_anterior = 0;
             bdsaldo_atual = 0;

             --#alt:17388 - Removi o campo bdformula do retorno, pois estava duplicado e atribuia direto pro return deixando o retorno com valor incorreto. Ana - 23/01/2018
             FOR SELECT bdconta, bdclassificacao, bdnomeconta, bdtipconta, BDGRUPOCONTA,
                        bdsaldo_ant_deb, bdsaldo_ant_cre, bdsaldo_deb,
                        bdsaldo_cre, bdsaldo_atual, bdsaldo_anterior,
                        bdformula, bdrelconta, bdclanom, /*bdformula,*/ bdapecta,
                        bdsaldo_ant_deb_dre, bdsaldo_ant_cre_dre, bdsaldo_anterior_dre,
                        bdcodtpcc, bdnomtpcc, bdtpcclon
                        FROM vsuc_sp_retorna_saldo_contas_xz(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prindice, :prignora_zeramento, :prcodtpcc,
                                                            :bdcodplapadrao, :prlansemcc, :prordem, :prnaomostracontacomp, :prconsolidada, :prniveisconta,
                                                            :prcontabilizacao, :prmatrizfilialconsolidado, :prdre) tsalcta
                        INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta,
                             :wsaldo_ant_deb, :wsaldo_ant_cre, :wsaldo_deb,
                             :wsaldo_cre, :wsaldo_atual, :wsaldo_anterior,
                             :wformula, :bdrelcta, :wclanom, /*:bdformula,*/ :bdapecta,
                             :wsaldo_ant_deb_dre, :wsaldo_ant_cre_dre, :wsaldo_anterior_dre,
                             :wcodtpcc, :wnomtpcc, :wtpcclon DO
                      BEGIN
                         --alt:9381 - Quando for nullo troca para zero, sen?o n?o consegue totalizar
                         --corretamente por centro de custo onde for sem centro de custos. Pedro
                         IF (wcodtpcc IS NULL) THEN
                           wcodtpcc = 0;

                         --#Alt:19049
                         bdraizcnpjparticipante = '';
                         --#alt:20416. Ana - 22/09/2017
                         bdraizclassificacaocta = '';

                         --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
                         --#alt:11436 - Adicionada condição do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
                         IF ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                             (BDTIPCTA = 0) OR (bdformula <> '') OR  (prtodoplanocontas = 1)) THEN
                             BEGIN
                               IF ((wctalonant <> wctalon) OR (COALESCE(wcodtpccant, 0) <> COALESCE(wcodtpcc, 0))) THEN
                                  SUSPEND;

                               bdcodcta  = wconta;
                               bdctalon  = wctalon;
                               bdnomcta  = wnomcta;
                               bdtipcta  = wtipcta;
                               bdclanom  = wclanom;
                               bdgrpcta  = wgrpcta;
                               bdformula = wformula;
                               bdcodtpcc = wcodtpcc;
                               bdnomtpcc = wnomtpcc;
                               bdtpcclon = wtpcclon;
 
                               bdsaldo_ant_cre = wsaldo_ant_cre;
                               bdsaldo_ant_deb = wsaldo_ant_deb;
                               bdsaldo_cre = wsaldo_cre;
                               bdsaldo_deb = wsaldo_deb;
                               bdsaldo_anterior = wsaldo_anterior;
                               bdsaldo_atual = wsaldo_atual;

                               --alt:9179 - N?o estava imprimindo o BDMOVIMENTO para os centros de custos. Pedro
                               bdmovimento = bdsaldo_atual - bdsaldo_anterior;
 
                               bdsaldo_ant_cre_dre = wsaldo_ant_cre_dre;
                               bdsaldo_ant_deb_dre = wsaldo_ant_deb_dre;
                               bdsaldo_anterior_dre = wsaldo_anterior_dre;
                             END
                         ELSE
                             BEGIN
                               bdcodcta  = wconta;
                               bdctalon  = wctalon;
                               bdnomcta  = wnomcta;
                               bdtipcta  = wtipcta;
                               bdclanom  = wclanom;
                               bdgrpcta  = wgrpcta;
                               bdformula = wformula;
                               bdcodtpcc = wcodtpcc;
                               bdnomtpcc = wnomtpcc;
                               bdtpcclon = wtpcclon;

                               bdsaldo_ant_cre = bdsaldo_ant_cre + wsaldo_ant_cre;
                               bdsaldo_ant_deb = bdsaldo_ant_deb + wsaldo_ant_deb;
                               bdsaldo_cre = bdsaldo_cre + wsaldo_cre;
                               bdsaldo_deb = bdsaldo_deb + wsaldo_deb;
                               bdsaldo_anterior = bdsaldo_anterior + wsaldo_anterior;
                               bdsaldo_atual = bdsaldo_atual + wsaldo_atual;

                               --alt:9179 - N?o estava imprimindo o BDMOVIMENTO para os centros de custos. Pedro
                               bdmovimento = bdsaldo_atual - bdsaldo_anterior;
 
                               bdsaldo_ant_cre_dre = bdsaldo_ant_cre_dre + wsaldo_ant_cre_dre;
                               bdsaldo_ant_deb_dre = bdsaldo_ant_deb_dre + wsaldo_ant_deb_dre;
                               bdsaldo_anterior_dre = bdsaldo_anterior_dre + wsaldo_anterior_dre;
                            END
                         wctalonant = wctalon;
                         wcodtpccant = wcodtpcc;
                      END

             --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
             --#alt:11436 - Adicionada condição do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
             --alt:9386 - Adicionado esse suspend porque se ele soma centros de custos iguais, o ?ltimo n?o ? impresso. Pedro
             IF ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                 (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                 (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR (BDTIPCTA = 0) OR (bdformula <> '') OR (prtodoplanocontas = 1)) THEN
                   SUSPEND;
             --alt:9386 - Fim

           END

--        delete from vsuc_empresas_tbalancete_2 where bdcodemp <> 0 and bddatahora = :wdatahora;
        DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;

      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_BALANCO_PATRIMO */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRIMO(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRCTASEMMOV INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDANAVER NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20))
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(4096);
DECLARE VARIABLE WLENGTH INTEGER;
DECLARE VARIABLE WVALTIT NUMERIC(15,2);
DECLARE VARIABLE WSQLTCC VARCHAR(1024);
DECLARE VARIABLE WSEQCTA VARCHAR(100);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
BEGIN
  wsqlemp = 'select case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos <> 0) THEN
     wsqlemp = wsqlemp||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsqlemp = wsqlemp||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsqlemp = wsqlemp||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsqlemp = wsqlemp||'       end bdcodemp, ';
  wsqlemp = wsqlemp||'       temp.bdcodemp bdcodempfilial, ';
  wsqlemp = wsqlemp||'       tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';

  wdatahora = CURRENT_TIMESTAMP;

  FOR EXECUTE STATEMENT wsqlemp
--      into :wcodemp, :bdcodmatriz, :wcodplapadrao, :wcodcentros do
      INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        IF (bdcodmatriz IS NULL) THEN
           bdcodmatriz = 0;
        -- retorna a primeira conta referente a classificacao
        SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :bdcodplapadrao
        AND planos_tpla.bdctalon = :prctalonini
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini;
        -- retorna a ultima conta referente a classificacao
        SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :bdcodplapadrao
        AND planos_tpla.bdctalon = :prctalonfin
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctafin;
        -- sql responsavel pela limpeza da tabela cache de saldos
        --delete from VSUC_EMPRESAS_TBALANCETE_2; Fabiano: 23/05/2012 N?o pode apagar tudo porque tem outros usu?rios que est?o comitando dados. S? posso apagar o que ? meu.
--        delete from vsuc_empresas_tbalancete_2 where bdcodemp <> 0 and bddatahora = :wdatahora;
        DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
        -- verificacao dos centro de custos selecionados
        IF ((TRIM(prlistacc) <> '') AND (wcodcentros IS NOT NULL)) THEN
           BEGIN
             wsqltcc = 'select tpcc.bdcodtpcc, tpcc.bdnomcta from centros_tpcc tpcc ';
             wsqltcc = wsqltcc||'where tpcc.bdcodcentro = '||wcodcentros;
             wsqltcc = wsqltcc||' and tpcc.bdcodtpcc in ('||prlistacc||')';
           END
        ELSE
        -- o retorno desse sql deve ser 0 para que o laco passe pelo menos uma vez pelo calculo de saldos,
        -- isso deve acontecer quando nao ha centro de custo selecionado
           BEGIN
             wsqltcc = 'select case when (temp.bdcodemp <> 0) then 0 end, tref.bdnomemp ';
             wsqltcc = wsqltcc||'from tempresas temp ';
             wsqltcc = wsqltcc||'inner join tempresas_ref tref on (tref.bdcodemp = temp.bdcodemp) ';
             --Pegava sempre a mesma empresa
             --wsqltcc = wsqltcc||'where temp.bdcodemp = '||bdcodemp;
             wsqltcc = wsqltcc||'where temp.bdcodemp = '||bdcodempfilial;
             wsqltcc = wsqltcc||' and tref.bdrefemp = (select first 1 tempresas_ref.bdrefemp from tempresas_ref ';
             wsqltcc = wsqltcc||                      'where tempresas_ref.bdcodemp = temp.bdcodemp ';
             wsqltcc = wsqltcc||                      'and tempresas_ref.bdrefemp <= '||prrefemp;
             wsqltcc = wsqltcc||                      ' order by tempresas_ref.bdrefemp desc) ';
           END
        -- laco dos centro de custos
        IF (NOT ((bdcodplapadrao IS NULL) AND (wcodcentros IS NULL))) THEN
        FOR EXECUTE STATEMENT wsqltcc
            INTO :bdcodtpcc, :bdnomtpcc DO
            BEGIN
              -- caso nao ha centro de custo selecionado, o nome do mesmo deve ser em branco
              IF (bdcodtpcc = 0) THEN
                 BEGIN
                   bdnomtpcc = '';
                   bdcodcentros = 0;
                 END
              ELSE
                 bdcodcentros = wcodcentros;
              -- laco do calculo dos saldos do plano de contas
              FOR SELECT tsal.codemp, tsal.codplapadrao, tsal.conta, tsal.classificacao,
                         tsal.nomeconta, tsal.tipconta, tsal.saldo_anterior, tsal.saldo_atual,
                         tref.bdnomemp, temp.bdcnpjemp, tsal.formula, tsal.grupoconta, tsal.participante, tsal.apecta
                  FROM vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :wcodctaini, :wcodctafin, :prdatini, :prindice, :prdatfin, :prignzer, :bdcodtpcc, :bdcodplapadrao,
                                                      0,:prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                  LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.codemp)
                  LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                  WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                         WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                         AND tempresas_ref.bdrefemp <= :prrefemp
                                         ORDER BY tempresas_ref.bdrefemp DESC)
                  INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                       :bdsalant, :bdsalatu, :bdnomemp, :bdcnpjemp, :bdformula, :BDGRPCTA,  :wparticipante, :bdapecta DO
              BEGIN
                -- Detalhado por participante
                IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                  BEGIN
                    --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                    FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                        --from vsuc_sp_retorna_saldos_cta_part(:bdcodemp,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,-- alt:#6647 - gilberto - 12/09/2013
                        FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodemp,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                             :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                        INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 03 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                            END

                          -- se a conta for "patrimonio liquido"
                          IF (bdctalon = prctalonpas) THEN
                            BEGIN
                              wseqcta = bdnomcta;
                              IF (bdsalatu IS NULL) THEN
                                wvaltit = 0;
                              ELSE
                                wvaltit = bdsalatu;
                            END
                          bdsalmov = bdsalatu - bdsalant;
                          bdseqcta = wseqcta;
                          -- c?lculo do percentual da analise vertical
                          IF (wvaltit = 0) THEN
                            bdanaver = 0;
                          ELSE
                            bdanaver = (bdsalatu * 100) / wvaltit;

                          SUSPEND;
                        END
                  END
                ELSE
                  BEGIN
                    -- sql para verificar se a conta atual ? uma titulo geral
                    SELECT FIRST 1 tpos.pos FROM pos('.', :bdctalon) tpos INTO :wlength;
                    IF (wlength IS NULL) THEN
                      wlength = 0;
                    -- se a conta for uma "titulo geral" ou "patrimonio liquido"
                    IF ((wlength = 0) OR (bdctalon = prctalonpas)) THEN
                      BEGIN
                        wseqcta = bdnomcta;
                        IF (bdsalatu IS NULL) THEN
                          wvaltit = 0;
                        ELSE
                          wvaltit = bdsalatu;
                      END
                    bdsalmov = bdsalatu - bdsalant;
                    bdseqcta = wseqcta;
                    -- caculo do percentual da analise vertical
                    IF (wvaltit = 0) THEN
                      bdanaver = 0;
                    ELSE
                      bdanaver = (bdsalatu * 100) / wvaltit;

                --alt:7847 - Algu?m, talvez o Gilberto havia comentado esta parte que s? d? o suspend se a conta tiver movimento ou for para imprimir contas sem movimento.
                --Estou descomentando essa parte e comentando a que foi adicionada para imprimir sempre as contas consolidadas, pois pelo que vimos, atualmente n?o faz sentido. Pedro
                IF ((prctasemmov = 0) AND ((bdsalatu <> 0) OR (bdsalmov <> 0)) OR (prctasemmov = 1)) THEN
                   SUSPEND;
--                     gilberto
/*                    if ((not prconsolidada is null) and (prconsolidada <> 0)) then
                      suspend;
                    else
                      begin
                        select bdresult from vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) into :wfind;
                        if ((wfind is null) or (wfind = 0)) then
                          suspend;
                        else
                          if (bdtipcta = 2) then
                            suspend;
                      end*/
                  END
              END
            END
      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_COMPARATIVO */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO(PREMPRESAS VARCHAR(1024),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRINDICE INTEGER,
PRTIPCOMP INTEGER,
PRCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDFORMULA VARCHAR(1024))
 AS
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WFIND INTEGER;
DECLARE VARIABLE WCLASSINI VARCHAR(50);
DECLARE VARIABLE WCLASSFIN VARCHAR(50);
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WSQLUPDATE VARCHAR(10240);
DECLARE VARIABLE WSQLTPCC VARCHAR(10240);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCTA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WNOMTPCC VARCHAR(40);
DECLARE VARIABLE WSALATU NUMERIC(15,2);
DECLARE VARIABLE WMOVIMENTO NUMERIC(15,2);
DECLARE VARIABLE WSALDORELATORIO NUMERIC(15,2);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WSQLCONTAS VARCHAR(10240);
DECLARE VARIABLE WSQLMESES VARCHAR(10240);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
BEGIN
  wdatahora = CURRENT_TIMESTAMP;
  --delete from vsuc_empresas_comparativo;

  wsql = 'select first 1 bdcodplapadrao from vw_empresas_ref_atual  ';
  wsql = wsql||'where bdcodemp in ('||prempresas||') ';
  EXECUTE STATEMENT wsql INTO :wcodplapadrao;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prctaini
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prctafin
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas anal?ticas
  SELECT BDRPOS FROM RPOS(',1,',','||:prniveisconta||',') INTO :wimpanalitica;

  wsql = 'select bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp, bdcodplapadrao ';
  wsql = wsql||'from vw_empresas_ref_atual ';
  wsql = wsql||'where bdcodemp in ('||prempresas||') ';

  wcount    = 0;
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao DO
      BEGIN
        -- giovanni... insere somente as contas com lancamentos

        wsqlcontas = '';
        wsqlcontas = wsqlcontas||' select distinct CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta, CONTAS.bdgrupocta, CONTAS.bdnomcta, CONTAS.bdformula, ';
        --alt:7211 - Alterado de wcodemp para prempresas para passar a empresa matriz e suas filiais, caso sejam informadas. Pedro
        --wsqlcontas = wsqlcontas||' CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS('||wcodemp||', '||wcodplapadrao||','''||prdatini||''','''||prdatfin||''','''||wclassini||''','''||wclassfin||''',0,0,0,3,0) CONTAS ';
        wsqlcontas = wsqlcontas||' CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS('''||prempresas||''', '||wcodplapadrao||','''||prdatini||''','''||prdatfin||''','''||wclassini||''','''||wclassfin||''',0,0,0,3,0) CONTAS ';
        wsqlcontas = wsqlcontas||' order by BDCTALON';


        FOR EXECUTE STATEMENT wsqlcontas
            INTO :wcodcta, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wformula, :wparticipante DO
          BEGIN
            -- Filtro pelo n?vel da conta
            SELECT contar_char FROM contar_char(:wctalon,'.') INTO :wnivelconta;
            wnivelconta = wnivelconta + 1;
            SELECT BDRPOS FROM RPOS(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',') INTO :windice;
            IF ((prniveisconta = '9999') OR           -- N?o tem filtro
                (wnivelconta = 1) OR                  -- O primeiro n?vel sempre imprime
                ((windice > 0) AND (:wtipcta = 0)) OR -- O n?vel da conta foi selecionado no filtro e ? t?tulo
                ((windice > 0) AND (wimpanalitica > 0) AND (:wtipcta = 1))) THEN -- ? do n?vel selecionado, anal?tica e foi selecionado para imprimir as contas anal?ticas
              BEGIN
                -- Tratamento para detalhar participante
                IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (wtipcta = 1)) THEN
                  BEGIN
                    FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdcodparticipante
                        --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfin,:wcodcta,:prignzer,0,1,0, -- alt:#6647 - gilberto - 12/09/2013
                        FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfin,:wcodcta,:prindice,:prignzer,0,1,0,
                                                             :prempresas,:prcontabilizacao,:prmatrizfilialconsolidado) tsalctapar
                        INTO :wnomcta, :wctalon, :wcodparticipante DO
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 03 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              wnomcta = wcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                            END

                          INSERT INTO vsuc_empresas_comparativo (bddatahora, bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp, bdcodplapadrao, bdcodcta,
                                                                 bdctalon, bdtipcta, bdgrpcta, bdnomcta, bdformula)
                          VALUES(:wdatahora, :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao, :wcodcta, :wctalon, :wtipcta, :wgrpcta ,:wnomcta, :wformula);
                        END
                  END
                ELSE
                  BEGIN
                    INSERT INTO vsuc_empresas_comparativo (bddatahora, bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp,
                                                           bdcodplapadrao, bdcodcta, bdctalon, bdtipcta, bdgrpcta, bdnomcta, bdformula)
                    VALUES (:wdatahora, :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao, :wcodcta, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wformula);
                  END
              END
          END
      END

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdatini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatfin FROM 1 FOR 4)||SUBSTRING(prdatfin FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdatini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = CAST(SUBSTRING(prdatfin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdatini FROM 1 FOR 4) AS INTEGER);
       IF (wtotal = 0) THEN
          wtotal = 1;
       ELSE
          wTotal = wTotal +1;
     END

  wcount = 0;
  WHILE (wcount < wtotal) DO
    BEGIN
      -- mensal ________________________________________________________
      IF (prtipcomp = 0) THEN
         BEGIN
           wdata_inicial = addmonth(prdatini, wcount);
           wdata_final   = addmonth(prdatini, wcount+1)-1;
         END
      ELSE
      -- anual _________________________________________________________
         BEGIN
           wdata_inicial = addyear(prdatini, wcount);
           wdata_final   = addyear(prdatini, wcount+1)-1;
         END

      IF (wdata_final <= prdatfin) THEN
         BEGIN
           wsqlmeses = '';
           wsqlmeses = wsqlmeses|| ' select bdcodemp, bdnomemp, bdcnpjemp, bdcodmatriz, bdcodplapadrao, bdcodcta, bdctalon, bdnomcta, bdtipcta, bdgrpcta, bdcodtpcc, bdnomtpcc, ';
           wsqlmeses = wsqlmeses|| ' bdsaldo_atual, bdmovimento ';
           wsqlmeses = wsqlmeses|| ' from vsuc_sp_retorna_balancete(''' || :prempresas || ''', ''' || :wdata_inicial || ''', ''';
           wsqlmeses = wsqlmeses|| :wdata_final || ''', ' || :prignzer || ', ' || :prctaini || ', ' || :prctafin || ', '||:prindice||', ''' ||  :prcc || ''' , ' || :prrefemp || ', ';
           wsqlmeses = wsqlmeses|| :prlansemcc || ', 0, 0, 0,'|| :prdetalharctaparticipante || ',0, '''|| :prniveisconta ||''',0,'||:prcontabilizacao||','||:prmatrizfilialconsolidado||')';

/*
           if (prtiposaldo = 2) then
              wsqlmeses = wsqlmeses|| ' where bdsaldo_atual <> 0';
           else
              wsqlmeses = wsqlmeses|| ' where bdmovimento <> 0';*/
           ----
           FOR EXECUTE STATEMENT wsqlmeses
               INTO :wcodemp, :wnomemp, :wcnpjemp, :wcodmatriz, :wcodplapadrao,
                    :wcodcta, :wctalon, :wnomcta, :wtipcta, :wgrpcta, :wcodtpcc, :wnomtpcc,
                    :wsalatu, :wmovimento DO
           BEGIN
             --alt:7333 - Retirado o filtro, pois agora deve trazer tano o saldo quanto o movimento. Pedro
             /*if (prtiposaldo = 2) then
                wSaldoRelatorio = wsalatu;
             else
                wSaldoRelatorio = wmovimento;*/

             --alt:7333 - Adicionados campos do movimento. Pedro
             wsqlupdate = 'update vsuc_empresas_comparativo set ';
             IF (wcount = 0) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO01 = coalesce(BDSALDO01, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO01 = coalesce(BDMOVIMENTO01, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 1) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO02 = coalesce(BDSALDO02, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO02 = coalesce(BDMOVIMENTO02, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 2) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO03 = coalesce(BDSALDO03, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO03 = coalesce(BDMOVIMENTO03, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 3) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO04 = coalesce(BDSALDO04, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO04 = coalesce(BDMOVIMENTO04, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 4) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO05 = coalesce(BDSALDO05, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO05 = coalesce(BDMOVIMENTO05, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 5) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO06 = coalesce(BDSALDO06, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO06 = coalesce(BDMOVIMENTO06, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 6) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO07 = coalesce(BDSALDO07, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO07 = coalesce(BDMOVIMENTO07, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 7) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO08 = coalesce(BDSALDO08, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO08 = coalesce(BDMOVIMENTO08, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 8) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO09 = coalesce(BDSALDO09, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO09 = coalesce(BDMOVIMENTO09, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 9) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO10 = coalesce(BDSALDO10, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO10 = coalesce(BDMOVIMENTO10, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 10) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO11 = coalesce(BDSALDO11, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO11 = coalesce(BDMOVIMENTO11, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 11) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO12 = coalesce(BDSALDO12, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO12 = coalesce(BDMOVIMENTO12, 0) + '||COALESCE(wMovimento, 0);
                END
             wSqlUpdate = wSqlUpdate||' where bdcodemp = '||wcodemp;
             wSqlUpdate = wSqlUpdate||' and bddatahora = '''||wdatahora||'''';
             wSqlUpdate = wSqlUpdate||' and bdcodcta = '||wcodcta;
             wSqlUpdate = wSqlUpdate||' and bdctalon = '''||wctalon||'''';
             IF (TRIM(prcc) <> '') THEN
                wSqlUpdate = wSqlUpdate||' and bdcodtpcc = '||wcodtpcc;

             EXECUTE STATEMENT wSqlUpdate;
           END
         END
      wcount = wcount + 1;
    END

  -- implementado para que se possa agrupar todas as filiais somando os saldos
  IF (PRAGRUPAEMPRESAFILIAIS = 1) THEN
     BEGIN
       wsql = 'select first 1 bdcodemp, bdcodmatriz, bdcnpjemp, bdnomemp, bdcodplapadrao ';
       wsql = wsql||'from vw_empresas_ref_atual ';
       wsql = wsql||'where bdcodemp in ('||prempresas||') ';
       EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodmatriz, :bdcnpjemp, :bdnomemp, :bdcodplapadrao;

       --alt:7333 - Adicionados campos do movimento. Pedro
       FOR SELECT DISTINCT  tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA, tcomp.BDTIPCTA, tcomp.BDGRPCTA, COALESCE(tcomp.BDCODTPCC, 0), tcomp.BDNOMTPCC, tcomp.bdformula,
                  SUM(COALESCE(tcomp.BDSALDO01, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO01, 0)), SUM(COALESCE(tcomp.BDSALDO02, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO02, 0)),
                  SUM(COALESCE(tcomp.BDSALDO03, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO03, 0)), SUM(COALESCE(tcomp.BDSALDO04, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO04, 0)),
                  SUM(COALESCE(tcomp.BDSALDO05, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO05, 0)), SUM(COALESCE(tcomp.BDSALDO06, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO06, 0)),
                  SUM(COALESCE(tcomp.BDSALDO07, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO07, 0)), SUM(COALESCE(tcomp.BDSALDO08, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO08, 0)),
                  SUM(COALESCE(tcomp.BDSALDO09, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO09, 0)), SUM(COALESCE(tcomp.BDSALDO10, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO10, 0)),
                  SUM(COALESCE(tcomp.BDSALDO11, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO11, 0)), SUM(COALESCE(tcomp.BDSALDO12, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO12, 0))
           FROM vsuc_empresas_comparativo tcomp
           WHERE  (bddatahora = :wdatahora)
           GROUP BY tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA, tcomp.BDTIPCTA, tcomp.BDGRPCTA, tcomp.BDCODTPCC, tcomp.BDNOMTPCC, tcomp.bdformula
           ORDER BY tcomp.bdctalon, tcomp.bdcodtpcc
           --alt:7333 - Adicionados campos do movimento. Pedro
           INTO :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :bdformula,
                :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02,
                :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
                :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06,
                :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
                :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10,
                :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
           BEGIN
             BDQTDCOMP = wtotal;
             --alt:7333 - Adicionados campos do movimento. Pedro
             IF ((BDSALDO01 <> 0 OR BDSALDO02 <> 0 OR BDSALDO03 <> 0 OR BDSALDO04 <> 0 OR
                  BDSALDO05 <> 0 OR BDSALDO06 <> 0 OR BDSALDO07 <> 0 OR BDSALDO08 <> 0 OR
                  BDSALDO09 <> 0 OR BDSALDO10 <> 0 OR BDSALDO11 <> 0 OR BDSALDO12 <> 0) OR
                 (BDMOVIMENTO01 <> 0 OR BDMOVIMENTO02 <> 0 OR BDMOVIMENTO03 <> 0 OR BDMOVIMENTO04 <> 0 OR
                  BDMOVIMENTO05 <> 0 OR BDMOVIMENTO06 <> 0 OR BDMOVIMENTO07 <> 0 OR BDMOVIMENTO08 <> 0 OR
                  BDMOVIMENTO09 <> 0 OR BDMOVIMENTO10 <> 0 OR BDMOVIMENTO11 <> 0 OR BDMOVIMENTO12 <> 0) OR
                 (BDTIPCTA = 0) OR (BDFORMULA <> '')) THEN
                 SUSPEND;
           END
     END
  ELSE
  --alt:7333 - Adicionados campos do movimento. Pedro
  FOR SELECT tcomp.BDCODEMP, tcomp.BDCODMATRIZ, tcomp.BDNOMEMP, tcomp.BDCNPJEMP,
             tcomp.bdcodplapadrao, tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA,
             tcomp.BDTIPCTA, tcomp.BDGRPCTA, COALESCE(tcomp.BDCODTPCC, 0), tcomp.BDNOMTPCC,
             tcomp.BDSALDO01, tcomp.BDMOVIMENTO01, tcomp.BDSALDO02, tcomp.BDMOVIMENTO02,
             tcomp.BDSALDO03, tcomp.BDMOVIMENTO03, tcomp.BDSALDO04, tcomp.BDMOVIMENTO04,
             tcomp.BDSALDO05, tcomp.BDMOVIMENTO05, tcomp.BDSALDO06, tcomp.BDMOVIMENTO06,
             tcomp.BDSALDO07, tcomp.BDMOVIMENTO07, tcomp.BDSALDO08, tcomp.BDMOVIMENTO08,
             tcomp.BDSALDO09, tcomp.BDMOVIMENTO09, tcomp.BDSALDO10, tcomp.BDMOVIMENTO10,
             tcomp.BDSALDO11, tcomp.BDMOVIMENTO11, tcomp.BDSALDO12, tcomp.BDMOVIMENTO12, tcomp.bdformula
      FROM vsuc_empresas_comparativo tcomp
      WHERE  (bddatahora = :wdatahora)
      --alt:7333 - Adicionados campos do movimento. Pedro
      ORDER BY tcomp.bdcodemp, tcomp.bdcodmatriz, tcomp.bdctalon, tcomp.bdcodtpcc
      INTO :BDCODEMP, :bdcodmatriz, :BDNOMEMP, :BDCNPJEMP, :bdcodplapadrao,
           :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC,
           :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02,
           :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
           :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06,
           :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
           :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10,
           :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12, :bdformula DO
      BEGIN
        BDQTDCOMP = wtotal;
        SUSPEND;
      END

  --N?o utiliza mais o "vsuc_empresas_tbalancete", mas sim o "vsuc_empresas_tbalancete_2"
  --delete from vsuc_empresas_tbalancete;
  DELETE FROM vsuc_empresas_comparativo WHERE bdcodemp <> 0 AND bddatahora = :wdatahora;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_COMPARATIVO_X */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO_X(PRCODEMP VARCHAR(255),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATAINI DATE,
PRDATAFIN DATE,
PRINDICE INTEGER,
PRCTASEMMOV INTEGER,
PRIMPRIMIRCOLUNASEXTRAS INTEGER,
PRTIPCOMP INTEGER,
PRCODTPCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRCTACONSOLIDADA INTEGER,
PRFORMACALC INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP VARCHAR(100),
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDFORMULA VARCHAR(1024),
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDMEDIASALDO NUMERIC(15,2),
BDTOTALSALDO NUMERIC(15,2),
BDMEDIAMOVIMENTO NUMERIC(15,2),
BDTOTALMOVIMENTO NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(24000);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  --#alt:20462. Criada nova SP para melhorar o desempenho. A antiga permanecer? para caso houver lentid?es ou erros futuros. Ana - 08/05/2018
  IF (PRFORMACALC = 1) THEN
   BEGIN
     FOR SELECT BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA, BDCODEMPFILIAL,
                BDSALDO01, BDMOVIMENTO01, BDSALDO02, BDMOVIMENTO02, BDSALDO03, BDMOVIMENTO03, BDSALDO04, BDMOVIMENTO04,
                BDSALDO05, BDMOVIMENTO05, BDSALDO06, BDMOVIMENTO06, BDSALDO07, BDMOVIMENTO07, BDSALDO08, BDMOVIMENTO08,
                BDSALDO09, BDMOVIMENTO09, BDSALDO10, BDMOVIMENTO10, BDSALDO11, BDMOVIMENTO11, BDSALDO12, BDMOVIMENTO12,
                BDQTDCOMP
         FROM VSUC_SP_RETORNA_COMPARATIVO_Y(:prcodemp, :prctaini, :prctafin, :prdataini, :prdatafin, :prindice, :prctasemmov, :prtipcomp, :prcodtpcc, :prtiposaldo, :prrefemp, :prignzer,
                                            :prlansemcc, :pragrupaempresafiliais, :prdetalharctaparticipante, :prniveisconta, :prcontabilizacao, :prmatrizfilialconsolidado,
                                            :prctaconsolidada)

      INTO
      :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
      :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
      :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
      :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12,
      :BDQTDCOMP DO
        SUSPEND;

   END
  ELSE
  BEGIN
      -- Caso seja para agrupar as empresas eu busco o c?digo, nome e CNPJ separadamente
      IF (pragrupaempresafiliais = 1) THEN
        BEGIN
          wpos = POSITION(',', :prcodemp);
          IF (wpos <> 0) THEN
            wcodemp = COALESCE(CAST(SUBSTRING(prcodemp FROM 1 FOR (wpos -1)) AS INTEGER),0);
          ELSE
            wcodemp = COALESCE(CAST(:prcodemp AS INTEGER),0);
    
          SELECT emp.bdcodemp,emp.bdcnpjemp,ref.bdnomemp  FROM tempresas emp
          INNER JOIN vw_empresas_ref_atual ref ON (ref.bdcodemp = emp.bdcodemp)
          WHERE (emp.bdcodemp = :wcodemp) INTO :wcodemp, :wcnpjemp, :wnomemp;
        END
    
      -- mensal ____________________________________________________________________
      IF (prtipcomp = 0) THEN
         BEGIN
           wtotal = 0;
           wdata_inicial = prdataini;
           WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafin FROM 1 FOR 4)||SUBSTRING(prdatafin FROM 6 FOR 2) AS INTEGER)) DO
             BEGIN
               wtotal = wtotal + 1;
               wdata_inicial = addmonth(prdataini, wtotal);
             END
         END
      ELSE
      -- anual _____________________________________________________________________
         BEGIN
           wtotal = CAST(SUBSTRING(prdatafin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER);
           IF (wtotal = 0) THEN
              wtotal = 1;
           ELSE
              wTotal = wTotal +1;
         END
    
      wcount = 0;
      WHILE (wcount < wtotal) DO
        BEGIN
          -- mensal ________________________________________________________
          IF (prtipcomp = 0) THEN
             BEGIN
               wdata_inicial = addmonth(prdataini, wcount);
               wdata_final   = addmonth(prdataini, wcount + 1) - 1;
             END
          ELSE
          -- anual _________________________________________________________
             BEGIN
               wdata_inicial = addyear(prdataini, wcount);
               wdata_final   = addyear(prdataini, wcount + 1) - 1;
             END
    
          IF (wsql IS NULL) THEN
             BEGIN
               IF (pragrupaempresafiliais = 1) THEN
                 wsql = 'Select null as BDCODEMP, BDCODPLAPADRAO, BDCODCTA, null as BDCODMATRIZ, null as BDNOMEMP, null as BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,null as BDCODEMPFILIAL,';
               ELSE
                 wsql = 'Select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
    
               wsql = wsql||' sum(coalesce(BDSALDO01, 0)) as BDSALDO01, sum(coalesce(BDMOVIMENTO01, 0)) as BDMOVIMENTO01, sum(coalesce(BDSALDO02, 0)) as BDSALDO02, sum(coalesce(BDMOVIMENTO02, 0)) as BDMOVIMENTO02,';
               wsql = wsql||' sum(coalesce(BDSALDO03, 0)) as BDSALDO03, sum(coalesce(BDMOVIMENTO03, 0)) as BDMOVIMENTO03, sum(coalesce(BDSALDO04, 0)) as BDSALDO04, sum(coalesce(BDMOVIMENTO04, 0)) as BDMOVIMENTO04,';
               wsql = wsql||' sum(coalesce(BDSALDO05, 0)) as BDSALDO05, sum(coalesce(BDMOVIMENTO05, 0)) as BDMOVIMENTO05, sum(coalesce(BDSALDO06, 0)) as BDSALDO06, sum(coalesce(BDMOVIMENTO06, 0)) as BDMOVIMENTO06,';
               wsql = wsql||' sum(coalesce(BDSALDO07, 0)) as BDSALDO07, sum(coalesce(BDMOVIMENTO07, 0)) as BDMOVIMENTO07, sum(coalesce(BDSALDO08, 0)) as BDSALDO08, sum(coalesce(BDMOVIMENTO08, 0)) as BDMOVIMENTO08,';
               wsql = wsql||' sum(coalesce(BDSALDO09, 0)) as BDSALDO09, sum(coalesce(BDMOVIMENTO09, 0)) as BDMOVIMENTO09, sum(coalesce(BDSALDO10, 0)) as BDSALDO10, sum(coalesce(BDMOVIMENTO10, 0)) as BDMOVIMENTO10,';
               wsql = wsql||' sum(coalesce(BDSALDO11, 0)) as BDSALDO11, sum(coalesce(BDMOVIMENTO11, 0)) as BDMOVIMENTO11, sum(coalesce(BDSALDO12, 0)) as BDSALDO12, sum(coalesce(BDMOVIMENTO12, 0)) as BDMOVIMENTO12';
               wsql = wsql||' from (';
             END
          ELSE
             wsql = wsql||' union all ';
    
          IF (wcount = 0) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' bdsaldo_atual as BDSALDO01, bdmovimento as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
          ELSE
          IF (wcount = 1) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, bdsaldo_atual as BDSALDO02, bdmovimento as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE  
           IF (wcount = 2) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' bdsaldo_atual as BDSALDO03, bdmovimento as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 3) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, bdsaldo_atual as BDSALDO04, bdmovimento as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 4) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' bdsaldo_atual as BDSALDO05, bdmovimento as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 5) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, bdsaldo_atual as BDSALDO06, bdmovimento as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 6) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' bdsaldo_atual as BDSALDO07, bdmovimento as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 7) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, bdsaldo_atual as BDSALDO08, bdmovimento as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 8) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' bdsaldo_atual as BDSALDO09, bdmovimento as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 9) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, bdsaldo_atual as BDSALDO10, bdmovimento as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 10) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' bdsaldo_atual as BDSALDO11, bdmovimento as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 11) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, bdsaldo_atual as BDSALDO12, bdmovimento as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
    
          wcount = wcount + 1;
        END
    
      wsql = wsql||' ) group by BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDNOMEMP, BDCODMATRIZ, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA, BDCODEMPFILIAL';
    
      FOR EXECUTE STATEMENT wsql INTO
          :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
          :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
          :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
          :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
        BEGIN
          IF (pragrupaempresafiliais = 1) THEN
            BEGIN
              bdcodemp       = wcodemp;
              bdcnpjemp      = wcnpjemp;
              bdnomemp       = wnomemp;
              bdcodempfilial = bdcodemp;
            END
    
          BDQTDCOMP = wtotal;
    
          IF ((PRFORMACALC = 0) AND (PRIMPRIMIRCOLUNASEXTRAS = 1)) THEN
             BEGIN
               BDTOTALSALDO = (COALESCE(BDSALDO01, 0) + COALESCE(BDSALDO02, 0) + COALESCE(BDSALDO03, 0) + COALESCE(BDSALDO04, 0) + COALESCE(BDSALDO05, 0) + COALESCE(BDSALDO06, 0) +
                               COALESCE(BDSALDO07, 0) + COALESCE(BDSALDO08, 0) + COALESCE(BDSALDO09, 0) + COALESCE(BDSALDO10, 0) + COALESCE(BDSALDO11, 0) + COALESCE(BDSALDO12, 0));
               BDMEDIASALDO = BDTOTALSALDO / wtotal;
    
               BDTOTALMOVIMENTO = (COALESCE(BDMOVIMENTO01, 0) + COALESCE(BDMOVIMENTO02, 0) + COALESCE(BDMOVIMENTO03, 0) + COALESCE(BDMOVIMENTO04, 0) +
                                   COALESCE(BDMOVIMENTO05, 0) + COALESCE(BDMOVIMENTO06, 0) + COALESCE(BDMOVIMENTO07, 0) + COALESCE(BDMOVIMENTO08, 0) +
                                   COALESCE(BDMOVIMENTO09, 0) + COALESCE(BDMOVIMENTO10, 0) + COALESCE(BDMOVIMENTO11, 0) + COALESCE(BDMOVIMENTO12, 0));
               BDMEDIAMOVIMENTO = BDTOTALMOVIMENTO / wtotal;
             END
    
          SUSPEND;
        END
  END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_REL_ORCA */
ALTER PROCEDURE VSUC_SP_RETORNA_REL_ORCA(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDOREALIZADO NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER)
 AS
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WSALDOREALIZADO NUMERIC(15,2);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WGRPCTA SMALLINT;
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
BEGIN
  wdatahora = CURRENT_TIMESTAMP;

  -- retorna as empresas selecionadas
  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        DELETE FROM VSUC_EMPRESAS_REL_TORCAMENTO WHERE bdcodemp <> 0 AND bddatahora = :wdatahora;
        -- verifica se existe centro de custo selecionado
        IF (prcodtpcc = '') THEN
           BEGIN
             bdcodtpcc = 0;
             bdnomtpcc = '';
             bdtpcclon = '';
             -- retorna todas as contas do plano de contas sem o centro de custo
             FOR SELECT tsalcta.conta, tsalcta.classificacao, tsalcta.nomeconta, tsalcta.tipconta, tsalcta.GRUPOCONTA,
                        tsalcta.bdrealizado,  tsalcta.formula, tsalcta.relconta
                 FROM vsuc_sp_retorna_saldo_orca(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prIndice, :prignora_zeramento, 0, :bdcodplapadrao,
                                                 :wdatahora,:prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsalcta
                 INTO :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta, :bdgrpcta,
                      :bdsaldorealizado,  :bdformula, :bdrelcta DO
                 BEGIN
                       BEGIN
                         --bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                         SUSPEND;
                       END
                 END
           END
        ELSE
           BEGIN
             -- retorna a conta londa da conta inicial
             SELECT tpla.bdctalon FROM planos_tpla tpla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :prctaini
             INTO :wctalonant;
             -- inicializa as variaveis
             bdsaldorealizado = 0;
             -- sql por centro de custo selecionado
             wsql = 'select tpcc.bdcodtpcc, tpcc.bdnomcta, tpcc.bdctalon from centros_tpcc tpcc ';
             wsql = wsql||'where tpcc.bdcodcentro = (select first 1 temp.bdcodcentros from tempresas_ref temp ';
             wsql = wsql||                          'where temp.bdcodemp in ('||bdcodemp||')';
             wsql = wsql||                         ' and temp.bdrefemp <= '||prrefemp;
             wsql = wsql||                         ' order by temp.bdrefemp desc) ';
             wsql = wsql||'and tpcc.bdcodtpcc in ('||prcodtpcc||')';
             -- execucao do sql por centro de custo para trazer os lancamnetos sem o centro de custo
             IF (prlansemcc = 1) THEN
                BEGIN
                  FOR EXECUTE STATEMENT wsql
                      INTO :bdcodtpcc, :bdnomtpcc, :bdtpcclon DO
                      BEGIN
                        -- laco que retorna as contas por centro de custo selecionado
                        FOR SELECT bdcodcta, bdctalon, bdnomcta, bdtipcta, bdgrpcta, bdsalantdeb, bdformula, bdrelcta, bdformula
                            FROM vsuc_sp_retorna_saldo_contas_cc(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prignora_zeramento, :bdcodtpcc,
                                                                 :bdcodplapadrao,0)
                            INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta, : wsaldorealizado, :wformula, :bdrelcta, :bdformula DO
                            BEGIN
                              IF (wctalonant <> wctalon) THEN
                                 BEGIN
                                       BEGIN
                                         bdcodtpcc = NULL;
                                         bdnomtpcc = 'Sem Centro de Custo';
                                         bdtpcclon = NULL;
                                         -- bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                                         SUSPEND;
                                       END
     
                                   bdcodcta = wconta;
                                   bdctalon = wctalon;
                                   bdnomcta = wnomcta;
                                   bdtipcta = wtipcta;
                                   bdgrpcta = wgrpcta;
                                   bdformula = wformula;
                                 END
                              ELSE
                                 BEGIN
                                   bdcodcta = wconta;
                                   bdctalon = wctalon;
                                   bdnomcta = wnomcta;
                                   bdtipcta = wtipcta;
                                   bdgrpcta = wgrpcta;
                                   bdformula = wformula;
                                 END
                              wctalonant = wctalon;
                            END
                      END
                END

             -- execucao do sql por centro de custo
             FOR EXECUTE STATEMENT wsql
                 INTO :bdcodtpcc, :bdnomtpcc, :bdtpcclon DO
                 BEGIN
                   -- laco que retorna as contas por centro de custo selecionado
                   FOR SELECT conta, classificacao, nomeconta, tipconta, GRUPOCONTA, bdrealizado,
                              formula, relconta
                       FROM vsuc_sp_retorna_saldo_orca(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prIndice, :prignora_zeramento, :bdcodtpcc,
                                                       :bdcodplapadrao,:wdatahora,:prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado)
                       INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta,
                            :wsaldorealizado, :wformula, :bdrelcta DO
                       BEGIN
                         IF (wctalonant <> wctalon) THEN
                            BEGIN
                              SUSPEND;
                              bdcodcta = wconta;
                              bdctalon = wctalon;
                              bdnomcta = wnomcta;
                              bdtipcta = wtipcta;
                              bdgrpcta = wgrpcta;
                              bdformula = wformula;
                              bdsaldorealizado = :wsaldorealizado;
                            END
                         ELSE
                            BEGIN
                              bdcodcta = wconta;
                              bdctalon = wctalon;
                              bdnomcta = wnomcta;
                              bdtipcta = wtipcta;
                              bdgrpcta = wgrpcta;
                              bdformula = wformula;
                              bdsaldorealizado = :wsaldorealizado;
                            END
                         wctalonant = wctalon;
                       END
                 END
           END
      END
END
^

/* Create Views... */
/* Create view: VW_TAREFAS_USUARIO */
SET TERM ; ^

CREATE VIEW VW_TAREFAS_USUARIO(
BDCODEMP,
BDAPEEMP,
BDCODST,
BDDATAPREVISAO,
BDDATASOLICITADA,
BDDATAFIM,
BDDATASOL,
BDCODUSU,
BDTIPOSOLICITACAO,
BDTIPO,
BDDATA,
BDHORA,
BDCODUSURESPONSAVEL,
BDCODIMP,
BDCODOBRIGACAO,
BDCODSERVICO,
BDTIPODESCRICAO,
BDSTATUS,
BDALERTA,
BDCODCID,
BDNOMCID,
BDSIGLAUF,
BDASCENDENTE,
BDCODSIS,
BDNOMSIS,
BDCODPERIODICIDADE,
BDPERIODICIDADE,
BDCOMPETENCIA,
BDVENCIMENTO,
BDENTREGA,
BDTEMPOESTIMADO,
BDCODPTS,
BDSERIEPTS,
BDNOMEMP,
BDFILIAL,
BDNOMEFILIAL,
BDCODIMPOBRSER,
BDOBSUSUARIO,
BDCODCOL,
BDCODCOLVINC,
BDNOMCOLVINC)
 AS 
SELECT BDCODEMP, BDAPEEMP, BDCODST, BDDATAPREVISAO, bddatasolicitada, BDDATAFIM, BDDATASOL, tar.BDCODUSU,
       BDTIPOSOLICITACAO, BDTIPO, BDDATA, BDHORA, BDCODUSURESPONSAVEL, BDCODIMP,
       BDCODOBRIGACAO, BDCODSERVICO, BDTIPODESCRICAO, BDSTATUS, BDALERTA, BDCODCID,
       BDNOMCID, BDSIGLAUF, BDASCENDENTE, BDCODSIS, BDNOMSIS,
       bdcodperiodicidade, bdperiodicidade, tar.bdcompetencia, tar.bdvencimento, tar.BDENTREGA, tar.BDTEMPOESTIMADO,
       tar.bdcodpts, tar.bdseriepts, BDNOMEMP, BDFILIAL, BDNOMEFILIAL, bdcodimpobrser, bdobsusuario, tar.bdcodcol, tar.bdcodcolvinc, tar.bdnomcolvinc
FROM vw_tarefas tar
INNER JOIN VW_VARIAVEIS_SESSAO_BANCO tusu ON (tusu.bdcodusu = tar.bdcodusuresponsavel OR tar.bdcodusuresponsavel IS NULL)
WHERE ((bdcodusuresponsavel = (SELECT bdcodusu FROM VW_VARIAVEIS_SESSAO_BANCO)) OR (bdcodusuresponsavel IS NULL))
ORDER BY tar.bddataprevisao
;

/* Create view: VW_UNION_FGTS */
CREATE VIEW VW_UNION_FGTS(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_NORMAL
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_COMPLEMENTAR
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_A13
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_13S
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_C13
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_AVULSA
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM vw_ficha_fgts
;

/* Create view: VW_VEF_TOT_CID_ENT */
CREATE VIEW VW_VEF_TOT_CID_ENT(
BDCODEMP,
BDREFLAN,
BDCODCID,
BDNOMCID,
BDCODUF,
BDPRURALTER,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB)
 AS 
SELECT ENT.BDCODEMP,
       ENT.BDREFLAN,
       TER.BDCODCID,
       CID.BDNOMCID,
       CID.BDCODUF,
       TER.BDPRURALTER,
       ITENS.BDCODNAT,
       ITENS.BDPREFIXONAT,
       SUM(COALESCE(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB 
FROM VEF_EMP_TMOVENT ENT 
LEFT OUTER JOIN VEF_EMP_TMOVENTITENS ITENS ON ENT.BDCODEMP = ITENS.BDCODEMP AND ENT.BDCHAVE = ITENS.BDCHAVE 
LEFT OUTER JOIN VW_TTERCEIRO TER ON TER.BDCODTER = ENT.BDCODTER 
LEFT OUTER JOIN TCIDADE CID ON CID.BDCODCID = TER.BDCODCID 

GROUP BY ENT.BDCODEMP, ENT.BDREFLAN, TER.BDCODCID, CID.BDNOMCID, CID.BDCODUF, TER.BDPRURALTER, ITENS.BDCODNAT, ITENS.BDPREFIXONAT 
ORDER BY ENT.BDCODEMP, ENT.BDREFLAN, TER.BDCODCID, ITENS.BDCODNAT, ITENS.BDPREFIXONAT
;

/* Create view: VW_VEF_TOT_CID_SAI */
CREATE VIEW VW_VEF_TOT_CID_SAI(
BDCODEMP,
BDREFLAN,
BDCODCID,
BDNOMCID,
BDCODUF,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB)
 AS 
SELECT SAI.BDCODEMP,
       SAI.BDREFLAN,
       SAI.BDCODCID,
       CID.BDNOMCID,
       CID.BDCODUF,
       ITENS.BDCODNAT,
       ITENS.BDPREFIXONAT,
       SUM(COALESCE(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB 
FROM VEF_EMP_TMOVSAI SAI 
LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS ITENS ON SAI.BDCODEMP = ITENS.BDCODEMP AND SAI.BDCHAVE = ITENS.BDCHAVE 
LEFT OUTER JOIN VW_TTERCEIRO TER ON TER.BDCODTER = SAI.BDCODTER 
LEFT OUTER JOIN TCIDADE CID ON CID.BDCODCID = SAI.BDCODCID 

GROUP BY SAI.BDCODEMP, SAI.BDREFLAN, SAI.BDCODCID, CID.BDNOMCID, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT 
ORDER BY SAI.BDCODEMP, SAI.BDREFLAN, SAI.BDCODCID, ITENS.BDCODNAT, ITENS.BDPREFIXONAT
;

/* Create view: VW_VEF_TOT_NAT_ENT_UF */
CREATE VIEW VW_VEF_TOT_NAT_ENT_UF(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDCODUF,
BDCODOPDAPI,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENT,
BDDIFALIQENT,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  MOV.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        cid.bdcoduf, 
        nat.BDCODOPDAPI,
        COALESCE(SUM(itens.BDVLRCONTAB),0) BDVLRCONTAB,
        COALESCE(SUM(itens.BDBASEICMS),0) BDBASEICMS,
        COALESCE(SUM(itens.BDBASEIPI),0) BDBASEIPI,
        COALESCE(SUM(itens.BDBASEST),0) BDBASEST,
        COALESCE(SUM(itens.BDISENTASICMS),0) BDISENTASICMS,
        COALESCE(SUM(itens.BDISENTASIPI),0) BDISENTASIPI,
        COALESCE(SUM(itens.BDOUTRASICMS),0) BDOUTRASICMS,
        COALESCE(SUM(itens.BDOUTRASIPI),0) BDOUTRASIPI,
        COALESCE(SUM(itens.BDVLRICMS),0) BDVLRICMS,
        COALESCE(SUM(itens.BDVLRIPI),0) BDVLRIPI,
        COALESCE(SUM(itens.BDVLRST),0) BDVLRST,
        COALESCE(SUM(itens.BDIMPEXCLUIDAS),0) BDIMPEXCLUIDAS,
        COALESCE(SUM(itens.BDOUTROSIMP),0) BDOUTROSIMP,
        COALESCE(SUM(itens.BDDESCONTO),0) BDDESCONTO,
        COALESCE(SUM(itens.BDICMSRETENT),0) BDICMSRETENT,
        COALESCE(SUM(itens.BDDIFALIQENT),0) BDDIFALIQENT,
        COALESCE(SUM(r.bdimpsubstituto),0) bdimpsubstituto,
        COALESCE(SUM(r.bdimpsubstituido),0) bdimpsubstituido,
        COALESCE(SUM(itens.BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(itens.BDVLRCOFINS),0) BDVLRCOFINS

FROM vef_emp_tmoventitens itens
JOIN TEMPRESAS E ON (itens.bdcodemp = e.bdcodemp)
JOIN vef_emp_tmovent MOV ON ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
LEFT OUTER JOIN VEF_EMP_TMOVENTIMPRETSP r ON (MOV.bdcodemp = r.bdcodemp AND MOV.bdchave = r.bdchave AND itens.bdordem = r.bdordem)
LEFT OUTER JOIN vw_tterceiro ter ON (mov.bdcodter = ter.bdcodter)
LEFT OUTER JOIN tcidade cid ON (ter.bdcodcid = cid.bdcodcid)
JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
WHERE MOV.bdcodsitnf NOT IN (2,3,4,5)
GROUP BY MOV.bdreflan, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat, cid.bdcoduf, nat.BDCODOPDAPI
ORDER BY itens.bdcodemp,mov.bdreflan,cid.bdcoduf
;

/* Create view: VW_VEF_TOT_NAT_SAI_UF */
CREATE VIEW VW_VEF_TOT_NAT_SAI_UF(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDCODUF,
BDCODOPDAPI,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  BDREFLAN,bdcodemp,bdcodmatriz,bdcodnat,BDPREFIXONAT,bdcoduf,BDCODOPDAPI,
        COALESCE(SUM(bdvlrcontab),0) bdvlrcontab,
        COALESCE(SUM(bdbaseicms),0) bdbaseicms,
        COALESCE(SUM(bdvlricms),0) bdvlricms,
        COALESCE(SUM(BDBASEIPI),0) BDBASEIPI,
        COALESCE(SUM(BDBASEST),0) BDBASEST,
        COALESCE(SUM(BDISENTASICMS),0) BDISENTASICMS,
        COALESCE(SUM(BDISENTASIPI),0) BDISENTASIPI,
        COALESCE(SUM(BDOUTRASICMS),0) BDOUTRASICMS,
        COALESCE(SUM(BDOUTRASIPI),0) BDOUTRASIPI,
        COALESCE(SUM(BDVLRIPI),0) BDVLRIPI,
        COALESCE(SUM(BDVLRST),0) BDVLRST,
        COALESCE(SUM(BDIMPEXCLUIDAS),0) BDIMPEXCLUIDAS,
        COALESCE(SUM(BDOUTROSIMP),0) BDOUTROSIMP,
        COALESCE(SUM(BDDESCONTO),0) BDDESCONTO,
        COALESCE(SUM(BDICMSFRETESAI),0) BDICMSFRETESAI,
        COALESCE(SUM(BDACRECFINSAI),0) BDACRECFINSAI,
        COALESCE(SUM(bdimpsubstituto),0) bdimpsubstituto,
        COALESCE(SUM(bdimpsubstituido),0) bdimpsubstituido,
        COALESCE(SUM(BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(BDVLRCOFINS),0) BDVLRCOFINS
FROM (
    SELECT  SAI.BDREFLAN,itens.bdcodemp,COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,itens.bdcodnat,itens.BDPREFIXONAT,cid.bdcoduf,nat.BDCODOPDAPI,SUM(itens.bdvlrcontab) bdvlrcontab,SUM(itens.bdbaseicms) bdbaseicms,
            SUM(itens.bdvlricms) bdvlricms,SUM(BDBASEIPI) BDBASEIPI,SUM(BDBASEST) BDBASEST,SUM(BDISENTASICMS) BDISENTASICMS,SUM(BDISENTASIPI) BDISENTASIPI,
            SUM(BDOUTRASICMS) BDOUTRASICMS,SUM(BDOUTRASIPI) BDOUTRASIPI,SUM(BDVLRIPI) BDVLRIPI,SUM(BDVLRST) BDVLRST,SUM(BDIMPEXCLUIDAS) BDIMPEXCLUIDAS,
            SUM(BDOUTROSIMP) BDOUTROSIMP,SUM(BDDESCONTO) BDDESCONTO,SUM(BDICMSFRETESAI) BDICMSFRETESAI,SUM(BDACRECFINSAI) BDACRECFINSAI,
            SUM(r.bdimpsubstituto) bdimpsubstituto,SUM(r.bdimpsubstituido) bdimpsubstituido,SUM(itens.BDVLRPIS) BDVLRPIS,SUM(itens.BDVLRCOFINS) BDVLRCOFINS
    FROM vef_emp_tmovsaiitens itens
    JOIN tempresas e ON (itens.bdcodemp = e.bdcodemp)
    JOIN vef_emp_tmovsai sai ON ((itens.bdcodemp = sai.bdcodemp) AND (itens.bdchave = sai.bdchave))
    LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP r ON (SAI.bdcodemp = r.bdcodemp AND SAI.bdchave = r.bdchave AND itens.bdordem = r.bdordem)
    LEFT OUTER JOIN vw_tterceiro ter ON (sai.bdcodter = ter.bdcodter)
    LEFT OUTER JOIN tcidade cid ON (SAI.bdcodcid = cid.bdcodcid)
    JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
    WHERE SAI.bdcodsitnf NOT IN (2,3,4,5)
    GROUP BY SAI.bdreflan, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat, cid.bdcoduf,nat.BDCODOPDAPI

) s
GROUP BY bdreflan, bdcodemp,bdcodmatriz,bdcodnat,bdprefixonat,bdcoduf,BDCODOPDAPI
;

/* Create view: VW_VEF_TOT_UF_ENT */
CREATE VIEW VW_VEF_TOT_UF_ENT(
BDCODEMP,
BDREFLAN,
BDCODUF,
BDSIGLAUF,
BDCODNAT,
BDPREFIXONAT,
BDTIPORETENT,
BDVLRCONTAB,
BDBASEICMS,
BDOUTRASICMS,
BDICMSRETENT)
 AS 
SELECT ENT.BDCODEMP,
       ENT.BDREFLAN,
       CID.BDCODUF,
       UF.BDSIGLAUF,
       ITENS.BDCODNAT,
       ITENS.BDPREFIXONAT,
       ITENS.BDTIPORETENT,
       SUM(COALESCE(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB,
       SUM(COALESCE(ITENS.BDBASEICMS, 0)) BDBASEICMS,
       SUM(COALESCE(ITENS.BDOUTRASICMS, 0)) + SUM(COALESCE(ITENS.BDISENTASICMS, 0)) BDOUTRASICMS,
       SUM(COALESCE(ITENS.BDICMSRETENT, 0)) BDICMSRETENT 
FROM VEF_EMP_TMOVENT ENT 
LEFT OUTER JOIN VEF_EMP_TMOVENTITENS ITENS ON ENT.BDCODEMP = ITENS.BDCODEMP AND ENT.BDCHAVE = ITENS.BDCHAVE 
LEFT OUTER JOIN VW_TTERCEIRO TER ON ENT.BDCODTER = TER.BDCODTER 
LEFT OUTER JOIN TCIDADE CID ON TER.BDCODCID = CID.BDCODCID 
LEFT OUTER JOIN TUF UF ON CID.BDCODUF = UF.BDCODUF 
WHERE ENT.bdcodsitnf NOT IN (2,3,4,5)

GROUP BY ENT.BDCODEMP, ENT.BDREFLAN, CID.BDCODUF, UF.BDSIGLAUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT, ITENS.BDTIPORETENT 
ORDER BY ENT.BDCODEMP, ENT.BDREFLAN, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT, ITENS.BDTIPORETENT
;

/* Create view: VW_VEF_TOT_UF_SAI */
CREATE VIEW VW_VEF_TOT_UF_SAI(
BDCODEMP,
BDREFLAN,
BDCODUF,
BDSIGLAUF,
BDCODNAT,
BDPREFIXONAT,
BDIETER,
BDVLRCONTAB,
BDBASEICMS,
BDOUTRASICMS,
BDICMSRETSAI)
 AS 
SELECT SAI.BDCODEMP,
       SAI.BDREFLAN,
       CID.BDCODUF,
       UF.BDSIGLAUF,
       ITENS.BDCODNAT,
       ITENS.BDPREFIXONAT,
       TER.BDIETER,
       SUM(COALESCE(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB,
       SUM(COALESCE(ITENS.BDBASEICMS, 0)) BDBASEICMS,
       SUM(COALESCE(ITENS.BDOUTRASICMS, 0)) + SUM(COALESCE(ITENS.BDISENTASICMS, 0)) BDOUTRASICMS,
       SUM(COALESCE(ITENS.BDVLRST, 0)) BDVLRST 
FROM VEF_EMP_TMOVSAI SAI 
LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS ITENS ON SAI.BDCODEMP = ITENS.BDCODEMP AND SAI.BDCHAVE = ITENS.BDCHAVE 
LEFT OUTER JOIN VW_TTERCEIRO TER ON SAI.BDCODTER = TER.BDCODTER 
LEFT OUTER JOIN TCIDADE CID ON SAI.BDCODCID = CID.BDCODCID 
LEFT OUTER JOIN TUF UF ON CID.BDCODUF = UF.BDCODUF 
WHERE SAI.bdcodsitnf NOT IN (2,3,4,5)

GROUP BY SAI.BDCODEMP, SAI.BDREFLAN, CID.BDCODUF, UF.BDSIGLAUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT, TER.BDIETER 
ORDER BY SAI.BDCODEMP, SAI.BDREFLAN, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT
;

/* Create view: VW_VEF_TOTEXP_UF_ENT_GIASP */
CREATE VIEW VW_VEF_TOTEXP_UF_ENT_GIASP(
BDCODEMP,
BDREFERENCIA,
BDSIGLAUF,
BDCODNAT,
BDTIPORETENT,
BDDIGOPERNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDOUTRASICMS,
BDVLRST,
BDICMSRET,
BDOUTROSIMPOSTOS,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO)
 AS 
SELECT  itens.bdcodemp,
        ENT.bdreflan,
        uf.bdsiglauf,
        itens.bdcodnat,
        itens.bdtiporetent,
        itens.BDDIGOPERNAT,
        itens.bdprefixonat,
        SUM(COALESCE(itens.bdvlrcontab,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.bdvlrst,0)) BDVLRST,
        SUM(COALESCE(itens.bdicmsretent,0)) bdicmsret,
        SUM(0) BDOUTROSIMPOSTOS,
        SUM(COALESCE(impret.bdimpsubstituto,0)) bdimpsusbstituto,
        SUM(COALESCE(impret.bdimpsubstituido,0)) bdimpsusbstituido

FROM vef_emp_tmoventitens itens

LEFT OUTER JOIN VEF_EMP_TMOVENTIMPRETSP impret ON (impret.bdcodemp = itens.bdcodemp AND impret.bdchave = itens.bdchave AND impret.bdordem = itens.bdordem)
LEFT OUTER JOIN vef_emp_tmovent ent ON (ent.bdcodemp = itens.bdcodemp AND ent.bdchave = itens.bdchave)
LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = ent.bdcodter)
LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = ter.bdcodcid)
LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf)
LEFT OUTER JOIN VEF_BASE_TNATOP tnat ON (tnat.bdcodnat = itens.bdcodnat)

WHERE ent.bdcodsitnf NOT IN (2,3,4,5)

GROUP BY itens.bdcodemp, ent.bdreflan, cidade.bdcoduf, uf.bdsiglauf,itens.bdcodnat, itens.BDDIGOPERNAT, itens.bdprefixonat,itens.bdtiporetent
ORDER BY itens.bdcodemp, ent.bdreflan, cidade.bdcoduf, itens.bdcodnat,itens.BDDIGOPERNAT, itens.bdprefixonat
;

/* Create view: VW_VEF_TOTEXP_UF_SAI_GIASP */
CREATE VIEW VW_VEF_TOTEXP_UF_SAI_GIASP(
BDCODEMP,
BDREFERENCIA,
BDSIGLAUF,
BDCODNAT,
BDTIPORETENT,
BDDIGOPERNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDOUTRASICMS,
BDVLRST,
BDICMSRET,
BDOUTROSIMPOSTOS,
BDVLRCONT1,
BDBASEICMS1,
BDVLRCONT2,
BDBASEICMS2,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO)
 AS 
SELECT  itens.bdcodemp,
        SAI.bdreflan,
        uf.bdsiglauf,
        itens.bdcodnat,
        NULL bdtiporetent,
        itens.BDDIGOPERNAT,
        itens.bdprefixonat,
        SUM(COALESCE(itens.bdvlrcontab,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.bdvlrst,0)) BDVLRST,
        SUM(0) bdicmsret,
        SUM(0) BDOUTROSIMPOSTOS,
        SUM(0) BDVLRCONT1,
        SUM(0) BDBASEICMS1,
        SUM(COALESCE(itens.bdvlrcontab,0)) BDVLRCONT2,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS2,
        SUM(COALESCE(impret.bdIMPSUBSTITUTO,0)) BDIMPSUBSTITUTO,
        SUM(COALESCE(impret.bdIMPSUBSTITUIDO,0)) BDIMPSUBSTITUIDO


FROM vef_emp_tmovSAIitens itens

LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = itens.bdcodemp AND impret.bdchave = itens.bdchave AND impret.bdordem = itens.bdordem)
LEFT OUTER JOIN vef_emp_tmovSAI SAI ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave)
LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = SAI.bdcodter)
LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = ter.bdcodcid)
LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf)
LEFT OUTER JOIN VEF_BASE_TNATOP tnat ON (tnat.bdcodnat = itens.bdcodnat)

WHERE ((ter.bdieter IS NULL) OR (ter.bdieter = '') OR (UPPER(ter.bdieter) = 'ISENTO'))

  AND sai.bdcodsitnf NOT IN (2,3,4,5)
  AND itens.BDVLRCONTAB > 0

GROUP BY itens.bdcodemp, SAI.bdreflan, cidade.bdcoduf, uf.bdsiglauf,itens.bdcodnat, itens.BDDIGOPERNAT, itens.bdprefixonat,bdtiporetENT

UNION

SELECT  itens.bdcodemp,
        SAI.bdreflan,
        uf.bdsiglauf,
        itens.bdcodnat,
        NULL bdtiporetent,
        itens.BDDIGOPERNAT,
        itens.bdprefixonat,
        SUM(itens.bdvlrcontab) BDVLRCONTAB,
        SUM(itens.BDBASEICMS) BDBASEICMS,
        SUM(itens.bdvlricms) bdvlricms,
        SUM(itens.BDOUTRASICMS) BDOUTRASICMS,
        SUM(itens.bdvlrst) BDVLRST,
        SUM(0) bdicmsret,
        SUM(0) BDOUTROSIMPOSTOS,
        SUM(itens.bdvlrcontab) BDVLRCONT1,
        SUM(itens.BDBASEICMS) BDBASEICMS1,
        SUM(0) BDVLRCONT2,
        SUM(0) BDBASEICMS2,
        SUM(impret.bdIMPSUBSTITUTO) BDIMPSUBSTITUTO,
        SUM(impret.bdIMPSUBSTITUIDO) BDIMPSUBSTITUIDO

FROM vef_emp_tmovSAIitens itens

LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = itens.bdcodemp AND impret.bdchave = itens.bdchave AND impret.bdordem = itens.bdordem)
LEFT OUTER JOIN vef_emp_tmovSAI SAI ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave)
LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = SAI.bdcodter)
LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = ter.bdcodcid)
LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf)
LEFT OUTER JOIN VEF_BASE_TNATOP tnat ON (tnat.bdcodnat = itens.bdcodnat)

WHERE ((ter.bdieter IS NOT NULL) AND (ter.bdieter <> '') AND (UPPER(ter.bdieter) <> 'ISENTO'))

  AND sai.bdcodsitnf NOT IN (2,3,4,5)
  AND itens.BDVLRCONTAB > 0

GROUP BY itens.bdcodemp, SAI.bdreflan, cidade.bdcoduf, uf.bdsiglauf,itens.bdcodnat, itens.BDDIGOPERNAT, itens.bdprefixonat,bdtiporetENT--, BDIETER
;

/* Create view: VW_VEF_TOTEXP_UF_GIASP */
CREATE VIEW VW_VEF_TOTEXP_UF_GIASP(
BDCODEMP,
BDREFERENCIA,
BDSIGLAUF,
BDCODNAT,
BDTIPORETENT,
BDDIGOPERNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDOUTRASICMS,
BDVLRST,
BDICMSRET,
BDOUTROSIMPOSTOS,
BDVLRCONT1,
BDBASEICMS1,
BDVLRCONT2,
BDBASEICMS2,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO)
 AS 
SELECT sai.BDCODEMP,
       sai.BDREFERENCIA,
       sai.BDSIGLAUF,
       sai.BDCODNAT,
       sai.BDTIPORETENT,
       sai.BDDIGOPERNAT,
       sai.BDPREFIXONAT,
       SUM(COALESCE(sai.BDVLRCONTAB,0)) BDVLRCONTAB,
       SUM(COALESCE(sai.BDBASEICMS,0)) BDBASEICMS,
       SUM(COALESCE(sai.BDVLRICMS,0)) BDVLRICMS,
       SUM(COALESCE(sai.BDOUTRASICMS,0)) BDOUTRASICMS,
       SUM(COALESCE(sai.BDVLRST,0)) BDVLRST,
       SUM(COALESCE(sai.BDICMSRET,0)) BDICMSRET,
       SUM(COALESCE(sai.BDOUTROSIMPOSTOS,0)) BDOUTROSIMPOSTOS,
       SUM(COALESCE(sai.BDVLRCONT1,0)) BDVLRCONT1,
       SUM(COALESCE(sai.BDBASEICMS1,0)) BDBASEICMS1,
       SUM(COALESCE(sai.BDVLRCONT2,0)) BDVLRCONT2,
       SUM(COALESCE(sai.BDBASEICMS2,0)) BDBASEICMS2,
       SUM(COALESCE(sai.bdimpsubstituto,0)) bdimpsubstituto,
       SUM(COALESCE(sai.bdimpsubstituido,0)) bdimpsubstituido

FROM VW_VEF_TOTEXP_UF_SAI_GIASP sai

GROUP BY sai.BDCODEMP, sai.BDREFERENCIA, sai.BDSIGLAUF, sai.BDCODNAT, sai.BDDIGOPERNAT, sai.BDPREFIXONAT, sai.BDTIPORETENT
ORDER BY sai.BDCODEMP, sai.BDREFERENCIA, sai.BDCODNAT, sai.BDDIGOPERNAT, sai.BDPREFIXONAT
;

/* Create view: VWEF_EMPMENSAL_ABA_FEDE_REF */
CREATE VIEW VWEF_EMPMENSAL_ABA_FEDE_REF(
BDCODEMP,
BDREFEMP,
BDPERFILSPED,
BDATIVIDADESPED,
BDTIPODECLARANTEDMED,
BDREGISTROANSDMED,
BDNUMEROCNESDMED,
BDLRISSSN,
BDINDNATPJ,
BDINDATIV,
BDCODACESSOSN)
 AS 
SELECT
    BDCODEMP,
    BDREFEMP,
    BDPERFILSPED,
    BDATIVIDADESPED,
    BDTIPODECLARANTEDMED,
    BDREGISTROANSDMED,
    BDNUMEROCNESDMED,
    BDLRISSSN,
    BDINDNATPJ,
    BDINDATIV,
    BDCODACESSOSN
FROM VWEF_EMPMENSAL_ABA_FEDE x
WHERE x.bdrefemp = COALESCE(

  (SELECT MAX(y.bdrefemp) bdrefempx FROM VWEF_EMPMENSAL_ABA_FEDE y
    WHERE y.bdrefemp <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) AND y.bdcodemp = x.bdcodemp GROUP BY y.bdcodemp)
  ,
  (SELECT MIN(y.bdrefemp) bdrefempx FROM VWEF_EMPMENSAL_ABA_FEDE y WHERE y.bdcodemp = x.bdcodemp GROUP BY y.bdcodemp)

  )
;


/* Altering existing trigger... */
SET TERM ^ ;

ALTER TRIGGER EMPRESAS_TSOC_BU0
AS
  DECLARE VARIABLE vCODCOL INTEGER;
  DECLARE VARIABLE vREFCOL INTEGER;
BEGIN
/* Gilberto - 25/10/2017 - 20915 - Esse processo ? feito pelo ?nico

   vCODCOL = NULL;
   SELECT FIRST 1 x.bdCODCOL FROM vrh_emp_tcolcon_doc x
   LEFT OUTER JOIN vrh_emp_trescisao r ON (x.bdcodemp = r.bdcodemp AND x.bdcodcol = r.bdcodcol)
   WHERE (x.BDCODEMP = NEW.bdcodemp) AND (x.BDCONTRCOL = 1) AND  -- and (r.bddatarescisao is null) and
         (x.BDCPFCOL = NEW.bdcgcceisoc) INTO :vCODCOL;

   -- Seleciona dados basicos do colaborados e joga nas vari?veis
   IF (vCODCOL IS NOT NULL) THEN
     BEGIN
       UPDATE vrh_emp_tcolcon
         SET BDDATANASCCOL = NEW.BDDATANASCSOC,
             BDCODCIDNASC = NEW.BDCODCIDNASC
       WHERE (BDCODEMP    = NEW.bdcodemp) AND
             (BDCONTRCOL  = 1) AND
             (BDCODCOL    = :vCODCOL);

       UPDATE vrh_emp_tcol_hist
         SET BDCODPAIS = NEW.BDCODPAISORIG,
             BDNATURALIZADOCOL = NEW.BDNATURALIZADO,
             BDPORTNAT = NEW.BDPORTNAT,
             BDDATANATURALIZACAO = NEW.BDDATANATURALIZACAO,
             BDDTAPOSENT = new.BDDATACHEBRASIL
       WHERE (BDCODEMP = NEW.BDCODEMP) AND
             (BDCONTRCOL = 1) AND
             (BDCODCOL   = :vCODCOL);
       
       SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database INTO :vREFCOL;
       if (COALESCE(vREFCOL, 0) = 0) then
         vREFCOL = SUBSTRING(NEW.BDDATAENTSOC FROM 1 FOR 4)||SUBSTRING(NEW.BDDATAENTSOC FROM 6 FOR 2);

       UPDATE OR INSERT INTO VRH_EMP_TCOLCON_REF
              (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL)
       VALUES (NEW.BDCODEMP, :vCODCOL, :vREFCOL, 1)
       MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);

       UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CAD
              (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL, BDCODCID,
--               BDNOMCOL, Gilberto - 19/10/2017 - 20915
               BDENDCOL, BDNUMCOL, BDCOMPLCOL, BDBAICOL, BDCEPCOL,
               BDLOGRCOL, BDSEXOCOL, BDGRAUINSTCOL, BDDATACHEBRASILCOL,
               BDESTCIVCOL, BDCODPAISRES)
       VALUES (NEW.BDCODEMP, :vCODCOL, :vREFCOL, 1, NEW.BDCODCID,
--               NEW.BDNOMSOC, Gilberto - 19/10/2017 - 20915
               NEW.BDENDSOC, NEW.BDNUMSOC, NEW.BDCOMPLSOC, NEW.BDBAISOC, NEW.BDCEPSOC,
               NEW.BDLOGRSOC, NEW.BDSEXO, NEW.BDGRAUINST, NEW.BDDATACHEBRASIL,
               new.bdestcivilsoc, NEW.bdcodpais)
       MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);

       if (new.bdcodpais is null) then
       begin
         UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CAD
                (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL, BDCODPAISRES)
         VALUES (NEW.BDCODEMP, :vCODCOL, :vREFCOL, 1, (select first 1 BDCODPAIS from TPAIS where upper(bddescpais)='BRASIL'))
         MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);
       end


       UPDATE OR INSERT INTO VRH_EMP_TCOLCON_DOCREF
              (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL,
               BDRGCOL, BDORGEMIRGCOL, BDCODUFRG, BDDATAEMIRGCOL, BDPISCOL)
       VALUES (NEW.BDCODEMP, :vCODCOL, :vREFCOL, 1,
               NEW.BDRGSOC, NEW.BDORGEMISOC, NEW.BDCODUFRG, NEW.BDDATAEMIRG, NEW.BDINSCNIT)
       MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);
    END
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER EMPRESAS_TSOC_REF_AIU0
AS
  DECLARE VARIABLE vCODCOL INTEGER;
BEGIN
/* Gilberto - 25/10/2017 - 20915 - Esse processo ? feito pelo ?nico

   vCODCOL = NULL;
   SELECT FIRST 1 x.bdCODCOL FROM vrh_emp_tcolcon_doc x
   INNER JOIN empresas_tsoc soc ON (soc.bdcodemp = x.bdcodemp AND soc.bdcodsoc = NEW.bdcodsoc AND soc.bdcgcceisoc = x.BDCPFCOL)
   LEFT OUTER JOIN vrh_emp_trescisao r ON (x.bdcodemp = r.bdcodemp AND x.bdcodcol = r.bdcodcol)
   WHERE (x.BDCODEMP = NEW.bdcodemp)
   AND (x.BDCONTRCOL = 1)
   INTO :vCODCOL;

   IF ((vCODCOL IS NOT NULL) AND (vCODCOL > 0) AND (NEW.bdnomsoc IS NOT NULL)) THEN
   BEGIN
     UPDATE OR INSERT INTO VRH_EMP_TCOLCON_REF
            (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL)
     VALUES (NEW.BDCODEMP, :vCODCOL, NEW.BDREFSOC, 1)
     MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);

     UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CAD
            (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL,
             BDNOMCOL, BDDDDCOL, BDFONECOL, BDDDDCELCOL, BDCELCOL, BDEMAILCOL)
     VALUES (NEW.BDCODEMP, :vCODCOL, NEW.BDREFSOC, 1,
             NEW.BDNOMSOC, NEW.BDDDDSOC, NEW.BDTELRESSOC, NEW.BDDDCELSOC, NEW.BDTELCELSOC, NEW.BDEMAILSOC)
     MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);
   END
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMP_SPED_FCONT_REF_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo;   --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
          BEGIN
            SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo;--#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
          END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAIMPOSTO_AI0
AS
  DECLARE VARIABLE wcodemp INTEGER;
  DECLARE VARIABLE wcodimp INTEGER;
  DECLARE VARIABLE wrefemp INTEGER;
  DECLARE VARIABLE wreffim INTEGER;
  DECLARE VARIABLE wrefant INTEGER;
  DECLARE VARIABLE wdata DATE;
  DECLARE VARIABLE wtotal INTEGER;
BEGIN
/*
  wdata = addmonth(CAST(SUBSTRING(NEW.bdrefemp FROM 1 FOR 4)||'-'||SUBSTRING(NEW.bdrefemp FROM 5 FOR 2)||'-01' AS TIMESTAMP), -1);
  wrefant = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);

  FOR SELECT bdcodemp, bdcodimp, bdrefemp, bdreffimimp FROM tempresaimposto
      WHERE bdcodemp = NEW.bdcodemp
      AND bdcodimp = NEW.bdcodimp
      AND bdrefemp <> NEW.bdrefemp
      ORDER BY bdrefemp DESC
      INTO :wcodemp, :wcodimp, :wrefemp, :wreffim DO
      BEGIN
        IF ((wreffim IS NULL) AND (wrefant >= wrefemp)) THEN
           BEGIN
             UPDATE tempresaimposto SET
             bdreffimimp = :wrefant
             WHERE bdcodemp = :wcodemp
             AND bdcodimp = :wcodimp
             AND bdrefemp = :wrefemp;
           END
         wdata = addmonth(CAST(SUBSTRING(wrefemp FROM 1 FOR 4)||'-'||SUBSTRING(wrefemp FROM 5 FOR 2)||'-01' AS TIMESTAMP), -1);
         wrefant = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);
      END

-- gilberto - 02/07/2015 - ALT:#11974 - retirado porque fica muito lento ao selecionar tributos por empresa
--  SELECT total FROM vct_tarefas_automaticas(NEW.bdcodemp) INTO wTotal;-- Gilberto - 04/09/2014 - ALT:#9748 - Centraliza??o da rotina
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAIMPOSTO_BI0
AS
BEGIN
  -- gilberto - ALT:#10115 - dias ?teis para entrega
  SELECT bdentrega FROM timposto WHERE bdcodimp = NEW.bdcodimp INTO NEW.bdentrega;
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAS_AU0
AS
  DECLARE VARIABLE vEMPREF INTEGER;
  DECLARE VARIABLE vCODIMP INTEGER;
  DECLARE VARIABLE vCLASSIMP VARCHAR(40);
BEGIN
  -- gilberto - 11/03/2014 - ALT#:7290 - finaliza impostos que s?o calculados apenas pela matriz. Obs.: verificar automatismo da tabela TEMPRESAS_REF
  IF ((COALESCE(OLD.bdcodmatriz, 0) <> COALESCE(NEW.bdcodmatriz, 0)) AND (NEW.bdcodmatriz IS NOT NULL)) THEN
     BEGIN
       SELECT bdempref FROM vw_empresas_ref_atual WHERE bdcodemp = NEW.bdcodemp INTO :vempref;
       IF (SUBSTRING(vempref FROM 5 FOR 2) = '01') THEN
          vempref = vempref - 89;
       ELSE
          vempref = vempref - 1;

       FOR SELECT emp.bdcodimp, timp.bdclassimp FROM tempresaimposto emp
           INNER JOIN timposto timp ON (timp.bdcodimp = emp.bdcodimp)
           WHERE emp.bdcodemp = NEW.bdcodemp
           AND ((SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.01.03')) = '01.01.01.03') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.01.04')) = '01.01.01.04') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.01')) = '01.01.02.01') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.02')) = '01.01.02.02') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.03')) = '01.01.02.03') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.04')) = '01.01.02.04') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.06')) = '01.01.02.06') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.08')) = '01.01.02.08') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.09')) = '01.01.02.09') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.10')) = '01.01.02.10'))
           INTO :vcodimp, :vclassimp DO
           BEGIN
             UPDATE tempresaimposto SET
             bdreffimimp = :vempref
             WHERE bdcodemp = NEW.bdcodemp
             AND bdcodimp = :vcodimp;
           END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAS_BU0
AS
  DECLARE VARIABLE vCODESC INTEGER;
  DECLARE VARIABLE vCODPLANOONLINE INTEGER;
  DECLARE VARIABLE vCODPLAPADRAO INTEGER;
  DECLARE VARIABLE vCODHIST INTEGER;
  DECLARE VARIABLE vCODCENTROS INTEGER;
  DECLARE VARIABLE vCODEMPLANC INTEGER;
BEGIN
  IF (NEW.bdcodmatriz IS NULL) THEN
     UPDATE tempresas SET bdcodesc = NEW.bdcodesc WHERE bdcodmatriz = NEW.bdcodemp AND bdcodesc <> NEW.bdcodesc;
  ELSE
  IF (COALESCE(NEW.BDCODMATRIZ,0) <> COALESCE(OLD.BDCODMATRIZ, 0)) THEN
     BEGIN
       SELECT bdcodesc FROM tempresas WHERE bdcodemp = NEW.bdcodmatriz INTO :vcodesc;
       NEW.bdcodesc = vcodesc;

       --#Alt:19940 - Precisamos verificar se n?o existe movimenta??o na matriz e filiais antes de fazer a altera??o
       SELECT FIRST 1 bdCODEMP FROM vsuc_empresas_tlan
       WHERE
       bdCODEMP IN (SELECT bdCODEMP FROM tempresas WHERE ((bdCODEMP = NEW.bdCODMATRIZ) OR (bdCODMATRIZ = NEW.bdCODMATRIZ)))
       INTO :vCODEMPLANC;

       IF (vCODEMPLANC IS NULL) THEN
          BEGIN
            SELECT FIRST 1 BDCODPLANOONLINE, BDCODPLAPADRAO, BDCODHIST, BDCODCENTROS
            FROM vw_empresas_ref_atual
            WHERE bdcodemp = NEW.bdcodmatriz
            INTO :vCODPLANOONLINE, :vCODPLAPADRAO, :vCODHIST, :vCODCENTROS;
    
            UPDATE tempresas_ref SET
            BDCODPLANOONLINE = :vcodplanoonline,
            BDCODPLAPADRAO = :vCODPLAPADRAO,
            BDCODHIST = :vCODHIST,
            BDCODCENTROS = :vCODCENTROS
            WHERE
            (bdcodemp = NEW.bdcodemp) AND
            ((BDCODPLANOONLINE <> :vcodplanoonline) OR
             (BDCODPLAPADRAO <> :vCODPLAPADRAO) OR
             (BDCODHIST <> :vCODHIST) OR
             (BDCODCENTROS <> :vCODCENTROS));
          END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAS_HIST_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 14/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 14/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAS_IMG_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo;  --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
          BEGIN
            SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo;  --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
          END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAS_REF_AI1
AS
  DECLARE VARIABLE vCount INTEGER;
  DECLARE VARIABLE vrefant INTEGER;
  DECLARE VARIABLE vrefini INTEGER;
  DECLARE VARIABLE vreffin INTEGER;
  DECLARE VARIABLE vrefaux INTEGER;
  DECLARE VARIABLE vcodmatriz INTEGER;
  DECLARE VARIABLE vcodimp INTEGER;
  DECLARE VARIABLE vcodimp1 INTEGER;
  DECLARE VARIABLE vcodimp2 INTEGER;
  DECLARE VARIABLE vclassimp VARCHAR(20);
  DECLARE VARIABLE vcodplatrib INTEGER;
  DECLARE VARIABLE vnovaempresa SMALLINT;
BEGIN
  EXECUTE PROCEDURE sp_atualiza_apelido_ie_emp(NEW.bdcodemp,NEW.bdrefemp);

  /* IMPOSTOS COM MAIS DE UMA REFERENCIA EM ABERTO */
  FOR SELECT bdcodimp, bdrefemp, bdreffimimp FROM tempresaimposto imp
      WHERE bdcodemp = NEW.bdcodemp
      AND (SELECT COUNT(*) FROM tempresaimposto WHERE bdcodemp = imp.bdcodemp AND bdcodimp = imp.bdcodimp AND bdreffimimp IS NULL) > 1
      ORDER BY bdcodemp, bdcodimp, bdrefemp DESC
      INTO :vcodimp, :vrefini, :vreffin DO
      BEGIN
        IF (vcodimp <> vcodimp1) THEN
           vrefant = NULL;
        IF (vrefant IS NOT NULL) THEN
        BEGIN
          IF (SUBSTRING(vrefant FROM 5 FOR 2) = '01') THEN
             vrefant = vrefant - 89;
          ELSE
             vrefant = vrefant - 1;
          UPDATE tempresaimposto SET bdreffimimp = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp = :vrefini;
        END
        vcodimp1 = vcodimp;
        vrefant = vrefini;
      END
  /* OBRIGA??ES COM MAIS DE UMA REFERENCIA EM ABERTO */
  FOR SELECT bdcodobr, bdrefini, bdreffin FROM vct_tributario_empresa trib
      WHERE bdcodemp = NEW.BDCODEMP
      AND bdcodobr IS NOT NULL
      AND (SELECT COUNT(bdcodemp) FROM vct_tributario_empresa WHERE bdcodemp = trib.bdcodemp AND bdcodobr = trib.bdcodobr AND bdreffin IS NULL) > 1
      ORDER BY bdcodemp, bdcodobr, bdrefini DESC
      INTO :vcodimp, :vrefini, :vreffin DO
      BEGIN
        IF (vcodimp <> vcodimp1) THEN
           vrefant = NULL;
        IF (vrefant IS NOT NULL) THEN
        BEGIN
          IF (SUBSTRING(vrefant FROM 5 FOR 2) = '01') THEN
             vrefant = vrefant - 89;
          ELSE
             vrefant = vrefant - 1;
          UPDATE VCT_TRIBUTARIO_EMPRESA SET bdreffiN = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodOBR = :vcodimp AND bdrefINI = :vrefini;
        END
        vcodimp1 = vcodimp;
        vrefant = vrefini;
      END
  /* SERVI?OS COM MAIS DE UMA REFERENCIA EM ABERTO */
  FOR SELECT bdcodobr, bdrefini, bdreffin FROM vct_tributario_empresa trib
      WHERE bdcodemp = NEW.BDCODEMP
      AND bdcodSER IS NOT NULL
      AND (SELECT COUNT(bdcodemp) FROM vct_tributario_empresa WHERE bdcodemp = trib.bdcodemp AND bdcodSER = trib.bdcodser AND bdreffin IS NULL) > 1
      ORDER BY bdcodemp, bdcodobr, bdrefini DESC
      INTO :vcodimp, :vrefini, :vreffin DO
      BEGIN
        IF (vcodimp <> vcodimp1) THEN
           vrefant = NULL;
        IF (vrefant IS NOT NULL) THEN
        BEGIN
          IF (SUBSTRING(vrefant FROM 5 FOR 2) = '01') THEN
             vrefant = vrefant - 89;
          ELSE
             vrefant = vrefant - 1;
          UPDATE VCT_TRIBUTARIO_EMPRESA SET bdreffiN = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodSER = :vcodimp AND bdrefINI = :vrefini;
        END
        vcodimp1 = vcodimp;
        vrefant = vrefini;
      END

  SELECT COUNT(*) FROM tempresas_ref WHERE bdcodemp = NEW.bdcodemp INTO :vnovaempresa;
  SELECT FIRST 1 emp.bdcodplatrib FROM tempresas_ref emp WHERE emp.bdcodemp = NEW.bdcodemp AND emp.bdrefemp <= NEW.bdrefemp ORDER BY emp.bdrefemp INTO :vcodplatrib;
  /* APENAS SE HOUVER MUDAN?A DE PLANO TRIBUT?RIO ----------------------------------------------------------------------------------------------------------------------------------------------------- */
  IF (((COALESCE(NEW.bdcodplatrib, 0) <> COALESCE(vcodplatrib, 0))) OR ((vnovaempresa <= 1) AND (OLD.bdcodemp IS NULL))) THEN
  BEGIN
    /* PLANO TRIBUT?RIO ANTERIOR */
    IF (OLD.bdcodplatrib IS NULL) THEN
       SELECT FIRST 1 BDCODPLATRIB FROM tempresas_ref WHERE BDCODEMP = NEW.BDCODEMP AND BDREFEMP < NEW.bdrefemp ORDER BY BDREFEMP DESC INTO :vcodplatrib;
    ELSE
       vcodplatrib = OLD.bdcodplatrib;
    /* REFERENCIA ANTERIOR */
    vrefant = NEW.bdrefemp;
    IF (SUBSTRING(vrefant FROM 5 FOR 2) = '01') THEN
       vrefant = vrefant - 89;
    ELSE
       vrefant = vrefant - 1;
    /* MATRIZ */
    SELECT bdcodmatriz FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO :vcodmatriz;

/* IMPOSTOS ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    /* LISTA OS IMPOSTOS DOS DOIS PLANOS, ANTERIOR E ATUAL, PARA COMPARAR AS MUDAN?AS E COM ISSO FINALIZA OU INSERE OS IMPOSTOS */
    FOR SELECT DISTINCT --bdcodplatrib1, bdcodplatrib2,
               CASE WHEN (bdcodimp1 IS NULL) THEN bdcodimp2 ELSE bdcodimp1 END bdcodimp,
               bdcodimp1, bdcodimp2, imp.bdclassimp AS bdclassimp2
        FROM (
        SELECT trib1.bdcodplatrib AS bdcodplatrib1, trib1.bdcodimp AS bdcodimp1, trib2.bdcodplatrib AS bdcodplatrib2, trib2.bdcodimp AS bdcodimp2 FROM vct_tributos_plano_tributario trib1
        LEFT JOIN vct_tributos_plano_tributario trib2 ON (trib2.bdcodplatrib = NEW.BDCODPLATRIB AND trib2.bdcodimp IS NOT NULL AND trib1.bdcodimp = trib2.bdcodimp)
        WHERE trib1.bdcodplatrib = :vcodplatrib
        AND trib1.bdcodimp IS NOT NULL
        UNION
        SELECT trib2.bdcodplatrib, trib2.bdcodimp, trib1.bdcodplatrib, trib1.bdcodimp FROM vct_tributos_plano_tributario trib1
        LEFT JOIN vct_tributos_plano_tributario trib2 ON (trib2.bdcodplatrib = :vcodplatrib AND trib2.bdcodimp IS NOT NULL AND trib1.bdcodimp = trib2.bdcodimp)
        WHERE trib1.bdcodplatrib = NEW.BDCODPLATRIB
        AND trib1.bdcodimp IS NOT NULL
        )
        LEFT OUTER JOIN timposto imp ON (imp.bdcodimp = bdcodimp2 AND imp.bdperapuracao <> 11)
        ORDER BY bdcodimp
        INTO :vcodimp, :vcodimp1, :vcodimp2, :vclassimp DO
        BEGIN
          IF (vcodimp2 IS NULL) THEN
          BEGIN
            UPDATE tempresaimposto SET bdreffimimp = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND (bdreffimimp IS NULL OR (bdreffimimp = 0));
          END
          ELSE
          /* quando for filial, n?o importar esses tributos, pois os mesmos s?o calculados apenas pela matriz */
          IF ((vcodmatriz IS NULL) OR
              ((vcodmatriz IS NOT NULL) AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.01.03')) <> '01.01.01.03') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.01.04')) <> '01.01.01.04') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.01')) <> '01.01.02.01') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.02')) <> '01.01.02.02') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.03')) <> '01.01.02.03') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.04')) <> '01.01.02.04') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.06')) <> '01.01.02.06') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.08')) <> '01.01.02.08') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.09')) <> '01.01.02.09') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.10')) <> '01.01.02.10'))) THEN
          BEGIN
            vcount = NULL;
            SELECT FIRST 1 bdcodimp FROM tempresaimposto WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp <= NEW.bdrefemp AND bdreffimimp IS NULL INTO :vcount;
            IF (vcount IS NULL) THEN
               UPDATE OR INSERT INTO tempresaimposto (bdcodemp, bdrefemp, bdcodimp, bdreffimimp) VALUES (NEW.bdcodemp, NEW.bdrefemp, :vcodimp, NULL) MATCHING (bdcodemp, bdrefemp, bdcodimp);

            vrefaux = NULL;
            FOR SELECT bdrefemp FROM tempresaimposto WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp > NEW.bdrefemp AND bdreffimimp IS NULL INTO :vrefaux DO
            BEGIN
              IF (vrefaux IS NOT NULL) THEN
              BEGIN
                IF (SUBSTRING(vrefaux FROM 5 FOR 2) = '01') THEN
                   vrefaux = vrefaux - 89;
                ELSE
                   vrefaux = vrefaux - 1;
  
                UPDATE tempresaimposto SET bdreffimimp = :vrefaux WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp = NEW.bdrefemp AND bdreffimimp IS NULL;
              END
            END
          END
        END
    /* AJUSTA REFER?NCIAS QUANDO ALTERA UM ANTERIOR A OUTRA QUE J? FOI INSERIDA */
    vcodimp1 = 0;
    FOR SELECT bdcodimp, bdrefemp, bdreffimimp
        FROM tempresaimposto imp
        WHERE bdcodemp = NEW.bdcodemp
        AND (SELECT COUNT(*) FROM tempresaimposto WHERE bdcodemp = imp.bdcodemp AND bdcodimp = imp.bdcodimp) > 1
        ORDER BY bdcodemp, bdcodimp, bdrefemp DESC
        INTO :vcodimp, :vrefini, :vreffin DO
        BEGIN
          IF (vcodimp1 <> vcodimp) THEN
             vrefant = 0;

          IF ((vrefini IS NOT NULL) AND (vrefant <> 0)) THEN
          BEGIN
            IF (NOT ((vreffin >= vrefini) AND (vreffin <= vrefant))) THEN
            BEGIN
              UPDATE tempresaimposto SET bdreffimimp = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp = :vrefini;
            END
          END

          vcodimp1 = vcodimp;
          IF (SUBSTRING(vrefini FROM 5 FOR 2) = '01') THEN
             vrefant = vrefini - 89;
          ELSE
             vrefant = vrefini - 1;
        END

/* OBRIGA??ES ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    /* LISTA OS IMPOSTOS DOS DOIS PLANOS, ANTERIOR E ATUAL, PARA COMPARAR AS MUDAN?AS E COM ISSO FINALIZA OU INSERE OS IMPOSTOS */
    FOR SELECT DISTINCT --bdcodplatrib1, bdcodplatrib2,
               CASE WHEN (bdcodOBR1 IS NULL) THEN bdcodOBR2 ELSE bdcodOBR1 END bdcodimp,
               bdcodOBR1, bdcodOBR2
        FROM (
        SELECT trib1.bdcodplatrib AS bdcodplatrib1, trib1.bdcodobr AS bdcodOBR1, trib2.bdcodplatrib AS bdcodplatrib2, trib2.bdcodobr AS bdcodOBR2 FROM vct_tributos_plano_tributario trib1
        LEFT JOIN vct_tributos_plano_tributario trib2 ON (trib2.bdcodplatrib = NEW.bdcodplatrib AND trib2.bdcodOBR IS NOT NULL AND trib1.bdcodOBR = trib2.bdcodobr)
        WHERE trib1.bdcodplatrib = :vcodplatrib
        AND trib1.bdcodOBR IS NOT NULL
        UNION
        SELECT trib2.bdcodplatrib, trib2.bdcodOBR, trib1.bdcodplatrib, trib1.bdcodobr FROM vct_tributos_plano_tributario trib1
        LEFT JOIN vct_tributos_plano_tributario trib2 ON (trib2.bdcodplatrib = :vcodplatrib AND trib2.bdcodOBR IS NOT NULL AND trib1.bdcodOBR = trib2.bdcodOBR)
        WHERE trib1.bdcodplatrib = NEW.bdcodplatrib 
        AND trib1.bdcodOBR IS NOT NULL
        )
        LEFT OUTER JOIN vct_base_obrigacao imp ON (imp.bdcodobrser = bdcodOBR2 AND imp.bdperiodicidade <> 11)
        ORDER BY bdcodimp
        INTO :vcodimp, :vcodimp1, :vcodimp2 DO
        BEGIN
          IF (vcodimp2 IS NULL) THEN
          BEGIN
            UPDATE vct_tributario_empresa SET bdreffiN = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodOBR = :vcodimp AND (bdreffiN IS NULL OR (bdreffiN = 0));
          END
          ELSE
          BEGIN
            vcount = NULL;
            SELECT FIRST 1 bdcodOBR FROM vct_tributario_empresa WHERE bdcodemp = NEW.bdcodemp AND bdcodOBR = :vcodimp AND bdrefINI <= NEW.bdrefemp AND bdreffiN IS NULL INTO :vcount;
            IF (vcount IS NULL) THEN
               UPDATE OR INSERT INTO vct_tributario_empresa (bdcodemp, bdrefINI, bdcodOBR, bdreffiN) VALUES (NEW.bdcodemp, NEW.bdrefemp, :vcodimp, NULL) MATCHING (bdcodemp, bdrefINI, bdcodOBR);

            vrefaux = NULL;
            FOR SELECT bdrefINI FROM vct_tributario_empresa WHERE bdcodemp = NEW.bdcodemp AND bdcodOBR = :vcodimp AND bdrefINI > NEW.bdrefemp AND bdreffiN IS NULL INTO :vrefaux DO
            BEGIN
              IF (vrefaux IS NOT NULL) THEN
              BEGIN
                IF (SUBSTRING(vrefaux FROM 5 FOR 2) = '01') THEN
                   vrefaux = vrefaux - 89;
                ELSE
                   vrefaux = vrefaux - 1;
  
                UPDATE vct_tributario_empresa SET bdreffiN = :vrefaux WHERE bdcodemp = NEW.bdcodemp AND bdcodOBR = :vcodimp AND bdrefINI = NEW.bdrefemp AND bdreffiN IS NULL;
              END
            END
          END
        END
    /* AJUSTA REFER?NCIAS QUANDO ALTERA UM ANTERIOR A OUTRA QUE J? FOI INSERIDA */
    vcodimp1 = 0;
    FOR SELECT bdcodobr, bdrefini, bdreffin
        FROM vct_tributario_empresa imp
        WHERE bdcodemp = NEW.bdcodemp
        AND bdcodobr IS NOT NULL
        AND (SELECT COUNT(*) FROM vct_tributario_empresa WHERE bdcodemp = imp.bdcodemp AND bdcodobr = imp.bdcodobr) > 1
        ORDER BY bdcodemp, bdcodobr, bdrefini DESC
        INTO :vcodimp, :vrefini, :vreffin DO
        BEGIN
          IF (vcodimp1 <> vcodimp) THEN
             vrefant = 0;

          IF ((vrefini IS NOT NULL) AND (vrefant <> 0)) THEN
          BEGIN
            IF (NOT ((vreffin >= vrefini) AND (vreffin <= vrefant))) THEN
            BEGIN
              UPDATE vct_tributario_empresa SET bdreffin = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodobr = :vcodimp AND bdrefini = :vrefini;
            END
          END

          vcodimp1 = vcodimp;
          IF (SUBSTRING(vrefini FROM 5 FOR 2) = '01') THEN
             vrefant = vrefini - 89;
          ELSE
             vrefant = vrefini - 1;
        END

/* SERVI?OS ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    /* LISTA OS IMPOSTOS DOS DOIS PLANOS, ANTERIOR E ATUAL, PARA COMPARAR AS MUDAN?AS E COM ISSO FINALIZA OU INSERE OS IMPOSTOS */
    FOR SELECT DISTINCT --bdcodplatrib1, bdcodplatrib2,
               CASE WHEN (bdcodSER1 IS NULL) THEN bdcodSER2 ELSE bdcodSER1 END bdcodimp,
               bdcodSER1, bdcodSER2
        FROM (
        SELECT trib1.bdcodplatrib AS bdcodplatrib1, trib1.bdcodSER AS bdcodSER1, trib2.bdcodplatrib AS bdcodplatrib2, trib2.bdcodSER AS bdcodSER2 FROM vct_tributos_plano_tributario trib1
        LEFT JOIN vct_tributos_plano_tributario trib2 ON (trib2.bdcodplatrib = NEW.bdcodplatrib AND trib2.bdcodser IS NOT NULL AND trib1.bdcodSER = trib2.bdcodSER)
        WHERE trib1.bdcodplatrib = :vcodplatrib
        AND trib1.bdcodSER IS NOT NULL
        UNION
        SELECT trib2.bdcodplatrib, trib2.bdcodSER, trib1.bdcodplatrib, trib1.bdcodSER FROM vct_tributos_plano_tributario trib1
        LEFT JOIN vct_tributos_plano_tributario trib2 ON (trib2.bdcodplatrib = :vcodplatrib AND trib2.bdcodSER IS NOT NULL AND trib1.bdcodSER = trib2.bdcodSER)
        WHERE trib1.bdcodplatrib = NEW.bdcodplatrib 
        AND trib1.bdcodSER IS NOT NULL
        )
        LEFT OUTER JOIN vct_base_obrigacao imp ON (imp.bdcodobrser = bdcodSER2 AND imp.bdperiodicidade <> 11)
        ORDER BY bdcodimp
        INTO :vcodimp, :vcodimp1, :vcodimp2 DO
        BEGIN
          IF (vcodimp2 IS NULL) THEN
          BEGIN
            UPDATE vct_tributario_empresa SET bdreffiN = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodser = :vcodimp AND (bdreffiN IS NULL OR (bdreffiN = 0));
          END
          ELSE
          BEGIN
            vcount = NULL;
            SELECT FIRST 1 bdcodser FROM vct_tributario_empresa WHERE bdcodemp = NEW.bdcodemp AND bdcodser = :vcodimp AND bdrefINI <= NEW.bdrefemp AND bdreffiN IS NULL INTO :vcount;
            IF (vcount IS NULL) THEN
               UPDATE OR INSERT INTO vct_tributario_empresa (bdcodemp, bdrefINI, bdcodser, bdreffiN) VALUES (NEW.bdcodemp, NEW.bdrefemp, :vcodimp, NULL) MATCHING (bdcodemp, bdrefINI, bdcodser);

            vrefaux = NULL;
            FOR SELECT bdrefINI FROM vct_tributario_empresa WHERE bdcodemp = NEW.bdcodemp AND bdcodser = :vcodimp AND bdrefINI > NEW.bdrefemp AND bdreffiN IS NULL INTO :vrefaux DO
            BEGIN
              IF (vrefaux IS NOT NULL) THEN
              BEGIN
                IF (SUBSTRING(vrefaux FROM 5 FOR 2) = '01') THEN
                   vrefaux = vrefaux - 89;
                ELSE
                   vrefaux = vrefaux - 1;
  
                UPDATE vct_tributario_empresa SET bdreffiN = :vrefaux WHERE bdcodemp = NEW.bdcodemp AND bdcodser = :vcodimp AND bdrefINI = NEW.bdrefemp AND bdreffiN IS NULL;
              END
            END
          END
        END
    /* AJUSTA REFER?NCIAS QUANDO ALTERA UM ANTERIOR A OUTRA QUE J? FOI INSERIDA */
    vcodimp1 = 0;
    FOR SELECT bdcodser, bdrefini, bdreffin
        FROM vct_tributario_empresa imp
        WHERE bdcodemp = NEW.bdcodemp
        AND bdcodser IS NOT NULL
        AND (SELECT COUNT(*) FROM vct_tributario_empresa WHERE bdcodemp = imp.bdcodemp AND bdcodser = imp.bdcodser) > 1
        ORDER BY bdcodemp, bdcodser, bdrefini DESC
        INTO :vcodimp, :vrefini, :vreffin DO
        BEGIN
          IF (vcodimp1 <> vcodimp) THEN
             vrefant = 0;

          IF ((vrefini IS NOT NULL) AND (vrefant <> 0)) THEN
          BEGIN
            IF (NOT ((vreffin >= vrefini) AND (vreffin <= vrefant))) THEN
            BEGIN
              UPDATE vct_tributario_empresa SET bdreffin = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodser = :vcodimp AND bdrefini = :vrefini;
            END
          END

          vcodimp1 = vcodimp;
          IF (SUBSTRING(vrefini FROM 5 FOR 2) = '01') THEN
             vrefant = vrefini - 89;
          ELSE
             vrefant = vrefini - 1;
        END
  END


  /* CASO REFERENCIA FINAL FOR MENOR QUE INICIAL */
  UPDATE tempresaimposto SET bdreffimimp = bdrefemp WHERE bdreffimimp < bdrefemp;
  UPDATE vct_tributario_empresa SET bdreffin = bdrefINI WHERE bdreffin < bdrefini AND BDCODOBR IS NOT NULL;
  UPDATE vct_tributario_empresa SET bdreffin = bdrefINI WHERE bdreffin < bdrefini AND BDCODSER IS NOT NULL;
  /* ELIMINA IMPOSTOS INDEFINIDOS */
  DELETE FROM tempresaimposto IMP WHERE EXISTS (SELECT * FROM TIMPOSTO WHERE BDCODIMP = IMP.BDCODIMP AND bdperapuracao = 11);
  DELETE FROM vct_tributario_empresa IMP WHERE EXISTS (SELECT * FROM vct_base_obrigacao WHERE BDCODobrser = IMP.BDCODOBR AND bdperiodicidade = 11);
  DELETE FROM vct_tributario_empresa IMP WHERE EXISTS (SELECT * FROM vct_base_obrigacao WHERE BDCODobrser = IMP.bdcodser AND bdperiodicidade = 11);
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAS_REF_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 26/01/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 26/01/2018
            NEW.bdcodemp = vcodigo;
         END
    END

  --#Alt:19940.
  IF (NEW.bdcodcentros = 0) THEN
     NEW.bdcodcentros = NULL; 
END
^

/* Altering existing trigger... */
ALTER TRIGGER TEMPRESAS_SCP_BI
AS
DECLARE VARIABLE wCodEmp INTEGER;
DECLARE VARIABLE wRefEmp INTEGER;
DECLARE VARIABLE wCodSCP INTEGER;
BEGIN
  wCodEmp = 0;
  wRefEmp = 0;
  wCodSCP = 0;

  IF ( (NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0) ) THEN
    BEGIN
      SELECT COALESCE(MAX(bdcodemp), 1) FROM tempresas
      WHERE (BDSTATUSEMP <> 1) INTO wCodEmp; --#Alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 14/02/2018

      NEW.bdcodemp = :wCodEmp;
    END 

  IF ( (NEW.bdrefemp IS NULL) OR (NEW.bdrefemp = 0) ) THEN
    BEGIN
      SELECT CAST(TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) AS INTEGER) FROM rdb$database INTO :wRefEmp;
      NEW.bdrefemp = :wRefEmp;
    END 

  IF ( (NEW.bdcodscp IS NULL) OR (NEW.bdcodscp = 0) ) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodscp) + 1), 1) FROM tempresas_scp WHERE ( bdcodemp = NEW.bdcodemp ) AND ( bdrefemp = NEW.bdrefemp ) INTO :wCodSCP;
      NEW.bdcodscp = :wCodSCP;
    END
  ELSE
    BEGIN
      SELECT bdcodscp FROM tempresas_scp WHERE ( bdcodemp = NEW.bdcodemp ) AND ( bdrefemp = NEW.bdrefemp ) AND ( bdcodscp = NEW.bdcodscp ) INTO :wCodSCP;

      IF ( :wCodSCP > 0 ) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodscp) + 1), 1) FROM tempresas_scp WHERE ( bdcodemp = NEW.bdcodemp ) AND ( bdrefemp = NEW.bdrefemp ) INTO :wCodSCP;
          NEW.bdcodscp = :wCodSCP;
        END 
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TENQFED_BIO
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vRef INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
--        select coalesce((max(bdcodemp)),1) from tempresas_ref into vcodigo;
        --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 14/02/2018
        /*SELECT FIRST 1 COALESCE(bdcodemp,1), bdrefemp FROM tempresas_ref
        ORDER BY bdcodemp DESC
        INTO vcodigo, vref;*/
        select first 1 coalesce(REF.BDCODEMP, 1), BDREFEMP from TEMPRESAS_REF REF
        inner join TEMPRESAS EMP on (REF.BDCODEMP = EMP.BDCODEMP and EMP.BDSTATUSEMP <> 1)
        order by REF.BDCODEMP desc  
        into vcodigo, vref;

        NEW.bdcodemp = vcodigo;
        NEW.bdrefemp = vref;
     END
  ELSE
    BEGIN
--       select bdcodemp from tempresas_ref where bdcodemp = NEW.bdcodemp into vcodigo;
        SELECT FIRST 1 COALESCE(bdcodemp,1), bdrefemp FROM tempresas_ref
        WHERE bdcodemp = NEW.bdcodemp
        ORDER BY bdcodemp DESC
        INTO vcodigo, vref;

       IF (vcodigo = 0) THEN
         BEGIN
--            select coalesce((max(bdcodemp)),1) from tempresas_ref into vcodigo;
            --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 14/02/2018
            /*SELECT FIRST 1 COALESCE(bdcodemp,1), bdrefemp FROM tempresas_ref
            ORDER BY bdcodemp DESC
            INTO vcodigo, vref;   */
            select first 1 coalesce(REF.BDCODEMP, 1), BDREFEMP from TEMPRESAS_REF REF
            inner join TEMPRESAS EMP on (REF.BDCODEMP = EMP.BDCODEMP and EMP.BDSTATUSEMP <> 1)
            order by REF.BDCODEMP desc
            into vcodigo, vref;

            NEW.bdcodemp = vcodigo;
            NEW.bdrefemp = vref;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TIMPOSTO_AI0
AS
  DECLARE VARIABLE vcodemp INTEGER;
  DECLARE VARIABLE vrefemp INTEGER;
BEGIN
/* Gilberto - 25/03/2015 - ALT:#11161 - Tirado para n?o inserir nos planos tribut?rios
  INSERT INTO VCT_TRIBUTOS_PLANO_TRIBUTARIO
  SELECT NULL AS bdcodtrib, tpla.bdcodplatrib, timp.bdcodimp, NULL AS bdcodser, NULL AS bdcodobr
  FROM timposto timp
  INNER JOIN vct_plano_tributario tpla ON (tpla.bdcodplatrib IS NOT NULL)
  WHERE timp.bdtipoclassimp = 1
  AND NOT timp.bdcodimp IN (SELECT DISTINCT bdcodimp
                            FROM vct_tributos_plano_tributario
                            WHERE bdcodimp IS NOT NULL)
  AND timp.bdcodimp = NEW.bdcodimp;

  FOR SELECT ref.bdcodemp, ref.bdempref
      FROM vw_empresas_ref_atual ref
      INNER JOIN tempresas emp ON (emp.bdcodemp = ref.bdcodemp)-- gilberto - 26/09/2014 - ALT:#9986
      WHERE ref.bdcodemp IN (SELECT DISTINCT bdcodemp FROM vct_tributario_empresa)
      AND bdempref >= SUBSTRING(bddatainiativemp FROM 1 FOR 4)||SUBSTRING(bddatainiativemp FROM 6 FOR 2)-- gilberto - 26/09/2014 - ALT:#9986
      INTO :vcodemp, :vrefemp DO
      BEGIN
        EXECUTE STATEMENT 'insert into tempresaimposto (BDCODEMP, BDREFEMP, BDCODIMP, BDREFFIMIMP) values ('||vcodemp||', '||vrefemp||', '||NEW.bdcodimp||', null)';
      END
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER TLOG_BU0
AS
BEGIN
  --alt:15642 - 13/09/2016 - Registros do tipo "exclus?o de lan?amentos cont?beis" (13) tamb?m devem ser agrupados. Pedro
  --alt:15307 - 15/08/2016 - Criada trigger para quando for impress?o de relat?rio em v?deo, somar os tempos em um s? registro, para n?o estufar muito o banco. Pedro
  IF (((NEW.BDTIPOACAO = 5) AND (NEW.BDTIPOIMPRESSAO = 0)) OR (NEW.BDTIPOACAO = 13)) THEN --Impress?o de relat?rio em v?deo
    BEGIN
      NEW.BDDATA = DATEADD(SECOND, NEW.BDHORAFINAL - NEW.BDHORAINICIAL, CAST(OLD.BDDATA||' '||OLD.BDHORAFINAL AS TIMESTAMP)); --Data final, somado dia caso passe das 24 horas
      NEW.BDDATASISTEMA = OLD.BDDATASISTEMA; --Data inicial (mant?m a antiga, neste caso)
      NEW.BDHORAFINAL = DATEADD(SECOND, NEW.BDHORAFINAL - NEW.BDHORAINICIAL, OLD.BDHORAFINAL); --Hora final, mant?m a antiga somando com a diferen?a de horas do novo registro
      NEW.BDHORAINICIAL = OLD.BDHORAINICIAL; --Hora inicial (mant?m a antiga, neste caso)
      NEW.BDQUANTIDADE = COALESCE(OLD.BDQUANTIDADE, 1) + 1; --Quantidade de registros que est?o sendo agrupados aqui.
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TMP_MOVSAIITENS_TEMP_COMPHIST
AS
DECLARE VARIABLE wComplemento VARCHAR(1000);
DECLARE VARIABLE wVar         VARCHAR(200);
DECLARE VARIABLE wNumDoc      INTEGER;
DECLARE VARIABLE wNomeTer     VARCHAR(100);
DECLARE VARIABLE wRefLan      INTEGER;
DECLARE VARIABLE wValue       VARCHAR(100);
DECLARE VARIABLE wVlrNf       NUMERIC(15, 6);
DECLARE VARIABLE wChave       INTEGER;
DECLARE VARIABLE wNrDocAte    INTEGER;
DECLARE VARIABLE wEspecie     VARCHAR(5);
DECLARE VARIABLE wSerie       VARCHAR(6);
DECLARE VARIABLE wModelo      VARCHAR(2);
DECLARE VARIABLE wEmitente    VARCHAR(9);
DECLARE VARIABLE wSituacao    INTEGER;
DECLARE VARIABLE wDataEmissao DATE;
DECLARE VARIABLE wDataSaida   DATE;
DECLARE VARIABLE wCondPgto    VARCHAR(6);
DECLARE VARIABLE wCnpj        VARCHAR(18);
DECLARE VARIABLE wNomCidPart  VARCHAR(40);
DECLARE VARIABLE wPos         INTEGER;
DECLARE VARIABLE wPosUltDel   INTEGER;
BEGIN

  /*Joga a chave do cont?bil na tabela*/
  IF (COALESCE(NEW.BDCHAVE_VSUC, 0) > 0) THEN
    BEGIN
      NEW.BDCHAVE_VSUC = (NEW.BDCHAVE_VSUC - (OLD.BDCHAVE))+1;
    END

  IF (COALESCE(NEW.BDTRANSACAO, 0) > 0) THEN
    BEGIN
      NEW.BDTRANSACAO = (NEW.BDTRANSACAO - (OLD.BDCHAVE))+1;
      EXIT;
    END

  wComplemento = NULL;
  IF ((COALESCE(NEW.BDCOMPHIST_VLRCONTAB, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRCONTAB) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRCONTAB||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRPIS, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRPIS) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRPIS||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRICMS, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRICMS) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRICMS||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRICMSST, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRICMSST) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRICMSST||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRIPI, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRIPI) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRIPI||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRCOFINS, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRCOFINS) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRCOFINS||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRPISRET, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRPISRET) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRPISRET||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRCOFRET, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRCOFRET) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRCOFRET||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRCSRET, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRCSRET) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRCSRET||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRIRRET, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRIRRET) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRIRRET||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRINSSRET, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRINSSRET) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRINSSRET||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRDESCONTO, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRDESCONTO) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRDESCONTO||' ';
  ELSE
    EXIT;

  /*Monta o complemento hist?rico da contabiliza??o*/
  SELECT ST.bdnumdocini, ST.bdnometer, ST.BDREFLAN,
         ST.BDVALORNOTA, ST.BDEDITCHAVE, ST.BDNUMDOCFIM,
         ST.BDESPECIE, ST.BDSERIE, M.BDMODELOSTR, IIF(ST.BDMODELO = 0, 'Pr?prio', 'Terceiros'),
         ST.BDCODSITNF, ST.BDDATAEMISSAO, ST.BDDATASAIDA, CASE WHEN ST.BDCONDPGTO = 0 THEN 'Vista'
                                                               WHEN ST.BDCONDPGTO = 1 THEN 'Prazo'
                                                               WHEN ST.BDCONDPGTO = 2 THEN 'Outras'
                                                          END,
         ST.BDCNPJ, C.BDNOMCID
  FROM TMP_VEF_EMP_TMOVSAI_TEMP ST
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = ST.BDMODELO)
  LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ST.BDCODCID)
  WHERE ST.BDSESSAO = OLD.BDSESSAO
  AND ST.BDCODEMP = OLD.BDCODEMP
  AND ST.BDCHAVE = OLD.BDCHAVE
  INTO :wNumDoc, :wNomeTer, :wRefLan, :wVlrNf, :wChave, :wNrDocAte,
       :wEspecie, :wSerie, :wModelo, :wEmitente, :wSituacao, :wDataEmissao,
       :wDataSaida, :wCondPgto, :wCnpj, :wNomCidPart;

  WHILE (POSITION('*', :wComplemento) > 0) DO
    BEGIN
      wPosUltDel = 1000;
      wPos = POSITION(' ', SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR CHAR_LENGTH(:wComplemento))); -- N?o tem o -1 porque ? um espa?o, o Trim j? remove ele.
      wPosUltDel = POSITION(',', SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR CHAR_LENGTH(:wComplemento)))-1; -- -1 para n?o pegar a , junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wPosUltDel = 1000;
      wPosUltDel = POSITION('.', SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR CHAR_LENGTH(:wComplemento)))-1; -- -1 para n?o pegar o . junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wVar = TRIM(SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR :wPos));
      wVar =  UPPER(REPLACE(REPLACE(:wVar, '(', ''), ')', ''));

      IF (:wVar = '*NRDOC') THEN
        wValue = COALESCE(:wNumDoc, 0);
      ELSE
      IF (:wVar = '*NOMEPART') THEN
        wValue = COALESCE(:wNomeTer, '');
      ELSE
      IF (:wVar = '*REF') THEN
        wValue = COALESCE(SUBSTRING(:wRefLan FROM 5 FOR 2)||'/'||SUBSTRING(:wRefLan FROM 1 FOR 4), '');
      ELSE
      IF (:wVar = '*VLRNF') THEN
        wValue = :wVlrNf;
      ELSE
      IF (:wVar = '*CHAVENF') THEN
        wValue = :wChave;
      ELSE
      IF (:wVar = '*NRDOCATE') THEN
        wValue = :wNrDocAte;
      ELSE
      IF (:wVar = '*ESPECIE') THEN
        wValue = :wEspecie;
      ELSE
      IF (:wVar = '*SERIE') THEN
        wValue = :wSerie;
      ELSE
      IF (:wVar = '*MODELO') THEN
        wValue = :wModelo;
      ELSE
      IF (:wVar = '*EMITENTE') THEN
        wValue = :wEmitente;
      ELSE
      IF (:wVar = '*SITUACAO') THEN
        wValue = :wSituacao;
      ELSE
      IF (:wVar = '*DATAEMISSAO') THEN
        wValue = :wDataEmissao;
      ELSE
      IF (:wVar = '*DATASAIDA') THEN
        wValue = :wDataSaida;
      ELSE
      IF (:wVar = '*CFOP') THEN
        wValue = SUBSTRING(OLD.BDCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(OLD.BDCODNAT FROM 2 FOR 3)||'-'||SUBSTRING(OLD.BDCODNAT FROM 5 FOR 3);
      ELSE
      IF (:wVar = '*CONDICAO') THEN
        wValue = :wCondPgto;
      ELSE
      IF (:wVar = '*MES') THEN
        wValue = COALESCE(SUBSTRING(:wRefLan FROM 5 FOR 2), '');
      ELSE
      IF (:wVar = '*ANO') THEN
        wValue = COALESCE(SUBSTRING(:wRefLan FROM 1 FOR 4), '');
      ELSE
      IF (:wVar = '*CNPJPART') THEN
        wValue = :wCnpj;
      ELSE
      IF (:wVar = '*NOMCIDPART') THEN
        wValue = :wNomCidPart;

      --wComplemento = SUBSTRING(:wComplemento FROM 1 FOR (POSITION('*', :wComplemento)-1))||COALESCE(:wValue, wVar)||SUBSTRING(:wComplemento FROM (POSITION(' ', SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR CHAR_LENGTH(:wComplemento)))+POSITION('*', :wComplemento)-1) FOR CHAR_LENGTH(:wComplemento));
      wComplemento = REPLACE(:wComplemento, :wVar, :wValue);
      wVar   = NULL;
      wValue = NULL;
    END

  IF (((NEW.BDCOMPHIST_VLRCONTAB <> '') OR (NEW.BDCOMPHIST_VLRCONTAB IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRCONTAB) AND (POSITION('*', NEW.BDCOMPHIST_VLRCONTAB) > 0))  THEN
    NEW.BDCOMPHIST_VLRCONTAB = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRPIS <> '') OR (NEW.BDCOMPHIST_VLRPIS IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRPIS) AND (POSITION('*', NEW.BDCOMPHIST_VLRPIS) > 0))  THEN
    NEW.BDCOMPHIST_VLRPIS = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRICMS <> '') OR (NEW.BDCOMPHIST_VLRICMS IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRICMS) AND (POSITION('*', NEW.BDCOMPHIST_VLRICMS) > 0))  THEN
    NEW.BDCOMPHIST_VLRICMS = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRICMSST <> '') OR (NEW.BDCOMPHIST_VLRICMSST IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRICMSST) AND (POSITION('*', NEW.BDCOMPHIST_VLRICMSST) > 0))  THEN
    NEW.BDCOMPHIST_VLRICMSST = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRIPI <> '') OR (NEW.BDCOMPHIST_VLRIPI IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRIPI) AND (POSITION('*', NEW.BDCOMPHIST_VLRIPI) > 0))  THEN
    NEW.BDCOMPHIST_VLRIPI = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRCOFINS <> '') OR (NEW.BDCOMPHIST_VLRCOFINS IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRCOFINS) AND (POSITION('*', NEW.BDCOMPHIST_VLRCOFINS) > 0))  THEN
    NEW.BDCOMPHIST_VLRCOFINS = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRPISRET <> '') OR (NEW.BDCOMPHIST_VLRPISRET IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRPISRET) AND (POSITION('*', NEW.BDCOMPHIST_VLRPISRET) > 0))  THEN
    NEW.BDCOMPHIST_VLRPISRET = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRCOFRET <> '') OR (NEW.BDCOMPHIST_VLRCOFRET IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRCOFRET) AND (POSITION('*', NEW.BDCOMPHIST_VLRCOFRET) > 0))  THEN
    NEW.BDCOMPHIST_VLRCOFRET = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRCSRET <> '') OR (NEW.BDCOMPHIST_VLRCSRET IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRCSRET) AND (POSITION('*', NEW.BDCOMPHIST_VLRCSRET) > 0))  THEN
    NEW.BDCOMPHIST_VLRCSRET = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRIRRET <> '') OR (NEW.BDCOMPHIST_VLRIRRET IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRIRRET) AND (POSITION('*', NEW.BDCOMPHIST_VLRIRRET) > 0))  THEN
    NEW.BDCOMPHIST_VLRIRRET = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRINSSRET <> '') OR (NEW.BDCOMPHIST_VLRINSSRET IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRINSSRET) AND (POSITION('*', NEW.BDCOMPHIST_VLRINSSRET) > 0))  THEN
    NEW.BDCOMPHIST_VLRINSSRET = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRDESCONTO <> '') OR (NEW.BDCOMPHIST_VLRDESCONTO IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRDESCONTO) AND (POSITION('*', NEW.BDCOMPHIST_VLRDESCONTO) > 0))  THEN
    NEW.BDCOMPHIST_VLRDESCONTO = :wComplemento;
END
^

/* Altering existing trigger... */
ALTER TRIGGER TMP_VEF_EMP_TMOVSER_BI
AS
BEGIN
  /* sol.: #9828 Jean 17/12/2014: os campos s?o comparados com igual (sem fazer coalesce)
  se algum comparado no where estiver nulo, o resultado sempre ser? nulo */
  IF (NEW.bdtiplan IS NULL) THEN
    NEW.bdtiplan = 0;

  IF (NEW.bdnumdocini IS NULL) THEN
    NEW.bdnumdocini = '';

  IF (NEW.bdnumdocfim IS NULL) THEN
    NEW.bdnumdocfim = '';

  IF (NEW.bdespecie IS NULL) THEN
    NEW.bdespecie = '';

  IF (NEW.bdserie IS NULL) THEN
    NEW.bdserie = '';

  IF (NEW.bdsubserie IS NULL) THEN
    NEW.bdsubserie = '';

  IF (NEW.bddataemissao IS NULL) THEN
    NEW.bddataemissao = CURRENT_DATE;
END
^

/* Altering existing trigger... */
ALTER TRIGGER TMP_VEF_EMP_TMOVSER_BU
AS
BEGIN
  /* sol.: #9828 Jean 17/12/2014: os campos s?o comparados com igual (sem fazer coalesce)
  se algum comparado no where estiver nulo, o resultado sempre ser? nulo */
  IF (NEW.bdtiplan IS NULL) THEN
    NEW.bdtiplan = 0;

  IF (NEW.bdnumdocini IS NULL) THEN
    NEW.bdnumdocini = '';

  IF (NEW.bdnumdocfim IS NULL) THEN
    NEW.bdnumdocfim = '';

  IF (NEW.bdespecie IS NULL) THEN
    NEW.bdespecie = '';

  IF (NEW.bdserie IS NULL) THEN
    NEW.bdserie = '';

  IF (NEW.bdsubserie IS NULL) THEN
    NEW.bdsubserie = '';

  IF (NEW.bddataemissao IS NULL) THEN
    NEW.bddataemissao = CURRENT_DATE;
END
^

/* Altering existing trigger... */
ALTER TRIGGER TOL_VEF_EMP_TLANRH_SN_AD0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  --sol:16476 - removido daqui pois ? preciso saber se o darf ? um complemento e nesse momento o registro ja foi apagado
  /*vcodigo = 0;

  SELECT bdORDEMCOMPL FROM tdarfpadrao WHERE (bdCODEMP = OLD.bdCODEMP) AND (bdCHAVEDARF = OLD.bdCHAVEDARF) into vcodigo;

  IF ((vcodigo IS NULL) or (vcodigo = 0)) THEN
     DELETE FROM VRH_EMP_TTRIBUTACAO_SN sn WHERE sn.BDCODEMP = OLD.bdcodfilial AND sn.BDREFERENCIA = OLD.BDREFERENCIA;*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_DELETE_TDARFPADRAO
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN

--  delete from tdarfpadrao where BDORDEMCOMPL = old.bdordem and bdcodemp = old.bdcodemp and bdchavedarf <> old.bdchavedarf;

--  exception ex_date 'executando update';
  -- Gilberto - 11/09/2014 - N?o pode excluir documento gerado, deve apenas eliminar sua refer?ncia com o imposto gerado
  UPDATE vct_empresa_docsgerados SET bdchavedarf = NULL WHERE (bdcodemp = OLD.bdcodemp) AND (bdchavedarf = OLD.bdchavedarf) AND (bdcodpts IS NOT NULL) AND (bdcodipts IS NOT NULL);
  -- gilberto - 12/12/2014 - quando excluir imposto deve manter hist?rico nos protocolos
  UPDATE vct_empresa_protodocsaida SET bdchavedarf = NULL WHERE bdcodemp = OLD.bdcodemp AND bdchavedarf = OLD.bdchavedarf;
--  DELETE FROM vct_empresa_docsgerados WHERE bdcodemp = OLD.bdcodemp AND bdchavedarf = OLD.bdchavedarf;

  -- gilberto - 24/02/2015 - ALT:#10494 - deve excluir documento gerados que n?o pertence a nenhumprotocolo quando excluir o imposto
  DELETE FROM vct_empresa_docsgerados WHERE (bdcodemp = OLD.bdcodemp) AND (bdchavedarf = OLD.bdchavedarf) AND (bdcodpts IS NULL) AND (bdcodipts IS NULL);

  --sol:16476 - verifica se ? um complemento pra remover o registro do VRH_EMP_TTRIBUTACAO_SN
  vcodigo = 0;

  SELECT bdORDEMCOMPL FROM tdarfpadrao WHERE (bdCODEMP = OLD.bdCODEMP) AND (bdCHAVEDARF = OLD.bdCHAVEDARF) INTO vcodigo;

  IF ((vcodigo IS NULL) OR (vcodigo = 0)) THEN
     BEGIN
       FOR EXECUTE STATEMENT 'SELECT bdCODFILIAL FROM tol_vef_emp_tlanrh_sn WHERE (bdCODEMP = '||OLD.bdCODEMP||') AND (bdCHAVEDARF = '||OLD.bdCHAVEDARF||')'
       INTO
         vcodigo
       DO
        BEGIN
          DELETE FROM tol_vef_emp_tlanrh_sn WHERE (bdCODEMP = OLD.bdCODEMP) AND (bdCHAVEDARF = OLD.bdCHAVEDARF) AND (bdCODFILIAL = :vcodigo);
          DELETE FROM VRH_EMP_TTRIBUTACAO_SN sn WHERE (sn.BDCODEMP = :vcodigo) AND (sn.BDREFERENCIA = OLD.BDREFERENCIA);
        END
     END
  ELSE
     DELETE FROM tol_vef_emp_tlanrh_sn WHERE (bdCODEMP = OLD.bdCODEMP) AND (bdCHAVEDARF = OLD.bdCHAVEDARF);
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_PLANOS_TPLA
AS
  DECLARE VARIABLE  vCodigo INTEGER;
  DECLARE VARIABLE  vNova_Chave INTEGER;
  DECLARE VARIABLE  wparte VARCHAR(140);
  DECLARE VARIABLE  wrpos INTEGER;
  DECLARE VARIABLE  wnivel INTEGER;
BEGIN
  --Trigger text
  vcodigo = 0;
  wrpos = 0;
  IF ((NEW.bdcodtpla IS NULL) OR (NEW.bdcodtpla = 0))  THEN
    --NEW.bdcodtpla = GEN_ID(gen_planos_tpla, 1);
    BEGIN
      SELECT COALESCE((MAX(bdcodtpla)+1), 1) FROM planos_tpla WHERE bdcodplapadrao = NEW.bdcodplapadrao INTO vNova_Chave;
      NEW.bdcodtpla = vNova_Chave;
    END
  ELSE
    BEGIN
       --#alt:12280 - Criado novo procedimento para gerar novo c?digo. Ana - 06/10/2016
       EXECUTE PROCEDURE SP_VERIFICA_NOVO_CODIGO(NEW.BDCODPLAPADRAO, NEW.BDCODTPLA, NEW.BDCTALON)
       RETURNING_VALUES :vCodigo;

       IF ((NOT (vCodigo IS NULL)) AND (vcodigo > 0)) THEN
          NEW.bdcodtpla = vCodigo;

       /*SELECT bdcodtpla FROM planos_tpla WHERE (bdcodtpla = NEW.bdcodtpla) AND (bdcodplapadrao = NEW.bdcodplapadrao) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtpla)+1), 1) FROM planos_tpla WHERE bdcodplapadrao = NEW.bdcodplapadrao INTO vNova_Chave;
           NEW.bdcodtpla = vNova_Chave;
           --NEW.bdcodtpla = GEN_ID(gen_planos_tpla, 1);
           --*exception ex_valor_text+NEW.bdcodtpcc;
         END*/
       --#alt:12280. fim
    END

  --gravar bdclanom para ordernar por nome e classificacao  inicio
  wparte = NEW.bdctalon;
  --se nao for conta titulo
  IF (NEW.bdtipcta = 1) THEN
     BEGIN
       SELECT bdrpos FROM rpos('.',:wparte) INTO wrpos;
       IF (wrpos > 0) THEN
          BEGIN
            wparte = SUBSTRING(wparte FROM 1 FOR wrpos - 1);
            SELECT bdretorno FROM preenche_direita(:wparte,40,' ') INTO wparte;
            wparte = wparte || NEW.bdnomcta;
          END
     END

  NEW.bdclanom = wparte;
  /* gravar bdclanom para ordernar por nome e classificacao  fim*/
  EXECUTE PROCEDURE CONTAR_CHAR(NEW.BDCTALON, '.') RETURNING_VALUES :wNivel;
  NEW.bdnivel = :wNivel;
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_TEMPRESAS
AS
--  DECLARE VARIABLE vCodemp INTEGER;
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)+1),1) FROM tempresas
        WHERE
        (BDSTATUSEMP <> 1) --#Alt:16965 - Carlos Mello (06/10/2017) - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas
        INTO vcodigo;

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)+1),1) FROM tempresas
            WHERE
            (BDSTATUSEMP <> 1) --#Alt:16965 - Carlos Mello (06/10/2017) - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas
            INTO vcodigo;

            NEW.bdcodemp = vcodigo;
         END
    END

  --#Alt:16965 - Carlos Mello (02/04/2018) - Caso n?o tenha nenhuma informa??o precisamos setar como sendo uma empresa "Normal"
  IF (NEW.BDSTATUSEMP IS NULL) THEN
    NEW.BDSTATUSEMP = 0;
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_TESCRITORIO
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vApelido VARCHAR(20);
  DECLARE VARIABLE vNomeReduzido VARCHAR(40);
  DECLARE VARIABLE vCodHist INTEGER;
  DECLARE VARIABLE vCODPLAPADRAO INTEGER;
  DECLARE VARIABLE vRefAtual VARCHAR(6);
BEGIN
  /* somente na inser??o */
  IF (OLD.bdcnpjesc IS NULL) THEN
     BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodesc)+1),1) FROM tescritorio INTO vcodigo;
       NEW.bdcodesc = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)+1),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
    END
     END

  /*criar/atualizar empresa que representa o gestor para a online*/
  SELECT bdcodplapadrao, bdcodhist
  FROM TPLANO_CONF_ONLINE
  WHERE BDCODPLANOONLINE = (COALESCE(NEW.BDCODPLANOONLINE, OLD.bdcodplanoonline))
  INTO :vCODPLAPADRAO, :vcodhist;


  vRefAtual = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database);

  IF (vRefAtual IS NULL) THEN
     vRefAtual = SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2);

  /*TEMPRESAS*/
  IF (NEW.bdnomesc IS NOT NULL) THEN
  vapelido      = SUBSTRING(NEW.bdnomesc FROM 1 FOR 20);
  ELSE
     vapelido      = SUBSTRING(OLD.bdnomesc FROM 1 FOR 20);

  IF (NEW.bdnomesc IS NOT NULL) THEN
     vNomeReduzido = SUBSTRING(NEW.bdnomesc FROM 1 FOR 40);
  ELSE
     vNomeReduzido = SUBSTRING(OLD.bdnomesc FROM 1 FOR 40);

  IF (NEW.bdcodempinteg IS NOT NULL) THEN
     BEGIN
       UPDATE tempresas e SET
       BDDATAINIATIVEMP = COALESCE(NEW.bdiniativesc, e.bddatainiativemp),
       BDDATAFIMATIVEMP = COALESCE(NEW.bdfimativesc, e.bddatafimativemp),
       BDAPELIDO = COALESCE(:vapelido, e.bdapelido),
       BDIE = COALESCE(NEW.bdieesc, e.bdie)
       WHERE BDCODEMP = NEW.bdcodempinteg;
     END
  ELSE
     BEGIN
        IF (OLD.bdcnpjesc IS NULL) THEN
          BEGIN
            INSERT INTO tempresas(BDCODEMP,
                                  BDCNPJEMP,
                                  BDDATAINIATIVEMP,
                                  BDDATAFIMATIVEMP,
                                  BDAPELIDO,
                                  BDIE,
                                  BDDATACADEMP,
                  BDSTATUSEMP)
            VALUES (NEW.bdcodempinteg,
                    COALESCE(NEW.bdCNPJESC, OLD.bdcnpjesc),
                    COALESCE(NEW.bdiniativesc, OLD.bdiniativesc),
                    COALESCE(NEW.bdfimativesc, OLD.bdfimativesc),
                    :vApelido,
                    COALESCE(NEW.bdieesc, OLD.bdieesc),
                    CURRENT_DATE,
            0);
         END
    END

   /*TEMPRESAS_REF*/ /*por enquanto somente na inser??o do escrit?rio, pois atualizar empresa por refer?ncia - deve-se criar registros em todas tabelas por refer?ncia????*/
   IF (OLD.bdcnpjesc IS NULL AND NEW.bdcodempinteg IS NULL) THEN
      BEGIN
          vRefAtual = CAST(SUBSTRING(CAST(NEW.bdiniativesc AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bdiniativesc AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
          UPDATE OR INSERT
          INTO TEMPRESAS_REF(BDCODEMP,
                             BDREFEMP,
                             BDCODPLAPADRAO,
                             BDCODHIST,
                             BDCODCID,
                             BDCODCONT,
                             BDCODCONTEF,
                             BDCODCONTRH,
                             BDCODCENTROS,
                             BDCODCNAE,
                             BDNOMEMP,
                             BDAPEEMP,
                             BDENDEMP,
                             BDNUMEMP,
                             BDBAIEMP,
                             BDCEPEMP,
                             BDDDDEMP,
                             BDFONEEMP,
                             BDFAXEMP,
                             BDDDDCELULAREMP,
                             BDCELULAREMP,
                             BDEMAILEMP,
                             BDCOMPLEMP,
                             BDLOGREMP,
                             BDIEEMP,
                             BDIMEMP,
                             BDSITEMP,
                             BDDDDFAXEMP,
                             BDCODPLANOONLINE,
                             BDNOMREDUZEMP,
                             BDCODPLATRIB
                             )
          VALUES(NEW.bdcodempinteg,
                 :vRefAtual,
                 :vCODPLAPADRAO,
                 :vcodhist,
                         COALESCE(NEW.bdcodcid, OLD.bdcodcid),
                         COALESCE(NEW.bdcodcont, OLD.bdcodcont),
                         COALESCE(NEW.bdCODCONTEF, OLD.bdcodcontef),
                         COALESCE(NEW.bdCODCONTRH, OLD.bdcodcontrh),
                         COALESCE(NEW.bdCODCENTRO, OLD.bdcodcentro),
                         COALESCE(NEW.bdCODCNAE, OLD.bdcodcnae),
                         COALESCE(NEW.BDNOMESC, OLD.bdnomesc),
                 :vapelido,
                         COALESCE(NEW.bdendesc, OLD.bdendesc),
                         COALESCE(NEW.bdnumesc, OLD.bdnumesc),
                         COALESCE(NEW.bdbaiesc, OLD.bdbaiesc),
                         COALESCE(NEW.bdcepesc, OLD.bdcepesc),
                         COALESCE(NEW.bddddesc, OLD.bddddesc),
                         COALESCE(NEW.bdfoneesc, OLD.bdfoneesc),
                         COALESCE(NEW.bdfaxesc, OLD.bdfaxesc),
                         COALESCE(NEW.bddddcelularesc, OLD.bddddcelularesc),
                         COALESCE(NEW.bdcelularesc, OLD.bdcelularesc),
                         COALESCE(NEW.bdemailesc, OLD.bdemailesc),
                         COALESCE(NEW.bdcomplesc, OLD.bdcomplesc),
                         COALESCE(NEW.bdlogresc, OLD.bdlogresc),
                         COALESCE(NEW.bdieesc, OLD.bdieesc),
                         COALESCE(NEW.bdimesc, OLD.bdimesc),
                 'FALSE',
                         COALESCE(NEW.bddddfaxesc,OLD.bddddfaxesc),
                         COALESCE(NEW.bdcodplanoonline, OLD.bdcodplanoonline),
                 :vNomeReduzido,
                         COALESCE(NEW.bdcodplatrib, OLD.bdcodplatrib)
                         ) MATCHING (BDCODEMP, BDREFEMP);

       END

      /*TEMPRESAS_REF*/
     /* update or insert
      into TEMPRESAS_REF(BDCODEMP,
                         BDREFEMP,
                         BDCODPLAPADRAO,
                         BDCODHIST,
                         BDCODCID,
                         BDCODCONT,
                         BDCODCONTEF,
                         BDCODCONTRH,
                         BDCODCENTROS,
                         BDCODCNAE,
                         BDNOMEMP,
                         BDAPEEMP,
                         BDENDEMP,
                         BDNUMEMP,
                         BDBAIEMP,
                         BDCEPEMP,
                         BDDDDEMP,
                         BDFONEEMP,
                         BDFAXEMP,
                         BDDDDCELULAREMP,
                         BDCELULAREMP,
                         BDEMAILEMP,
                         BDCOMPLEMP,
                         BDLOGREMP,
                         BDIEEMP,
                         BDIMEMP,
                         BDSITEMP,
                         BDDDDFAXEMP,
                         BDCODPLANOONLINE,
                         BDNOMREDUZEMP,
                         BDCODPLATRIB
                         )
      values(new.bdcodempinteg,
             :vRefAtual,
             :vCODPLAPADRAO,
             :vcodhist,
             coalesce(new.bdcodcid, old.bdcodcid),
             coalesce(new.bdcodcont, old.bdcodcont),
             coalesce(new.bdCODCONTEF, old.bdcodcontef),
             coalesce(new.bdCODCONTRH, old.bdcodcontrh),
             coalesce(new.bdCODCENTRO, old.bdcodcentro),
             coalesce(new.bdCODCNAE, old.bdcodcnae),
             coalesce(new.BDNOMESC, old.bdnomesc),
             :vapelido,
             coalesce(new.bdendesc, old.bdendesc),
             coalesce(new.bdnumesc, old.bdnumesc),
             coalesce(new.bdbaiesc, old.bdbaiesc),
             coalesce(new.bdcepesc, old.bdcepesc),
             coalesce(new.bddddesc, old.bddddesc),
             coalesce(new.bdfoneesc, old.bdfoneesc),
             coalesce(new.bdfaxesc, old.bdfaxesc),
             coalesce(new.bddddcelularesc, old.bddddcelularesc),
             coalesce(new.bdcelularesc, old.bdcelularesc),
             coalesce(new.bdemailesc, old.bdemailesc),
             coalesce(new.bdcomplesc, old.bdcomplesc),
             coalesce(new.bdlogresc, old.bdlogresc),
             coalesce(new.bdieesc, old.bdieesc),
             coalesce(new.bdimesc, old.bdimesc),
             'FALSE',
             coalesce(new.bddddfaxesc,old.bddddfaxesc),
             coalesce(new.bdcodplanoonline, old.bdcodplanoonline),
             :vNomeReduzido,
             coalesce(new.bdcodplatrib, old.bdcodplatrib)
             ) matching (BDCODEMP, BDREFEMP);
   */


  /*caso for inserir a empresa pegar o ?ltimo c?digo gerado e jogar no campo BDCODEMPINTEG*/
  /*inserir registro TENFED para aparecer na consulta, pois ? um inner join, criar aqui pois pode ser inserido pela tela do escrit?rio em outros m?dulo e n?o
  passar pelo automatismo de VFIN_BASE_TESCPARFAT*/
  IF (NEW.bdcodempinteg IS NULL AND OLD.bdcnpjesc IS NULL) THEN
     BEGIN
        SELECT COALESCE(MAX(bdcodemp),0) FROM tempresas
        WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 14/02/2018

        IF (vcodigo > 0) THEN
          NEW.bdcodempinteg  = :vcodigo;

        UPDATE OR INSERT INTO TENQFED (BDCODENQFED, BDCODEMP, BDREFEMP)
        VALUES(3, NEW.bdcodempinteg, :vrefatual) MATCHING (BDCODENQFED, BDCODEMP, BDREFEMP);
      END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_TPLANO_PADRAO
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodplapadrao IS NULL) OR (NEW.bdcodplapadrao = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplapadrao)+1),1) FROM tplano_padrao INTO vcodigo;
        NEW.bdcodplapadrao = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodplapadrao FROM tplano_padrao WHERE bdcodplapadrao = NEW.bdcodplapadrao INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodplapadrao)+1),1) FROM tplano_padrao INTO vcodigo;
            NEW.bdcodplapadrao = vcodigo;
         END
    END

  --#alt:17928 - Quando efetuava a c?pia do plano de contabiliza??o, e ja existia estes planos mas n?o o plano de contas padrao, estava gerando erro. Ana - 21/03/2017
  vCodigo = 0;
  SELECT bdcodplapadrao_sped FROM TPLANO_PADRAO_SPED WHERE bdcodplapadrao_sped = NEW.bdcodplapadrao INTO vcodigo;
  IF (vcodigo > 0) THEN
    DELETE FROM TPLANO_PADRAO_SPED WHERE bdcodplapadrao_sped = NEW.bdcodplapadrao;

  vCodigo = 0;
  SELECT bdcodplapadrao_fcont FROM TPLANO_PADRAO_FCONT WHERE bdcodplapadrao_fcont = NEW.bdcodplapadrao INTO vcodigo;
  IF (vcodigo > 0) THEN
    DELETE FROM TPLANO_PADRAO_FCONT WHERE bdcodplapadrao_fcont = NEW.bdcodplapadrao;
  --#alt:17928 .fim
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TNATOP
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE str VARCHAR(20);
  DECLARE VARIABLE wCont VARCHAR(5);  
BEGIN
  /* Trigger text */

  /* Alt.: 21963 - Marca o "bdCONTABILIZA" conforme estiver na classifica??o acima da que est? sendo inserida */
  SELECT FIRST 1 bdCONTABILIZA
  FROM VEF_BASE_TNATOP
  WHERE bdCLASSIFICACAO LIKE ''||SUBSTRING(new.bdCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(new.bdCODNAT FROM 2 FOR 2)||'0.'||SUBSTRING(new.bdCODNAT FROM 2 FOR 3)||''
     OR bdCLASSIFICACAO LIKE ''||SUBSTRING(new.bdCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(new.bdCODNAT FROM 2 FOR 1)||'%.'||SUBSTRING(new.bdCODNAT FROM 2 FOR 3)||''
  ORDER BY bdCLASSIFICACAO
  INTO wCont;

  IF (wCont = 'TRUE') THEN
    new.bdCONTABILIZA = 'TRUE';

  vcodigo = 0;
  IF ((NEW.bdcodnat IS NULL) OR (NEW.bdcodnat = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodnat)+1),1) FROM vef_base_tnatop INTO vcodigo;
       NEW.bdcodnat = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodnat FROM vef_base_tnatop WHERE bdcodnat = NEW.bdcodnat INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodnat)+1),1) FROM vef_base_tnatop INTO vcodigo;
            NEW.bdcodnat = vcodigo;
         END
    END

  IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 5) AS INTEGER) = 0) THEN
      -- 1
      NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1);
  ELSE
    BEGIN
      IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3) AS INTEGER) IN (100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950)) THEN
        --1.100
        NEW.bdclassificacao =  SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' || SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3);
      ELSE
        BEGIN
            IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 3 FOR 2) AS INTEGER) < 50 ) THEN
              str = SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 1) ||'00';
            ELSE
              str = SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 1) ||'50';
    
            IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 5 FOR 3) AS INTEGER) = 0) THEN
              --1.100.101
              NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' ||str||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3);-- substring( cast(new.bdcodnat as varchar(7)) from 2 for 3);
            ELSE
              --1.100.101.001
              NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' ||str||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3)||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 5 FOR 3);
        END
      /*Sol: 12368 Patrick T. S? 28/10/2015. Deve buscar o bdliberacontabiliza do primeiro nivel da CFOP.*/
      IF (NEW.bdliberacontabiliza IS NULL) THEN
        BEGIN
          SELECT NATOP.bdliberacontabiliza FROM VEF_BASE_TNATOP NATOP WHERE NATOP.bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR 9) INTO NEW.bdliberacontabiliza;
          IF (NEW.bdliberacontabiliza IS NULL) THEN
            SELECT NATOP.bdliberacontabiliza FROM VEF_BASE_TNATOP NATOP WHERE NATOP.bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR 5) INTO NEW.bdliberacontabiliza;
        END
    END


END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVENT
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
BEGIN
  /*
  Fabiano 03/07/2013 - N?o tem que pegar nova chave aqui. Tem que pedir para o servidor de aplica??o.
  if ((new.bdcodtipo = 101) or (new.bdcodtipo = 102)) then
     begin
        vcodigo = 0;
        if ((NEW.bdchave is null) or (NEW.bdchave = 0)) then
          begin
    --      select coalesce((max(bdchave)+1), 1) from vef_emp_tmovent where bdcodemp = new.bdcodemp into vNova_Chave;
            select bdresult+1 from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vef_emp_tmovent') into vNova_Chave;
            NEW.bdchave = vNova_Chave;
          end
        else
          begin
            select bdchave from vef_emp_tmovent where (bdchave = NEW.bdchave) and (bdcodemp = NEW.bdcodemp) into vcodigo;
            if (vcodigo > 0) then
              begin
  --           select coalesce((max(bdchave)+1), 1) from vef_emp_tmovent where bdcodemp = new.bdcodemp into vNova_Chave;
               Select bdresult+1 from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vef_emp_tmovent') into vNova_Chave;
               NEW.bdchave = vNova_Chave;
              end
          end

       select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
       new.bdcodusu = vcodigo;
     end
*/
  -- s? atribui o usu?rio se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataentradaent AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataentradaent AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAI
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
BEGIN
  /*
  Fabiano 03/07/2013 - n?o pode gerar nova chave aqui
  if ((new.bdCodTipo = 101) or (new.bdcodtipo = 102)) then
     begin
       vcodigo = 0;
       if ((NEW.bdchave is null) or (NEW.bdchave = 0)) then
         begin
           select coalesce((max(bdchave)+1), 1) from vef_emp_tmovsai where bdcodemp = new.bdcodemp into vNova_Chave;
           NEW.bdchave = vNova_Chave;
         end
       else
         begin
            select bdchave from vef_emp_tmovsai where (bdchave = NEW.bdchave) and (bdcodemp = NEW.bdcodemp) into vcodigo;
            if (vcodigo > 0) then
              begin
                select coalesce((max(bdchave)+1), 1) from vef_emp_tmovsai where bdcodemp = new.bdcodemp into vNova_Chave;
                NEW.bdchave = vNova_Chave;
              end
         end

       select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
       new.bdcodusu = vcodigo;
     end
   */

  -- s? atribui o usu?rio se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSER
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
BEGIN
/*
  Fabiano: 03/07/2013 N?o tem que gerar nova chave aqui. Tem que pegar do servidor de aplica??o.
  if ((new.bdcodtipo = 101) or (new.bdcodtipo = 102)) then
     begin
       vcodigo = 0;
       if ((NEW.bdchave is null) or (NEW.bdchave = 0)) then
         begin
     --      select coalesce((max(bdchave)+1), 1) from vef_emp_tmovser where bdcodemp = new.bdcodemp into vNova_Chave;
           select bdresult+1 from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vef_emp_tmovser') into vNova_Chave;
    
           NEW.bdchave = vNova_Chave;
         end
       else
         begin
           select bdchave from vef_emp_tmovser where (bdchave = NEW.bdchave) and (bdcodemp = NEW.bdcodemp) into vcodigo;

           if (vcodigo > 0) then
              begin
                select bdresult+1 from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vef_emp_tmovser') into vNova_Chave;
     --           select coalesce((max(bdchave)+1), 1) from vef_emp_tmovser where bdcodemp = new.bdcodemp into vNova_Chave;
                NEW.bdchave = vNova_Chave;
              end
        end

        select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
        new.bdcodusu = vcodigo;
     end
*/

  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;

  /* sol.: #9828 Jean 16/12/2014: SUBSERIE n?o pode mais ser NULL*/
  IF (NEW.BDSUBSERIE IS NULL) THEN
     NEW.BDSUBSERIE = '';   

END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_VLAL_BASE_TEMP
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
          BEGIN
            SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
          END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TENC
AS
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  --alt:9720 - Comentado isso pois n?o permitia gravar o c?digo do usu?rio. N?o sabemos porque fazia isso. Pedro
  --new.bdcodusu = null;

  IF ((NEW.bdchavezer IS NULL) OR (NEW.bdchavezer = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavezer)+1), 1) FROM vsuc_empresas_tencexe INTO vNova_Chave;
      NEW.bdchavezer = vNova_Chave;
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TLAN
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
--  declare variable vusuario varchar(20);
  DECLARE VARIABLE vCodUsu INTEGER;
  DECLARE VARIABLE VRECONTABILIZANDO dm_boolean;
BEGIN
  vcodigo = 0;

  /* Almir 19/06/2012 */
  /* N?o pode ser lan?ado nenhum lan?amento sem a chave pois a chave n?o pode ser gerada uma pelo banco e outra pelo servidor pq sen?o da erro */
--  if ((NEW.bdchave is null) or (NEW.bdchave = 0)) then
--      exception EX_GETCHAVELAN;

  -- Carlos Mello(05/10/2011) - Caso seja "Importação TXT" ou "Importação Extrato Bancário" não precisa fazer os
  -- tratamentos porque o sistema já está garantindo as informações passada, desta forma torna as importações mais rápidas.
  -- Fabiano 03/07/2013: N?o pode gerar nova chave aqui. Tem que usar o servidor de aplica??o
  /*
    if ((NEW.BDTIPOLAN <> 2) and (NEW.BDTIPOLAN <> 21) and (NEW.BDTIPOLAN <> 100) and (NEW.BDTIPOLAN <> 200)) then
    begin
      if ((NEW.bdchave is null) or (NEW.bdchave = 0)) then
        begin
          select bdresult+1 from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vsuc_empresas_tlan') into vNova_Chave;
--          select coalesce((max(bdchave)+1), 1) from vsuc_empresas_tlan where bdcodemp = new.bdcodemp into vNova_Chave;
          NEW.bdchave = vNova_Chave;
        end
      else
        begin
          -- Fabiano - Na importacao do Visual Sucessor ja mando a chave, estou sozinho na importacao ninguem mandara mais nada.
          if (NEW.BDTIPOLAN <> 300) then
            begin
               select bdchave from vsuc_empresas_tlan where (bdchave = NEW.bdchave) and (bdcodemp = NEW.bdcodemp) into vcodigo;

               if (vcodigo > 0) then
                 begin
                   select bdresult+1 from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vsuc_empresas_tlan') into vNova_Chave;
--                   select coalesce((max(bdchave)+1), 1) from vsuc_empresas_tlan where bdcodemp = new.bdcodemp into vNova_Chave;
                   NEW.bdchave = vNova_Chave;
                 end
            end
        end
    end */

  SELECT CAST(BDAAAAMM AS INTEGER) FROM AAAAMM(NEW.bddata) INTO NEW.bdreferencia;
  -- GRAVA OS CAMPOS AUTOMATICO --

--  if ((new.bdcodusu is null) or (new.bdcodusu = 0)) then
--  begin
--    select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
--    new.bdcodusu = vcodigo;
--  end

  -- Fabiano - Na importacao do Visual Sucessor ja estou trazendo este valor
  IF (NEW.bddatalan IS NULL) THEN
    NEW.bddatalan = CURRENT_DATE;

  -- Fabiano - Na importacao do Visual Sucessor ja estou trazendo este valor
  IF (NEW.bdhoralan IS NULL) THEN
    NEW.bdhoralan = CURRENT_TIME;

  IF ((NEW.BDTIPOLAN IS NULL) OR (NEW.BDTIPOLAN = 0)) THEN
     NEW.BDTIPOLAN = 1;

  --Carlos Mello(12/06/2013) - Alt: 5837. Quando for lan?amento de online deve setar o BDTIPOLANCFILIAL = 0(Nenhum) e o BDCONTABILIZACAO = 0(Ambos)
  IF ((NEW.BDTIPOLAN = 100) OR--online
      (NEW.BDTIPOLAN = 200) OR--online
      (NEW.BDTIPOLAN = 400) OR--online com lalur - gilberto - 04/07/2014
      (NEW.BDTIPOLAN = 10) OR--zeramento
      (NEW.bdtipolan = 2) OR--importa??o TXT
      (NEW.bdtipolan = 21) OR--importa??o extrato banc?rio
      (NEW.bdtipolan = 9) OR--lan?amento de planilha
      (NEW.bdtipolan = 3000)) THEN --online do financeiro
    BEGIN
      IF (NEW.bdtipolancfilial IS NULL) THEN
        NEW.bdtipolancfilial = 0;
      IF (NEW.bdcontabilizacao IS NULL) THEN
        NEW.bdcontabilizacao = 0;
    END

  IF (NEW.BDTIPOLAN = 26) THEN
    NEW.bdcontabilizacao = NEW.bdcontabilizacao + 1; --#alt:15359 - No combo do valor presente so tem fiscal e societ?ria, por isso soma. 0 - ambas, 1 - fiscal, 2 - societ?ria. Ana - 07/10/2016

  -- Gilberto - 21/05/2012 - rotina respons?vel por vetar os lan?amentos bloqueados para on-line
  IF ((NEW.bdtipolan <> 2) AND (NEW.bdtipolan <> 300)) THEN
     BEGIN
  -- sol:5822 - Elizeu - 06-04-2013 - comentado o codigo abaixo porque, estava pegando o c?digo do usu?rio do lan?amento e n?o o usu?rio logado
  --isso ocasionava problema quando o usu?rio que fez o lan?amento estava bloqueado e o que estava alterando n?o estava ex:
  -- usu?rio 6 fez o lan?amento sem permiss?o
  -- usu?rio 11 est? alterando com permiss?o
--       if ((new.bdcodusu is not null) and (new.bdcodusu <> 0)) then
--          vCodUsu = new.bdcodusu;
--       else
          SELECT FIRST 1 bdcodusu FROM sp_get_usuario INTO :vCodUsu;

       /* sol.: #10892 Jean 19/01/2015: para verificar se esta executando processo de recontabiliza??o */ 
       SELECT TRIM(UPPER(COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_RECONTABILIZA'), '')))
       FROM RDB$DATABASE
       INTO :VRECONTABILIZANDO;
     
--       SELECT COUNT(*) Denicio 05/07/2016: N?o precisa fazer o COUNT da tabela. Pode apenas ver se tem algum registro. Dessa forma ? mais r?pido.
       vcodigo = NULL;
       SELECT FIRST 1 BDCODUSU
       FROM tbloqlan_usuario tblu
       INNER JOIN tbloqlan_empresa tble ON (tble.bdcodemp = tblu.bdcodemp AND tble.bdcodblq = tblu.bdcodblq AND tble.bdcodble = tblu.bdcodble)
       INNER JOIN tbloqlan tbloq ON (tbloq.bdcodblq = tble.bdcodblq)
       WHERE tbloq.bdcodsis = 4
       AND UPPER(tbloq.bdrecurso) = UPPER('frlancamento')
       AND ((bddatainicial >= NEW.bddata AND (bddatafinal <= NEW.bddata OR bddatafinal IS NULL))
       OR (bddatainicial <= NEW.bddata AND ((bddatafinal BETWEEN NEW.bddata AND NEW.bddata) OR bddatafinal IS NULL))
       OR (bddatainicial <= NEW.bddata AND (bddatafinal >= NEW.bddata OR bddatafinal IS NULL)) )
       AND tble.bdcodemp = NEW.bdcodemp
       AND tblu.bdcodusu = :vcodusu
       INTO :vcodigo;

       /* sol.: #10892 Jean 19/01/2015: Lan?ar exce??o somente se n?o estiver recontabilizando */
       IF ((vcodigo IS NOT NULL) AND (vcodigo > 0) AND (VRECONTABILIZANDO <> 'TRUE')) THEN
          EXCEPTION ex_bloqlan;
     END

     --#alt:13456 - Atribui ao novo campo o valor de 0 se este n?o possui nenhum valor. Ana - 28/10/2016
     IF (NEW.bdtipoconc IS NULL) THEN
        NEW.bdtipoconc = 0;
     --#alt:13456. fim
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_UPDATE_VSUC_EMPRESAS_TLAN
AS
BEGIN
   IF (NEW.BDTIPOLAN = 26) THEN
    IF (NEW.bdcontabilizacao <= 0) THEN
        NEW.bdcontabilizacao = 1;
      ELSE
        IF (NEW.bdcontabilizacao >= 1) THEN
            NEW.bdcontabilizacao = 2; --#alt:15359 - No combo so tem fiscal e societ?ria, por isso soma. 0 - ambas, 1 - fiscal, 2 - societ?ria. Ana - 07/10/2016

   --#alt:13456 - Atribui ao novo campo o valor de 0 se este n?o possui nenhum valor. Ana - 28/10/2016
   IF ((NEW.bdtipoconc IS NULL) AND (OLD.bdtipolan IS NULL)) THEN
        NEW.bdtipoconc = 0;
   --#alt:13456. fim

   --alt:14942 - 18/01/2017 - Caso marque os lan?amentos como conciliados que antes eram pendentes, deve demover o devido status. Pedro
   IF ((UPPER(COALESCE(OLD.BDCONCD, 'FALSE')) = 'FALSE') AND (UPPER(COALESCE(NEW.BDCONCD, 'FALSE')) = 'TRUE') AND (OLD.BDCONCILIACAOPENDENTE IN (1,3))) THEN
     BEGIN
       NEW.BDCONCILIACAOPENDENTE = OLD.BDCONCILIACAOPENDENTE -1;
       DELETE FROM VSUC_EMPRESAS_TOBS WHERE BDCODEMP = NEW.BDCODEMP AND BDCHAVE = NEW.BDCHAVE AND BDDEBCRE = 0;
     END

   IF ((UPPER(COALESCE(OLD.BDCONCC, 'FALSE')) = 'FALSE') AND (UPPER(COALESCE(NEW.BDCONCC, 'FALSE')) = 'TRUE') AND (OLD.BDCONCILIACAOPENDENTE IN (2,3))) THEN
     BEGIN
       NEW.BDCONCILIACAOPENDENTE = OLD.BDCONCILIACAOPENDENTE -2;
       DELETE FROM VSUC_EMPRESAS_TOBS WHERE BDCODEMP = NEW.BDCODEMP AND BDCHAVE = NEW.BDCHAVE AND BDDEBCRE = 1;
     END
   --alt:14942 - Fim
END
^

/* Altering existing trigger... */
ALTER TRIGGER TR_BF_UPDATE_VSUC_EMPRESAS_VP
AS
BEGIN
  IF (NEW.bdcontabilizacao <= 0) THEN
    NEW.bdcontabilizacao = 1;
  ELSE
    IF (NEW.bdcontabilizacao >= 1) THEN
        NEW.bdcontabilizacao = 2; --#alt:15359 - No combo so tem fiscal e societ?ria, por isso soma. 0 - ambas, 1 - fiscal, 2 - societ?ria. Ana - 07/10/2016
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_BASE_OBRIGACAO_AI0
AS
  DECLARE VARIABLE vcodemp INTEGER;
  DECLARE VARIABLE vrefemp INTEGER;
BEGIN
/* Gilberto - 25/03/2015 - ALT:#11161 - Tirado para n?o inserir nos planos tribut?rios
  INSERT INTO VCT_TRIBUTOS_PLANO_TRIBUTARIO
  SELECT NULL AS bdcodtrib, tpla.bdcodplatrib, NULL AS bdcodimp, NULL AS bdcodser, tobr.bdcodobrser
  FROM vct_base_obrigacao tobr
  INNER JOIN vct_plano_tributario tpla ON (tpla.bdcodplatrib IS NOT NULL)
  WHERE tobr.bdtipo = 1
  AND NOT tobr.bdcodobrser IN (SELECT DISTINCT bdcodobr
                               FROM vct_tributos_plano_tributario
                               WHERE bdcodobr IS NOT NULL)
  AND tobr.bdcodobrser = NEW.bdcodobrser;


  FOR SELECT bdcodemp, bdempref FROM vw_empresas_ref_atual
      WHERE bdcodemp IN (SELECT DISTINCT bdcodemp FROM vct_tributario_empresa)
      INTO :vcodemp, vrefemp DO
      BEGIN
        EXECUTE STATEMENT 'insert into vct_tributario_empresa (BDCODEMP, BDCODOBR, BDREFINI, BDREFFIN) values ('||vcodemp||', '||NEW.bdcodobrser||',  '||vrefemp||', null)';
      END
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_BASE_SERVICO_AI0
AS
  DECLARE VARIABLE vcodemp INTEGER;
  DECLARE VARIABLE vrefemp INTEGER;
BEGIN
/* Gilberto - 25/03/2015 - ALT:#11161 - Tirado para n?o inserir nos planos tribut?rios
  INSERT INTO VCT_TRIBUTOS_PLANO_TRIBUTARIO
  SELECT NULL AS bdcodtrib, tpla.bdcodplatrib, NULL AS bdcodimp, tser.bdcodobrser, NULL AS bdcodobr
  FROM vct_base_servico tser
  INNER JOIN vct_plano_tributario tpla ON (tpla.bdcodplatrib IS NOT NULL)
  WHERE tser.bdtipo = 1
  AND NOT tser.bdcodobrser IN (SELECT DISTINCT bdcodser
                               FROM vct_tributos_plano_tributario
                               WHERE bdcodser IS NOT NULL)
  AND tser.bdcodobrser = NEW.bdcodobrser;


  FOR SELECT bdcodemp, bdempref FROM vw_empresas_ref_atual
      WHERE bdcodemp IN (SELECT DISTINCT bdcodemp FROM vct_tributario_empresa)
      INTO :vcodemp, vrefemp DO
      BEGIN
        EXECUTE STATEMENT 'insert into vct_tributario_empresa (BDCODEMP, BDCODSER, BDREFINI, BDREFFIN) values ('||vcodemp||', '||NEW.bdcodobrser||',  '||vrefemp||', null)';
      END
*/
  /*Adilson Hasckel: sol. 14282 - 04/05/2016 - criar automaticamente os servi?os na configura??o de Online do Financeiro. */
  EXECUTE PROCEDURE vfin_insert_novo_servico_online(NEW.bdclassificacao,NEW.bdcodobrser);
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_BASE_SERVICO_AU0
AS
BEGIN
  IF (OLD.bdclassificacao <> NEW.bdclassificacao) THEN
     BEGIN
       --Adilson Hasckel: sol. 14282 - 04/05/2016 - atualizar a configura??o de servi?os da online, caso ocorra a troca de classifica??o do servi?o
       EXECUTE PROCEDURE vfin_update_servico_online(OLD.bdclassificacao,NEW.bdclassificacao,NEW.BDCODOBRSER);
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_EMPRESA_DOCSGERADOS_BI0
AS
  DECLARE VARIABLE vCODDOCGER INTEGER;
BEGIN
  IF ((NEW.bdcoddocger IS NULL) OR (NEW.bdcoddocger = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODDOCGER) + 1, 1)
       FROM vct_empresa_docsgerados
       WHERE BDCODEMP = NEW.bdcodemp
       INTO :vCODDOCGER;

       NEW.bdcoddocger = :vCODDOCGER;
     END

  IF (NEW.bdchavedarf IS NOT NULL) THEN
     BEGIN
       SELECT bdcodimp, bddatavcto, bdtotal FROM tdarfpadrao
       WHERE bdcodemp = NEW.bdcodemp
       AND bdchavedarf = NEW.bdchavedarf
       INTO NEW.bdcodimp, NEW.bddatavcto, NEW.bdvalor;
     END

  IF (NEW.bddata IS NULL) THEN
     NEW.bddata = CURRENT_DATE;

  /* gilberto - 01/04/2015 - ALT:#11246 - n?o pode haver valor nesses campos caso um deles esteja nulo, isso faz com que os documentos fiquem duplicados e/ou n?o apare?am na tela de protocolo */
  IF ((NEW.bdcodpts IS NULL) OR (NEW.bdcodipts IS NULL)) THEN
     BEGIN
       NEW.bdcodpts = NULL;
       NEW.bdcodipts = NULL;
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_EMPRESA_PROTODOCSAIDA_BD0
AS
BEGIN
  -- gilberto - 19/05/2015 - ALT:#11246 - desvincular documentos gerados e documentos protocolados
  UPDATE vct_empresa_docsgerados SET
  bdcodpts = NULL, bdcodipts = NULL
  WHERE bdcodemp = OLD.bdcodemp
  AND bdcodpts = OLD.bdcodpts
  AND bdcodipts = OLD.bdcodipts;
  -- aten??o: verificar exclus?o do protocolo de sa?da -------- gilberto - 19/05/2015 - ALT:#11246

/*
  IF (OLD.bdchavedarf IS NOT NULL) THEN
     BEGIN
       UPDATE vct_empresa_docsgerados SET
       bdcodpts = NULL,
       bdcodipts = NULL
       WHERE bdcodemp = OLD.bdcodemp
       AND bdchavedarf = OLD.bdchavedarf;
     END
  ELSE
  IF (OLD.bdcodtelasis IS NOT NULL) THEN
     BEGIN
       IF (OLD.bdcomplemento IS NULL) THEN
          BEGIN
            UPDATE vct_empresa_docsgerados SET
            bdcodpts = NULL,
            bdcodipts = NULL
            WHERE bdcodemp = OLD.bdcodemp
            AND bdcodtelasis = OLD.bdcodtelasis;
          END
       ELSE
          BEGIN
            UPDATE vct_empresa_docsgerados SET
            bdcodpts = NULL,
            bdcodipts = NULL
            WHERE bdcodemp = OLD.bdcodemp
            AND bdcodtelasis = OLD.bdcodtelasis
            AND UPPER(bdcomplemento) = UPPER(OLD.bdcomplemento);
          END
     END
  ELSE
  IF ((OLD.bdcodpte IS NOT NULL) AND (OLD.bdcodipte IS NOT NULL)) THEN
     BEGIN
       UPDATE vct_empresa_docsgerados SET
       bdcodpts = NULL,
       bdcodipts = NULL
       WHERE bdcodemp = OLD.bdcodemp
       AND bdcodpte = OLD.bdcodpte
       AND bdcodipte = OLD.bdcodipte;

       UPDATE vct_empresa_protodocentrada SET
       bddatabaixa = NULL
       WHERE bdcodemp = OLD.bdcodemp
       AND bdcodpte = OLD.bdcodpte
       AND bdcodipte = OLD.bdcodipte;
     END
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_EMPRESA_PROTOENT_BI0
AS
  DECLARE VARIABLE vCODPTE INTEGER;
  DECLARE VARIABLE vseq INTEGER;
  DECLARE VARIABLE vesc INTEGER;
  DECLARE VARIABLE vemp INTEGER;
BEGIN
  IF ((NEW.bdcodpte IS NULL) OR (NEW.bdcodpte = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPTE) + 1, 1)
       FROM vct_empresa_protocoloentrada
       WHERE BDCODEMP = NEW.bdcodemp
       INTO :vCODPTE;

       NEW.bdcodpte = :vCODPTE;
     END
/*
  if ((new.bdserie is null) or (new.bdserie = '')) then
     begin  --alt:7036 Agora grava como "PE", para manter o padr?o
       new.bdserie = 'PE'||substring(current_date from 1 for 4)||substring(current_date from 6 for 2)||substring(current_date from 9 for 2)||substring(current_time from 1 for 2)||substring(current_time from 4 for 2)||substring(current_time from 7 for 2);
     end
*/

  /*
  Leonardo Pereira - 18/12/2017 - 21708 - Atualizar serie quando usuario selecionar outro escritorio
  SELECT FIRST 1 cnf.bdseqent,
         cnf.bdcodesc, cnf.bdcodemp
  FROM VCT_CONFIG_PROTO_EMP cnf
  INNER JOIN tempresas emp ON (emp.bdcodemp = cnf.bdcodemp AND ((emp.bdcodesc = cnf.bdcodesc) OR (emp.bdcodesc IS NULL)))
  WHERE ((cnf.bdserieent IS NOT NULL) AND (cnf.bdserieent <> ''))
  AND cnf.bdcodemp = NEW.bdcodemp
  INTO :vseq, :vesc, :vemp;*/

  SELECT FIRST 1 cnf.bdseqent,
         cnf.bdcodesc, cnf.bdcodemp
  FROM VCT_CONFIG_PROTO_EMP cnf
  WHERE ((cnf.bdserieent IS NOT NULL) AND (cnf.bdserieent <> '') and (cnf.bdcodesc = new.bdcodesc) and (cnf.bdcodemp =  new.bdcodemp))
  INTO :vseq, :vesc, :vemp;

  IF (vseq IS NOT NULL) THEN
     BEGIN
       UPDATE vct_config_proto_emp SET bdseqent = bdseqent+1 WHERE bdcodesc = :vesc AND bdcodemp = :vemp;
     END
  ELSE
     BEGIN
       /* Leonardo Pereira - 18/12/2017 - 21708 - Atualizar serie quando usuario selecionar outro escritorio
       SELECT FIRST 1 cnf.bdseqent, cnf.bdcodesc
       FROM VCT_CONFIG_PROTO_ESC cnf
       INNER JOIN tempresas emp ON (((emp.bdcodesc = cnf.bdcodesc) OR (emp.bdcodesc IS NULL)) AND (emp.bdcodemp = NEW.bdcodemp))
       WHERE ((cnf.bdserieent IS NOT NULL) AND (cnf.bdserieent <> ''))
       AND NOT EXISTS (SELECT * FROM VCT_CONFIG_PROTO_EMP x
                       WHERE x.bdcodemp = emp.bdcodemp AND x.bdcodesc = cnf.bdcodesc)
       INTO :vseq, :vesc;*/

       SELECT FIRST 1 cnf.bdseqent, cnf.bdcodesc
       FROM VCT_CONFIG_PROTO_ESC cnf
       WHERE ((cnf.bdserieent IS NOT NULL) AND (cnf.bdserieent <> '') and (cnf.bdcodesc =  new.bdcodesc))
       AND NOT EXISTS (SELECT * FROM VCT_CONFIG_PROTO_EMP x
                       WHERE x.bdcodemp = new.bdcodemp AND x.bdcodesc = cnf.bdcodesc)
       INTO :vseq, :vesc;


       IF (vseq IS NOT NULL) THEN
          BEGIN
            UPDATE vct_config_proto_esc SET bdseqent = bdseqent+1 WHERE bdcodesc = :vesc;
          END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_EMPRESA_PROTOSAI_BI0
AS
  DECLARE VARIABLE vCODPTS INTEGER;
  DECLARE VARIABLE vseq INTEGER;
  DECLARE VARIABLE vesc INTEGER;
  DECLARE VARIABLE vemp INTEGER;
BEGIN
  IF ((NEW.bdcodpts IS NULL) OR (NEW.bdcodpts = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPTS) + 1, 1)
       FROM vct_empresa_protocolosaida
       WHERE BDCODEMP = NEW.bdcodemp
       INTO :vCODPTS;

       NEW.bdcodpts = :vcodpts;
     END
/*
  if ((new.bdserie is null) or (new.bdserie = '')) then
     begin  --alt:7036 Agora grava como "PS", para manter o padr?o
       new.bdserie = 'PS'||substring(current_date from 1 for 4)||substring(current_date from 6 for 2)||substring(current_date from 9 for 2)||substring(current_time from 1 for 2)||substring(current_time from 4 for 2)||substring(current_time from 7 for 2);
     end
*/

/* Leonardo Pereira - 18/12/2017 - 21708 - Atualizar serie quando usuario selecionar outro escritorio
    SELECT FIRST 1 cnf.bdseqsai,
         cnf.bdcodesc, cnf.bdcodemp
  FROM VCT_CONFIG_PROTO_EMP cnf
  INNER JOIN tempresas emp ON (emp.bdcodemp = cnf.bdcodemp AND ((emp.bdcodesc = cnf.bdcodesc) OR (emp.bdcodesc IS NULL)))
  WHERE ((cnf.bdseriesai IS NOT NULL) AND (cnf.bdseriesai <> ''))
  AND cnf.bdcodemp = NEW.bdcodemp
  INTO :vseq, :vesc, :vemp;*/

  SELECT FIRST 1 cnf.bdseqsai,
         cnf.bdcodesc, cnf.bdcodemp
  FROM VCT_CONFIG_PROTO_EMP cnf
  WHERE ((cnf.bdseriesai IS NOT NULL) AND (cnf.bdseriesai <> '') and (cnf.bdcodesc = new.bdcodesc) and (cnf.bdcodemp =  new.bdcodemp))
  INTO :vseq, :vesc, :vemp;

  IF (vseq IS NOT NULL) THEN
     BEGIN
       UPDATE vct_config_proto_emp SET bdseqsai = bdseqsai+1 WHERE bdcodesc = :vesc AND bdcodemp = :vemp;
     END
  ELSE
     BEGIN
       /* Leonardo Pereira - 18/12/2017 - 21708 - Atualizar serie quando usuario selecionar outro escritorio
       SELECT FIRST 1 cnf.bdseqsai, cnf.bdcodesc
       FROM VCT_CONFIG_PROTO_ESC cnf
       INNER JOIN tempresas emp ON (((emp.bdcodesc = cnf.bdcodesc) OR (emp.bdcodesc IS NULL)) AND (emp.bdcodemp = NEW.bdcodemp))
       WHERE ((cnf.bdseriesai IS NOT NULL) AND (cnf.bdseriesai <> ''))
       AND NOT EXISTS (SELECT * FROM VCT_CONFIG_PROTO_EMP x
                       WHERE x.bdcodemp = emp.bdcodemp AND x.bdcodesc = cnf.bdcodesc)
       INTO :vseq, :vesc;*/

       SELECT FIRST 1 cnf.bdseqsai, cnf.bdcodesc
       FROM VCT_CONFIG_PROTO_ESC cnf
       WHERE ((cnf.bdseriesai IS NOT NULL) AND (cnf.bdseriesai <> '') and (cnf.bdcodesc =  new.bdcodesc))
       AND NOT EXISTS (SELECT * FROM VCT_CONFIG_PROTO_EMP x
                       WHERE x.bdcodemp = new.bdcodemp AND x.bdcodesc = cnf.bdcodesc)
       INTO :vseq, :vesc;

       IF (vseq IS NOT NULL) THEN
          BEGIN
            UPDATE vct_config_proto_esc SET bdseqsai = bdseqsai+1 WHERE bdcodesc = :vesc;
          END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_EMPRESA_THISTTAREFA_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodst IS NULL) OR (NEW.bdcodst = 0)) THEN
     BEGIN
       SELECT MAX(bdcodst) FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = NEW.bdcodemp INTO :vcodigo;
       NEW.bdcodst = vcodigo;
     END


  vcodigo = 0;
  IF ((NEW.bdCODHT IS NULL) OR (NEW.bdCODHT = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdCODHT)+1),1) FROM vct_empresa_thistoricotarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST INTO vcodigo;
       NEW.bdCODHT = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdCODHT FROM vct_empresa_thistoricotarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST AND bdCODHT = NEW.bdCODHT INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdCODHT)+1),1) FROM vct_empresa_thistoricotarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST INTO vcodigo;
            NEW.bdCODHT = vcodigo;
         END
    END

  IF (NEW.bddata IS NULL) THEN
     NEW.bddata = CURRENT_DATE;
  IF (NEW.bdhora IS NULL) THEN
     NEW.bdhora = CURRENT_TIME;

  /* Somente atribuir um valor ao campo BDCODSITWEB se ele vier nulo.
  Se a tarefa for autom?tica, esta informa??o j? ? setada ao inseri-la */
  IF (NEW.BDCODSITWEB IS NULL) THEN
     BEGIN
       vcodigo = 0;
       SELECT FIRST 1 BDCODHT FROM vct_empresa_thistoricotarefa WHERE BDCODEMP = NEW.BDCODEMP AND BDCODST = NEW.BDCODST INTO vcodigo;
       IF (vcodigo = 0) THEN
          BEGIN
            NEW.BDCODSITWEB = 2; --Inser??o pendente
          END
       ELSE
         BEGIN
           NEW.BDCODSITWEB = 3; --Edi??o pendente
         END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_EMPRESA_TSOLICITATAREFA_AI0
AS
  DECLARE VARIABLE vcodser INTEGER;
  DECLARE VARIABLE vnomusu VARCHAR(40);
  DECLARE VARIABLE vcodusu INTEGER;
  DECLARE VARIABLE vcodemp INTEGER;
  DECLARE VARIABLE vcodimp INTEGER;
  DECLARE VARIABLE vcodgrupo INTEGER;
BEGIN
  IF (NEW.bdcodtipo = 501) THEN
  BEGIN
    -- Lan?amento de usu?rios para solicita??es de impostos
    IF (EXISTS (SELECT * FROM vct_empresa_usuario_imp WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = NEW.bdcodimp)) THEN
    BEGIN
      IF (EXISTS (SELECT * FROM vct_empresa_usuario_imp WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = NEW.bdcodimp AND bdcodusu IS NULL AND bdcodgrupo IS NULL)) THEN
         BEGIN
           IF (NEW.bdcodimp IS NOT NULL) THEN
              INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                                       VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                       'Lan?ado pelo processo autom?tico de gera??o de tarefas para todos os usu?rios.', 2);
         END
      ELSE
         BEGIN
      FOR SELECT DISTINCT sol.bdcodemp, sol.bdcodimp, sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
          SELECT emp.bdcodemp, emp.bdcodimp, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_imp emp
          INNER JOIN tusuario usu ON (usu.bdcodusu = emp.bdcodusu)
          WHERE(bdcodgrupo IS NULL)AND(emp.bdcodimp = NEW.bdcodimp)AND(emp.bdcodemp = NEW.bdcodemp)
          UNION ALL
          SELECT emp.bdcodemp, emp.bdcodimp, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_imp emp
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo AND usu.bdcodusu = emp.bdcodusu)
          WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodimp = NEW.bdcodimp)AND(emp.bdcodemp = NEW.bdcodemp)
          UNION ALL
          SELECT emp.bdcodemp, emp.bdcodimp, emp.bdcodgrupo, usu.bdcodusu FROM vct_empresa_usuario_imp emp
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo)
          WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodusu IS NULL)AND(emp.bdcodimp = NEW.bdcodimp)AND(emp.bdcodemp = NEW.bdcodemp)
          ) AS sol
          LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
          ORDER BY bdcodemp, bdcodimp, bdcodgrupo, bdcodusu
          INTO :vcodemp, :vcodimp, :vcodgrupo, :vcodusu, :vnomusu DO
          BEGIN
                 INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                              VALUES (:vcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                      'Lan?ado pelo processo autom?tico de gera??o de tarefas para o usu?rio "'||:vnomusu||'", com base nas configura??es do cadastro de impostos.', 2);
          END
    END
    END
    ELSE
    IF (EXISTS (SELECT * FROM vct_base_usuarioimposto WHERE bdcodimp = NEW.bdcodimp)) THEN
    BEGIN
      FOR SELECT DISTINCT sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
          SELECT bdcodgrupo, bdcodusu FROM vct_base_usuarioimposto tui
          WHERE tui.bdcodimp = NEW.bdcodimp AND (tui.bdcodgrupo IS NULL)
          UNION ALL
          SELECT tui.bdcodgrupo, tui.bdcodusu FROM vct_base_usuarioimposto tui
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = tui.bdcodgrupo AND usu.bdcodusu = tui.bdcodusu)
          WHERE tui.bdcodimp = NEW.bdcodimp AND (tui.bdcodgrupo IS NOT NULL)
          UNION ALL
          SELECT tui.bdcodgrupo, usu.bdcodusu FROM vct_base_usuarioimposto tui
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = tui.bdcodgrupo)
          WHERE tui.bdcodimp = NEW.bdcodimp AND (tui.bdcodgrupo IS NOT NULL) AND (tui.bdcodusu IS NULL)) AS sol
          LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
          ORDER BY bdcodgrupo, bdcodusu
          INTO :vcodgrupo, :vcodusu, :vnomusu DO
          BEGIN
            INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                              VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                      'Lan?ado pelo processo autom?tico de gera??o de tarefas para o usu?rio "'||:vnomusu||'", com base nas configura??es do cadastro de impostos.', 2);
          END
    END
    ELSE
    BEGIN
      -- Gilberto - 01/02/2017 - ALT:17095
      IF (NEW.bdcodimp IS NOT NULL) THEN
         INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                          VALUES (NEW.bdcodemp, NEW.bdcodst, NULL, NULL, CURRENT_DATE, CURRENT_TIME, 6,
                                                'Lan?ado pelo processo autom?tico de gera??o de tarefas para todos os usu?rios.', 2);
    END

    -- Lan?amento de usu?rios para solicita??es de obriga??es
    IF (EXISTS (SELECT * FROM vct_empresa_usuario_obr WHERE bdcodemp = NEW.bdcodemp AND bdcodobrser = NEW.bdcodobrigacao)) THEN
    BEGIN
      IF (EXISTS (SELECT * FROM vct_empresa_usuario_obr WHERE bdcodemp = NEW.bdcodemp AND bdcodobrser = NEW.bdcodobrigacao AND bdcodusu IS NULL AND bdcodgrupo IS NULL)) THEN
         BEGIN
           IF (NEW.bdcodobrigacao IS NOT NULL) THEN
              INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                                        VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                       'Lan?ado pelo processo autom?tico de gera??o de tarefas para todos os usu?rios.', 2);
         END
      ELSE
         BEGIN
      FOR SELECT DISTINCT sol.bdcodemp, sol.bdcodobrser, sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
          SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_obr emp
          INNER JOIN tusuario usu ON (usu.bdcodusu = emp.bdcodusu)
          WHERE(bdcodgrupo IS NULL)AND(emp.bdcodobrser = NEW.bdcodobrigacao)
          UNION ALL
          SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_obr emp
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo AND usu.bdcodusu = emp.bdcodusu)
          WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodobrser = NEW.bdcodobrigacao)
          UNION ALL
          SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, usu.bdcodusu FROM vct_empresa_usuario_obr emp
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo)
          WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodusu IS NULL)AND(emp.bdcodobrser = NEW.bdcodobrigacao)
          ) AS sol
          LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
          WHERE sol.bdcodemp = NEW.bdcodemp
          ORDER BY bdcodemp, bdcodobrser, bdcodgrupo, bdcodusu
          INTO :vcodemp, :vcodimp, :vcodgrupo, :vcodusu, :vnomusu DO
          BEGIN
                 INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                              VALUES (:vcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                      'Lan?ado pelo processo autom?tico de gera??o de tarefas para o usu?rio "'||:vnomusu||'", com base nas configura??es do cadastro de obriga??es.', 2);
          END
    END
    END
    ELSE
    IF (EXISTS (SELECT * FROM vct_base_usuarioobrigacao WHERE bdcodobrser = NEW.bdcodobrigacao)) THEN
    BEGIN
      FOR SELECT DISTINCT sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
          SELECT bdcodgrupo, bdcodusu FROM vct_base_usuarioobrigacao tui
          WHERE tui.bdcodobrser = NEW.bdcodobrigacao AND (tui.bdcodgrupo IS NULL)
          UNION ALL
          SELECT tui.bdcodgrupo, tui.bdcodusu FROM vct_base_usuarioobrigacao tui
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = tui.bdcodgrupo AND usu.bdcodusu = tui.bdcodusu)
          WHERE tui.bdcodobrser = NEW.bdcodobrigacao AND (tui.bdcodgrupo IS NOT NULL)
          UNION ALL
          SELECT tui.bdcodgrupo, usu.bdcodusu FROM vct_base_usuarioobrigacao tui
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = tui.bdcodgrupo)
          WHERE tui.bdcodobrser = NEW.bdcodobrigacao AND (tui.bdcodgrupo IS NOT NULL) AND (tui.bdcodusu IS NULL)) AS sol
          LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
          ORDER BY bdcodgrupo, bdcodusu
          INTO :vcodgrupo, :vcodusu, :vnomusu DO
          BEGIN
            INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                              VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                      'Lan?ado pelo processo autom?tico de gera??o de tarefas para o usu?rio "'||:vnomusu||'", com base nas configura??es do cadastro de obriga??es.', 2);
          END
    END
    ELSE
    BEGIN
      -- Gilberto - 01/02/2017 - ALT:17095
         IF (NEW.bdcodobrigacao IS NOT NULL) THEN 
            INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                         VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                'Lan?ado pelo processo autom?tico de gera??o de tarefas para todos os usu?rios.', 2);
    END

    -- Lan?amento de usu?rios para solicita??es de servi?os
    IF (EXISTS (SELECT * FROM vct_empresa_usuario_ser WHERE bdcodemp = NEW.bdcodemp AND bdcodobrser = NEW.bdcodservico)) THEN
    BEGIN
      IF (EXISTS (SELECT * FROM vct_empresa_usuario_ser WHERE bdcodemp = NEW.bdcodemp AND bdcodobrser = NEW.bdcodservico AND bdcodusu IS NULL AND bdcodgrupo IS NULL)) THEN
         BEGIN
           IF (NEW.bdcodservico IS NOT NULL) THEN      
              INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                                       VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                       'Lan?ado pelo processo autom?tico de gera??o de tarefas para todos os usu?rios.', 2);
         END
      ELSE
         BEGIN
      FOR SELECT DISTINCT sol.bdcodemp, sol.bdcodobrser, sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
          SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_ser emp
          INNER JOIN tusuario usu ON (usu.bdcodusu = emp.bdcodusu)
          WHERE(bdcodgrupo IS NULL)AND(emp.bdcodobrser = NEW.bdcodservico)
          UNION ALL
          SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_ser emp
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo AND usu.bdcodusu = emp.bdcodusu)
          WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodobrser = NEW.bdcodservico)
          UNION ALL
          SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, usu.bdcodusu FROM vct_empresa_usuario_ser emp
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo)
          WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodusu IS NULL)AND(emp.bdcodobrser = NEW.bdcodservico)
          ) AS sol
          LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
          WHERE sol.bdcodemp = NEW.bdcodemp
          ORDER BY bdcodemp, bdcodobrser, bdcodgrupo, bdcodusu
          INTO :vcodemp, :vcodimp, :vcodgrupo, :vcodusu, :vnomusu DO
          BEGIN
                    INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                              VALUES (:vcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                      'Lan?ado pelo processo autom?tico de gera??o de tarefas para o usu?rio "'||:vnomusu||'", com base nas configura??es do cadastro de servi?os.', 2);
          END
    END
    END
    ELSE
    IF (EXISTS (SELECT * FROM vct_base_usuarioservico WHERE bdcodobrser = NEW.bdcodservico)) THEN
    BEGIN
      FOR SELECT DISTINCT sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
          SELECT bdcodgrupo, bdcodusu FROM vct_base_usuarioservico tui
          WHERE tui.bdcodobrser = NEW.bdcodservico AND (tui.bdcodgrupo IS NULL)
          UNION ALL
          SELECT tui.bdcodgrupo, tui.bdcodusu FROM vct_base_usuarioservico tui
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = tui.bdcodgrupo AND usu.bdcodusu = tui.bdcodusu)
          WHERE tui.bdcodobrser = NEW.bdcodservico AND (tui.bdcodgrupo IS NOT NULL)
          UNION ALL
          SELECT tui.bdcodgrupo, usu.bdcodusu FROM vct_base_usuarioservico tui
          INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = tui.bdcodgrupo)
          WHERE tui.bdcodobrser = NEW.bdcodservico AND (tui.bdcodgrupo IS NOT NULL) AND (tui.bdcodusu IS NULL)) AS sol
          LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
          ORDER BY bdcodgrupo, bdcodusu
          INTO :vcodgrupo, :vcodusu, :vnomusu DO
          BEGIN
            INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                              VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                      'Lan?ado pelo processo autom?tico de gera??o de tarefas para o usu?rio "'||:vnomusu||'", com base nas configura??es do cadastro de servi?os.', 2);
          END
    END
    ELSE
    BEGIN
      -- Gilberto - 01/02/2017 - ALT:17095
        IF (NEW.bdcodservico IS NOT NULL) THEN      
           INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
                                        VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 6,
                                                'Lan?ado pelo processo autom?tico de gera??o de tarefas para todos os usu?rios.', 2);
    END

  END

  -- Servi?os subordinadas
  IF (NEW.bdcodservico IS NOT NULL) THEN
     BEGIN
       FOR SELECT BDCODSERSUB FROM VCT_BASE_SERVICOSUBORDINADO WHERE BDCODOBRSER = NEW.bdcodservico INTO :vcodser DO
           BEGIN
             INSERT INTO vct_empresa_tsolicitatarefa
             (BDCODEMP, BDCODST, BDCODUSU, BDCODCOL, BDCODIMP, BDCODOBRIGACAO, BDCODSERVICO,
              BDCODTIPO, BDDATASOL, BDFATURAR, BDDATASOLICITADA, BDDATAPREVISAO, BDDATAFIM,
              BDSERIE, BDREFSOL, BDQUANTIDADE, BDVALORUNITARIO, BDVALORDESCONTO, BDTIPODESCONTO,
              BDPARCELAS, BDTIPOSOLICITACAO, BDCHAVEWEB, BDAGUARD, BDVENCIMENTO, BDENTREGA,
              BDALERTA, BDHORAPREVISAO, BDTEMPOESTIMADO, BDFILIAL)
             VALUES
             (NEW.BDCODEMP, NULL, NEW.BDCODUSU, NEW.BDCODCOL, NULL, NULL, :vcodser,
              NEW.BDCODTIPO, NEW.BDDATASOL, NEW.BDFATURAR, NEW.BDDATASOLICITADA, NEW.BDDATAPREVISAO, NEW.BDDATAFIM,
              NEW.BDSERIE, NEW.BDREFSOL, NEW.BDQUANTIDADE, NEW.BDVALORUNITARIO, NEW.BDVALORDESCONTO, NEW.BDTIPODESCONTO,
              NEW.BDPARCELAS, NEW.BDTIPOSOLICITACAO, NEW.BDCHAVEWEB, NEW.BDAGUARD, NEW.BDVENCIMENTO, NEW.BDENTREGA,
              NEW.BDALERTA, NEW.BDHORAPREVISAO, NEW.BDTEMPOESTIMADO, NEW.BDFILIAL);
           END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_EMPRESA_TSOLICITATAREFA_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vClass VARCHAR(40);
  DECLARE VARIABLE vCount INTEGER;
BEGIN
  /* lan?amento autom?tico dos servi?os */
  IF (NEW.bdcodservico IS NOT NULL) THEN
     BEGIN
       SELECT tser.bdtipo, tser.bdclassificacao FROM vct_base_servico tser WHERE tser.bdcodobrser = NEW.bdcodservico INTO :vcodigo, :vclass;
       IF (vcodigo = 0) THEN
          BEGIN
            vCount = 0;
            FOR SELECT tser.bdcodobrser
                FROM vct_base_servico tser
                WHERE SUBSTRING(tser.bdclassificacao FROM 1 FOR CHAR_LENGTH(:vclass)) = :vclass
                AND tser.bdtipo = 1
                INTO :vcodigo DO
                BEGIN
                  IF (vCount = 0) THEN
                     NEW.bdcodservico = :vcodigo;
                  ELSE
                     BEGIN
                       INSERT INTO vct_empresa_tsolicitatarefa
                       (BDCODEMP, BDCODST, BDCODUSU, BDCODCOL, BDCODIMP,
                        BDCODOBRIGACAO, BDCODSERVICO, BDCODTIPO, BDDATASOL,
                        BDFATURAR, BDDATASOLICITADA, BDDATAPREVISAO,
                        BDDATAFIM, BDSERIE, BDREFSOL,
                        BDQUANTIDADE, BDVALORUNITARIO, BDVALORDESCONTO,
                        BDTIPODESCONTO, BDPARCELAS, BDTIPOSOLICITACAO, BDCHAVEWEB)
                       VALUES
                       (NEW.BDCODEMP, NULL, NEW.BDCODUSU, NEW.BDCODCOL, NEW.BDCODIMP,
                        NEW.BDCODOBRIGACAO, :vcodigo, NEW.BDCODTIPO, NEW.BDDATASOL,
                        NEW.BDFATURAR, NEW.BDDATASOLICITADA, NEW.BDDATAPREVISAO,
                        NEW.BDDATAFIM, NEW.BDSERIE, NEW.BDREFSOL,
                        NEW.BDQUANTIDADE, NEW.BDVALORUNITARIO, NEW.BDVALORDESCONTO,
                        NEW.BDTIPODESCONTO, NEW.BDPARCELAS, NEW.BDTIPOSOLICITACAO, NEW.BDCHAVEWEB);
                      END
                  vCount = vcount + 1;
                END
          END
     END
  /* lan?amento autom?tico das obriga??es */
  IF (NEW.bdcodobrigacao IS NOT NULL) THEN
     BEGIN
       SELECT tobr.bdtipo, tobr.bdclassificacao FROM vct_base_obrigacao tobr WHERE tobr.bdcodobrser = NEW.bdcodobrigacao INTO :vcodigo, :vclass;
       IF (vcodigo = 0) THEN
          BEGIN
            vCount = 0;
            FOR SELECT DISTINCT tobr.bdcodobrser
                FROM vct_base_obrigacao tobr
                /* considerar apenas obriga??es configuradas para empresa _____________________________________________________*/
                INNER JOIN VCT_TRIBUTARIO_EMPRESA temp ON (temp.bdcodemp = NEW.bdcodemp AND temp.bdcodobr = tobr.bdcodobrser)
                INNER JOIN vw_empresas_ref_atual tref ON (tref.bdcodemp = temp.bdcodemp AND ((tref.bdempref >= temp.bdrefini) AND
                                                                                             ((tref.bdempref <= temp.bdreffin) OR
                                                                                              (temp.bdreffin IS NULL))))
                /* ___________________________________________________________________________________________________________ */
                WHERE SUBSTRING(tobr.bdclassificacao FROM 1 FOR CHAR_LENGTH(:vclass)) = :vclass
                AND tobr.bdtipo = 1
                INTO :vcodigo DO
                BEGIN
                  IF (:vcount = 0) THEN
                     NEW.bdcodobrigacao = :vcodigo;
                  ELSE
                     BEGIN
                       INSERT INTO vct_empresa_tsolicitatarefa
                       (BDCODEMP, BDCODST, BDCODUSU, BDCODCOL, BDCODIMP,
                        BDCODOBRIGACAO, BDCODSERVICO, BDCODTIPO, BDDATASOL,
                        BDFATURAR, BDDATASOLICITADA, BDDATAPREVISAO,
                        BDDATAFIM, BDSERIE, BDREFSOL,
                        BDQUANTIDADE, BDVALORUNITARIO, BDVALORDESCONTO,
                        BDTIPODESCONTO, BDPARCELAS, BDTIPOSOLICITACAO, BDCHAVEWEB)
                       VALUES
                       (NEW.BDCODEMP, NULL, NEW.BDCODUSU, NEW.BDCODCOL, NEW.BDCODIMP,
                        :vcodigo, NEW.bdcodservico, NEW.BDCODTIPO, NEW.BDDATASOL,
                        NEW.BDFATURAR, NEW.BDDATASOLICITADA, NEW.BDDATAPREVISAO,
                        NEW.BDDATAFIM, NEW.BDSERIE, NEW.BDREFSOL,
                        NEW.BDQUANTIDADE, NEW.BDVALORUNITARIO, NEW.BDVALORDESCONTO,
                        NEW.BDTIPODESCONTO, NEW.BDPARCELAS, NEW.BDTIPOSOLICITACAO, NEW.BDCHAVEWEB);
                     END
                  vcount = vcount + 1;
                END
          END
     END



  /* gerador autom?tico da chave */
  vcodigo = 0;
  IF ((NEW.bdCODST IS NULL) OR (NEW.bdCODST = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdCODST)+1),1) FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
       NEW.bdCODST = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdCODST FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdCODST)+1),1) FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
            NEW.bdCODST = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_TRIBUTARIO_EMPRESA_AI0
AS
  DECLARE VARIABLE wcodemp INTEGER;
  DECLARE VARIABLE wcodimp INTEGER;
  DECLARE VARIABLE wrefini INTEGER;
  DECLARE VARIABLE wreffin INTEGER;
  DECLARE VARIABLE wrefant INTEGER;
  DECLARE VARIABLE wdata DATE;
  DECLARE VARIABLE wtotal INTEGER;
BEGIN
/*
  -- obriga??o
  wdata = addmonth(CAST(SUBSTRING(NEW.bdrefini FROM 1 FOR 4)||'-'||SUBSTRING(NEW.bdrefini FROM 5 FOR 2)||'-01' AS TIMESTAMP), -1);
  wrefant = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);

  FOR SELECT bdcodemp, bdcodobr, bdrefini, bdreffin FROM vct_tributario_empresa
      WHERE bdcodemp = NEW.bdcodemp
      AND bdcodobr = NEW.bdcodobr
      AND bdrefini <> NEW.bdrefini
      AND bdcodser IS NULL
      ORDER BY bdrefini DESC
      INTO :wcodemp, :wcodimp, :wrefini, :wreffin DO
      BEGIN
        IF ((wreffin IS NULL) AND (wrefant > wrefini)) THEN
           BEGIN
             UPDATE vct_tributario_empresa SET
             bdreffin = :wrefant
             WHERE bdcodemp = :wcodemp
             AND bdcodobr = :wcodimp
             AND bdrefini = :wrefini
             AND bdcodser IS NULL;
           END
         wdata = addmonth(CAST(SUBSTRING(wrefini FROM 1 FOR 4)||'-'||SUBSTRING(wrefini FROM 5 FOR 2)||'-01' AS TIMESTAMP), -1);
         wrefant = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);
      END

  -- servi?o
  wdata = addmonth(CAST(SUBSTRING(NEW.bdrefini FROM 1 FOR 4)||'-'||SUBSTRING(NEW.bdrefini FROM 5 FOR 2)||'-01' AS TIMESTAMP), -1);
  wrefant = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);

  FOR SELECT bdcodemp, bdcodser, bdrefini, bdreffin FROM vct_tributario_empresa
      WHERE bdcodemp = NEW.bdcodemp
      AND bdcodser = NEW.bdcodser
      AND bdrefini <> NEW.bdrefini
      AND bdcodobr IS NULL
      ORDER BY bdrefini DESC
      INTO :wcodemp, :wcodimp, :wrefini, :wreffin DO
      BEGIN
        IF (wreffin IS NULL) THEN
           BEGIN
             UPDATE vct_tributario_empresa SET
             bdreffin = :wrefant
             WHERE bdcodemp = :wcodemp
             AND bdcodser = :wcodimp
             AND bdrefini = :wrefini
             AND bdcodobr IS NULL;
           END
         wdata = addmonth(CAST(SUBSTRING(wrefini FROM 1 FOR 4)||'-'||SUBSTRING(wrefini FROM 5 FOR 2)||'-01' AS TIMESTAMP), -1);
         wrefant = CAST(SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2) AS INTEGER);
      END

-- gilberto - 02/07/2015 - ALT:#11974 - retirado porque fica muito lento ao selecionar tributos por empresa
--  SELECT total FROM vct_tarefas_automaticas(NEW.bdcodemp) INTO wTotal;-- Gilberto - 04/09/2014 - ALT:#9748 - Centraliza??o da rotina
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_TRIBUTARIO_EMPRESA_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdchave)+1),1) FROM vct_tributario_empresa WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
       NEW.bdchave = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vct_tributario_empresa WHERE bdchave = NEW.bdchave AND bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdchave)+1),1) FROM vct_tributario_empresa WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
            NEW.bdchave = vcodigo;
         END
    END

  -- gilberto - ALT:#10115 - dias ?teis para entrega
  IF (NEW.bdcodser IS NOT NULL) THEN
     SELECT bdentrega FROM vct_base_servico WHERE bdcodobrser = NEW.bdcodser INTO NEW.bdentrega;
  ELSE
  IF (NEW.bdcodobr IS NOT NULL) THEN
     SELECT bdentrega FROM vct_base_obrigacao WHERE bdcodobrser = NEW.bdcodser INTO NEW.bdentrega;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VCT_TRIBUTOS_PLANO_TRIB_AI0
AS
  DECLARE VARIABLE vcodtrib INTEGER;
  DECLARE VARIABLE vcodplatrib INTEGER;
  DECLARE VARIABLE vCODIMP INTEGER;
  DECLARE VARIABLE vCODOBRSER INTEGER;
  DECLARE VARIABLE vcodplatribcopia INTEGER;

  DECLARE VARIABLE wTotal INTEGER;
BEGIN
--  select total from vct_tarefas_automaticas(0) into wTotal;-- Gilberto - 04/09/2014 - ALT:#9748 - Centraliza??o da rotina
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPCADATV_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
         END
    END
/*
  select first 1 BDREFEMP from SP_CONSULTA_EMP_POR_REF(new.bdcodemp, new.bdrefemp)
  into new.bdrefemp;

  delete from vef_base_tempcadatv tatv
  where tatv.bdcodemp = new.bdcodemp
  and tatv.bdrefemp = new.bdrefemp;
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPITEMSATV_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
         END
    END

/*
  select first 1 tsp.bdrefemp from SP_CONSULTA_EMP_POR_REF(new.bdcodemp, new.bdrefemp) tsp
  into new.bdrefemp;

  delete from vef_base_tempitemsatv tatv
  where tatv.bdcodemp = new.bdcodemp
  and tatv.bdrefemp = new.bdrefemp;
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPAREST_BIO
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARESTES_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END

END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARESTMG_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARESTPR_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARESTRJ_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.BDCODEMP IS NULL) OR (NEW.BDCODEMP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODEMP)),1) FROM TEMPRESAS
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.BDCODEMP = vCodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODEMP FROM TEMPRESAS WHERE BDCODEMP = NEW.BDCODEMP INTO vCodigo;

       IF (vCodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODEMP)),1) FROM TEMPRESAS
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.BDCODEMP = vCodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARESTRO_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARESTSC_BIO
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARESTSP_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARFED_BIO
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARFEDPORATV_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
/*
  select first 1 BDREFEMP from SP_CONSULTA_EMP_POR_REF(new.bdcodemp, new.bdrefemp)
  into new.bdrefemp;

  delete from VEF_BASE_TEMPPARFEDPORATV tatv
  where tatv.bdcodemp = new.bdcodemp
  and tatv.bdrefemp = new.bdrefemp;
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARGER_BIO
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TEMPPARINTEG_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_BASE_TPLANOACOESTROCA_BI0
AS
  DECLARE VARIABLE wQtdeFil INTEGER;
BEGIN
  IF (NEW.BDQTDFILTRO IS NULL) THEN
    BEGIN
       wQtdeFil = 0;
       IF (NEW.BDTIPOLAN IS NOT NULL) THEN     -- Movimento
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDMODELO IS NOT NULL) THEN      -- Modelo
         wQtdeFil = wQtdeFil+1;
       IF ((NEW.BDESPECIE IS NOT NULL) AND (NEW.BDESPECIE <> '')) THEN -- Esp?cie
         wQtdeFil = wQtdeFil+1;
       IF ((NEW.BDSERIE IS NOT NULL) AND (NEW.BDSERIE <> '')) THEN     -- S?rie
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODNAT IS NOT NULL) THEN      -- CFOP
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODTER IS NOT NULL) THEN      -- Participante
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDNCMPROD IS NOT NULL) THEN     -- NBM-NCM/SH
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODPROD IS NOT NULL) THEN     -- Produto
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDVLRIGUALA IS NOT NULL) THEN   -- Valor igual a
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDVLRMENORQUE IS NOT NULL) THEN -- Menor que
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDVLRMAIORQUE IS NOT NULL) THEN -- Maior que
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDALIQICMSFIL IS NOT NULL) THEN -- Al?quota ICMS
         wQtdeFil = wQtdeFil+1;
       /* Entrada */
       IF (NEW.BDCODCSTICMSENTFIL IS NOT NULL) THEN -- CST ICMS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTIPIENTFIL IS NOT NULL) THEN  -- CST IPI
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTPISENTFIL IS NOT NULL) THEN  -- CST PIS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTCOFENTFIL IS NOT NULL) THEN  -- CST Cofins
         wQtdeFil = wQtdeFil+1;
       /* Sa?da */
       IF (NEW.BDCODCSTICMSSAIFIL IS NOT NULL) THEN -- CST ICMS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTIPISAIFIL IS NOT NULL) THEN  -- CST IPI
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTPISSAIFIL IS NOT NULL) THEN  -- CST PIS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTCOFSAIFIL IS NOT NULL) THEN  -- CST Cofins
         wQtdeFil = wQtdeFil+1;

       NEW.BDQTDFILTRO = wQtdeFil;
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_EMP_TCONSUB_BI0
AS
   DECLARE VARIABLE vCodigo INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
      BEGIN
        SELECT COALESCE(MAX(bdcodemp), 1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vCodigo;
      END

   IF ((NEW.bdcodconsub IS NULL) OR (NEW.bdcodconsub = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdcodconsub)+1),1) FROM vef_emp_tconsub WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
         NEW.bdcodconsub = vcodigo;
      END
   ELSE
      BEGIN
         SELECT bdcodconsub FROM vef_emp_tconsub WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodconsub = NEW.bdcodconsub) INTO vcodigo;

         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdcodconsub)+1),1) FROM vef_emp_tconsub WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
               NEW.bdcodconsub = vcodigo;
            END
      END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_EMP_TF1323A_DACON_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVEF1323ADACON IS NULL) OR (NEW.BDCHAVEF1323ADACON = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVEF1323ADACON)+1), 1) FROM VEF_EMP_TF1323A_DACON WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCHAVEF1323ADACON = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCHAVEF1323ADACON FROM VEF_EMP_TF1323A_DACON WHERE (BDCHAVEF1323ADACON = NEW.BDCHAVEF1323ADACON) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVEF1323ADACON)+1), 1) FROM VEF_EMP_TF1323A_DACON WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCHAVEF1323ADACON = vNova_Chave;
         END
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  --N?o est? buscando o c?digo do usu?rio, por isso esse c?digo ? setado na tela mesmo
  --select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
  --new.bdcodusu = vcodigo;
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_EMP_TMOVINV_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  IF ((NEW.bdcodtipo = 101) OR (NEW.bdcodtipo = 102)) THEN
     BEGIN
       vcodigo = 0;
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovinv WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
       ELSE
         BEGIN
           SELECT bdchave FROM vef_emp_tmovinv WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
    
           IF (vcodigo > 0) THEN
             BEGIN
               SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovinv WHERE bdcodemp = NEW.bdcodemp INTO vChave;
               NEW.bdchave = vChave;
             END
         END
     END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  -- s? atribui o usu?rio se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_EMP_TMOVOCO_GIASP_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;

  IF ((NEW.bdchaveocogiasp IS NULL) OR (NEW.bdchaveocogiasp = 0)) THEN
     BEGIN
        SELECT bdresult +1 FROM maxsci('bdchaveocogiasp', 'bdcodemp, bdchaveocogiasp', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTIPOOCOGIA = '||NEW.bdcodtipoocogia , 'VEF_EMP_TMOVOCO_GIASP') INTO vCodigo;
        NEW.bdchaveocogiasp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdchaveocogiasp FROM VEF_EMP_TMOVOCO_GIASP WHERE (bdchaveocogiasp = NEW.bdchaveocogiasp) AND (bdcodemp = NEW.bdcodemp) AND (bdcodtipoocogia = NEW.bdcodtipoocogia) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT bdresult +1 FROM maxsci('bdchaveocogiasp', 'bdcodemp, bdchaveocogiasp', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'bdcodtipoocogia = '||NEW.bdcodtipoocogia , 'VEF_EMP_TMOVOCO_GIASP') INTO vCodigo;
            NEW.bdchaveocogiasp = vcodigo;
         END
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  --N?o est? buscando o c?digo do usu?rio, por isso esse c?digo ? setado na tela mesmo
  --select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
  --new.bdcodusu = vcodigo;
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_EMP_TMOVOUTCREDCIAP_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCODOUTCREDCIAP IS NULL) OR (NEW.BDCODOUTCREDCIAP = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODOUTCREDCIAP)+1), 1) FROM VEF_EMP_TMOVOUTCREDCIAP WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCODOUTCREDCIAP = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCODOUTCREDCIAP FROM VEF_EMP_TMOVOUTCREDCIAP WHERE (BDCODOUTCREDCIAP = NEW.BDCODOUTCREDCIAP) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODOUTCREDCIAP)+1), 1) FROM VEF_EMP_TMOVOUTCREDCIAP WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCODOUTCREDCIAP = vNova_Chave;
         END
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  --N?o est? buscando o c?digo do usu?rio, por isso esse c?digo ? setado na tela mesmo
  --select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
  --new.bdcodusu = vcodigo;
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_EMP_TMOVSER_BU0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
  IF ((vcodigo <> 0 ) AND (vcodigo IS NOT NULL )) THEN
    NEW.bdcodusu = vcodigo;

  /* sol.: #9828 Jean 16/12/2014: SUBSERIE n?o pode mais ser NULL*/
  IF (NEW.BDSUBSERIE IS NULL) THEN
     NEW.BDSUBSERIE = '';

END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_EMP_TSALDOSN_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVESALDOSN IS NULL) OR (NEW.BDCHAVESALDOSN = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVESALDOSN)+1), 1) FROM vef_emp_tsaldosn WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCHAVESALDOSN = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCHAVESALDOSN FROM vef_emp_tsaldosn WHERE (BDCHAVESALDOSN = NEW.BDCHAVESALDOSN) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVESALDOSN)+1), 1) FROM vef_emp_tsaldosn WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCHAVESALDOSN = vNova_Chave;
         END
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  --N?o est? buscando o c?digo do usu?rio, por isso esse c?digo ? setado na tela mesmo
  --select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
  --new.bdcodusu = vcodigo;
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VEF_REINF_EVT_BU0
AS
  DECLARE VARIABLE wcodevt INTEGER;
BEGIN
  IF (OLD.bdcodtipo = 14 AND (OLD.BDCODSTATUS <> 3 AND NEW.bdcodstatus = 3)) THEN --Evento de exlus?o indo para o status de sucesso
    BEGIN
      wcodevt = 0;
      EXECUTE STATEMENT 'select bdcodevt from vef_reinf_evt where bdrecibo = ''' || OLD.bdparametros || '''' INTO :wcodevt;  --Parametro do R9000 ? o recibo do registro que deve ser removido
      IF (wcodevt > 0) THEN
        BEGIN                                                                                  
          UPDATE VEF_REINF_EVT SET BDCODRETIF = null WHERE (BDCODEMP = NEW.bdcodemp AND BDCODEVT = :wcodevt);
          DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.bdcodemp AND BDCODRETIF = :wcodevt;
          DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.bdcodemp AND BDCODEVT = :wcodevt;
        END
    END
   ELSE if ((OLD.bdcodstatus <> 3) AND (NEW.bdcodstatus = 3) AND (NEW.bdcodretif IS NOT NULL)) then
     BEGIN
       UPDATE VEF_REINF_EVT SET BDCODRETIF = NEW.BDCODEVT WHERE (BDCODEMP = NEW.bdcodemp AND BDCODRETIF = NEW.BDCODRETIF);
       update VEF_REINF_EVT SET BDCODSTATUS = 6, BDCODRETIF = NEW.BDCODEVT WHERE (BDCODEMP = NEW.bdcodemp AND BDCODEVT = NEW.bdcodretif);
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_BASE_TCLIENTE_AI0
AS
BEGIN
   /*Adilson Hasckel: sol. 15117 - 14/07/2016 - criar automaticamente os clientes fixos na configura??o de Online do Financeiro. */
  IF (NEW.bdcodtipocli <> 3) THEN
    EXECUTE PROCEDURE VFIN_INSERT_CLIENTE_ONLINE (NEW.bdcodcli);

   /*Sol: 18296 Morgana. 26/04/2017. Gerar uma situa??o financeira (ativo) ao inserir um cliente.*/
  INSERT INTO VFIN_BASE_TSITCLIENTE (bdcodcli, bdchavesitcli, bdcodsitcli, bddatasitcli)
         VALUES (NEW.bdcodcli, 1, 2, CURRENT_DATE);
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_BASE_TCLIENTE_AU0
AS
BEGIN
 /*Adilson Hasckel: sol. 15117 - 14/07/2016 - criar automaticamente os clientes fixos na configura??o de Online do Financeiro. */
  IF (OLD.bdcodtipocli = 3 AND NEW.bdcodtipocli <> 3) THEN
    EXECUTE PROCEDURE VFIN_INSERT_CLIENTE_ONLINE (NEW.bdcodcli);
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_BASE_TCLIENTE_BD0
AS
BEGIN
  /*excluir tabelas que possuem v?nculos quer n?o s?o CASCADE*/
  DELETE FROM VFIN_ESC_TFATURA WHERE bdcodcli = OLD.bdcodcli;
  DELETE FROM vfin_esc_tcabservicofixo WHERE bdcodcli = OLD.bdcodcli;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_BASE_TCLIENTE_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCodCli INTEGER;
  DECLARE VARIABLE vCodEmp INTEGER;
  DECLARE VARIABLE vControle INTEGER;
  DECLARE VARIABLE vControleCliente INTEGER;
  DECLARE VARIABLE vCNPJEmp VARCHAR(18);
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodcli IS NULL) OR (NEW.bdcodcli = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcli)+1),1) FROM vfin_base_tcliente INTO vcodigo;
        /*se ? registro novo e vier zerado ou nulo, o novo c?digo n?o pode existir no cadastro da empresa, j? que os c?digos devem ser coincidentes,
         se n?o tratar ficar? cliente e empresa diferentes com o mesmo c?digo*/
        vCodEmp = 0;
        vControle = 1;
        WHILE (vControle = 1) DO
          BEGIN
            vCodEmp = 0;
            SELECT COALESCE(bdcodemp, 0) FROM tempresas WHERE bdcodemp = :vcodigo INTO vCodEmp;
            IF (vCodEmp = 0) THEN
               BEGIN
                 NEW.bdcodcli = vcodigo;
                 vControle = 2;
               END
             vcodigo = :vCodigo + 1;
          END
        IF (vControle = 1) THEN
          NEW.bdcodcli = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcli)+1),1) FROM vfin_base_tcliente INTO vcodigo;
            /*O novo c?digo n?o pode existir no cadastro da empresa, j? que os c?digos devem ser coincidentes,
            se n?o tratar ficar? cliente e empresa diferentes com o mesmo c?digo*/
            vCodEmp = 0;
            vControle = 1;
            WHILE (vControle = 1) DO
              BEGIN
                vCodEmp = 0;
                SELECT COALESCE(bdcodemp, 0) FROM tempresas WHERE bdcodemp = :vcodigo INTO vCodEmp;
                IF (vCodEmp = 0) THEN
                   BEGIN
                     NEW.bdcodcli = vcodigo;
                     vControle = 2;
                   END
                vcodigo = :vCodigo + 1;
              END
             IF (vControle = 1) THEN
               NEW.bdcodcli = vcodigo;
         END
      ELSE
         BEGIN
           /*n?o existe o c?digo no cliente, por?m verificar na empresa se existe, j? que devem ser coincidentes */
           vCodEmp = 0;
           vControle = 1;
           vCodigo = NEW.bdcodcli;
           WHILE (vControle = 1) DO
              BEGIN
                vCodEmp = 0;
                SELECT COALESCE(bdcodemp, 0), bdCNPJEMP FROM tempresas WHERE bdcodemp = :vcodigo INTO vCodEmp, vCNPJEmp;
                /*c?digo n?o existe no cliente e tamb?m n?o existe na empresa*/
                IF (vCodEmp = 0) THEN
                   BEGIN
                     NEW.bdcodcli = vcodigo;
                     --vControle = 2;
                     BREAK;
                   END
                ELSE
                /*c?digo n?o existe no cliente, por?m existe na empresa. Verifcar se for o mesmo CNPJ manter a numera??o*/
                IF (vCNPJEmp = NEW.bdcnpjcli) THEN
                   BREAK;
                ELSE
                   vControleCliente = 1;
                   WHILE (vControleCliente = 1) DO
                     BEGIN
                       vcodigo = :vCodigo + 1;
                       vCodCli = 0;
                       SELECT COALESCE(bdcodcli, 0) FROM vfin_base_tcliente WHERE bdcodcli = :vCodigo INTO vcodcli;
                       IF (vCodCli = 0)  THEN
                          BREAK;
                     END
              END
         END
    END
   /*Adilson Hasckel: sol. 14103 em 15/04/2016 - buscar corretamente o c?digo do cliente que foi lan?ado. Pode ocorrer de ser digitado um c?digo para inser??o
    por?m j? existe na empresa e ent?o ? inserido outro c?digo*/
    rdb$set_context('USER_SESSION', 'W_CodCli_Atual', NEW.bdcodcli);
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_BASE_TESCPARFAT_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vRefAtual INTEGER;
  DECLARE VARIABLE vFormaTributacao INTEGER;
  DECLARE VARIABLE vCODEMP INTEGER;
BEGIN
  vFormaTributacao = 0;
  /* somente na inser??o */
  IF (OLD.bdcodesc IS NULL) THEN
     BEGIN
      vcodigo = 0;
      IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
      ELSE
        BEGIN
           SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;
    
           IF (vcodigo = 0) THEN
             BEGIN
                SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
                NEW.bdcodesc = vcodigo;
             END
        END
     END

  /*Atualizar empresa por refer?ncia - deve-se criar registros em todas tabelas por refer?ncia????, comentado por enquanto*/
  /*criar atualizar dados referente ao enqudramento federal na tabela de empresa que representa o gestor*/
  vCodigo = 0;
  SELECT BDCODEMPINTEG FROM tescritorio
  WHERE BDCODESC = NEW.BDCODESC INTO vCodigo;
  IF (vCodigo > 0) THEN
    BEGIN
      vRefAtual = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database);
      IF (vRefAtual IS NULL) THEN
         vRefAtual = SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2);


      SELECT BDCODEMP FROM TEMPRESAS_REF WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
      INTO :vCODEMP;

      IF (:vcodemp IS  NULL) THEN --pegar a ?ltima refer?ncia lan?ada
        BEGIN
         SELECT MAX(BDREFEMP) FROM TEMPRESAS_REF WHERE BDCODEMP = :vCodigo
         INTO :vRefAtual;
        END

          --TENQFED
        IF (NEW.bdcodenqfed <> 3) THEN
           vformatributacao = 0;


        vCODEMP = 0;
        SELECT BDCODEMP FROM TEMPRESAS_REF WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
        INTO :vCODEMP;

        IF (:vcodemp > 0) THEN
           BEGIN
             --inser??o
             IF (OLD.bdcodesc IS NULL) THEN
                BEGIN
                  DELETE FROM TENQFED WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
                END
             ELSE
                BEGIN
                  SELECT BDFORMATRIBUTACAO FROM TENQFED WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual INTO vFormaTributacao;
                  DELETE FROM TENQFED WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
                END

              UPDATE OR INSERT INTO TENQFED (BDCODENQFED, BDCODEMP, BDREFEMP, BDFORMATRIBUTACAO)
              VALUES(NEW.bdcodenqfed, :vcodigo, :vrefatual, :vformatributacao) MATCHING (BDCODENQFED, BDCODEMP, BDREFEMP);
            
              --VEF_BASE_TEMPCADATV e VEF_BASE_TEMPPARFEDPORATV
              --retirado update or insert, pois gerava erros ao salvar empresa que tinha gestor associado
              IF ((UPPER(NEW.BDANEXOIII) = 'TRUE') OR (UPPER(NEW.BDANEXOIV) = 'TRUE') OR (UPPER(NEW.BDANEXOV) = 'TRUE') OR (UPPER(NEW.BDANEXOVI) = 'TRUE')) THEN
                 BEGIN
                   vcodemp = 0;
                   SELECT BDCODEMP FROM VEF_BASE_TEMPCADATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
                   INTO :vCODEMP;

                   IF (:vCodEmp > 0) THEN
                      BEGIN
                        --exception ex_date vCodEmp||' U '||vRefAtual;
                        UPDATE VEF_BASE_TEMPCADATV SET BDSERVICO = 'TRUE' WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
                      END
                   ELSE
                      BEGIN
                        --exception ex_date vCodEmp||' I '||vRefAtual;
                        INSERT INTO VEF_BASE_TEMPCADATV (BDCODEMP, BDREFEMP, BDSERVICO) VALUES (:vCodigo, :vrefatual, 'TRUE');
                      END

                   vcodemp = 0;
                   SELECT BDCODEMP FROM VEF_BASE_TEMPPARFEDPORATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
                   INTO :vCODEMP;

                   IF (:vCodEmp > 0) THEN
                      UPDATE VEF_BASE_TEMPPARFEDPORATV SET BDSERVICO = 'TRUE' WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
                   ELSE
                      INSERT INTO VEF_BASE_TEMPPARFEDPORATV (BDCODEMP, BDREFEMP, BDSERVICO, BDCOMERCIO, BDINDUSTRIA, BDLRISSSN) VALUES (:vCodigo, :vrefatual, 'TRUE', 'FALSE', 'FALSE', 0);

                   --update or insert into VEF_BASE_TEMPCADATV(BDCODEMP, BDREFEMP, BDSERVICO)
                   --values (:vCodigo, :vrefatual, 'TRUE') matching (BDCODEMP, BDREFEMP);

                   --update or insert into VEF_BASE_TEMPPARFEDPORATV(BDCODEMP, BDREFEMP, BDSERVICO)
                   --values (:vCodigo, :vrefatual, 'TRUE') matching (BDCODEMP, BDREFEMP);
                 END
              ELSE
                 BEGIN
                   vcodemp = 0;
                   SELECT BDCODEMP FROM VEF_BASE_TEMPCADATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
                   INTO :vCODEMP;

                   IF (:vCodEmp > 0) THEN
                      UPDATE VEF_BASE_TEMPCADATV SET BDCOMERCIO = 'FALSE', BDINDUSTRIA = 'FALSE', BDSERVICO = 'FALSE' WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
                   ELSE
                      INSERT INTO VEF_BASE_TEMPCADATV (BDCODEMP, BDREFEMP, BDCOMERCIO, BDINDUSTRIA, BDSERVICO) VALUES (:vCodigo, :vrefatual, 'FALSE', 'FALSE', 'FALSE');


                   vcodemp = 0;
                   SELECT BDCODEMP FROM VEF_BASE_TEMPPARFEDPORATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
                   INTO :vCODEMP;

                   IF (:vCodEmp > 0) THEN
                      UPDATE VEF_BASE_TEMPPARFEDPORATV SET BDCOMERCIO = 'FALSE', BDINDUSTRIA = 'FALSE', BDSERVICO = 'FALSE' WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
                   ELSE
                      INSERT INTO VEF_BASE_TEMPPARFEDPORATV (BDCODEMP, BDREFEMP, BDCOMERCIO, BDINDUSTRIA, BDSERVICO, BDLRISSSN) VALUES (:vCodigo, :vrefatual, 'FALSE', 'FALSE', 'FALSE', 0);

                   --update or insert into VEF_BASE_TEMPCADATV(BDCODEMP, BDREFEMP, BDCOMERCIO, BDINDUSTRIA, BDSERVICO)
                   --values (:vCodigo, :vrefatual, 'FALSE', 'FALSE', 'FALSE') matching (BDCODEMP, BDREFEMP);

                   --update or insert into VEF_BASE_TEMPPARFEDPORATV(BDCODEMP, BDREFEMP, BDCOMERCIO, BDINDUSTRIA, BDSERVICO)
                   --values(:vCodigo, :vRefAtual, 'FALSE', 'FALSE', 'FALSE') matching (BDCODEMP, BDREFEMP);
                 END
            

              vcodemp = 0;
              SELECT BDCODEMP FROM VEF_BASE_TEMPITEMSATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
              INTO :vCODEMP;

              IF (:vCodEmp > 0) THEN
                 UPDATE VEF_BASE_TEMPITEMSATV SET
                 BDANEXOIII_2018 = NEW.BDANEXOIII,
                 BDANEXOIV_2018 = NEW.BDANEXOIV,
                 BDANEXOV_2018 = NEW.bdanexov
                 WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
              ELSE
                 INSERT INTO VEF_BASE_TEMPITEMSATV (BDCODEMP, BDREFEMP, BDANEXOIII_2018, BDANEXOIV_2018, BDANEXOV_2018)
                 VALUES (:vCodigo, :vrefatual, NEW.BDANEXOIII, NEW.BDANEXOIV, NEW.BDANEXOV);
              --VEF_BASE_TEMPITEMSATV
              --update or insert into VEF_BASE_TEMPITEMSATV(BDCODEMP, BDREFEMP, BDANEXOIII, BDANEXOIV, BDANEXOV, BDANEXOVI)
              --values(:vcodigo, :vrefatual, new.BDANEXOIII, new.BDANEXOIV, new.BDANEXOV, new.BDANEXOVI) matching (BDCODEMP, BDREFEMP);
          END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TBAIXARAPIDAFATURA_AD0
AS
BEGIN
  /*ao excluir um item de baixa r?pida da fatura (quando n?o vier por exclus?o por cascade da tabela master VFIN_ESC_TBAIXARAPIDA)
   atualizar o valor ba baixa r?pida na tabela de baixa r?pida que ? por gestor...
  */
  UPDATE vfin_esc_tbaixarapida
  SET BDVALORBAIRAP = COALESCE(BDVALORBAIRAP, 0) - COALESCE(OLD.bdvalrec, 0)
  WHERE BDCODESC = OLD.bdcodesc AND
        BDCODBAIRAP = OLD.bdcodbairap;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TCONTASBAN_AI0
AS
BEGIN
 /*Adilson Hasckel: sol. 14543 - 19/05/2016 - criar automaticamente as contas banc?rias na configura??o de Online do Financeiro. */
  EXECUTE PROCEDURE vfin_insert_contaban_online(NEW.bdchavectaban);
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TCONTASPAGARDESP_AIUD0
AS
  DECLARE VARIABLE vVALORTOTALDESP DM_NUMERIC_15_2;
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchavectapag INTEGER;
BEGIN
  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchavectapag IS NULL) THEN
     vchavectapag = OLD.bdchavectapag;
  ELSE
     vchavectapag = NEW.bdchavectapag;

  SELECT SUM(COALESCE(BDVALORDESP, 0)) FROM vfin_esc_tcontaspagardesp
  WHERE (bdcodesc = :vcodesc) AND (bdchavectapag = :vchavectapag)
  INTO vVALORTOTALDESP;

  UPDATE VFIN_ESC_TCONTASAPAGAR SET BDVALORTOTALDESP = :vVALORTOTALDESP
  WHERE (bdcodesc = :vcodesc) AND (bdchavectapag = :vchavectapag);

  -- Sol: 19751 Morgana. 21/08/2017. Excluir o lan?amento caso n?o possua mais despesas.
  DELETE FROM VFIN_ESC_TCONTASAPAGAR lan
  WHERE lan.bdcodesc = OLD.bdcodesc
  AND lan.bdchavectapag = OLD.bdchavectapag
  AND NOT EXISTS
    (
      SELECT desp.bdordemdesp FROM VFIN_ESC_TCONTASPAGARDESP desp
      WHERE desp.bdcodesc = lan.bdcodesc
      AND desp.bdchavectapag = lan.bdchavectapag
    );
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TCONTASPAGARDESP_BD0
AS
  DECLARE VARIABLE vCodCli INTEGER;
  DECLARE VARIABLE vChaveSerFix INTEGER;
  DECLARE VARIABLE vOrdemSerFix INTEGER;
BEGIN
  SELECT BDCODCLI, BDCHAVESERFIX, BDORDEMSERFIX FROM VFIN_ESC_TVINC_PAG_SERVIC
  WHERE BDCODESC = OLD.bdcodesc AND
        BDCHAVECTAPAG = OLD.BDCHAVECTAPAG AND
        BDORDEMDESP = OLD.bdordemdesp
  INTO :vcodcli, :vchaveserfix, :vordemserfix;
  IF (vCodCli > 0) THEN
     BEGIN
       DELETE FROM vfin_esc_tservicofixo ser
       WHERE ser.bdcodesc = OLD.bdcodesc AND
             ser.bdcodcli = :vCodCli AND
             ser.bdchaveserfix = :vChaveSerFix AND
             ser.bdordemserfix = :vOrdemSerFix;

      /*excluir cabe?alho do servi?o para faturamento se ficar vazio*/
      DELETE FROM vfin_esc_tcabservicofixo cab
      WHERE
      bdcodcli = :vCodCli AND
      bdcodesc = OLD.bdcodesc AND
      bdchaveserfix = :vChaveSerFix AND
      NOT EXISTS
        (
          SELECT bdordemserfix FROM vfin_esc_tservicofixo ser
          WHERE ser.bdcodcli = cab.bdcodcli AND
                ser.bdcodesc = cab.bdcodesc AND
                ser.bdchaveserfix = cab.bdchaveserfix
        );
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TCONTASPAGDESPOBS_BI0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavectapag INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavectapag)), 1) FROM vfin_esc_tcontasapagar
      WHERE (bdcodesc = NEW.bdcodesc) INTO vchavectapag;
      NEW.bdchavectapag = vchavectapag;
    END

   /*se for informado uma ordem que n?o existe, buscar nova ordem*/
   SELECT BDORDEMDESP FROM VFIN_ESC_TCONTASPAGARDESP
   WHERE (BDCODESC = NEW.BDCODESC) AND (bdchavectapag = NEW.bdchavectapag) AND (bdordemdesp = NEW.bdordemdesp) INTO vordem;

   IF (vordem IS NULL) THEN
      BEGIN
        /*selecionar a ?ltima ordem do servi?o fixo vinculado, */
        SELECT COALESCE((MAX(BDORDEMDESP)), 1) FROM VFIN_ESC_TCONTASPAGARDESP
        WHERE (BDCODESC = NEW.BDCODESC) AND (bdchavectapag = NEW.bdchavectapag) INTO vNova_Ordem;
        NEW.bdordemdesp = vNova_ordem;
      END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TCONTRATO_AU0
AS
  DECLARE VARIABLE vnewbddatafin INTEGER;
  DECLARE VARIABLE voldbddatafin INTEGER;
BEGIN
   /* Sol: 18826 Morgana. 30/06/2017. Comentado implementa??o abaixo pois ao alterar a data final do contrato
   n?o dever? mais atualizar a refer?ncia final de todos os servi?os fixos. Codifica??o feita na aplica??o.*/

   /*if (new.bddatafin is null) then
      vnewbddatafin = 0;
   else
     vnewbddatafin = cast((select bdaaaamm FROM aaaamm(new.bddatafin)) as integer);

   if (old.bddatafin is null) then
      voldbddatafin = 0;
   else
     voldbddatafin = cast((select bdaaaamm FROM aaaamm(old.bddatafin)) as integer);

   if (vnewbddatafin <> voldbddatafin) then
      begin
       update vfin_esc_tservicofixo set bdreffin = :vnewbddatafin
       where (bdcodcli = new.bdcodcli) and
             (bdcodesc = new.bdcodesc) and
             (bdcodcontr = new.bdcodcontr);
     end*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TFATURA_AD0
AS
  DECLARE VARIABLE vCodEsc INTEGER;
  DECLARE VARIABLE vChaveRPS INTEGER;
BEGIN
  /*Adilson Hasckel- Controle de exclus?o de RPS emitido vinculados aos servi?os da fatura exclu?da!!!!*/
  FOR
    SELECT BDCODESC, BDCHAVERPS FROM vfin_esc_trpsemitido rps
      WHERE (bdcodesc = OLD.bdcodesc) AND (bdchaverps IN
        (
          SELECT bdchaverps FROM vfin_esc_tservicofaturado
          WHERE (bdcodesc = OLD.bdcodesc) AND (bdcodcli = OLD.bdcodcli) AND
            (bdchavefatura = OLD.bdchavefatura) AND (bdchaverps > 0) AND (bdchaverps = rps.bdchaverps)
        )
      )
  INTO :vCodEsc, :vChaveRPS DO
   BEGIN
      UPDATE vfin_esc_tservicofaturado SET BDCHAVERPS = NULL
      WHERE BDCODESC = OLD.bdcodesc AND
            BDCODCLI = OLD.bdcodcli AND
            BDCHAVEFATURA = OLD.bdchavefatura AND BDCHAVERPS = :vchaverps;

      DELETE FROM vfin_esc_trpsemitido WHERE BDCODESC = :vcodesc AND BDCHAVERPS = :vchaverps;
   END

   IF (OLD.bdnossonum <> '') THEN
     BEGIN
       INSERT INTO vfin_esc_tfaturadel (bdchave, bdcodesc, bdcodcli, bdreffat, bdserie,
                                        bdnossonum, bddatavenc, bdvalorfatura, bdchavectaban)
                                VALUES (NULL, OLD.bdcodesc, OLD.bdcodcli, OLD.bdreffat, OLD.bdserie,
                                        OLD.bdnossonum, OLD.bddatavenc, OLD.bdvalorfatura, OLD.bdchavectaban);
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TPAGAMENTOSOBS_BI0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavectapag INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavectapag)), 1) FROM vfin_esc_tcontasapagar
      WHERE (bdcodesc = NEW.bdcodesc) INTO vchavectapag;
      NEW.bdchavectapag = vchavectapag;
    END

   /*se for informado uma ordem que n?o existe, buscar nova ordem*/
   SELECT BDORDEMPAG FROM vfin_esc_tpagamentos
   WHERE (BDCODESC = NEW.BDCODESC) AND (bdchavectapag = NEW.bdchavectapag) AND (bdordempag = NEW.bdordempag) INTO vordem;

   IF (vordem IS NULL) THEN
      BEGIN
        /*selecionar a ?ltima ordem do servi?o fixo vinculado, */
        SELECT COALESCE((MAX(BDORDEMPAG)), 1) FROM vfin_esc_tpagamentos
        WHERE (BDCODESC = NEW.BDCODESC) AND (bdchavectapag = NEW.bdchavectapag) INTO vNova_Ordem;
        NEW.bdordempag = vnova_ordem;
      END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TRECANTECIP_DEST_BIUD0
AS
BEGIN
 --controle saldo recebimento antecipado - exclus?o/inser??o e edi??om foi passado para VFIN_ESC_TRECANTECIP_DEST
 IF (NEW.bdcodcli IS NULL) THEN --exclus?o
    BEGIN
       IF (OLD.bdchaverecant > 0) THEN --ao excluir recebimento da fatura que tenha sido beneficiado por recebimento antecipado repor o valor utilizado no saldo
          BEGIN
            UPDATE VFIN_ESC_TRECANTECIPADO
            SET bdsaldorecant = COALESCE(bdsaldorecant, 0) + OLD.bdvalrecdest
            WHERE
            BDCODESC = OLD.bdcodesc AND
            BDCODCLI = OLD.bdcodcli AND
            BDCHAVERECANT = OLD.bdchaverecant;
          END
    END
 ELSE
 IF (NEW.bdchaverecant > 0) THEN --controle saldo
    BEGIN
      IF (OLD.bdvalrecdest IS NULL) THEN --inser??o
         BEGIN
           UPDATE VFIN_ESC_TRECANTECIPADO
           SET bdsaldorecant = COALESCE(bdsaldorecant, 0) - NEW.bdvalrecdest
           WHERE
           BDCODESC = NEW.bdcodesc AND
           BDCODCLI = NEW.bdcodcli AND
           BDCHAVERECANT = NEW.bdchaverecant;
         END
      ELSE
         BEGIN -- edi??o
           UPDATE VFIN_ESC_TRECANTECIPADO
           SET bdsaldorecant = COALESCE(bdsaldorecant, 0) - OLD.bdvalrecdest + NEW.bdvalrecdest
           WHERE
           BDCODESC = NEW.bdcodesc AND
           BDCODCLI = NEW.bdcodcli AND
           BDCHAVERECANT = NEW.bdchaverecant;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TRECFATURA_AIUD0
AS
  DECLARE VARIABLE vcodcli INTEGER;
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchavefatura INTEGER;
  DECLARE VARIABLE vTotRec NUMERIC(15,2);
  --declare variable vTotJur numeric(15,2);
  -- declare variable vTotDesc numeric(15,2);
  --declare variable vTotMul numeric(15, 2);
  DECLARE VARIABLE vTotGer NUMERIC(15, 2);
BEGIN
  IF (NEW.bdcodcli IS NULL) THEN
     vcodcli = OLD.bdcodcli;
  ELSE
     vcodcli = NEW.bdcodcli;

  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchavefatura IS NULL) THEN
     vchavefatura = OLD.bdchavefatura;
  ELSE
     vchavefatura = NEW.bdchavefatura;

  --os totais de multa e juros da tabela de faturas devem ser atualizados ao serem criados os servi?os de multa/juros/desconto
  SELECT SUM(COALESCE(BDVALREC, 0)),
         --sum(coalesce(BDJURREC, 0)),
         --sum(coalesce(BDMULTAREC, 0)),
         --sum(coalesce(BDDESCREC, 0)),
         SUM(COALESCE(BDVALREC, 0) + COALESCE(BDJURREC, 0) + COALESCE(BDMULTAREC, 0) - COALESCE(BDDESCREC, 0))
         FROM vfin_esc_trecebimentofatura
         WHERE (bdcodcli = :vcodcli) AND
               (bdcodesc = :vcodesc) AND
               (bdchavefatura = :vchavefatura)
  --into vTotRec, vtotjur, vtotmul, vTotDesc, vtotger;
  INTO vTotRec, vtotger;

  --atualizar totais da fatura
  UPDATE vfin_esc_tFatura
  SET BDTOTREC  = :vtotrec,
      /*BDTOTJUR  = :vtotjur,
      BDTOTMUL  = :vtotmul,
      BDTOTDESC = :vtotdesc,*/
      BDTOTGER = :vtotger,
      --BDTOTPENDENTE = (case when BDVALORFATURA - coalesce(:vtotrec, 0) > 0 then BDVALORFATURA - coalesce(:vtotrec, 0) else 0 end)
      BDTOTPENDENTE = (CASE WHEN (BDVALORFATURA + COALESCE(BDTOTMUL, 0) + COALESCE(BDTOTJUR, 0) - COALESCE(BDTOTDESC, 0)) - COALESCE(:vtotger, 0) > 0 THEN
                                (BDVALORFATURA + COALESCE(BDTOTMUL, 0) + COALESCE(BDTOTJUR, 0) - COALESCE(BDTOTDESC, 0)) - COALESCE(:vtotger, 0) ELSE 0 END)
  WHERE (bdcodcli = :vcodcli) AND
        (bdcodesc = :vcodesc) AND
        (bdchavefatura = :vchavefatura);


  IF (NEW.bdcodcli IS NULL) THEN --exclus?o
     BEGIN
       --Adilson Hasckel - sol. 15757 - exclus?o de recebimentos antecipados
       IF (OLD.bdchaverecant > 0) THEN
          BEGIN
            --excluir recebimento de faturas que foram beneficiadas pelo recebimento antecipado gerado a partir do recebimento que est? sendo exclu?do
            DELETE FROM vfin_esc_trecebimentofatura rec
            WHERE BDCODESC = :vcodesc AND
                  BDCODCLI = :vcodcli AND
            EXISTS
                ( SELECT BDCHAVERECANT FROM vfin_esc_trecantecip_dest
                  WHERE BDCODESC = :vCodEsc AND
                        BDCODCLI = :vCodCli AND
                        BDCHAVEFATURA = rec.bdchavefatura AND
                        BDORDEMREC = rec.bdordemrec AND
                        BDCHAVERECANT = OLD.BDCHAVERECANT
                );

            --excluir recebimento antecipado que foi gerado a partir do recebimento a maior (v?nculo com o recebimento que est? sendo exclu?do)
            DELETE FROM vfin_esc_trecantecipado
            WHERE BDCODESC = :vCodEsc AND
                  BDCODCLI = :vcodcli AND
                  BDCHAVERECANT = OLD.bdchaverecant;
          END
     END

 --controle saldo recebimento antecipado - exclus?o/inser??o e edi??om foi passado para VFIN_ESC_TRECANTECIP_DEST
 /*
 if (new.bdcodcli is null) then --exclus?o
    begin
       if (old.bdchaverecantdest > 0) then --ao excluir recebimento da fatura que tenha sido beneficiado por recebimento antecipado repor o valor utilizado no saldo
          begin
            update VFIN_ESC_TRECANTECIPADO
            set bdsaldorecant = coalesce(bdsaldorecant, 0) + old.bdvalrec
            where
            BDCODESC = old.bdcodesc and
            BDCODCLI = old.bdcodcli and
            BDCHAVERECANT = old.bdchaverecantdest;
          end
    end
 else
 if (new.bdchaverecantdest > 0) then --controle saldo
    begin
      if (old.bdvalrec is null) then --inser??o
         begin
           update VFIN_ESC_TRECANTECIPADO
           set bdsaldorecant = coalesce(bdsaldorecant, 0) - new.bdvalrec
           where
           BDCODESC = new.bdcodesc and
           BDCODCLI = new.bdcodcli and
           BDCHAVERECANT = new.bdchaverecantdest;
         end
      else
         begin -- edi??o
           update VFIN_ESC_TRECANTECIPADO
           set bdsaldorecant = coalesce(bdsaldorecant, 0) - old.bdvalrec + new.bdvalrec
           where
           BDCODESC = new.bdcodesc and
           BDCODCLI = new.bdcodcli and
           BDCHAVERECANT = new.bdchaverecantdest;
         end
    end
 */
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TSERVICOFIXO_AIU0
AS
  DECLARE VARIABLE vvalortotserfix NUMERIC(15,4);
  DECLARE VARIABLE vcodcli INTEGER;
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchaveserfix INTEGER;
BEGIN
  IF (NEW.bdcodcli IS NULL) THEN
     vcodcli = OLD.bdcodcli;
  ELSE
     vcodcli = NEW.bdcodcli;

  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchaveserfix IS NULL) THEN
     vchaveserfix = OLD.bdchaveserfix;
  ELSE
     vchaveserfix = NEW.bdchaveserfix;

  /*if (old.bdcodcli is not null) then
     vcodcli = old.bdcodcli;
  else
     vcodcli = new.bdcodcli;

  if (old.bdcodesc is not null) then
     vcodesc = old.bdcodesc;
  else
     vcodesc = new.bdcodesc;

  if (old.bdcodcontr is not null) then
     vcodcontr = old.bdcodcontr;
  else
     vcodcontr = new.bdcodcontr;

  if (old.bdchaveserfix is not null) then
     vchaveserfix = old.bdchaveserfix;
  else
     vchaveserfix = new.bdchaveserfix;*/


  /*select sum(coalesce(BDVLRTOTSERFIX, 0)) from VFIN_ESC_TSERVICOFIXO
  where (bdcodcli = :vcodcli) and (bdcodesc = :vcodesc) and (bdcodcontr = :vcodcontr) and (bdchaveserfix = :vchaveserfix)
  into vVALORTOTSERFIX;*/

  SELECT SUM(CASE WHEN (UPPER(ser.bddesconto) = 'TRUE') THEN COALESCE(BDVLRTOTSERFIX, 0) * -1 ELSE COALESCE(BDVLRTOTSERFIX, 0) END)
  FROM VFIN_ESC_TSERVICOFIXO serfix
  JOIN vct_base_servico ser ON ser.bdcodobrser = serfix.bdcodobrser
  WHERE (bdcodcli = :vcodcli) AND (bdcodesc = :vcodesc) AND (bdchaveserfix = :vchaveserfix)
  INTO vVALORTOTSERFIX;

  UPDATE vfin_esc_tcabservicofixo SET BDVALORTOTSERFIX = :vVALORTOTSERFIX
  WHERE (bdcodcli = :vcodcli) AND (bdcodesc = :vcodesc) AND (bdchaveserfix = :vchaveserfix);


  --somente na exclus?o de acordo, decorrente do cascade em BDCHAVEACOR, excluir cabe?alho caso n?o tenha mais servi?os fixos
  IF ((OLD.bdcodesc IS NOT NULL) AND (NEW.bdcodesc IS NULL)) THEN
    BEGIN
      IF (OLD.bdchaveacor IS NOT NULL) THEN
         BEGIN
      DELETE FROM vfin_esc_tcabservicofixo cab
      WHERE
      bdcodcli = OLD.bdcodcli AND
      bdcodesc = OLD.bdcodesc AND
      bdchaveserfix = OLD.bdchaveserfix AND
      NOT EXISTS
        (
           SELECT bdordemserfix FROM vfin_esc_tservicofixo ser
           WHERE ser.bdcodcli = cab.bdcodcli AND
                 ser.bdcodesc = cab.bdcodesc AND
                 ser.bdchaveserfix = cab.bdchaveserfix
        );
    END


      -- Excluir lan?amento geral caso n?o tenha mais servi?os fixos vinculados. Morgana.
      IF (OLD.bdchaveger IS NOT NULL) THEN
         BEGIN
           DELETE FROM VFIN_ESC_TSERVICOFIXOGER ger
           WHERE ger.bdchaveger = OLD.bdchaveger AND
           NOT EXISTS (
                       SELECT * FROM vfin_esc_tservicofixo ser
                       WHERE ser.bdchaveger = OLD.bdchaveger
                       );

       -- Sol: 23103 Morgana. 17/05/2018. Excluir o cabe?alho caso n?o tenha mais servi?os vinculados.
           DELETE FROM vfin_esc_tcabservicofixo cab
           WHERE
           bdcodcli = OLD.bdcodcli AND
           bdcodesc = OLD.bdcodesc AND
           bdchaveserfix = OLD.bdchaveserfix AND
           NOT EXISTS
             (
                SELECT bdordemserfix FROM vfin_esc_tservicofixo ser
                WHERE ser.bdcodcli = cab.bdcodcli AND
                      ser.bdcodesc = cab.bdcodesc AND
                      ser.bdchaveserfix = cab.bdchaveserfix
             );
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TSERVICOFIXOGER_BI0
AS
  DECLARE VARIABLE vcodusu INTEGER;
BEGIN
  -- GRAVA OS CAMPOS AUTOMATICO SE N?O TIVER SIDO INFORMADO VALORES--
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodusu;
      NEW.bdcodusu = vcodusu;
    END
  IF (NEW.bddatager IS NULL) THEN
     NEW.bddatager = CURRENT_DATE;
  IF (NEW.bdhorager IS NULL) THEN
     NEW.bdhorager = CURRENT_TIME;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VFIN_ESC_TSERVICOFIXOOBS_BI0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchaveserfix INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchaveserfix IS NULL) OR (NEW.bdchaveserfix = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchaveserfix)), 1) FROM vfin_esc_tcabservicofixo
      WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli)
      INTO vchaveserfix;
      NEW.bdchaveserfix = vchaveserfix;
    END

   /*se for informado uma ordem que n?o existe no seri?o fixo (tela), buscar nova ordem*/
   SELECT BDORDEMSERFIX FROM vfin_esc_tservicofixo
   WHERE (BDCODESC = NEW.BDCODESC) AND (BDCODCLI = NEW.bdcodcli) AND (bdchaveserfix = NEW.bdchaveserfix) AND (bdordemserfix = NEW.bdordemserfix) INTO vordem;

   IF (vordem IS NULL) THEN
      BEGIN
        /*selecionar a ?ltima ordem do servi?o fixo vinculado, */
        SELECT COALESCE((MAX(BDORDEMSERFIX)), 1) FROM vfin_esc_tservicofixo
        WHERE (BDCODESC = NEW.BDCODESC) AND (BDCODCLI = NEW.bdcodcli) AND (bdchaveserfix = NEW.bdchaveserfix) INTO vNova_Ordem;
        NEW.bdordemserfix = vNova_ordem;
      END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VLAL_IMP_CONTABLALUR_BD0
AS
BEGIN
  IF (OLD.bdtipo = 0) THEN -- Lucro Real (A parte do lucro presumido existe a chave de liga??o com o cascade habilitado)
     BEGIN
       DELETE FROM VLAL_EMPRESAS_TLLA WHERE BDCODEMP = OLD.BDCODEMP AND BDTIPLAN = 400 AND
              EXTRACT(YEAR FROM BDDATLLA)||LPAD(EXTRACT(MONTH FROM BDDATLLA), 2, '0') BETWEEN OLD.BDREFINICIAL AND OLD.BDREFFINAL;
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_BASE_TEMPVINC_BIO
AS
  DECLARE VARIABLE vCodigo INTEGER;
 -- DECLARE VARIABLE vcodemp INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo IS NULL OR (vcodigo = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END

 /*vcodemp = NULL;
  SELECT FIRST 1 BDCODEMP FROM VRHF_BASE_TVERBASEMP WHERE BDCODEMP = NEW.bdcodemp INTO :vcodemp;

  IF (vcodemp IS NULL) THEN
     BEGIN
       EXECUTE PROCEDURE SP_VRH_VERIFICAVERBASEMP_PADRAO(NEW.bdcodemp);
     END   */
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_TCOL_HIST_AU0
AS
  DECLARE VARIABLE vCODSOC INTEGER;
BEGIN
/* Gilberto - 25/10/2017 - 20915 - Esse processo ? feito pelo ?nico

  vCODSOC = NULL;
  SELECT FIRST 1 x.bdCODSOC FROM empresas_tsoc x
  WHERE (x.BDCODEMP = NEW.bdcodemp)
  AND (x.bdcgcceisoc = (select first 1 BDCPFCOL from vrh_emp_tcolcon where bdcodemp = new.bdcodemp and bdcodcol = new.bdcodcol))
  INTO :vcodsoc;

  if ((vCODSOC is not null) and (new.bdcontrcol = 1)) then
  begin
    update empresas_tsoc set
    BDCODPAISORIG = NEW.BDCODPAISNAS,
    BDNATURALIZADO = NEW.BDNATURALIZADOCOL,
    BDPORTNAT = NEW.BDPORTNAT,
    BDDATANATURALIZACAO = NEW.BDDATANATURALIZACAO,
    BDDATACHEBRASIL = new.BDDTAPOSENT
    WHERE (BDCODEMP = NEW.BDCODEMP)
    AND (BDCODSOC = :vCODSOC);
  end
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_TCOLCON_CAD_AU0
AS
  DECLARE VARIABLE vcodsoc INTEGER;
  DECLARE VARIABLE vexterior VARCHAR (5);
BEGIN
/* Gilberto - 25/10/2017 - 20915 - Esse processo ? feito pelo ?nico

 vCODSOC = NULL;
  SELECT FIRST 1 x.bdCODSOC FROM empresas_tsoc x
  WHERE (x.BDCODEMP = NEW.bdcodemp)
  AND (x.bdcgcceisoc = (select first 1 BDCPFCOL from vrh_emp_tcolcon where bdcodemp = new.bdcodemp and bdcodcol = new.bdcodcol))
  INTO :vcodsoc;

  select case when (upper(bddescpais) = 'BRASIL') then 'FALSE' else 'TRUE' end bdexterior from tpais where bdcodpais = new.bdcodpaisres into :vexterior;

  if ((vCODSOC is not null) and (new.bdcontrcol = 1)) then
  begin
    update empresas_tsoc set
    bdcodpais = NEW.bdcodpaisres,
    bdexteriorsoc = :vexterior
    WHERE (BDCODEMP = NEW.BDCODEMP)
    AND (BDCODSOC = :vCODSOC);
  end
*/
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_TCOLCON_PARTIDA_AD0
AS
  DECLARE VARIABLE vcodobr INTEGER;
  DECLARE VARIABLE vdesc VARCHAR(100);
  DECLARE VARIABLE vp1 INTEGER;
  DECLARE VARIABLE vp2 INTEGER;
  DECLARE VARIABLE vcodusu INTEGER;
BEGIN
  IF (UPPER(OLD.BDSEGDESCOL) = 'TRUE') THEN
     BEGIN
       vcodusu = 0;
       SELECT BDCODUSU FROM SP_GET_USUARIO INTO :vcodusu;
       IF (vcodusu IS NOT NULL AND vcodusu <> 0) THEN
          BEGIN
            vcodobr = 0;
            vdesc = '';
     
            FOR SELECT Y.BDCODOBRIGACAO, UPPER(Z.BDDESCRICAO) BDDESCRICAO
                FROM VCT_CONFIG_TELA X
                JOIN VCT_CONFIG_TELAOBRSER Y ON (Y.BDCODTELA = X.BDCODTELA)
                JOIN VCT_BASE_OBRIGACAO Z ON (Z.BDCODOBRSER = Y.BDCODOBRIGACAO)
                WHERE UPPER(X.BDTELA) = 'TFREXPORTACAOCAGED' AND UPPER(X.BDCOMPLEMENTO) = 'DI?RIO'
                INTO :vcodobr, :vdesc DO
              BEGIN
                IF (vcodobr <> 0) THEN
                   BEGIN
                     vp1 = 0;
                     vp2 = 0;
                     SELECT POS FROM POS('DI?RIO', :vdesc) INTO :vp1;
                     SELECT POS FROM POS('DIARIO', :vdesc) INTO :vp2;
                     IF ((vp1 > 0) OR (vp2 > 0)) THEN
                        BEGIN
                          DELETE FROM vct_empresa_tsolicitatarefa
                          WHERE bdcodemp = OLD.bdcodemp AND bdcodusu = :vcodusu AND bdcodcol = OLD.bdcodcol AND bdcodobrigacao = :vcodobr AND bdcodtipo = 501 AND
                                bddatasol = OLD.bddataadmcol AND bddatasolicitada = OLD.bddataadmcol AND bddataprevisao = OLD.bddataadmcol;
                        END
                   END
              END
          END
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_TCON_DOC_BI0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  DECLARE VARIABLE vCodPResc INTEGER;

/*  declare variable vCodSoc integer;
  declare variable vCODCID integer;
  declare variable vNOMCOL dm_bdnomcol;
  declare variable vENDCOL dm_bdendereco;
  declare variable vNUMCOL integer;
  declare variable vCOMPLCOL dm_bdcompendereco;
  declare variable vBAICOL dm_bdbairro;
  declare variable vCEPCOL varchar(9);
  declare variable vDDDCOL integer;
  declare variable vFONECOL dm_bdtelefone;
  declare variable vDDDCELCOL integer;
  declare variable vCELCOL dm_bdtelefone;
  declare variable vEMAILCOL dm_bdemail;
  declare variable vLOGRCOL varchar(15);
  declare variable vDATANASCCOL date;
  declare variable vDATAENTSOC date;
  declare variable vRG varchar(13);
  declare variable vORGEMIRG varchar(20);
  declare variable vCODUF integer;
  declare variable vCODCBO integer; */

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END

/* Essa atualiza??o da TEMPRESAS_SOC vai ser feita por dentro do sistema porque depende de mais de uma tabela para atualizar os s?cios.
   Tentamos fazer por trigger mas d? erro no banco porque quando grava na tabela de s?cios, ele tem outra trigger pra atualizar os dados dos contribuintes e entra em loop.
   -- Seleciona dados basicos do colaboradores e joga nas vari?veis.
   select col.BDCODCID,
          col.BDNOMCOL,
          col.BDENDCOL,
          col.BDNUMCOL,
          col.BDCOMPLCOL,
          col.BDBAICOL,
          col.BDCEPCOL,
          col.BDDDDCOL,
          col.BDFONECOL,
          col.BDDDDCELCOL,
          col.BDCELCOL,
          col.BDEMAILCOL,
          col.BDLOGRCOL,
          col.BDDATANASCCOL,
          col.BDDATAADMCOL,
          doc.BDRGCOL,
          doc.BDORGEMIRGCOL,
          doc.BDCODUFRG,
          tfuc.BDCODCBO
   from vrh_emp_tcolcon col
   left outer join vrh_emp_tcolcon_doc doc on (doc.BDCODEMP = col.BDCODEMP and doc.BDCODCOL = col.BDCODCOL)
   left outer join vw_vrh_emp_tcol_vincdia dia on (dia.BDCODEMP = col.BDCODEMP and dia.BDCODCOL = col.BDCODCOL)
   left outer join vrh_funcoes_tfuc tfuc on (tfuc.BDCODPLAFUC = dia.BDCODPLAFUC and tfuc.BDCODTFUC = dia.BDCODTFUC)
   where (col.BDCODEMP = new.bdcodemp) and (col.BDCODCOL = new.BDCODCOL)
       into :vCODCID, :vNOMCOL, :vENDCOL, :vNUMCOL, :vCOMPLCOL, :vBAICOL, :vCEPCOL,
            :vDDDCOL, :vFONECOL, :vDDDCELCOL, :vCELCOL, :vEMAILCOL, :vLOGRCOL, :vDATANASCCOL,
            :vDATAENTSOC, :vRG, :vORGEMIRG, :vCODUF, :vCODCBO;

   -- Cadastra o contribuinte na tabela de socios. Todo contribuinte eh um socio.

   select first 1 bdCODSOC from EMPRESAS_TSOC
   where (BDCODEMP = new.bdcodemp) and
         (BDCGCCEISOC = new.bdcpfcol) into :vCodSoc;

   if ((vCodSoc is null) or (vCodSoc = 0)) then
     begin
       INSERT INTO EMPRESAS_TSOC (BDCODEMP, BDCODCID, BDNOMSOC, BDENDSOC, BDNUMSOC,
                                  BDCOMPLSOC, BDBAISOC, BDCEPSOC, BDCGCCEISOC,
                                  BDDDSOC, BDTELRESSOC, BDDDCELSOC, BDTELCELSOC, BDEMAILSOC,
                                  BDLOGRSOC, BDDATANASCSOC, BDDATAENTSOC, BDDATASAISOC,
                                  BDRGSOC, BDORGEMISOC, BDCODUFRG, BDCODCBO)
              VALUES (new.bdcodemp, :vCODCID, :vNOMCOL,
                      :vENDCOL, :vNUMCOL, :vCOMPLCOL, :vBAICOL, :vCEPCOL, new.bdcpfcol,
                      :vDDDCOL, :vFONECOL, :vDDDCELCOL, :vCELCOL, :vEMAILCOL, :vLOGRCOL, :vDATANASCCOL,
                      :vDATAENTSOC, new.bddatabaixacol, :vRG, :vORGEMIRG, :vCODUF, :vCODCBO);

     end
   else
     begin
       UPDATE EMPRESAS_TSOC
         SET BDCODEMP      = new.bdcodemp,
             BDCODCID      = :vCODCID,
             BDNOMSOC      = :vNOMCOL,
             BDENDSOC      = :vENDCOL,
             BDNUMSOC      = :vNUMCOL,
             BDCOMPLSOC    = :vCOMPLCOL,
             BDBAISOC      = :vBAICOL,
             BDCEPSOC      = :vCEPCOL,
             BDDDSOC       = :vDDDCOL,
             BDTELRESSOC   = :vFONECOL,
             BDDDCELSOC    = :vDDDCELCOL,
             BDTELCELSOC   = :vCELCOL,
             BDEMAILSOC    = :vEMAILCOL,
             BDLOGRSOC     = :vLOGRCOL,
             BDDATANASCSOC = :vDATANASCCOL,
             BDDATAENTSOC  = :vDATAENTSOC,
             BDDATASAISOC  = new.BDDATABAIXACOL,
             BDRGSOC       = :vRG,
             BDORGEMISOC   = :vORGEMIRG,
             BDCODUFRG     = :vCODUF,
             BDCODCBO      = :vCODCBO

       WHERE (BDCODEMP = new.bdcodemp) and
             (BDCODSOC = :vCodSoc) and (
             (BDCODCID      <> :vCODCID) or
             (BDNOMSOC      <> :vNOMCOL) or
             (BDENDSOC      <> :vENDCOL) or
             (BDNUMSOC      <> :vNUMCOL) or
             (BDCOMPLSOC    <> :vCOMPLCOL) or
             (BDBAISOC      <> :vBAICOL) or
             (BDCEPSOC      <> :vCEPCOL) or
             (BDDDSOC       <> :vDDDCOL) or
             (BDTELRESSOC   <> :vFONECOL) or
             (BDDDCELSOC    <> :vDDDCELCOL) or
             (BDTELCELSOC   <> :vCELCOL) or
             (BDEMAILSOC    <> :vEMAILCOL) or
             (BDLOGRSOC     <> :vLOGRCOL) or
             (BDDATANASCSOC <> :vDATANASCCOL) or
             (BDDATAENTSOC  <> :vDATAENTSOC) or
             (BDDATASAISOC  <> new.BDDATABAIXACOL) or
             (BDRGSOC       <> :vRG) or
             (BDORGEMISOC   <> :vORGEMIRG) or
             (BDCODUFRG     <> :vCODUF) or
             (BDCODCBO      <> :vCODCBO) );
     end
*/

  IF (NEW.BDDATABAIXACOL IS NOT NULL) THEN
    BEGIN
      SELECT BDCODPRES FROM VRH_BASE_TPREPRESC WHERE BDCODPRES = 22 INTO :vCodPResc;   -- Demiss?o indireta

      IF (vCodPResc IS NOT NULL AND vCodPResc <> 0) THEN
        BEGIN
          IF ((NEW.BDDATABAIXACOL IS NOT NULL) AND (NEW.BDDATAPAGBAIXACOL IS NULL)) THEN    --Sol. 16982 - Bruno L. R. - 06/02/2017
             NEW.BDDATAPAGBAIXACOL = NEW.BDDATABAIXACOL;
          ELSE
          IF (NEW.BDDATABAIXACOL IS NULL) THEN
             NEW.BDDATAPAGBAIXACOL = NULL;

          UPDATE OR INSERT INTO VRH_EMP_TRESCISAO (BDCODEMP,BDCODCOL,BDDATARESCISAO,BDCODPRES,BDDATANOTIF,BDDATAPAGRESCISAO) VALUES (NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDDATABAIXACOL,:vcodpresc,NEW.BDDATABAIXACOL,NEW.BDDATAPAGBAIXACOL);   --Sol. 16982 - Bruno L. R. - 06/02/2017
        END
    END
  ELSE
    BEGIN
      DELETE FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL;
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_TCON_DOC_BU0
AS
  DECLARE VARIABLE vCodPResc INTEGER;

/*  declare variable vCodSoc integer;
  declare variable vCODCID integer;
  declare variable vNOMCOL dm_bdnomcol;
  declare variable vENDCOL dm_bdendereco;
  declare variable vNUMCOL integer;
  declare variable vCOMPLCOL dm_bdcompendereco;
  declare variable vBAICOL dm_bdbairro;
  declare variable vCEPCOL varchar(9);
  declare variable vDDDCOL integer;
  declare variable vFONECOL dm_bdtelefone;
  declare variable vDDDCELCOL integer;
  declare variable vCELCOL dm_bdtelefone;
  declare variable vEMAILCOL dm_bdemail;
  declare variable vLOGRCOL varchar(15);
  declare variable vDATANASCCOL date;
  declare variable vDATAENTSOC date; */
BEGIN

/*
   -- Seleciona dados basicos do colaborados e joga nas variaveis
   select BDCODCID,BDNOMCOL,BDENDCOL,BDNUMCOL,BDCOMPLCOL,BDBAICOL,
          BDCEPCOL,BDDDDCOL,BDFONECOL,BDDDDCELCOL,BDCELCOL,BDEMAILCOL,BDLOGRCOL,BDDATANASCCOL,
          BDDATAADMCOL
   from vrh_emp_tcolcon where (BDCODEMP = new.bdcodemp) and (BDCODCOL = new.BDCODCOL) into :vCODCID, :vNOMCOL, :vENDCOL, :vNUMCOL, :vCOMPLCOL, :vBAICOL, :vCEPCOL,
                                                                                           :vDDDCOL, :vFONECOL, :vDDDCELCOL, :vCELCOL, :vEMAILCOL, :vLOGRCOL, :vDATANASCCOL,
                                                                                           :vDATAENTSOC;

   -- Cadastra o contribuinte na tabela de socios. Todo contribuinte eh um socio.

   select first 1 bdCODSOC from EMPRESAS_TSOC
   where (BDCODEMP = new.bdcodemp) and
         (BDCGCCEISOC = new.bdcpfcol) into :vCodSoc;

   if ((vCodSoc is null) or (vCodSoc = 0)) then
      begin
        INSERT INTO EMPRESAS_TSOC (BDCODEMP, BDCODCID, BDNOMSOC, BDENDSOC, BDNUMSOC,
                                   BDCOMPLSOC, BDBAISOC, BDCEPSOC, BDCGCCEISOC,
                                   BDDDSOC, BDTELRESSOC, BDDDCELSOC, BDTELCELSOC, BDEMAILSOC,
                                   BDLOGRSOC, BDDATANASCSOC, BDDATAENTSOC, BDDATASAISOC) VALUES (new.bdcodemp, :vCODCID, :vNOMCOL,
                                                     :vENDCOL, :vNUMCOL, :vCOMPLCOL, :vBAICOL, :vCEPCOL, new.bdcpfcol,
                                                     :vDDDCOL, :vFONECOL, :vDDDCELCOL, :vCELCOL, :vEMAILCOL, :vLOGRCOL, :vDATANASCCOL,
                                                     :vDATAENTSOC, new.bddatabaixacol);
      end
   else
      begin
        UPDATE EMPRESAS_TSOC
          SET BDCODEMP      = new.bdcodemp,
              BDCODCID      = :vCODCID,
              BDNOMSOC      = :vNOMCOL,
              BDENDSOC      = :vENDCOL,
              BDNUMSOC      = :vNUMCOL,
              BDCOMPLSOC    = :vCOMPLCOL,
              BDBAISOC      = :vBAICOL,
              BDCEPSOC      = :vCEPCOL,
              BDDDSOC       = :vDDDCOL,
              BDTELRESSOC   = :vFONECOL,
              BDDDCELSOC    = :vDDDCELCOL,
              BDTELCELSOC   = :vCELCOL,
              BDEMAILSOC    = :vEMAILCOL,
              BDLOGRSOC     = :vLOGRCOL,
              BDDATANASCSOC = :vDATANASCCOL,
              BDDATAENTSOC  = :vDATAENTSOC,
              BDDATASAISOC  = new.bddatabaixacol
        WHERE (BDCODEMP = new.bdcodemp) and
              (BDCODSOC = :vCodSoc) and (
              (BDCODCID      <> :vCODCID) or
              (BDNOMSOC      <> :vNOMCOL) or
              (BDENDSOC      <> :vENDCOL) or
              (BDNUMSOC      <> :vNUMCOL) or
              (BDCOMPLSOC    <> :vCOMPLCOL) or
              (BDBAISOC      <> :vBAICOL) or
              (BDCEPSOC      <> :vCEPCOL) or
              (BDDDSOC       <> :vDDDCOL) or
              (BDTELRESSOC   <> :vFONECOL) or
              (BDDDCELSOC    <> :vDDDCELCOL) or
              (BDTELCELSOC   <> :vCELCOL) or
              (BDEMAILSOC    <> :vEMAILCOL) or
              (BDLOGRSOC     <> :vLOGRCOL) or
              (BDDATANASCSOC <> :vDATANASCCOL) or
              (BDDATAENTSOC  <> :vDATAENTSOC) or
              (BDDATASAISOC  <> new.bddatabaixacol) );
      end
  */

  IF (NEW.BDDATABAIXACOL IS NOT NULL) THEN
     BEGIN
       SELECT BDCODPRES FROM VRH_BASE_TPREPRESC WHERE BDCODPRES = 22 INTO :vCodPResc;   -- Demiss?o indireta
       IF (vCodPResc IS NOT NULL AND vCodPResc <> 0) THEN
          BEGIN
            IF ((NEW.BDDATABAIXACOL IS NOT NULL) AND (NEW.BDDATAPAGBAIXACOL IS NULL)) THEN    --Sol. 16982 - Bruno L. R. - 06/02/2017
               NEW.BDDATAPAGBAIXACOL = NEW.BDDATABAIXACOL;
            ELSE
            IF (NEW.BDDATABAIXACOL IS NULL) THEN
               NEW.BDDATAPAGBAIXACOL = NULL;

            UPDATE OR INSERT INTO VRH_EMP_TRESCISAO (BDCODEMP,BDCODCOL,BDDATARESCISAO,BDCODPRES,BDDATANOTIF,BDDATAPAGRESCISAO) VALUES (NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDDATABAIXACOL,:vcodpresc,NEW.BDDATABAIXACOL,NEW.BDDATAPAGBAIXACOL);   --Sol. 16982 - Bruno L. R. - 06/02/2017
          END
     END
  ELSE
     BEGIN
       DELETE FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL;
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_THIST_AUMHE_BI0
AS
  DECLARE VARIABLE vStatus INTEGER;
  DECLARE VARIABLE vCodHAumHe INTEGER;

BEGIN
  SELECT BDCODCOL FROM VRH_EMP_TCOL_SHE WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDDATASHE = NEW.BDDATAHAUMHE INTO :vStatus;

  IF (NEW.BDTIPOREGHAUMHE IS NULL) THEN
     BEGIN
       /* ? um registro novo */
       IF (:vStatus IS NULL OR (:vStatus = 0)) THEN
          NEW.BDTIPOREGHAUMHE = 0;
       ELSE  /* Esta alterando um registro de sal?rio que j? existe */
          NEW.BDTIPOREGHAUMHE = 1;
     END

  --Sol. 18901 - Bruno L. R. - 05/07/2017
  IF (NEW.BDCODHAUMHE IS NULL OR NEW.BDCODHAUMHE = 0) THEN
     BEGIN
       SELECT COALESCE((MAX(BDCODHAUMHE) + 1), 1) FROM VRH_EMP_THIST_AUMHE INTO vCodHAumHe;
       NEW.BDCODHAUMHE = vCodHAumHe;
     END
  --Sol. 18901 - Bruno L. R. - 05/07/2017

  UPDATE OR INSERT INTO VRH_EMP_TCOL_SHE (BDCODEMPSHE,BDCODEMP,BDCODCOL,BDCODSHE,BDDATASHE,BDCODMAS,BDSALSHE) VALUES (NEW.BDCODEMP,NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDCODSHE,NEW.BDDATAHAUMHE,NEW.BDCODMAS,NEW.BDSALBASEHAUMHE) MATCHING (BDCODEMPSHE,BDCODCOL,BDCODEMP,BDCODSHE,BDDATASHE);
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_TNOTIFICACOES_BI0
AS
  DECLARE VARIABLE vcod INTEGER;
  DECLARE VARIABLE vref INTEGER;
  DECLARE VARIABLE vdata DATE;

BEGIN
  IF (NEW.bdcodnotif IS NULL OR (NEW.bdcodnotif = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODNOTIF) + 1, 1) FROM vrh_emp_tnotificacoes WHERE BDCODEMP = NEW.bdcodemp INTO :vcod;
       NEW.bdcodnotif = :vcod;
     END

             -- suspens?o
  IF (NEW.bdtiponotif = 1 AND UPPER(NEW.bdfaltasnotif) = 'TRUE') THEN
     BEGIN
       vcod = 1;
       vdata = NEW.bddatasuspnotif;
       WHILE (vcod <= NEW.bddiasnotif) DO
         BEGIN
           vref = CAST((SUBSTRING(CAST(vdata AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(vdata AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
           UPDATE OR INSERT INTO vrh_emp_tfaltas (BDCODEMP,BDCODCOL,BDREFFAL) VALUES (NEW.bdcodemp, NEW.bdcodcol, :vref) MATCHING (BDCODEMP,BDCODCOL,BDREFFAL);
           UPDATE OR INSERT INTO vrh_emp_tfaltas_itens (BDCODEMP,BDCODCOL,BDREFFAL,BDDATAFAL,BDTIPOFAL,BDHORASFAL,BDTIPODSRFAL,BDTIPODESCFAL,BDCODTIPO,BDCODNOTIF) VALUES
                   (NEW.bdcodemp, NEW.bdcodcol, :vref, :vdata, 1, 1, 0, 0, 201, NEW.bdcodnotif) MATCHING (BDCODEMP,BDCODCOL,BDREFFAL,BDDATAFAL);
           vcod = vcod + 1;
           vdata = vdata + 1;
         END
     END

END
^

/* Altering existing trigger... */
ALTER TRIGGER VRH_EMP_TRESCISAO_AD0
AS
  DECLARE VARIABLE vcodrep INTEGER;
  DECLARE VARIABLE vcodobr INTEGER;
  DECLARE VARIABLE vcodusu INTEGER;

BEGIN
  vcodusu = 0;
  SELECT BDCODUSU FROM SP_GET_USUARIO INTO :vcodusu;

  IF (vcodusu IS NOT NULL AND vcodusu <> 0) THEN
     BEGIN
       /* Exclui a tarefa de exporta??o para seguro desemprego */
       vcodrep = 0;
       SELECT BDCODREP FROM TREPOSITORIO WHERE BDCHAVESCI = 17 INTO :vcodrep;
       IF (vcodrep IS NOT NULL AND vcodrep <> 0) THEN
          BEGIN
            vcodobr = 0;
            SELECT FIRST 1 Y.BDCODOBRIGACAO
            FROM VCT_CONFIG_TELA X
            JOIN VCT_CONFIG_TELAOBRSER Y ON (Y.BDCODTELA = X.BDCODTELA)
            WHERE UPPER(X.BDTELA) = 'TFRRELGERADORRELATORIORH-'||:vcodrep INTO :vcodobr;
            IF (vcodobr IS NOT NULL AND vcodobr <> 0) THEN
               BEGIN
                 DELETE FROM vct_empresa_tsolicitatarefa
                 WHERE bdcodemp = OLD.bdcodemp AND bdcodusu = :vcodusu AND bdcodcol = OLD.bdcodcol AND bdcodobrigacao = :vcodobr AND bdcodtipo = 501 AND
                       bddatasol = OLD.bddatanotif AND bddatasolicitada = OLD.bddatarescisao AND bddataprevisao = OLD.bddatapagrescisao;
               END
          END

       /* Exclui a tarefa de exporta??o para GRRF */
       vcodobr = 0;
       SELECT FIRST 1 Y.BDCODOBRIGACAO
       FROM VCT_CONFIG_TELA X
       JOIN VCT_CONFIG_TELAOBRSER Y ON (Y.BDCODTELA = X.BDCODTELA)
       WHERE UPPER(X.BDTELA) = 'TFRPROCESSOEXPORTACAOGRRF' INTO :vcodobr;
       IF (vcodobr IS NOT NULL AND vcodobr <> 0) THEN
          BEGIN
            DELETE FROM vct_empresa_tsolicitatarefa
            WHERE bdcodemp = OLD.bdcodemp AND bdcodusu = :vcodusu AND bdcodcol = OLD.bdcodcol AND bdcodobrigacao = :vcodobr AND bdcodtipo = 501 AND
                  bddatasol = OLD.bddatanotif AND bddatasolicitada = OLD.bddatarescisao AND bddataprevisao = OLD.bddatapaggrfc;
          END

     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPCALC_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END

  IF (NEW.bdtipcalcfercolinf IS NULL) THEN
     NEW.bdtipcalcfercolinf = 2;

  IF (NEW.bdtipcalcfercolsup IS NULL) THEN
     NEW.bdtipcalcfercolsup = 4;
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPDIRF_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPESOCIAL_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPGPS_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPGRCS_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPPAR_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPPROP_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPRAIS_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPSEFIP_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_BASE_TEMPVINC_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup n?o pode interferir na sequ?ncia dos c?digos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_EMP_TVERBARFE_BI0
AS
  DECLARE VARIABLE vData VARCHAR(10);

BEGIN
  IF (NEW.BDINIPERAQUISFE IS NOT NULL) THEN
     BEGIN
       vData = CAST(NEW.BDINIPERAQUISFE AS VARCHAR(10));

       NEW.BDDETALHERFE = 'C?d. f?rias: '||NEW.BDCODFE||'. Per. aquisitivo: '||SUBSTRING(vData FROM 9 FOR 2)||'/'||
                          SUBSTRING(vData FROM 6 FOR 2)||'/'||
                          SUBSTRING(vData FROM 1 FOR 4);
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_EMP_TVERBARFE_BU0
AS
  DECLARE VARIABLE vData VARCHAR(10);

BEGIN
  IF (NEW.BDINIPERAQUISFE IS NOT NULL) THEN
     BEGIN
       vData = CAST(NEW.BDINIPERAQUISFE AS VARCHAR(10));

       NEW.BDDETALHERFE = 'C?d. f?rias: '||NEW.BDCODFE||'. Per. aquisitivo: '||SUBSTRING(vData FROM 9 FOR 2)||'/'||
                          SUBSTRING(vData FROM 6 FOR 2)||'/'||
                          SUBSTRING(vData FROM 1 FOR 4);
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_EMP_TVERBATOMADOR_BI0
AS
  DECLARE VARIABLE vData VARCHAR(10);
  DECLARE VARIABLE vCta VARCHAR(100);
  DECLARE VARIABLE vDtInt INTEGER;
  DECLARE VARIABLE vCodCC INTEGER;

BEGIN
  IF (NEW.BDDATAENTRADAVFT IS NOT NULL) THEN
     BEGIN
       SELECT X.BDNOMCTA,X.BDCODTPCC FROM VW_UNION_DADOS_CC X WHERE
              X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDORDEM = NEW.BDORDEM
       INTO vCta,vCodCC;
       vData = CAST(NEW.BDDATAENTRADAVFT AS VARCHAR(10));
       vDtInt = CAST((SUBSTRING(vData FROM 1 FOR 4)||SUBSTRING(vData FROM 6 FOR 2)||SUBSTRING(vData FROM 9 FOR 2)) AS INTEGER);

       IF (vCodCC IS NOT NULL) THEN
          NEW.BDDETALHEVFT = SUBSTRING(('Aloca??o iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' no Centro/tomador: '||vCta) FROM 1 FOR 500);
       ELSE
          NEW.BDDETALHEVFT = SUBSTRING(('Aloca??o iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' na Empresa: '||vCta) FROM 1 FOR 500);

       NEW.BDITEMVFT = vDtInt;
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_EMP_TVERBATOMADOR_BU0
AS
  DECLARE VARIABLE vData VARCHAR(10);
  DECLARE VARIABLE vCta VARCHAR(100);
  DECLARE VARIABLE vCodCC INTEGER;
  DECLARE VARIABLE vDtInt INTEGER;

BEGIN
  IF (NEW.BDDATAENTRADAVFT IS NOT NULL) THEN
     BEGIN
       SELECT X.BDNOMCTA,X.BDCODTPCC FROM VW_UNION_DADOS_CC X WHERE
              X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDORDEM = NEW.BDORDEM
       INTO vCta,vCodCC;
       vData = CAST(NEW.BDDATAENTRADAVFT AS VARCHAR(10));
       vDtInt = CAST((SUBSTRING(vData FROM 1 FOR 4)||SUBSTRING(vData FROM 6 FOR 2)||SUBSTRING(vData FROM 9 FOR 2)) AS INTEGER);

       IF (vCodCC IS NOT NULL) THEN
          NEW.BDDETALHEVFT = SUBSTRING(('Aloca??o iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' no Centro/tomador: '||vCta) FROM 1 FOR 500);
       ELSE
          NEW.BDDETALHEVFT = SUBSTRING(('Aloca??o iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' na Empresa: '||vCta) FROM 1 FOR 500);

       NEW.BDITEMVFT = vDtInt;

     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_EMP_TVERBATOMINT_BI0
AS
  DECLARE VARIABLE vData VARCHAR(10);
  DECLARE VARIABLE vCta VARCHAR(100);
  DECLARE VARIABLE vDtInt INTEGER;
  DECLARE VARIABLE vCodCC INTEGER;

BEGIN
  IF (NEW.BDDATAENTRADAVFT IS NOT NULL) THEN
     BEGIN
       SELECT X.BDNOMCTA,X.BDCODTPCC FROM VW_UNION_DADOS_CC X WHERE
              X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDORDEM = NEW.BDORDEM
       INTO vCta,vCodCC;
       vData = CAST(NEW.BDDATAENTRADAVFT AS VARCHAR(10));
       vDtInt = CAST((SUBSTRING(vData FROM 1 FOR 4)||SUBSTRING(vData FROM 6 FOR 2)||SUBSTRING(vData FROM 9 FOR 2)) AS INTEGER);

       IF (vCodCC IS NOT NULL) THEN
          NEW.BDDETALHEVFT = SUBSTRING(('Aloca??o iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' no Centro/tomador: '||vCta) FROM 1 FOR 500);
       ELSE
          NEW.BDDETALHEVFT = SUBSTRING(('Aloca??o iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' na Empresa: '||vCta) FROM 1 FOR 500);

       NEW.BDITEMVFT = vDtInt;
     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VRHF_EMP_TVERBATOMINT_BU0
AS
  DECLARE VARIABLE vData VARCHAR(10);
  DECLARE VARIABLE vCta VARCHAR(100);
  DECLARE VARIABLE vCodCC INTEGER;
  DECLARE VARIABLE vDtInt INTEGER;

BEGIN
  IF (NEW.BDDATAENTRADAVFT IS NOT NULL) THEN
     BEGIN
       SELECT X.BDNOMCTA,X.BDCODTPCC FROM VW_UNION_DADOS_CC X WHERE
              X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDORDEM = NEW.BDORDEM
       INTO vCta,vCodCC;
       vData = CAST(NEW.BDDATAENTRADAVFT AS VARCHAR(10));
       vDtInt = CAST((SUBSTRING(vData FROM 1 FOR 4)||SUBSTRING(vData FROM 6 FOR 2)||SUBSTRING(vData FROM 9 FOR 2)) AS INTEGER);

       IF (vCodCC IS NOT NULL) THEN
          NEW.BDDETALHEVFT = SUBSTRING(('Aloca??o iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' no Centro/tomador: '||vCta) FROM 1 FOR 500);
       ELSE
          NEW.BDDETALHEVFT = SUBSTRING(('Aloca??o iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' na Empresa: '||vCta) FROM 1 FOR 500);

       NEW.BDITEMVFT = vDtInt;

     END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VSUC_EMP_TVINCTRAN_BD0
AS
BEGIN
  -- Ao excluir um v?nculo preciso eliminar as transa??es geradas por ela no lan?amento
  UPDATE vsuc_empresas_tlan SET bdTRANFECHADA = 'FALSE',bdTRANSACAO = NULL,bdCHAVEVINC = NULL
  WHERE
  (bdCHAVEVINC = OLD.bdchavevinc) AND
  (bdCODEMP IN (SELECT bdCODEMP FROM tempresas
                WHERE
                ((bdcodemp = (SELECT CASE WHEN (bdCODMATRIZ > 0) THEN bdCODMATRIZ ELSE bdCODEMP END FROM tempresas WHERE bdcodemp = OLD.bdcodemp)) OR
                 (bdcodmatriz = (SELECT CASE WHEN (bdCODMATRIZ > 0) THEN bdCODMATRIZ ELSE bdCODEMP END FROM tempresas WHERE bdcodemp = OLD.bdcodemp)))));
END
^

/* Altering existing trigger... */
ALTER TRIGGER VSUC_EMPRESAS_TLAN_BD0
AS
  DECLARE VARIABLE vCodUsu INTEGER;
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE VRECONTABILIZANDO DM_BOOLEAN;
  DECLARE VARIABLE vDataHora TIMESTAMP;
  DECLARE VARIABLE vEmpresaDeletandoLanRecont INTEGER;
BEGIN
  --#alt:16965 - N?o executa a trigger quando estiver deletando para a recontabiliza??o com plano de contas diferentes. Ana - 12/02/2018
  select trim(upper(coalesce(RDB$GET_CONTEXT('USER_SESSION', 'W_RECONTABILIZA_DELETE_EMPRESA'), 0)))
  from RDB$DATABASE
  into :VEMPRESADELETANDOLANRECONT;

  if ((VEMPRESADELETANDOLANRECONT <> 0) and (VEMPRESADELETANDOLANRECONT = OLD.BDCODEMP)) then
    exit;
  --#alt:16965.fim

     SELECT FIRST 1 bdcodusu FROM sp_get_usuario INTO :vCodUsu;

  /* sol.: #10892 Jean 19/01/2015: para verificar se esta executando processo de recontabiliza??o */ 
  SELECT TRIM(UPPER(COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_RECONTABILIZA'), '')))
  FROM RDB$DATABASE
  INTO :VRECONTABILIZANDO;

  SELECT COUNT(*)
  FROM tbloqlan_usuario tblu
  INNER JOIN tbloqlan_empresa tble ON (tble.bdcodemp = tblu.bdcodemp AND tble.bdcodblq = tblu.bdcodblq AND tble.bdcodble = tblu.bdcodble)
  INNER JOIN tbloqlan tbloq ON (tbloq.bdcodblq = tble.bdcodblq)
  WHERE tbloq.bdcodsis = 4
  AND UPPER(tbloq.bdrecurso) = UPPER('frlancamento')
  AND ((bddatainicial >= OLD.bddata AND (bddatafinal <= OLD.bddata OR bddatafinal IS NULL))
  OR (bddatainicial <= OLD.bddata AND ((bddatafinal BETWEEN OLD.bddata AND OLD.bddata) OR bddatafinal IS NULL))
  OR (bddatainicial <= OLD.bddata AND (bddatafinal >= OLD.bddata OR bddatafinal IS NULL)) )
  AND tble.bdcodemp = OLD.bdcodemp
  AND tblu.bdcodusu = :vcodusu
  INTO :vcodigo;

  /* sol.: #10892 Jean 19/01/2015: Lan?ar exce??o somente se n?o estiver recontabilizando */
  IF ((VCODIGO > 0) AND (VRECONTABILIZANDO <> 'TRUE')) THEN
    EXCEPTION EX_BLOQLAN;

  --alt:15642 - 13/09/2016 - Quando for excluir lan?amento manual, grava na tabela de log o tempo e quantidade de lan?amentos, para n?o perder a estat?stica dos trabalhos realizados. Pedro
  IF (OLD.BDTIPOLAN = 1) THEN
    BEGIN
      vDataHora = DATEADD(SECOND, DATEDIFF(SECOND, CAST(OLD.BDDATALAN||' '||OLD.BDHORALAN AS TIMESTAMP), CAST(OLD.BDDATALANINICIAL||' '||OLD.BDHORALANINICIAL AS TIMESTAMP)), CURRENT_TIMESTAMP);
      EXECUTE PROCEDURE SP_INSERIR_LOG(OLD.BDCODEMP, NULL, OLD.BDCODUSU, NULL, 4, NULL, vDataHora, vDataHora, '', 0, 13, 
                                       CURRENT_USER, 'SERVIDOR', 'TFRLANCAMENTO', 'Lan?amentos cont?beis', NULL, 'VSUC_EMPRESAS_TLAN', NULL, 'FALSE', vDataHora);
    END
END
^

/* Altering existing trigger... */
ALTER TRIGGER VSUC_EMPRESAS_VALORPRESENTE_BI0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodvlrpres IS NULL) OR (NEW.bdcodvlrpres = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodvlrpres)+1), 1) FROM vsuc_empresas_valorpresente WHERE bdcodemp = NEW.bdcodemp INTO :vcodigo;
      NEW.bdcodvlrpres = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodvlrpres FROM vsuc_empresas_valorpresente WHERE (bdcodvlrpres = NEW.bdcodvlrpres) AND (bdcodemp = NEW.bdcodemp) INTO :vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodvlrpres)+1), 1) FROM vsuc_empresas_valorpresente WHERE bdcodemp = NEW.bdcodemp INTO :vcodigo;
           NEW.bdcodvlrpres = vcodigo;
         END
    END
  NEW.bdcontabilizacao = NEW.bdcontabilizacao + 1; --#alt:15359 - No combo so tem fiscal e societ?ria, por isso soma. 0 - ambas, 1 - fiscal, 2 - societ?ria. Ana - 07/10/2016
END
^

/* Alter Procedure... */
/* empty dependent procedure body */
/* Clear: VRHF_SP_TTEMPOTRAB for: DIA_SEGUINTE */
ALTER PROCEDURE VRHF_SP_TTEMPOTRAB(PRCODEMP INTEGER,
PRCODFUN INTEGER,
PRDATAENT DATE,
PRHORAENT TIME,
PRDATASAI DATE,
PRHORASAI TIME)
 RETURNS(BDTEMPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

/* Alter (DIA_SEGUINTE) */
ALTER PROCEDURE DIA_SEGUINTE(PRDATA DATE)
 RETURNS(PRDIASEGUINTE DATE)
 AS
DECLARE VARIABLE WULTDIA SMALLINT;
DECLARE VARIABLE WDIA SMALLINT;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
BEGIN

  wdia = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 9 FOR 2) AS SMALLINT);
  wmes = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);

--  exception ex_date wdia||'-'||wmes||'-'||wano;

  SELECT UltDia FROM ultimo_dia_mes(:wmes,:wano) INTO :wultdia;

  IF (wultdia = wdia) THEN
     BEGIN
       wdia = 1;
       SELECT mes, ano FROM ref_seguinte(:wmes,:wano) INTO :wmes, :wAno;
     END
  ELSE
     BEGIN
       wdia = wdia + 1;
     END

  prdiaseguinte = :wmes||'/'||:wdia||'/'||:wano;

  SUSPEND;

END
^

/* Alter (MAXSCI) */
ALTER PROCEDURE MAXSCI(PRCAMPO VARCHAR(1024),
PRORDEM VARCHAR(1024),
PRCONDICAO VARCHAR(1024),
PRTABELA VARCHAR(1024))
 RETURNS(BDRESULT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WORDEM_TRAN VARCHAR(150);
BEGIN
  /* procedimento criado para substituir a clausula "MAX" nos automatismos
  obs: nao esquecer de criar o indice descendente na tabela que for usar o MAXSCI*/

  SELECT bdresult FROM strtran(:prordem, ',', ' desc,') INTO wordem_tran;

  wsql = 'select first 1 coalesce('||prcampo||', 0) from '||prtabela;
  IF (prcondicao <> '') THEN
     wsql = wsql||' where '||prcondicao;
  IF (prordem <> '') THEN
     wsql = wsql||' order by '||wordem_tran||' desc';
     --wsql = wsql||' order by '||prordem||' desc';


  EXECUTE STATEMENT wsql INTO :bdresult;
  IF (bdresult IS NULL) THEN
     bdresult = 0;
--  bdresult = bdresult +1;
  SUSPEND;
END
^

/* Alter (SP_APURACAO_BLOCOM) */
ALTER PROCEDURE SP_APURACAO_BLOCOM(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODCONFBLOCOM INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WWHEREEMPRESAS VARCHAR(500);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Obt?m a configura??o do Bloco M...
  SELECT BDCODCONFBLOCOM FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :prCODEMP INTO :wCODCONFBLOCOM;

  -- Quando n?o tiver configura??o de Blooo M na empresa, vai buscar uma configura??o padr?o...
  IF (wCODCONFBLOCOM IS NULL) THEN
    SELECT FIRST 1 BDCODCONF FROM VEF_BASE_TCONFBLOCOM WHERE BDPLANOPADRAO = 'TRUE' INTO :wCODCONFBLOCOM;

  wWhereEmpresas = '';
  /* Cria apura??o do Bloco M, necess?rio para os registros abaixo... */
  FOR
      SELECT ex.BDCODEMP
      FROM TEMPRESAS ex
      WHERE ex.BDCODEMP = :prCODEMP
         OR ex.BDCODMATRIZ = :prCODEMP
      INTO :wCODEMP
  DO
   BEGIN
     INSERT INTO VEF_EMP_TBLOCOMGER (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCONF) VALUES (7, :wCODEMP, :prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM);
     wWhereEmpresas = wWhereEmpresas || wCodEmp || ',';
   END

   wWhereEmpresas = ' bdCODEMP IN(' || SUBSTRING(wWhereEmpresas FROM 1 FOR CHARACTER_LENGTH(wWhereEmpresas) -1) ||') ';

  IF (:wCODCONFBLOCOM IS NOT NULL) THEN
    BEGIN
      /* REGISTRO 0111: TABELA DE RECEITA BRUTA MENSAL PARA FINS DE RATEIO DE CR?DITOS COMUNS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_0110 (:prCODEMP, :prREFERENCIA);

      /* REGISTRO M100: CR?DITO DE PIS/PASEP RELATIVO AO PER?ODO
         REGISTRO M500: CR?DITO DE COFINS RELATIVO AO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100_M500 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO 1100: CONTROLE DE CR?DITOS FISCAIS ? PIS/PASEP
         REGISTRO 1500: CONTROLE DE CR?DITOS FISCAIS ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_1100_1500 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO F600: CONTRIBUI??O RETIDA NA FONTE
         REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
         REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_F60013001700 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO M300: CONTRIBUI??O DE PIS/PASEP DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO.
         REGISTRO M700: COFINS DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M300_M700 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);

      /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP
         REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800 (:prCODEMP, :prREFERENCIA, :wWhereEmpresas);
    
      /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO
         REGISTRO M600: CONSOLIDA??O DA CONTRIBUI??O PARA A SEGURIDADE SOCIAL - COFINS DO PER?ODO */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M200_M600 (:prCODEMP, :prREFERENCIA,:wWhereEmpresas);

      /* Gera ?ltimos ajustes da apura??o */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_DADOSFINAIS (:prCODEMP, :prREFERENCIA);
      
      /* Cria a contabiliza??o */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE (:prCODEMP, :prREFERENCIA);

      /* Apaga os dados das tabelas tempor?rias, faz isso pq se apura-se mais de uma vez, somava todos os valores */
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_0110_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_VEF_EMP_TBLOCOM_0111_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
      DELETE FROM TMP_TCONF_CONTAS_ONLINE_TEMP tmp WHERE tmp.BDCODMATRIZ = :prCODEMP AND tmp.BDREFERENCIA = :prREFERENCIA;
    END
  ELSE
    BEGIN
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC) VALUES
                                   (7, :prCODEMP, :prCODEMP, :prREFERENCIA,
                                    COALESCE((SELECT MAX(x.BDCODBLOCOM)+1 FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA),1),
                                    NULL, NULL, NULL, NULL, 5);
    END
    
END
^

/* Alter (SP_APURACAO_BLOCOM_0110) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_0110(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,2);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,2);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,2);
DECLARE VARIABLE WRBCUM NUMERIC(15,2);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Incid?ncia tribut?ria
  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  -- Obt?m os valores das formulas apuradas
  wSQL =       'SELECT ';
  IF (:wINCTRIB IN (1,3)) THEN
    wSQL = wSQL||'       COALESCE(BDRBNCUMTRIBMI, 0) as BDRBNCUMTRIBMI, COALESCE(BDRBNCUMNTMI, 0) as BDRBNCUMNTMI, COALESCE(BDRBNCUMEXP, 0) as BDRBNCUMEXP, ';
  ELSE
    wSQL = wSQL||'       0 as BDRBNCUMTRIBMI, 0 as BDRBNCUMNTMI, 0 as BDRBNCUMEXP, ';

  IF (:wINCTRIB IN (2,3)) THEN
    wSQL = wSQL||'       COALESCE(BDRBCUM, 0) as BDRBCUM ';
  ELSE
    wSQL = wSQL||'       0 as BDRBCUM ';

  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_0110_TEMP aux ';
  wSQL = wSQL||'WHERE aux.BDCODEMP = '||:prCODEMP;
  wSQL = wSQL||'  AND aux.BDREFERENCIA = '||:prREFERENCIA;

  EXECUTE STATEMENT ( wSQL )
  INTO :wRBNCUMTRIBMI, :wRBNCUMNTMI, :wRBNCUMEXP, :wRBCUM;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 1, COALESCE(:wRBNCUMTRIBMI,0));

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 2, COALESCE(:wRBNCUMNTMI,0));

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 3, COALESCE(:wRBNCUMEXP,0));

  /* 35 - Contribui??o cumulativa */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 35, 1, COALESCE(:wRBCUM,0));

  /* 36 - Contribui??o Total (Valores n?o cumulativos + cumulativos) */
  -- Obt?m os valores das formulas apuradas
  SELECT SUM(BDVALOR)
  FROM VEF_EMP_TBLOCOMGERREG aux
  WHERE (aux.BDCODQUADRO IN (34,35)) /* 34 - Contribui??o n?o cumulativa / 35 - Contribui??o cumulativa */
    AND aux.BDCODEMP = :prCODEMP
    AND aux.BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 36, 1, COALESCE(:wRBNCUMTRIBMI,0));

END
^

/* Alter (SP_APURACAO_BLOCOM_1100_1500) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_1100_1500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDCREDITOSPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wCREDITOSPERANT;

  /* Caso tenha saldos no per?odo anterior a apura??o, vai carregar estes valores para a apura??o atual */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM) ';
  wSQL = wSQL||'SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = aux.BDCODQUADRO AND x.BDCODPERIODO = aux.BDCODPERIODO AND x.BDCODEMP = aux.BDCODEMP AND x.BDREFERENCIA = aux.BDREFERENCIA), ';
  wSQL = wSQL||       'aux.BDCODCRE_4_3_6, aux.BDPER_APU_CRED, aux.BDORIG_CRED, aux.BDCNPJ_SUC, ';
  wSQL = wSQL||       'SUM(COALESCE(aux.BDVL_CRED_APU,0)) as BDVL_CRED_APU, SUM(COALESCE(aux.BDVL_CRED_DESC_EFD,0)) as BDVL_CRED_DESC_EFD, SUM(COALESCE(aux.BDSLD_CRED_FIM,0)) as BDSLD_CRED_FIM ';
  wSQL = wSQL||'FROM ( ';
  --IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
    BEGIN
                         /* Saldos periodos anteriores a apura??o */
      wSQL = wSQL||      'SELECT m.BDCODQUADRO, m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, m.BDCODCRE_4_3_6, m.BDPER_APU_CRED, m.BDORIG_CRED, ';
      wSQL = wSQL||             'm.BDCNPJ_SUC, m.BDSLD_CRED_FIM AS BDVL_CRED_APU, 0 AS BDVL_CRED_DESC_EFD, m.BDSLD_CRED_FIM ';
      wSQL = wSQL||      'FROM VEF_EMP_TBLOCOM1100_1500 m ';
      wSQL = wSQL||      'WHERE (m.BDCODMATRIZ = '||:prCODEMP||') ';
      wSQL = wSQL||        'AND (m.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA ';
      wSQL = wSQL||                               'FROM VEF_EMP_TBLOCOM1100_1500 x ';
      wSQL = wSQL||                               'WHERE x.BDCODEMP = '||:prCODEMP||' ';
      wSQL = wSQL||                                 'AND x.BDREFERENCIA < '||:prREFERENCIA||' ';
      wSQL = wSQL||                                'ORDER BY x.BDREFERENCIA DESC)) ';
      wSQL = wSQL||        'AND m.BDSLD_CRED_FIM > 0 ';
    
      wSQL = wSQL||      'UNION ALL ';
    END
                     /* Saldos de PIS lan?ados */
  wSQL = wSQL||      'SELECT 52 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL||             's.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDCODCRE_4_3_6, s.BDREFAPUSALDO as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             's.BDCNPJCEDENTE as BDCNPJ_SUC, s.BDVLRCREPIS as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, s.BDVLRCREPIS as BDSLD_CRED_FIM ';
  wSQL = wSQL||      'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCREPIS > 0 ';

  wSQL = wSQL||      'UNION ALL ';
                     /* Saldos de Cofins lan?ados */
  wSQL = wSQL||      'SELECT 53 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL||             's.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDCODCRE_4_3_6, s.BDREFAPUSALDO as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             's.BDCNPJCEDENTE as BDCNPJ_SUC, s.BDVLRCRECOFINS as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, s.BDVLRCRECOFINS as BDSLD_CRED_FIM ';
  wSQL = wSQL||      'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCRECOFINS > 0 ';

  wSQL = wSQL||      ') aux ';
  wSQL = wSQL||'GROUP BY aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODCRE_4_3_6, ';
  wSQL = wSQL||         'aux.BDPER_APU_CRED, aux.BDORIG_CRED, aux.BDCNPJ_SUC';

  EXECUTE STATEMENT ( wSQL );
        
END
^

/* Alter (SP_APURACAO_BLOCOM_F60013001700) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_F60013001700(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WTIPOAPURACAORET INTEGER;
DECLARE VARIABLE WINDNATPJ INTEGER;
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wRETPISCOFPERANT;

  SELECT BDTIPOAPURACAORET FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :prCODEMP
  INTO :wTIPOAPURACAORET;

  SELECT BDINDNATPJ FROM VW_VEF_BASE_TEMPPARFED WHERE BDCODEMP = :prCODEMP
  INTO :wINDNATPJ;

  wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_F600_1300 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDREFAPUSALDO, BDCODTER, BDCNPJEMP, BDDATAEMISSAO, BDVLRCONTAB, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDIND_DEC, BDCODRECPIS, BDCODRECCOFINS, BDVLRPISRET, BDVLRCOFINSRET) ';
                     /* Saldos de PIS e/ou Cofins lan?ados */
  wSQL = wSQL||'SELECT s.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDREFERENCIA, s.BDREFAPUSALDO, 0 as BDCODTER, emp.BDCNPJEMP, ';
  wSQL = wSQL||       'CAST(SUBSTRING(s.BDREFERENCIA from 1 for 4)||''-''|| SUBSTRING(s.BDREFERENCIA from 5 for 2)||''-01'' as date) as BDDATAEMISSAO, ';
  wSQL = wSQL||       '0 as BDVLRCONTAB, s.BDCODIND_NAT_RET, s.BDTIPONATREC, 0 as BDIND_DEC, ';
  wSQL = wSQL||       'null as BDCODRECPIS, null as BDCODRECCOFINS, ';
  wSQL = wSQL||       'COALESCE(s.BDVLRRETPIS, 0) as BDVLRPISRET, COALESCE(s.BDVLRRETCOFINS, 0) as BDVLRCOFINSRET ';
  wSQL = wSQL||'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||'WHERE ((s.BDVLRRETPIS > 0) or (s.BDVLRRETCOFINS > 0)) ';
  wSQL = wSQL||        'AND (s.BDCREDRETIDOS = ''TRUE'') ';
  wSQL = wSQL||        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';

  wSQL = wSQL||'UNION ALL ';

               -- Solicita??o 4962
  wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDREFAPUSALDO, aux.BDCODTER, emp.BDCNPJEMP,  ';
  wSQL = wSQL||       'aux.BDDATAEMISSAO, aux.BDVLRCONTAB, nat.BDCODIND_NAT_RET, aux.BDTIPONATREC, aux.BDIND_DEC, ';
  wSQL = wSQL||       'aux.BDCODRECPIS, aux.BDCODRECCOFINS, aux.BDVLRPISRET, aux.BDVLRCOFINSRET ';
  wSQL = wSQL||'FROM ( ';
                     -- Demais documentos
  wSQL = wSQL||      'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN as BDREFERENCIA, dem.BDREFLAN as BDREFAPUSALDO, dem.BDCODTER, indoper.BDINDICADOR,';
  wSQL = wSQL||             'dem.BDDT_OPER as BDDATAEMISSAO, dem.BDVL_OPER as BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
  wSQL = wSQL||             'ret.BDVLRPIS as BDVLRPISRET, ret.BDVLRCOFINS as BDVLRCOFINSRET,';
  wSQL = wSQL||             'case when dem.BDIND_OPER = 1 then 1 else 0 end as BDIND_DEC '; -- Aquisi??o
  wSQL = wSQL||      'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
  wSQL = wSQL||      'JOIN VEF_BASE_TAB_TIPO_OPERACAO indoper on (indoper.BDIND_OPER = dem.BDIND_OPER) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
  wSQL = wSQL||      'WHERE dem.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND (CAST(SUBSTRING(dem.BDDT_OPER FROM 1 for 4)||SUBSTRING(dem.BDDT_OPER FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
    
  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||        'AND (dem.BDCONDPGTO <> 1) ';
    
  -- Caso incid?ncia tribut?ria 2 = regime cumulativo. Sped lucro presumido somente os lan?amentos de saidas(receitas) ent?o somente os lan?amentos com tipos 1 e 2.
  IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente aquisi??o e receita n?o sujeita ao pagamento de contribui??o
    wSQL = wSQL||        'AND (dem.BDIND_OPER <> 0) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||      'UNION ALL ';
                         -- Demais documentos - Pagamentos
      wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(EMP.BDCODMATRIZ, MOV.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, indoper.BDINDICADOR,';
      wSQL = wSQL||             'pgto.BDDATAPGTOPAR as BDDATAEMISSAO,';
      wSQL = wSQL||             '((pgto.BDVALORPGTOPAR)+';
      wSQL = wSQL||              '(COALESCE(pgto.BDVALORRETPIS, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCOFINS,0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCSLL, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETIRRF, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETISSQN, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETINSS, 0))) as BDVLRCONTAB,';
      wSQL = wSQL||             'ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
      wSQL = wSQL||             'pgto.BDVALORRETPIS as BDVLRPISRET, pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||             'case when mov.BDIND_OPER = 1 then 1 else 0 end as BDIND_DEC '; -- Aquisi??o
      wSQL = wSQL||      'FROM (';
      wSQL = wSQL||            'SELECT * ';
      wSQL = wSQL||            'FROM ( ';
      wSQL = wSQL||                  'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDIND_OPER, x.BDCODCSTPIS, x.BDCODCSTCOF ';
      wSQL = wSQL||                  'FROM VEF_EMP_TMOVDEMAISDOC_F100 x ';
      wSQL = wSQL||                  'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente aquisi??o e receita n?o sujeita ao pagamento de contribui??o
        wSQL = wSQL||                   'AND (x.BDIND_OPER <> 0) ';
      wSQL = wSQL||                  ') aux ';
      wSQL = wSQL||            'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                     'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||            ') mov ';
      wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVF100PARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||      'JOIN VEF_BASE_TAB_TIPO_OPERACAO INDOPER on (indoper.BDIND_OPER = mov.BDIND_OPER) ';
      wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = mov.BDCODEMP and ret.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||      'WHERE ((mov.BDCODCSTPIS is not null) or (mov.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||        'AND (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||        'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||      'UNION ALL ';
                     -- Lan?amentos de compensa??o de reten??es de servi?os emitidos
  wSQL = wSQL||      'SELECT ret.BDCODEMP, COALESCE(emp.BDCODMATRIZ, ret.BDCODEMP) as BDCODMATRIZ, ret.BDREFERENCIA, ret.BDREFERENCIA as BDREFAPUSALDO, ret.BDCODTER, ';
  wSQL = wSQL||             '0 AS BDINDICADOR, ret.BDDATALAN AS BDDATAEMISSAO, ret.BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             '0 as BDIND_DEC ';
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT r.BDCODEMP, r.BDCODTER, r.BDREFLAN AS BDREFERENCIA, r.BDDATALAN, r.BDVLRCONTAB, r.BDCODIND_NAT_RET, r.BDCODRECPIS, ';
  wSQL = wSQL||                   'r.BDCODRECCOFINS, r.BDVLRPIS, r.BDVLRCOFINS, r.BDTIPONATREC ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVCOMPRET r ';
  wSQL = wSQL||            'WHERE r.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (CAST(SUBSTRING(r.BDDATALAN FROM 1 for 4)||SUBSTRING(r.BDDATALAN FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
  wSQL = wSQL||            ') ret ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = ret.BDCODEMP) ';

  wSQL = wSQL||      'UNION ALL ';
                     -- Servi?o
  wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFERENCIA, mov.BDREFERENCIA as BDREFAPUSALDO, mov.BDCODTER, ';
  wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, mov.BDDATAEMISSAO, mov.BDVALORNOTA AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             'case when mov.BDTIPLAN = 1 then 1 else 0 end as BDIND_DEC '; -- Recebidos
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT ser.BDCODEMP, ser.BDCHAVE, ser.BDCODTER, ser.BDDATAEMISSAO, ser.BDVALORNOTA, ser.BDTIPLAN, ser.BDREFLAN AS BDREFERENCIA ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVSER ser ';
  wSQL = wSQL||            'WHERE ser.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (ser.BDREFLAN = '||:prREFERENCIA||') ';
  wSQL = wSQL||              'AND (ser.BDCODSITNF not in (2,3,4,5)) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
  -- caso incid?ncia tribut?ria 2 = regime cumulativo, exportar somente emitidos
  IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente servi?os emitidos
    wSQL = wSQL||              'AND (ser.BDTIPLAN = 0) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||              'AND (ser.BDCONDPGTO <> 1) ';

  wSQL = wSQL||            ') mov ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSERRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||      'UNION ALL ';
     
      wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, ';
      wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, pgto.BDDATAPGTOPAR as BDDATAEMISSAO, ';
      wSQL = wSQL||             '((pgto.BDVALORPGTOPAR)+ ';
      wSQL = wSQL||              '(COALESCE(pgto.BDVALORRETPIS,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
      wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ';
      wSQL = wSQL||             'pgto.BDVALORRETPIS as BDVLRPISRET,';
      wSQL = wSQL||             'pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||             'case when mov.BDTIPLAN = 1 then 1 else 0 end as BDIND_DEC '; -- Recebidos
      wSQL = wSQL||      'FROM ( ';
      wSQL = wSQL||            'SELECT * ';
      wSQL = wSQL||            'FROM ( ';
      wSQL = wSQL||                  'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDTIPLAN, x.BDCODSITNF, x.BDDATAEMISSAO ';
      wSQL = wSQL||                  'FROM VEF_EMP_TMOVSER x ';
      wSQL = wSQL||                  'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jur?dica n?o seja 1 e 4(Sociedade cooperativa), leva somente servi?os emitidos
        wSQL = wSQL||                    'AND (x.BDTIPLAN = 0) ';
      wSQL = wSQL||                  ') aux ';
    
      wSQL = wSQL||            'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                    'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND aux.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
      wSQL = wSQL||           ') mov ';
      wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERPARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||      'WHERE (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||        'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||      'UNION ALL ';
                     -- Sa?das
  wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFERENCIA, mov.BDREFERENCIA as BDREFAPUSALDO, mov.BDCODTER, ';
  wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, mov.BDDATAEMISSAO, mov.BDVALORNOTA AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             '0 as BDIND_DEC ';
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT sai.BDCODEMP, sai.BDCHAVE, sai.BDCODTER, sai.BDDATAEMISSAO, sai.BDVALORNOTA, sai.BDTIPLAN, sai.BDREFLAN AS BDREFERENCIA ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVSAI sai ';
  wSQL = wSQL||            'WHERE sai.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (CAST(SUBSTRING(sai.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(sai.BDDATAEMISSAO FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
  wSQL = wSQL||              'AND sai.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    wSQL = wSQL||              'AND (sai.BDCONDPGTO <> 1) ';

  wSQL = wSQL||            ') mov ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSAIRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo par?metro de tipo de apura??o da empresa
    BEGIN
      wSQL = wSQL||            'UNION ALL ';
    
      wSQL = wSQL||            'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, ';
      wSQL = wSQL||                   'mov.BDTIPLAN AS BDINDICADOR, pgto.BDDATAPGTOPAR as BDDATAEMISSAO, ';
      wSQL = wSQL||                   '((pgto.BDVALORPGTOPAR)+ ';
      wSQL = wSQL||                    '(COALESCE(pgto.BDVALORRETPIS,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
      wSQL = wSQL||                   'ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
      wSQL = wSQL||                   'pgto.BDVALORRETPIS as BDVLRPISRET,';
      wSQL = wSQL||                   'pgto.BDVALORRETCOFINS as BDVLRCOFINSRET,';
      wSQL = wSQL||                   '0 as BDIND_DEC ';
      wSQL = wSQL||             'FROM ( ';
      wSQL = wSQL||                   'SELECT * ';
      wSQL = wSQL||                   'FROM ( ';
      wSQL = wSQL||                          'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDTIPLAN, x.BDCODSITNF, x.BDDATAEMISSAO ';
      wSQL = wSQL||                          'FROM VEF_EMP_TMOVSAI x ';
      wSQL = wSQL||                          'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                         ') aux ';
      wSQL = wSQL||                   'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e ';
      wSQL = wSQL||                           'WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||                     'AND aux.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para n?o exportar documentos cancelados...
    
      wSQL = wSQL||                 ') mov ';
      wSQL = wSQL||            'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIPARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||            'WHERE (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      wSQL = wSQL||              'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
    END

  wSQL = wSQL||    ') aux ';
  wSQL = wSQL||'JOIN TEMPRESAS emp on (aux.BDCODEMP = emp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TIND_NAT_RET nat on (nat.BDCODIND_NAT_RET = aux.BDCODIND_NAT_RET) ';
  wSQL = wSQL||'LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.BDCODTER = aux.BDCODTER) ';
  wSQL = wSQL||'WHERE (nat.BDREGEXP in (''01'',''02'',''03'',''04'',''05'',''99'')) ';
  wSQL = wSQL||' AND (CHAR_LENGTH(ter.BDCGCTER) >= 18) ';
  --wSQL = wSQL||'ORDER BY aux.BDCODMATRIZ, aux.BDCODEMP ';

  EXECUTE STATEMENT ( wSQL );

  -- REGISTRO F600: CONTRIBUI??O RETIDA NA FONTE
  INSERT INTO VEF_EMP_TBLOCOMF600 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODREC, BDCODIND_NAT_RET, BDDT_RET, BDVL_BC_RET, BDVL_RET, BDCNPJPART, BDNOMEPART, BDVL_RET_PIS, BDVL_RET_COFINS, BDIND_DEC, BDIND_NAT_REC)
  SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOMF600 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = aux.BDCODMATRIZ AND x.BDCODQUADRO = 48 AND x.BDREFERENCIA = aux.BDREFERENCIA) AS BDCHAVE,
         aux.BDCODREC,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN aux.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE aux.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         aux.BDCODIND_NAT_RET,
         aux.BDDT_RET,
         SUM(aux.BDVL_BC_RET) AS BDVL_BC_RET, SUM(aux.BDVL_RET) AS BDVL_RET,
         ter.BDCGCTER AS BDCNPJPART, ter.BDNOME AS BDNOMEPART,
         SUM(aux.BDVL_RET_PIS) AS BDVL_RET_PIS, SUM(aux.BDVL_RET_COFINS) AS BDVL_RET_COFINS,
         aux.BDIND_DEC, aux.BDCOD_NAT_REC AS BDIND_NAT_REC
  FROM (-- PIS
        SELECT 48 AS BDCODQUADRO, 7 AS BDCODPERIODO,
               tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODTER, tmp.BDCODRECPIS AS BDCODREC, tmp.BDCODIND_NAT_RET, tmp.BDDATAEMISSAO AS BDDT_RET,
               tmp.BDVLRCONTAB AS BDVL_BC_RET, tmp.BDVLRPISRET AS BDVL_RET, tmp.BDVLRPISRET AS BDVL_RET_PIS, 0 AS BDVL_RET_COFINS, tmp.BDIND_DEC, tmp.BDCOD_NAT_REC
        FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
        WHERE tmp.BDCODRECPIS IS NOT NULL
          AND tmp.BDVLRPISRET IS NOT NULL
          AND tmp.BDCODMATRIZ = :prCODEMP
          AND tmp.BDREFERENCIA = :prREFERENCIA
        UNION ALL
        -- COFINS
        SELECT 48 AS BDCODQUADRO, 7 AS BDCODPERIODO,
               tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODTER, tmp.BDCODRECCOFINS AS BDCODREC, tmp.BDCODIND_NAT_RET, tmp.BDDATAEMISSAO AS BDDT_RET,
               IIF((tmp.BDCODRECPIS = tmp.BDCODRECCOFINS), 0, tmp.BDVLRCONTAB) AS BDVL_BC_RET, -- Caso seja mesmo c?digo de receita, j? trouxe o valor no PIS, da? n?o soma novamente aqui...
               tmp.BDVLRCOFINSRET AS BDVL_RET, 0 AS BDVL_RET_PIS, tmp.BDVLRCOFINSRET AS BDVL_RET_COFINS, tmp.BDIND_DEC, tmp.BDCOD_NAT_REC
        FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
        WHERE tmp.BDCODRECCOFINS IS NOT NULL
          AND tmp.BDVLRCOFINSRET IS NOT NULL
          AND tmp.BDCODMATRIZ = :prCODEMP
          AND tmp.BDREFERENCIA = :prREFERENCIA
        ) aux
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.BDCODTER = aux.BDCODTER)
  WHERE aux.BDCODMATRIZ = :prCODEMP
    AND aux.BDREFERENCIA = :prREFERENCIA
  GROUP BY aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODREC,
           aux.BDCODIND_NAT_RET, aux.BDDT_RET, aux.BDIND_DEC, aux.BDCOD_NAT_REC, ter.BDCGCTER, ter.BDNOME;

  /* Saldos de reten??es de per?odos anteriores */
  --IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Verifica o par?metro "Aproveitar AS reten??es de PIS e Cofins de per?odos anteriores", caso n?o esteja habilita, apenas busca a reten??o atual...
    BEGIN 
      -- REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
      -- REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS
      INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
      SELECT ant.BDCODQUADRO, ant.BDCODPERIODO, ant.BDCODEMP, ant.BDCODMATRIZ, :prREFERENCIA as BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1)
              FROM VEF_EMP_TBLOCOM1300_1700 x
              WHERE x.BDCODPERIODO = ant.BDCODPERIODO
                AND x.BDCODEMP = ant.BDCODEMP
                AND x.BDCODMATRIZ = ant.BDCODMATRIZ
                AND x.BDCODQUADRO = ant.BDCODQUADRO
                AND x.BDREFERENCIA = :prREFERENCIA ) AS BDCHAVE,
             ant.BDCODIND_NAT_RET, ant.BDCOD_NAT_REC, ant.BDPR_REC_RET, ant.BDSLD_RET as BDVL_RET_APU, 0 as BDVL_RET_DED, 0 as BDVL_RET_PER, 0 as BDVL_RET_DCOMP, ant.BDSLD_RET as BDSLD_RET
      FROM VEF_EMP_TBLOCOM1300_1700 ant
      WHERE ant.BDSLD_RET > 0
        AND ant.BDCODMATRIZ = :prCODEMP
        AND ant.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA
                                FROM VEF_EMP_TBLOCOM1300_1700 x
                                WHERE x.BDCODMATRIZ = :prCODEMP
                                  AND x.BDREFERENCIA < :prREFERENCIA
                                  AND x.BDCODPERIODO = 7
                                ORDER BY x.BDREFERENCIA DESC);
    END

  -- REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE ? PIS/PASEP
  INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
  SELECT 49 AS BDCODQUADRO, 7 AS BDCODPERIODO,
         tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM1300_1700 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDCODQUADRO = 49 AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCHAVE,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN tmp.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE tmp.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         tmp.BDCODIND_NAT_RET,
         tmp.BDCOD_NAT_REC,
         --(CAST(SUBSTRING(tmp.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(tmp.BDDATAEMISSAO FROM 6 for 2) AS INTEGER)) AS BDPR_REC_RET,
         tmp.BDREFAPUSALDO AS BDPR_REC_RET,
         SUM(COALESCE(tmp.BDVLRPISRET, 0)) AS BDVL_RET_APU,
         0 AS BDVL_RET_DED,
         0 AS BDVL_RET_PER, 0 AS BDVL_RET_DCOMP, SUM(COALESCE(tmp.BDVLRPISRET,0)) AS BDSLD_RET
  FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
  WHERE tmp.BDCODMATRIZ = :prCODEMP
    AND tmp.BDREFERENCIA = :prREFERENCIA
    AND tmp.BDVLRPISRET > 0
  GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODIND_NAT_RET, tmp.BDCOD_NAT_REC, tmp.BDDATAEMISSAO, tmp.BDREFAPUSALDO;

  -- REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE ? COFINS
  INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET)
  SELECT 50 AS BDCODQUADRO, 7 AS BDCODPERIODO,
         tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM1300_1700 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDCODQUADRO = 50 AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCHAVE,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN tmp.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribit?ria 3, faz a troca da natureza da reten??o...
--             CASE tmp.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                  THEN 7  -- 51 - Reten??o por ?rg?os, Autarquias e Funda??es Federais
--                WHEN 2 -- 02 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                  THEN 8  -- 52 - Reten??o por outras Entidades da Administra??o P?blica Federal
--                WHEN 3 -- 03 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                  THEN 9  -- 53 - Reten??o por Pessoas Jur?dicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Reten??o por Fabricante de M?quinas e Ve?culos
--                  THEN 11 -- 55 - Reten??o por Fabricante de M?quinas e Ve?culos
--                WHEN 6 -- 99 - Outras Reten??es - Rendimentos sujeitos ? regra geral de incid?ncia (n?o cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Reten??es - Rendimentos sujeitos ? regra espec?fica de incid?ncia cumulativa (art. 8? da Lei n? 10.637/2002 e art. 10 da Lei n? 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         tmp.BDCODIND_NAT_RET,
         tmp.BDCOD_NAT_REC,
         --(CAST(SUBSTRING(tmp.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(tmp.BDDATAEMISSAO FROM 6 for 2) AS INTEGER)) AS BDPR_REC_RET,
         tmp.BDREFAPUSALDO AS BDPR_REC_RET,
         SUM(COALESCE(tmp.BDVLRCOFINSRET,0)) AS BDVL_RET_APU,
         0 AS BDVL_RET_DED,
         0 AS BDVL_RET_PER, 0 AS BDVL_RET_DCOMP, SUM(COALESCE(tmp.BDVLRCOFINSRET,0)) AS BDSLD_RET
  FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
  WHERE tmp.BDCODMATRIZ = :prCODEMP
    AND tmp.BDREFERENCIA = :prREFERENCIA
    AND tmp.BDVLRCOFINSRET > 0
  GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODIND_NAT_RET, tmp.BDCOD_NAT_REC, tmp.BDDATAEMISSAO, tmp.BDREFAPUSALDO;

END
^

/* Alter (SP_APURACAO_BLOCOM_M100) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WMETODOAPRO INTEGER;
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,4);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configura??o da empresa na refer?ncia da apura??o...
  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDMETODOAPRO+1 -- M?todo de apropria??o
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 1
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 2
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMNTMI;

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 3
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMEXP;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      /* REGISTRO M100: CR?DITO DE PIS/PASEP RELATIVO AO PER?ODO */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM100_500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDIND_CRED_ORI, BDVL_BC, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CRED,';
      wSQL = wSQL||                                    'BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CRED_DIF, BDVL_CRED_DISP, BDIND_DESC_CRED, BDVL_CRED_DESC, BDSLD_CRED) ';
      wSQL = wSQL||'SELECT 11 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7) AS BDCHAVE,';
      wSQL = wSQL||       't436.BDCODCRE_4_3_6, 0 AS BDIND_CRED_ORI, SUM(COALESCE(tmp.BDBCPIS,0)) AS BDVL_BC, COALESCE(tmp.BDALIQPIS,0) AS BDALIQ,';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC, COALESCE(tmp.BDALIQPIS_QUANT,0) AS BDALIQ_QUANT,';
      wSQL = wSQL||       '(((SUM(COALESCE(tmp.BDBCPIS,0))*COALESCE(tmp.BDALIQPIS,1))/100)+(SUM(COALESCE(tmp.BDBCPIS_QUANT,0))*COALESCE(tmp.BDALIQPIS_QUANT,1))) AS BDVL_CRED,';
      wSQL = wSQL||       '0 AS BDVL_AJUS_ACRES, 0 AS BDVL_AJUS_REDUC, 0 AS BDVL_CRED_DIF, 0 AS BDVL_CRED_DISP,';
      wSQL = wSQL||       'NULL AS BDIND_DESC_CRED, 0 AS BDVL_CRED_DESC, 0 AS BDSLD_CRED ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED,';
      wSQL = wSQL||             'x.BDALIQPIS,';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT,';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT,';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED,';
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||            'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100  AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCPIS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
          wSQL = wSQL||             'x.BDCOD_CRED as BDCOD_CRED,';
          wSQL = wSQL||             'x.BDBCPIS ';
        END
      wSQL = wSQL||             'AS BDBCPIS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTPIS and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';
      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCPIS > 0) OR (tmp.BDBCPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQPIS > 0) OR (tmp.BDALIQPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ')';
      wSQL = wSQL||       ') ';
      --wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, t436.BDCODCRE_4_3_6, tmp.BDALIQPIS, tmp.BDALIQPIS_QUANT; ';

      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M105: DETALHAMENTO DA BASE DE CALCULO DO CR?DITO APURADO NO PER?ODO ? PIS/PASEP */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM105_M505 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCSTPIS, BDCODCSTCOF, BDCODNATBC, BDCODCRE_4_3_6,';
      wSQL = wSQL||                                     'BDVL_BC_TOT, BDVL_BC_CUM, BDVL_BC_NC, BDVL_BC, BDQUANT_BC_TOT, BDQUANT_BC, BDDESC_CRED, BDALIQ) ';
      wSQL = wSQL||'SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 11 AS BDCODQUADRO, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQPIS) OR (x.BDALIQ_QUANT = tmp.BDALIQPIS_QUANT))) AS BDCHAVE,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDORDEM)+1,1)';
      wSQL = wSQL||        'FROM VEF_EMP_TBLOCOM105_M505 x ';
      wSQL = wSQL||        'WHERE x.BDCODPERIODO = 7 ';
      wSQL = wSQL||          'AND x.BDCODEMP = tmp.BDCODEMP ';
      wSQL = wSQL||          'AND x.BDCODMATRIZ = tmp.BDCODMATRIZ ';
      wSQL = wSQL||          'AND x.BDCODQUADRO = 11 ';
      wSQL = wSQL||          'AND x.BDREFERENCIA = tmp.BDREFERENCIA ';
      wSQL = wSQL||          'AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 ';
      wSQL = wSQL||          'AND x.BDALIQ = COALESCE(tmp.BDALIQPIS,tmp.BDALIQPIS_QUANT) ';
      wSQL = wSQL||          'AND x.BDCHAVE = (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 11 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQPIS) OR (x.BDALIQ_QUANT = tmp.BDALIQPIS_QUANT))) ';
      wSQL = wSQL||        ') AS BDORDEM, ';
      wSQL = wSQL||       'tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED AS BDCODNATBC, t436.BDCODCRE_4_3_6, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPISTOTAL,0)) AS BDVL_BC_TOT, 0 AS BDVL_BC_CUM, /*(Campo 04 ? Campo 05)*/SUM(COALESCE(tmp.BDBCPISTOTAL,0)-0) AS BDVL_BC_NC, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCPIS,0)) AS BDVL_BC, SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC_TOT,  SUM(COALESCE(tmp.BDBCPIS_QUANT,0)) AS BDQUANT_BC, NULL AS BDDESC_CRED, COALESCE(tmp.BDALIQPIS,tmp.BDALIQPIS_QUANT,0) AS BDALIQ ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED, ';
      wSQL = wSQL||             'x.BDALIQPIS, x.BDBCPIS as BDBCPISTOTAL, ';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT, ';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT, ';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED,';
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||            'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100  AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCPIS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCPIS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCPIS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
          wSQL = wSQL||             'x.BDCOD_CRED as BDCOD_CRED, ';
          wSQL = wSQL||             'x.BDBCPIS ';
        END
      wSQL = wSQL||             'AS BDBCPIS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTPIS and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';
      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCPIS > 0) OR (tmp.BDBCPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQPIS > 0) OR (tmp.BDALIQPIS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED, t436.BDCODCRE_4_3_6, tmp.BDALIQPIS, tmp.BDALIQPIS_QUANT; ';

      EXECUTE STATEMENT ( wSQL );
   
      /* REGISTRO M110: AJUSTES DO CR?DITO DE PIS/PASEP APURADO */
      INSERT INTO VEF_EMP_TBLOCOM110_M510 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, BDDESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) as BDCODMATRIZ, 11 as BDCODQUADRO, m.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = m.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) AND x.BDCODQUADRO = 11 AND x.BDREFERENCIA = m.BDREFERENCIA AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6 AND ((x.BDALIQ = m.BDALIQPIS) OR (x.BDALIQ_QUANT = m.BDALIQPIS))) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM+1),1)
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 11
                AND x.BDCODEMP = m.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                AND x.BDREFERENCIA = m.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM100_500 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODQUADRO = 11 
                                   AND x.BDCODEMP = m.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                                   AND x.BDREFERENCIA = m.BDREFERENCIA
                                   AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                                   AND ((x.BDALIQ = m.BDALIQPIS) OR (x.BDALIQ_QUANT = m.BDALIQPIS))) ) as BDORDEM,
             m.BDCODAJUEFDC, m.BDTIPOAJUSTE as BDIND_AJ, SUM(m.BDVLRAJUPIS) as BDVL_AJ, m.BDNUMERODOC as BDNUM_DOC, m.BDDESCRICAO as BDDESCR_AJ, m.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TCREDAJU_M110_M510 m
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m.BDCODEMP)
      WHERE m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM100_500 m100
                    WHERE m100.BDCODPERIODO = 7
                      AND m100.BDCODQUADRO = 11
                      AND m100.BDCODEMP = m.BDCODEMP
                      AND m100.BDREFERENCIA = m.BDREFERENCIA
                      AND m100.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND ((m100.BDALIQ = m.BDALIQPIS) OR (m100.BDALIQ_QUANT = m.BDALIQPIS)) ))
      GROUP BY m.BDCODEMP, emp.BDCODMATRIZ, m.BDREFERENCIA, m.BDCODAJUEFDC, m.BDTIPOAJUSTE, m.BDNUMERODOC, m.BDDESCRICAO, m.BDDATAREF, m.BDCODCRE_4_3_6, m.BDALIQPIS;
   
      /* REGISTRO M115: DETALHAMENTO DOS AJUSTES DO CR?DITO DE PIS/PASEP APURADO */
      INSERT INTO VEF_EMP_TBLOCOM115_M515 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM15, BDCODCSTCOF, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m115.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP) as BDCODMATRIZ, 11 as BDCODQUADRO, m110.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDCODQUADRO = 11
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDNUM_DOC = m110.BDNUMERODOC
                AND x.BDDESCR_AJ = m110.BDDESCRICAO
                AND x.BDDT_REF = m110.BDDATAREF ) as BDCHAVE,
             (SELECT x.BDORDEM
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDCODQUADRO = 11
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDNUM_DOC = m110.BDNUMERODOC
                AND x.BDDESCR_AJ = m110.BDDESCRICAO
                AND x.BDDT_REF = m110.BDDATAREF ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM15+1),1)
              FROM VEF_EMP_TBLOCOM115_M515 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 11
                AND x.BDCODEMP = m115.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m115.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                                   AND x.BDCODQUADRO = 11
                                   AND x.BDREFERENCIA = m110.BDREFERENCIA
                                   AND x.BDNUM_DOC = m110.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m110.BDDESCRICAO
                                   AND x.BDDT_REF = m110.BDDATAREF)
                AND x.BDORDEM = (SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m115.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                                   AND x.BDCODQUADRO = 11
                                   AND x.BDREFERENCIA = m110.BDREFERENCIA
                                   AND x.BDNUM_DOC = m110.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m110.BDDESCRICAO
                                   AND x.BDDT_REF = m110.BDDATAREF) ) as BDORDEM15,
             m115.BDCODCSTCOF, m115.BDCODCSTPIS, m115.BDCODPLAPADRAO, m115.BDCODTPLA, SUM(m110.BDVLRAJUPIS) as BDDET_VALOR_AJ, SUM(m115.BDBCPIS) as BDDET_BC_CRED,
             m115.BDALIQPIS as BDDET_ALIQ, m115.BDDATAOPEPIS as BDDT_OPER_AJ, m115.BDDESCRICAOAJU as BDDESC_AJ, m115.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TCREDAJU_M110_M510 m110
      JOIN VEF_EMP_TDETAJU_M115_M515 m115 on (m115.BDCODEMP = m110.BDCODEMP AND m115.BDCHAVE = m110.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m110.BDCODEMP)
      WHERE m115.BDCODEMP IS NOT NULL
        AND m115.BDBCPIS > 0
        AND m110.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m110.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM110_M510 x
                    WHERE x.BDCODPERIODO = 7
                      AND x.BDCODEMP = m115.BDCODEMP
                      AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)
                      AND x.BDCODQUADRO = 11
                      AND x.BDREFERENCIA = m110.BDREFERENCIA
                      AND x.BDNUM_DOC = m110.BDNUMERODOC
                      AND x.BDDESCR_AJ = m110.BDDESCRICAO
                      AND x.BDDT_REF = m110.BDDATAREF ))
      GROUP BY m115.BDCODEMP, emp.BDCODMATRIZ, m110.BDREFERENCIA, m110.BDCODCRE_4_3_6,  m115.BDCODCSTCOF, m115.BDCODCSTPIS, m115.BDCODPLAPADRAO, m115.BDCODTPLA,
               m115.BDALIQPIS, m115.BDDATAOPEPIS, m115.BDDESCRICAOAJU, m115.BDINFCOMP,
               m110.BDNUMERODOC, m110.BDDESCRICAO, m110.BDDATAREF;
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M100_M500AUX) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WMOD_COMTELE VARCHAR(10);
DECLARE VARIABLE WMOD_ENERGAS VARCHAR(10);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
DECLARE VARIABLE WMOD_PROD VARCHAR(50);
DECLARE VARIABLE wMOD_COD_CRED_8 VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
-- Concatena todos os modelos anteriores, usar "NOT IN"...
wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;
-- Modelos que geram "Tipo de Cr?dito" com final 8, exporta??o...
wMOD_COD_CRED_8 = '1,100,4,55,65';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDCODCRIT    -- Crit?rio de escritura??o (cumulativo)
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR (:prCODEMP, :prREFERENCIA, :prWHEREEMPRESAS);

      wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M100_M500 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDPREFIXONAT, BDVL_ITEM, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCPIS_QUANT, BDALIQPIS_QUANT, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT, BDNAT_BC_CRED, BDCOD_CRED) ';

      wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDPREFIXONAT, aux.BDVL_ITEM, aux.BDCODCTA, aux.BDCODCSTPIS, aux.BDBCPIS,';
      wSQL = wSQL||       'aux.BDALIQPIS, aux.BDVLRPIS, aux.BDBCPIS_QUANT, aux.BDALIQPIS_QUANT, aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, aux.BDBCCOFINS_QUANT, aux.BDALIQCOFINS_QUANT, ';
      wSQL = wSQL||       'aux.BDNAT_BC_CRED,';

      wSQL = wSQL||       'Coalesce(aux.BDCOD_CRED,';
      wSQL = wSQL||                '(CASE WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 108 '; -- 108 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 208 '; -- 208 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 201 '; -- 201 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 202 '; -- 202 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
 
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 308 '; -- 308 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 301 '; -- 301 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 302 '; -- 302 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
 
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 202 '; -- 202 - Quando for al?quota diferente da b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 301 '; -- 301 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for al?quota b?sica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 302 '; -- 302 - Quando for aliquota for diferente da basica.  Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for al?quota for diferente da  b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 208 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da segunda linhar e calcular somente o credito referente a este percentual
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 202 '; -- 202 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando ? usado CFOP do exterior que tem cr?dito. E a empresa usa rateio para este c?digo deve ser verificado o percentual relativo a primeira linha do 0111 com rela??o a ultima e calcular o montante do cr?dito da CFOP do exterior com CST 56 para este c?digo.
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 60) OR (aux.BDCODCSTCOF = 60)) THEN 106 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 61) OR (aux.BDCODCSTCOF = 61)) THEN 206 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 62) OR (aux.BDCODCSTCOF = 62)) THEN 306 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 63) OR (aux.BDCODCSTCOF = 63)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 64) OR (aux.BDCODCSTCOF = 64)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 65) OR (aux.BDCODCSTCOF = 65)) THEN 206 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
      wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 66) OR (aux.BDCODCSTCOF = 66)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

      wSQL = wSQL||                 'else NULL end)';
      wSQL = wSQL||               ') AS BDCOD_CRED ';
      wSQL = wSQL||'FROM ( ';
                          /* Entradas - Produtos */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 1 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'p.BDVLRITEM AS BDVL_ITEM, p.BDCODCTA, p.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||              'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                'AND (e.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROENT p on (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'WHERE p.BDCODPROD is not null ';
      wSQL = wSQL||         'AND ((p.BDCODCSTPIS is not null) OR (p.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Servi?o de comunica??o e telecomunica??o (D500) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, d500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'd500.BDVLRSER AS BDVL_ITEM, d500.BDCODCTA, d500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'd500.BDCODCSTPIS, d500.BDVL_BC_PIS AS BDBCPIS, d500.BDALIQ_PIS AS BDALIQPIS, d500.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'd500.BDCODCSTCOF, d500.BDVL_BC_COF AS BDBCCOFINS, d500.BDALIQ_COF AS BDALIQCOFINS, d500.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_COMTELE||')) '; -- Servi?o de comunica??o e telecomunica??o
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||               'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||               'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = mov.BDCODEMP AND d500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE d500.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((d500.BDCODCSTPIS is not null) OR (d500.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'c500.BDVLRCONSFOR AS BDVL_ITEM, NULL AS BDCODCTA, c500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'c500.BDCODCSTPIS, c500.BDVL_BC_PIS AS BDBCPIS, c500.BDALIQ_PIS AS BDALIQPIS, c500.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'c500.BDCODCSTCOF, c500.BDVL_BC_COF AS BDBCCOFINS, c500.BDALIQ_COF AS BDALIQCOFINS, c500.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_ENERGAS||')) '; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||            ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = mov.BDCODEMP AND c500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE c500.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((c500.BDCODCSTPIS is not null) OR (c500.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Entradas - Transporte (D100) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, d100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'mov.BDVALORNOTA AS BDVL_ITEM, d100.BDCODCTA, d100.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||             'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDVALORNOTA, e.BDMODELO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE d100.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((d100.BDCODCSTPIS is not null) OR (d100.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';
                          /* Demais documentos */
      wSQL = wSQL||       'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN AS BDREFERENCIA, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
      wSQL = wSQL||              'dem.BDVL_OPER AS BDVL_ITEM, NULL AS BDCODCTA, dem.BDNAT_BC_CRED, ';
      wSQL = wSQL||              'CASE WHEN ((dem.BDCODCSTPIS = 60) or (dem.BDCODCSTCOF = 60)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 61) or (dem.BDCODCSTCOF = 61)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 62) or (dem.BDCODCSTCOF = 62)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 307 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 63) or (dem.BDCODCSTCOF = 63)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 64) or (dem.BDCODCSTCOF = 64)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 65) or (dem.BDCODCSTCOF = 65)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||                   'WHEN ((dem.BDCODCSTPIS = 66) or (dem.BDCODCSTCOF = 66)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||              'ELSE NULL ';
      wSQL = wSQL||              'END AS BDCOD_CRED,';
      wSQL = wSQL||              'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM  VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||       'WHERE ((dem.BDCODCSTPIS is not null) OR (dem.BDCODCSTCOF is not null)) ';
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||         'AND (dem.BDIND_OPER <> 1) '; -- Opera??o Representativa de Aquisi??o...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||         'AND (dem.BDCONDPGTO <> 1) ';
      wSQL = wSQL||           'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND dem.BDREFLAN = '||:prREFERENCIA||' ';

      wSQL = wSQL||       'union all ';
                          /* Servi?os tomados(Recebidos), tipolan = 1 */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL as BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'a.BDVL_ITEM, NULL AS BDCODCTA, a.BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
      wSQL = wSQL||              'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||                'AND (s.BDTIPLAN = 0) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TA170 a on (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'WHERE a.BDCODPROD is not null ';
      wSQL = wSQL||         'AND ((a.BDCODCSTPIS is not null) OR (a.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT bem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, bem.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA,';
      wSQL = wSQL||               'bem.BDCODBEM AS BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
--Sol. 22905 Gabriel Ariel (27/02/2018) - Buscar primeiro o valor da depreciacao
      wSQL = wSQL||                'bem.BDVL_ITEM, ';
      wSQL = wSQL||                'bem.BDCODTPLA AS BDCODCTA,';

      wSQL = wSQL||               'CASE bem.BDTIPOAPROCRED ';
      wSQL = wSQL||                 'WHEN 0 THEN ''10'' ';
      wSQL = wSQL||                 'WHEN 1 THEN ''09'' ';
      wSQL = wSQL||                 'WHEN 2 THEN ''11'' ';
      wSQL = wSQL||               'end AS BDNAT_BC_CRED, ';

      wSQL = wSQL||               'case ';
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 50) or (bem.BDCODCSTCOF = 50)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 51) or (bem.BDCODCSTCOF = 51)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 203 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 52) or (bem.BDCODCSTCOF = 52)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 303 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 53) or (bem.BDCODCSTCOF = 53)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 54) or (bem.BDCODCSTCOF = 54)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 55) or (bem.BDCODCSTCOF = 55)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 203 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 56) or (bem.BDCODCSTCOF = 56)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  -- Tipo de apropria??o: 1 - Valor de aquisi??o / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||               'else 101 ';
      wSQL = wSQL||               'end as BDCOD_CRED, ';

      wSQL = wSQL||               'bem.BDCODCSTPIS,';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDBCPIS,';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, bem.BDALIQPIS) AS BDALIQPIS,'; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)

      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDVLRPIS, ';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM), NULL)) AS BDBCPIS_QUANT, ';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), bem.BDALIQPIS, NULL) AS BDALIQPIS_QUANT,';
      wSQL = wSQL||               'bem.BDCODCSTCOF,';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) AS BDBCCOFINS,';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, bem.BDALIQCOFINS) AS BDALIQCOFINS,'; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)

      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDVLRCOFINS, ';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), '; -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM), NULL)) as BDBCCOFINS_QUANT, ';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), bem.BDALIQCOFINS, NULL) AS BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT tbem.*, ';
      wSQL = wSQL||                'coalesce((select cast(coalesce(PRDEPRECIACAOPERIODO, 0) as numeric(15,2)) PRDEPRECIACAOPERIODO ';
      wSQL = wSQL||                           'from SP_CONS_CALC_DEP('||:PRCODEMP||', TBEM.BDCODBEM, (substring('||:prREFERENCIA||' from 5 for 2) || ''/01/'' || substring('||:prREFERENCIA||' from 1 for 4)), (substring('||:prREFERENCIA||' from 5 for 2) || ''/'' ||(select ULTDIA ';
      wSQL = wSQL||                                                                                                                                                                                                ' from ULTIMO_DIA_MES(cast(substring('||:prREFERENCIA||' from 5 for 2) as integer), cast(substring('||:prREFERENCIA||' from 1 for 4) as integer))) || ''/'' || substring('||:prREFERENCIA||' from 1 for 4)), 0, 0) ';
      wSQL = wSQL||                           'where exists (select dep.bdcodemp from EMPRESAS_TDEPRECIACAO dep where dep.bdcodemp = TBEM.BDCODEMP and dep.bdcodbem = TBEM.BDCODBEM) and TBEM.BDTIPOAPROCRED <> 0), ';
--      wSQL = wSQL||                           'where PRDEPRECIACAOPERIODO > 0), ';
      wSQL = wSQL||               '(case TBEM.BDTIPOAPROCRED ';
      wSQL = wSQL||                  'when 0 then (TBEM.BDBCCALC/COALESCE(case Tbem.BDCODNRPARC '; -- F130 n?o deve abater a exclus?o
      wSQL = wSQL||                                                               'when 0 then 1 ';  -- 1 - Integral
      wSQL = wSQL||                                                               'when 1 then 12 '; -- 2 - 12 Meses
      wSQL = wSQL||                                                               'when 2 then 24 '; -- 3 - 24 Meses
      wSQL = wSQL||                                                               'when 3 then 48 '; -- 4 - 48 Meses
      wSQL = wSQL||                                                               'when 4 then 6 ';  -- 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                                                         'when 5 then COALESCE(Tbem.BDNUMPARC, 1) '; -- 9 - Outra periodicidade definida em Lei. #OBS.: Nesses casos pega o n?mero de parcelas do campo "Quantidade" da aba EFD - PIS/Cofins
      wSQL = wSQL||                                                             'end, 1)) ';
      wSQL = wSQL||                  'else (TBEM.BDBCCALC)-(Tbem.BDEXCBASE/COALESCE(Tbem.BDNUMPARC,1)) '; -- F120 deve abater a exclus?o
      wSQL = wSQL||                  'end)) as BDVL_ITEM ';
      wSQL = wSQL||              'FROM (SELECT TBEM.*, ';     
  --Sol. 22905 - Faz a proporcao para o primeiro e ultimo mes, que depender? dos par?metros do bem
      wSQL = wSQL||               'CASE WHEN ((BDDEPDIARIA = ''TRUE'') and (TBEM.BDTIPOAPROCRED <> 0)) THEN CASE WHEN ('||:PRREFERENCIA||' = extract(year from BDDTINI) || LPAD(extract(month from BDDTINI),2,''0'')) then cast(cast(TBEM.BDBASECALC * (iif(BDNUMDIAS <= 1, 30, (select ULTDIA  from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) - iif((BDNUMDIAS <= 1) and ((extract(day from BDDTINI) ) > 30), 30, (extract(day from BDDTINI) ))) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) as numeric(15,2))';
      wSQL = wSQL||               '                                                                              WHEN ('||:PRREFERENCIA||' = extract(year from BDDTFIM) || LPAD(extract(month from BDDTFIM),2,''0'')) then cast(cast(TBEM.BDBASECALC * (iif((BDNUMDIAS <= 1) and (extract(day from BDDTFIM) > 30), 30, extract(day from BDDTFIM) )) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTFIM), extract(year from BDDTFIM)))) as numeric(15,2))';
      wSQL = wSQL||               '                                                                         ELSE TBEM.BDBASECALC ';
      wSQL = wSQL||               '                                         END ';
      wSQL = wSQL||               '     ELSE TBEM.BDBASECALC ';
      wSQL = wSQL||               'END BDBCCALC ';
      wSQL = wSQL||                'FROM (SELECT TBEM.*, ';           
  --Sol. 22905 - Pega a data da primeira e ultima parcela, para verificar se o bem est? no primeiro ou ?ltimo m?s, onde o c?lculo ? diferente
      wSQL = wSQL||                    'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end))BDDTFIM,';
      wSQL = wSQL||                    'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end))BDDTINI ';
      Wsql = wSQL||                 'FROM EMPRESAS_TBEM tbem ';
      wSQL = wSQL||                'WHERE tbem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND ((tbem.BDCODCSTPIS is not null) OR (tbem.BDCODCSTCOF is not null)) ';
                                   -- sol:15691 - deve trazer os registros sem data de baixa OU
                                   --             (se tiver baixa) todos que a baixa seja posterior ao periodo de apura??o OU
                                   --             (se a baixa for menor que a data final da apura??o) os registros em que o mes da baixa seja igual ao da apura??o E estiver parametrizado para depreciar no mes da baixa
      wSQL = wSQL||                'AND ((tbem.BDDATABAIXA is null) OR ';
      wSQL = wSQL||                     '(Cast(SubString(tbem.BDDATABAIXA FROM 1 for 4)||SubString(tbem.BDDATABAIXA FROM 6 for 2) AS Integer) > '||:prREFERENCIA||') OR ';
      wSQL = wSQL||                     '((tbem.BDDEPMESBAIXABEM = ''TRUE'') AND (LPAD(EXTRACT(MONTH FROM tbem.BDDATABAIXA), 2, ''0'') = SubString('||:prREFERENCIA||' FROM 5 for 2)) AND ';
      wSQL = wSQL||                      '(tbem.BDTIPOAPROCRED <> 0))) '; -- sol:15691 - n?o levar no mes da baixa se for bdtipoaprocred = 0(10), que ? do F130
                                   -- sol:15691 - obedecer o parametro BDDEPMESAQUIBEM que diz se deve depreciar no mes da aquisi??o ou no pr?ximo
      wSQL = wSQL||                'AND (';
      wSQL = wSQL||                     '(Cast(SubString((CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC - 1 + 1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end) FROM 1 for 4)||';
      wSQL = wSQL||                           'SubString((CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC - 1 + 1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end) FROM 6 for 2) AS Integer) >= '||:prREFERENCIA||') AND ';
      wSQL = wSQL||                     '((Cast(SubString((CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end) FROM 1 for 4)||';
      wSQL = wSQL||                            'SubString((CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end) FROM 6 for 2) AS Integer) <= '||:prREFERENCIA||')) ';
      wSQL = wSQL||                     ') ';
                                   -- sol:15653 - somente se cst for diferente de 70
      wSQL = wSQL||                'AND (tbem.BDCODCSTPIS <> 70) AND (tbem.BDCODCSTCOF <> 70) ';
      wSQL = wSQL||              ')TBEM ';
      wSQL = wSQL||           ')TBEM ';
      wSQL = wSQL||             ') bem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = bem.BDCODEMP) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, (cast(substring(pgto.BDDATAPGTO FROM 1 for 4)||substring(pgto.BDDATAPGTO FROM 6 for 2) AS integer)) AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, pgto.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVLRTOTRECPAR AS BDVL_ITEM, NULL AS BDCODCTA, 109 AS BDNAT_BC_CRED, 109 AS BDCOD_CRED,';
      wSQL = wSQL||              'f205.BDCODCSTPIS, f205.BDBASEPIS AS BDBCPIS, f205.BDALIQPIS, f205.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'f205.BDCODCSTCOF, f205.BDBASECOFINS AS BDBCCOFINS, f205.BDALIQCOFINS, f205.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT f.* FROM VEF_EMP_TMOVOPIMOBI_F200_PGTO f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND (cast(substring(f.BDDATAPGTO FROM 1 for 4)||substring(f.BDDATAPGTO FROM 6 for 2) AS integer) = '||:prREFERENCIA||') ';
      wSQL = wSQL||             ') pgto ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVOPIMOBCUSINCOR f205) f205 on (f205.BDCODEMP = pgto.BDCODEMP AND f205.BDCHAVE = pgto.BDCHAVE AND f205.BDORDEMPGTO = pgto.BDORDEMPGTO) ';

      wSQL = wSQL||       'union all ';

      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, (cast(substring(pgto.BDDATAPGTO FROM 1 for 4)||substring(pgto.BDDATAPGTO FROM 6 for 2) AS integer)) AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, pgto.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVLRTOTRECPAR AS BDVL_ITEM, NULL AS BDCODCTA, 109 AS BDNAT_BC_CRED, 109 AS BDCOD_CRED,';
      wSQL = wSQL||              'f210.BDCODCSTPIS, f210.BDBASEPIS AS BDBCPIS, f210.BDALIQPIS, f210.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'f210.BDCODCSTCOF, f210.BDBASECOFINS AS BDBCCOFINS, f210.BDALIQCOFINS, f210.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT f.* FROM VEF_EMP_TMOVOPIMOBI_F200_PGTO f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND (cast(substring(f.BDDATAPGTO FROM 1 for 4)||substring(f.BDDATAPGTO FROM 6 for 2) AS integer) = '||:prREFERENCIA||') ';
      wSQL = wSQL||             ') pgto ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVOPIMOBCUSORCA f210) f210 on (f210.BDCODEMP = pgto.BDCODEMP AND f210.BDCHAVE = pgto.BDCHAVE AND f210.BDORDEMPGTO = pgto.BDORDEMPGTO) ';

      wSQL = wSQL||      ') aux ';
      wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS not in (4,6,7,8,9)) or ((aux.BDCODCSTPIS = 5) and ((aux.BDALIQPIS = 0) or (aux.BDALIQCOFINS = 0)))) '; -- CSTs que n?o geram regitros M100/500...

      EXECUTE STATEMENT ( wSQL );

    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M100_M500PAR) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WMOD_COMTELE VARCHAR(10);
DECLARE VARIABLE WMOD_ENERGAS VARCHAR(10);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
DECLARE VARIABLE WMOD_PROD VARCHAR(50);
DECLARE VARIABLE wMOD_COD_CRED_8 VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
-- Concatena todos os modelos anteriores, usar "NOT IN"...
wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;
-- Modelos que geram "Tipo de Cr?dito" com final 8, exporta??o...
wMOD_COD_CRED_8 = '1,100,4,55,65';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDCODCRIT    -- Crit?rio de escritura??o (cumulativo)
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M100_M500 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDPREFIXONAT, BDVL_ITEM, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCPIS_QUANT, BDALIQPIS_QUANT, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT, BDNAT_BC_CRED, BDCOD_CRED) ';
    
          wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDPREFIXONAT, aux.BDVL_ITEM, aux.BDCODCTA, aux.BDCODCSTPIS, aux.BDBCPIS,';
          wSQL = wSQL||       'aux.BDALIQPIS, aux.BDVLRPIS, aux.BDBCPIS_QUANT, aux.BDALIQPIS_QUANT, aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, aux.BDBCCOFINS_QUANT, aux.BDALIQCOFINS_QUANT, ';
          wSQL = wSQL||       'aux.BDNAT_BC_CRED,';

          wSQL = wSQL||       'Coalesce(aux.BDCOD_CRED,';
          wSQL = wSQL||                '(CASE WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 108 '; -- 108 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 208 '; -- 208 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 201 '; -- 201 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 202 '; -- 202 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
     
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 308 '; -- 308 - Quando ? usado CFOP do exterior que seja geradora de cr?dito.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 301 '; -- 301 - Vai gerar o campo 2 do M100 com este c?digo quando: A al?quota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 302 '; -- 302 - Se a al?quota constante da CFOP na nota for diferente de 1,65 ou 0,65.
     
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 202 '; -- 202 - Quando for al?quota diferente da b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 301 '; -- 301 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for al?quota b?sica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 302 '; -- 302 - Quando for aliquota for diferente da basica.  Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa ? Exporta??o
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for al?quota for diferente da  b?sica. Aqui ser? aplicado o percentual de rateio da linha da receita bruta n?o cumulativa - Tributada no mercado interno do 0111 com rela??o ao percentual total do 0111.
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 208 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da segunda linhar e calcular somente o credito referente a este percentual
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 202 '; -- 202 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
    
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando ? usado CFOP do exterior que tem cr?dito. E a empresa usa rateio para este c?digo deve ser verificado o percentual relativo a primeira linha do 0111 com rela??o a ultima e calcular o montante do cr?dito da CFOP do exterior com CST 56 para este c?digo.
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 60) OR (aux.BDCODCSTCOF = 60)) THEN 106 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 61) OR (aux.BDCODCSTCOF = 61)) THEN 206 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 62) OR (aux.BDCODCSTCOF = 62)) THEN 306 '; -- Se a empresa usa rateio ent?o soma-se as tres primeiras linhas do 0111 e depois calcula o cr?dito da soma desse percentual com rela??o ao faturamento. Se ela n?o tem 0111 usa-se o valor total da bc e valor do cr?dito de PIS .
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 63) OR (aux.BDCODCSTCOF = 63)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 64) OR (aux.BDCODCSTCOF = 64)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 65) OR (aux.BDCODCSTCOF = 65)) THEN 206 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno
          wSQL = wSQL||                      'WHEN ((aux.BDCODCSTPIS = 66) OR (aux.BDCODCSTCOF = 66)) THEN 106 '; -- Aqui ser? aplicado o percentual de rateiro da linha da receita bruta n?o cumulativa - N?o Tributada no mercado interno

          wSQL = wSQL||                 'else NULL end)';
          wSQL = wSQL||               ') AS BDCOD_CRED ';
          wSQL = wSQL||'FROM ( ';

          wSQL = wSQL||'SELECT ent.BDCODEMP, COALESCE(emp.BDCODMATRIZ, ent.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 1 AS BDCODTP, ent.BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||      '(CAST(ROUND(('; -- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                   '(IIF(qtdepro.BDQTDEPRO < 1, pgto.bdvalorpgtopar,'; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                              '((COALESCE(pgto.bdvalorpgtopar,0)*(( COALESCE(movpro.BDVLRITEM,0)/i.BDVLRCONTAB)))) ))+';
          wSQL = wSQL||                   '(IIF(qtdepro.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETINSS,0) ),+';
          wSQL = wSQL||                                             '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) )))';
          wSQL = wSQL||                   ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM,';
          wSQL = wSQL||      'movpro.BDCODCTA, movpro.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||      'movpro.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'movpro.BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'movpro.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'movpro.BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||      'WHERE (e.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||        'AND (e.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||        'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||              'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') ent ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = ent.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVENTPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = ent.BDCODEMP AND x.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTPAR par on (par.BDCODEMP = ent.BDCODEMP AND par.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVENTPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = ent.BDCODEMP AND i.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, Count(*) AS BDQTDEPRO FROM VEF_EMP_TMOVPROENT p group by p.BDCODEMP, p.BDCHAVE, p.BDORDEM) qtdepro on ';
          wSQL = wSQL||                                             '(qtdepro.BDCODEMP = i.BDCODEMP AND qtdepro.BDCHAVE = i.BDCHAVE AND qtdepro.BDORDEM = i.BDORDEM) ';
          wSQL = wSQL||'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODNATBC, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||             'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVPROENT p) movpro on (i.BDCODEMP = movpro.BDCODEMP AND i.BDCHAVE = movpro.BDCHAVE AND i.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||'WHERE ((movpro.BDCODCSTPIS is not null) OR (movpro.BDCODCSTCOF is not null)) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT ent.BDCODEMP, ent.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, ent.BDCHAVE, ent.BDORDEM, ent.BDORDEMPRO, ent.BDCODTP, ent.BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||         '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETINSS,0) ) AS BDVL_ITEM,';

          wSQL = wSQL||      'ent.BDCODCTA, ent.BDNAT_BC_CRED, ent.BDCOD_CRED,';
          wSQL = wSQL||      'ent.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'ent.BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'ent.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'ent.BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
                             /* Entradas - Servi?o de comunica??o e telecomunica??o (D500) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'd500.BDVLRSER AS BDVL_ITEM, d500.BDCODCTA, d500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'd500.BDCODCSTPIS, d500.BDVL_BC_PIS AS BDBCPIS, d500.BDALIQ_PIS AS BDALIQPIS, d500.BDVLRPIS,';
          wSQL = wSQL||             'd500.BDCODCSTCOF, d500.BDVL_BC_COF AS BDBCCOFINS, d500.BDALIQ_COF AS BDALIQCOFINS, d500.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM (';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_COMTELE||' )) '; -- Servi?o de comunica??o e telecomunica??o
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||              'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                    'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = mov.BDCODEMP AND d500.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE d500.BDCHAVE is not null ';
      
          wSQL = wSQL||      'union all ';
                             /* Entradas - Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'c500.BDVLRCONSFOR AS BDVL_ITEM, NULL AS BDCODCTA, c500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'c500.BDCODCSTPIS, c500.BDVL_BC_PIS AS BDBCPIS, c500.BDALIQ_PIS AS BDALIQPIS, c500.BDVLRPIS,';
          wSQL = wSQL||             'c500.BDCODCSTCOF, c500.BDVL_BC_COF AS BDBCCOFINS, c500.BDALIQ_COF AS BDALIQCOFINS, c500.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM ( ';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_ENERGAS||')) '; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||             'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                   'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = mov.BDCODEMP AND c500.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE c500.BDCHAVE is not null ';
      
          wSQL = wSQL||      'union all ';
                             /* Entradas - Transporte (D100) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'd100.BDVLR_FCP_UF_DEST AS BDVL_ITEM, d100.BDCODCTA, d100.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
          wSQL = wSQL||             'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM ( ';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||             'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                   'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE d100.BDCHAVE is not null ';

          wSQL = wSQL||    ') ent ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVENTPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = ent.BDCODEMP AND x.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTPAR par on (par.BDCODEMP = ent.BDCODEMP AND par.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVENTPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = ent.BDCODEMP AND i.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||'WHERE ((ent.BDCODCSTPIS is not null) OR (ent.BDCODCSTCOF is not null)) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL as BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||      '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||      'NULL AS BDCODCTA, a170.BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||      'a170.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'a170.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||      'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||        'AND (s.BDTIPLAN = 0) ';
          wSQL = wSQL||        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||              'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') mov ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||' )) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVSERITENS i on (mov.BDCODEMP = i.BDCODEMP AND mov.BDCHAVE = i.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TA170 a170 on (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND i.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit on (mov.BDCODSITNF = sit.BDCODSITNF) ';
          wSQL = wSQL||'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
          wSQL = wSQL||       '(pgto.bdvalorpgtopar +(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||       'NULL AS BDCODCTA, mov.BDNAT_BC_CRED, ';
          wSQL = wSQL||       'CASE WHEN ((mov.BDCODCSTPIS = 60) or (mov.BDCODCSTCOF = 60)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 61) or (mov.BDCODCSTCOF = 61)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 62) or (mov.BDCODCSTCOF = 62)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 307 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 63) or (mov.BDCODCSTCOF = 63)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 64) or (mov.BDCODCSTCOF = 64)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 65) or (mov.BDCODCSTCOF = 65)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 207 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 66) or (mov.BDCODCSTCOF = 66)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED = 13) THEN 107 '; -- 1 - Opera??o no Mercado Interno / 13 - Outras Opera??es com Direito a Cr?dito
          wSQL = wSQL||       'ELSE NULL ';
          wSQL = wSQL||       'END AS BDCOD_CRED,';
          wSQL = wSQL||       'mov.BDCODCSTPIS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||       'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||       'NULL as BDBCPIS_QUANT, 0 as BDALIQPIS_QUANT,';
          wSQL = wSQL||       'mov.BDCODCSTCOF,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||       'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||       'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT dem.BDCODEMP, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.BDIND_ORIG_CRED, dem.BDNAT_BC_CRED,';
          wSQL = wSQL||             'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||             'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||      'WHERE ((dem.BDCODCSTPIS is not null) OR (dem.BDCODCSTCOF is not null)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||        'AND (dem.BDIND_OPER <> 1) '; -- Opera??o Representativa de Aquisi??o...
          wSQL = wSQL||        'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||             ' WHERE e.BDCODEMP = dem.BDCODEMP AND e.BDREFEMP <= dem.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') mov ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'WHERE ((mov.BDCODCSTPIS is not null) OR (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||  'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||      ') aux ';
          wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS not in (4,6,7,8,9)) or ((aux.BDCODCSTPIS = 5) and ((aux.BDALIQPIS = 0) or (aux.BDALIQCOFINS = 0)))) '; -- CSTs que n?o geram regitros M100/500...

          EXECUTE STATEMENT ( wSQL );
          
        END
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M200) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M200(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WVLRAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRUP NUMERIC(15,2);
DECLARE VARIABLE WVLRUPAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRSLD NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT_ORIGINAL NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT_TOTAL NUMERIC(15,2);
DECLARE VARIABLE WINTAUX INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WPER_APU_CRED INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCRE_4_3_6 INTEGER;
DECLARE VARIABLE WIND_CRED_ORI INTEGER;
DECLARE VARIABLE WCOD_NAT_REC INTEGER;
DECLARE VARIABLE WCHAVEAUX INTEGER;
DECLARE VARIABLE WORDENACAO INTEGER;
DECLARE VARIABLE WIND_DESC_CRED INTEGER;
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCREDITOSPERANT, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCREDITOSPERANT, :wRETPISCOFPERANT;

  /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  /* 1 - Exclusivamente no regime n?o-cumulativo */
  IF (wINCTRIB IN (1,3)) THEN
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      wVLRTOTCONT = 0;
      SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR
      FROM VEF_EMP_TBLOCOM210_M610 m
      LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL)
      WHERE (t435.BDCODCSOCIALEXP IN (01,02,03,04,32,71))
        AND (m.BDCODQUADRO = 19) -- M210 - Detalhamento da contribui??o para o PIS/PASEP
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRTOTCONT;

      wVLRTOTCONT_ORIGINAL = wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 2, COALESCE(:wVLRTOTCONT,0));

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100)
         Caso esteja configurado para usar saldo do per?odo anterior, deve descontar ele primeiro, antes do cr?dito do per?odo atual... */
      wVLRCREDPERANT = 0;
      wVLRCREDPERANT_TOTAL = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 52) -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL = wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
              END
          END
        END

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      SELECT COUNT(m.BDCHAVE) as BDQTD
      FROM VEF_EMP_TBLOCOM100_500 m
      WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO wQTD;

      IF ((wQTD = 0) OR (wVLRTOTCONT = 0) OR (wVLRTOTCONT IS NULL))  THEN -- Caso n?o tenha dados no M100/M500 ou o valor do cr?dito seja zerado...
        BEGIN
          UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                               VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, 0)
                                             MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
            UPDATE VEF_EMP_TBLOCOM100_500 m
            SET m.BDIND_DESC_CRED = 1,
                m.BDVL_CRED_DESC  = 0,
                m.BDSLD_CRED      = m.BDVL_CRED_DISP
            WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA;

            /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
            SELECT COUNT(*)
            FROM VEF_EMP_TBLOCOM1100_1500 m
            WHERE m.BDCODPERIODO = 7
              AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA
              AND m.BDPER_APU_CRED = :prREFERENCIA
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDORIG_CRED = :wIND_CRED_ORI
            INTO :wQTD;
  
            IF (:wQTD > 0) THEN
              BEGIN
                /* Caso tenha registros atualiza */
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                    m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                    m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
      ELSE
        BEGIN
                /* Caso n?o tenha lan?amento de saldos insere */
                INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                              VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                      (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                      7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
              END
          END
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            IF (:wVLRTOTCONT > 0) THEN
              BEGIN
                /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
                IF (:wVLR < :wVLRTOTCONT) THEN
                  BEGIN
                    wVLRSLD        = 0;
                    wVLRTOTCONT    = :wVLRTOTCONT - :wVLR;
                    wIND_DESC_CRED = 0; -- 0 ? Utiliza??o do valor total para desconto da contribui??o apurada no per?odo, no Registro M200;
                  END
                ELSE
                  BEGIN
                    /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                    wVLRSLD        = :wVLR - :wVLRTOTCONT;
                    wVLR           = :wVLR - :wVLRSLD;
                    wVLRTOTCONT    = 0;
                    wIND_DESC_CRED = 1; -- 1 ? Utiliza??o de valor parcial para desconto da contribui??o apurada no per?odo, no Registro M200.
                  END

                -- Atualiza os cr?ditos descontados do M100...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = :wIND_DESC_CRED,
                    m.BDVL_CRED_DESC  = :wVLR,
                    m.BDSLD_CRED      = :wVLRSLD
                WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDCHAVE = :wCHAVE
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI;

                IF (wVLRSLD > 0) THEN
                  BEGIN
                /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                SELECT COUNT(*)
                FROM VEF_EMP_TBLOCOM1100_1500 m
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI
                INTO :wQTD;
      
                IF (:wQTD > 0) THEN
                  BEGIN
                    /* Caso tenha registros atualiza */
                    UPDATE VEF_EMP_TBLOCOM1100_1500 m
                    SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI;
                  END
                ELSE
                  BEGIN
                    /* Caso n?o tenha lan?amento de saldos insere */
                    INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                  VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                          (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                              7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', (:wVLR + :wVLRSLD) /*:wVLR*/, :wVLR/*0*/, :wVLRSLD/*:wVLR*/);
                  END
              END

                wVLRAUX = 0;
                SELECT COALESCE(BDVALOR, 0)
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
                  AND BDREFERENCIA = :prREFERENCIA
                  AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
                  AND BDNUMCAMPO   = 3
                INTO wVLRAUX;
         
                IF (wVLRAUX IS NULL) THEN
                  wVLRAUX = 0;
         
                UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, COALESCE(:wVLR+:wVLRAUX,0))
                                                   MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

                  END
                ELSE
                  BEGIN
                -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = 1,
                    m.BDVL_CRED_DESC  = 0,
                    m.BDSLD_CRED      = m.BDVL_CRED_DISP
                WHERE (m.BDCODQUADRO = 11) -- M100 - Cr?dito de PIS/PASEP
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDCHAVE = :wCHAVE;
          
                    /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                    SELECT COUNT(*)
                    FROM VEF_EMP_TBLOCOM1100_1500 m
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI
                    INTO :wQTD;
          
                    IF (:wQTD > 0) THEN
                      BEGIN
                        /* Caso tenha registros atualiza */
                        UPDATE VEF_EMP_TBLOCOM1100_1500 m
                        SET m.BDVL_CRED_APU = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                        WHERE m.BDCODPERIODO = 7
                          AND m.BDCODQUADRO = 52 -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                          AND m.BDCODEMP = :wCODEMP
                          AND m.BDCODMATRIZ = :wCODMATRIZ
                          AND m.BDREFERENCIA = :prREFERENCIA
                          AND m.BDPER_APU_CRED = :prREFERENCIA
                          AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                          AND m.BDORIG_CRED = :wIND_CRED_ORI;
                      END
                    ELSE
                      BEGIN
                        /* Caso n?o tenha lan?amento de saldos insere */
                        INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                      VALUES (52, -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                                                              (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 52 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                          7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
                      END
                          END
                          END
                      END

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      wVLR = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          wVLR = wVLRCREDPERANT_TOTAL;
        END
      ELSE
        BEGIN
          wVLRCREDPERANT_TOTAL = 0;
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 52) -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END
    
                wVLRCREDPERANT_TOTAL =  wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1100 - Controle de cr?ditos fiscais PIS/PASEP
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
          END

          wVLR = wVLRCREDPERANT_TOTAL;
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 4, COALESCE(:wVLR,0));

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (2))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (3,4))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP,  :prCODEMP, :prREFERENCIA, 15, 5, COALESCE(:wVLR,0));

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';
    
      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
              AND BDNUMCAMPO   = 6
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END


      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRPIS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 1 -- 0 - Dedu??o de Natureza N?o Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 7, COALESCE(:wVLR,0));

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR) as BDVALOR, SUM(aux.BDVLRSUB) as BDVALORSUB
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (5))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (6,7))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR, :wVLRAUX;

      IF ((wVLR - wVLRAUX) >= 0) THEN -- Se tiver valor de contribbui??o, calcula os campos a somar e subtrair...
        wVLR = (wVLR - wVLRAUX);
      ELSE
      /* Se o valor do campo 5(Valor Total da Contribui??o) menos o valor do campo 6(Valor Retido na Fonte) for menor que zero, ent?o este valor deve ser levado como saldo no registro 1300. */
      IF ((wVLR - wVLRAUX) < 0) THEN -- Se n?o tiver valor de contribbui??o, leva zerado...
        BEGIN
          /* Atualiza o valor do campo 6, Valor Retido na Fonte, s? pode usar aquilo que abater e n?o o total... */
          UPDATE VEF_EMP_TBLOCOMGERREG
          SET BDVALOR = :wVLR
          WHERE BDCODMATRIZ  = :prCODEMP
            AND BDREFERENCIA = :prREFERENCIA
            AND BDCODQUADRO  = 15
            AND BDNUMCAMPO   = 6;

          /* Caso tenha lan?amentos, desconta o valor da contribui??o deles */
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, COALESCE(m.BDVL_RET_APU, 0)
              FROM VEF_EMP_TBLOCOM1300_1700 m
              WHERE (m.BDCODQUADRO = 49) -- 1300 - Ficha de reten??o do PIS/PASEP
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUP
          DO
            BEGIN
              IF (wVLR > 0) THEN
                BEGIN
                  /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                  IF (:wVLRUP < :wVLR) THEN
                    BEGIN
                      wVLRUPAUX = :wVLRUP;
                      wVLRSLD   = 0;
                      wVLR      = :wVLR-:wVLRUP; /* Cr?dito j? descontado vai ser abatido... */
                    END
                  ELSE
                    BEGIN
                      wVLRUPAUX = :wVLR;
                      wVLRSLD   = :wVLRUP - :wVLR;
                    END
    
                  UPDATE OR INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDVL_RET_DED, BDSLD_RET)
                                                          VALUES (:wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUPAUX  , :wVLRSLD)
                                                        MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE);
                END
            END

          wVLR = 0; -- Se n?o tiver valor de contribbui??o, leva zerado...
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 8, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 2, 0);

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 3, 0);

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 4, 0);

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 5, 0);

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 6, 0);

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 7, 0);

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 8, 0);
    END

  /* 2 - Exclusivamente no regime cumulativo */
  IF (wINCTRIB IN (2,3)) THEN
    BEGIN
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      wVLRTOTCONT = 0;
      wSQL =        'SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM210_M610 m ';
      wSQL = wSQL|| 'LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL) ';
      IF (wINCTRIB IN (3)) THEN -- Quando ? regime n?o-cumulativo e cumulativo, j? considerou algumas contribui??es no campo 2...
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,51,52,53,54,72)) ';
      ELSE
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,32,51,52,53,54,72)) ';
      wSQL = wSQL|| '  AND (m.BDCODQUADRO = 19) '; -- M210 - Detalhamento da contribui??o para o PIS/PASEP
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 9, COALESCE(:wVLRTOTCONT,0));

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de reten??o do PIS/PASEP
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
                  AND BDNUMCAMPO   = 10
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                         VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRPIS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 2 -- 1 - Dedu??o de Natureza Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 11, COALESCE(:wVLR,0));

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (9))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 15)
              AND (m.BDNUMCAMPO in (10,11))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 12, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN -- Joga os valores zerados...
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 9, 0);

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 10, 0);

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 11, 0);

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 15, 12, 0);
    END

  /* 3 - Regimes n?o-cumulativo e cumulativo */
  /* 13 - VL_TOT_CONT_REC - VALOR TOTAL DA CONTRIBUI??O A RECOLHER/PAGAR NO PER?ODO (08 + 12) */
  WVLR = 0;
  SELECT SUM(COALESCE(M.BDVALOR,0)) AS BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG M
  WHERE (M.BDCODQUADRO = 15)
    AND (M.BDNUMCAMPO IN (8,12))
    AND M.BDCODMATRIZ = :PRCODEMP
    AND M.BDREFERENCIA = :PRREFERENCIA
  INTO :WVLR;
 
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, 15, 13, COALESCE(:WVLR,0));

END
^

/* Alter (SP_APURACAO_BLOCOM_M210_M610) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M210_M610(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32000);
declare variable WMOD_TRANSPORTE varchar(30);
declare variable WMOD_PROD varchar(50);
declare variable WALIQ_PIS_IT_1 varchar(5);
declare variable WALIQ_COF_IT_1 varchar(5);
declare variable WALIQ_PIS_IT_2 varchar(5);
declare variable WALIQ_COF_IT_2 varchar(5);
BEGIN
/* ***** Constantes das CFOPs que geram "NAT_BC_CRED" da tabela 4.3.7. ***** */
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
--wMOD_COMTELE = '21,22'; -- Lan?amento de servi?o de comunica??o e telecomunica??o D500/^D600 (modelo 21 e 22)
--wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia el?trica, ?gua ou g?s (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
--wMOD_CFe = '59'; -- CF-e
-- Concatena todos os modelos anteriores, usar "NOT IN"...
--wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;--||','||wMOD_CFe;
wMOD_PROD = wMOD_TRANSPORTE;--||','||wMOD_CFe;

--wCST_NAO_CUM = '1,2,3,4,32,71'; -- CSTs do regime n?o cumulativo
--wCST_CUM = '31,32,51,52,53,54,72'; -- CSTs do regime cumulativo

/* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
wALIQ_PIS_IT_1 = '1.65';
wALIQ_COF_IT_1 = '7.60';
/* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
wALIQ_PIS_IT_2 = '0.65';
wALIQ_COF_IT_2 = '3.00';
/*****************************************************************************/
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
--      IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
--        wCST = wCST_NAO_CUM; -- CSTs do regime n?o cumulativo
--      ELSE
--      IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
--        wCST = wCST_CUM; -- CSTs do regime cumulativo
--      ELSE
--      IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
--        wCST = wCST_NAO_CUM||','||wCST_CUM; -- CSTs do regime n?o cumulativo e cumulativo

      wSQL =        'INSERT INTO TMP_VEF_EMP_TBLOCOM_M210_M610 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDCODCSTPIS, BDCODCSTCOF, BDCOD_CONT_PIS, BDCOD_CONT_COF, BDVL_REC_BRT, BDVL_BC_CONT_PIS, BDVL_BC_CONT_COF, BDALIQ_PIS, BDALIQ_COF, BDQUANT_BC_PIS, BDQUANT_BC_COF, BDALIQ_QUANT_PIS, BDALIQ_QUANT_COF) ';

      wSQL = wSQL|| 'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDCODCSTPIS, aux.BDCODCSTCOF, ';
      IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                        'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))), 01, null) ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                        'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))), 01, null) ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_1||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      ELSE
      IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                       'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 51, null) ';
          wSQL = wSQL||                                       'WHEN 2 THEN 52 ';
          wSQL = wSQL||                                       'WHEN 3 THEN 53 ';
          wSQL = wSQL||                                       'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                       'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 51, null) ';
          wSQL = wSQL||                                       'WHEN 2 THEN 52 ';
          wSQL = wSQL||                                       'WHEN 3 THEN 53 ';
          wSQL = wSQL||                                       'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      ELSE
      IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
        BEGIN
          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQL = wSQL||                                        'WHEN 1 THEN ';
          wSQL = wSQL||                                           'CASE CAST(aux.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 01 ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 51 ';
          wSQL = wSQL||                                           'END ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQL = wSQL||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQL = wSQL||                                        'WHEN 1 THEN ';
          wSQL = wSQL||                                           'CASE CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 01 ';
          wSQL = wSQL||                                              'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 51 ';
          wSQL = wSQL||                                           'END ';
          wSQL = wSQL||                                        'WHEN 2 THEN 02 ';
          wSQL = wSQL||                                        'WHEN 3 THEN 03 ';
          wSQL = wSQL||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQL = wSQL||                                     'ELSE null ';
          wSQL = wSQL||                                     'end)) AS BDCOD_CONT_COF,';
        END
      wSQL = wSQL||        'aux.BDVL_ITEM AS BDVL_REC_BRT,';
      /* Se tiver campo de valor da base de calculo por quandtidade e al?quota em R$, leva os mesmo, caso contr?rio, verifica pela CST, se for = 3, vai nas quantidades e al?quotas em R$... */
      wSQL = wSQL||        'iif(((aux.BDQUANT_BC_PIS is null) AND (AUX.BDCODCSTPIS = 3)), 0, AUX.BDBCPIS) AS BDVL_BC_CONT_PIS,';
      wSQL = wSQL||        'iif(((aux.BDQUANT_BC_COF is null) AND (AUX.BDCODCSTCOF = 3)), 0, AUX.BDBCCOFINS) AS BDVL_BC_CONT_COF,';
      wSQL = wSQL||        'iif(((aux.BDALIQ_PIS_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQPIS) AS BDALIQ_PIS,';
      wSQL = wSQL||        'iif(((aux.BDALIQ_COF_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQCOFINS) AS BDALIQ_COF,';
      wSQL = wSQL||        'COALESCE(aux.BDQUANT_BC_PIS, iif(aux.BDCODCSTPIS = 3, aux.BDBCPIS, 0)) AS BDQUANT_BC_PIS,';
      wSQL = wSQL||        'COALESCE(aux.BDQUANT_BC_COF, iif(AUX.BDCODCSTCOF = 3, AUX.BDBCCOFINS, 0)) AS BDQUANT_BC_COF,';
      wSQL = wSQL||        'COALESCE(aux.BDALIQ_PIS_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQPIS, 0)) AS BDALIQ_QUANT_PIS,';
      wSQL = wSQL||        'COALESCE(aux.BDALIQ_COF_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQCOFINS, 0)) AS BDALIQ_QUANT_COF ';
      wSQL = wSQL|| 'FROM ( ';

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 2 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||              '(CAST(ROUND(( '; -- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                     '(IIF(mov.BDQTDEPRO < 1, pgto.bdvalorpgtopar, '; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                                '((COALESCE(pgto.bdvalorpgtopar,0)*((CAST( COALESCE(movpro.BDVLRITEM,0) AS NUMERIC(15,6))/i.BDVLRCONTAB)))) ))+ ';
          wSQL = wSQL||                     '(IIF(mov.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
          wSQL = wSQL||                                                   'COALESCE(pgto.BDVALORRETINSS,0) ),+ ';
          wSQL = wSQL||                                               '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) + ';
          wSQL = wSQL||                                                 '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) ))) ';
          wSQL = wSQL||                     ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM, ';
          wSQL = wSQL||              'movpro.BDCODCSTPIS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS, ';
          wSQL = wSQL||              'movpro.BDALIQPIS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS, ';
          wSQL = wSQL||              'movpro.BDCODCSTCOF, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS, ';
          wSQL = wSQL||              'movpro.BDALIQCOFINS, ';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(mov.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT, ';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM ( ';
          wSQL = wSQL||                'SELECT aux.BDCODEMP, aux.BDCHAVE, aux.BDREFLAN, SUM(aux.BDQTDEPRO) AS BDQTDEPRO, SUM(aux.BDQTDEPARC) AS BDQTDEPARC ';
          wSQL = wSQL||                'FROM ( ';
          wSQL = wSQL||                       'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, COUNT(pro.bdCODEMP) AS BDQTDEPRO, 0 AS BDQTDEPARC ';
          wSQL = wSQL||                       'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE) ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVPROSAI pro ON (pro.bdCODEMP = i.bdCODEMP AND pro.bdCHAVE = i.bdCHAVE AND pro.bdORDEM = i.bdORDEM) ';
          wSQL = wSQL||                       'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                        'AND (s.'||TRIM(:prWHEREEMPRESAS)||') ';
          wSQL = wSQL||                        'AND (s.BDMODELO not in ('||wMOD_PROD||')) ';  -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                       'GROUP BY s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||                       'UNION ALL ';
          wSQL = wSQL||                       'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, 0 AS BDQTDEPRO, COUNT(par.bdCODEMP) AS BDQTDEPARC ';
          wSQL = wSQL||                       'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                       'JOIN VEF_EMP_TMOVSAIPAR par ON (par.bdCODEMP = s.bdCODEMP AND par.bdCHAVE = s.bdCHAVE) ';
          wSQL = wSQL||                       'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                         'AND (s.'||TRIM(:prWHEREEMPRESAS)||') ';
          wSQL = wSQL||                         'AND (s.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                       'GROUP BY s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||                      ') aux ';
          wSQL = wSQL||                'WHERE ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                        'WHERE p.BDCODEMP = aux.BDCODEMP AND p.BDREFEMP <= aux.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||                'GROUP BY aux.BDCODEMP, aux.BDCHAVE, aux.BDREFLAN ';
          wSQL = wSQL||              ') mov ';
          wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIPAR par on (par.BDCODEMP = mov.BDCODEMP AND par.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||              'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                 'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||        'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||                      'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS ';
          wSQL = wSQL||               'FROM VEF_EMP_TMOVPROSAI p ';
          wSQL = wSQL||               'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              ') movpro on (i.BDCODEMP = movpro.BDCODEMP AND i.BDCHAVE = movpro.BDCHAVE AND i.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||        'WHERE (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, mov.BDORDEM, mov.BDORDEMPRO, mov.BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||                '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETINSS,0) ) AS BDVL_ITEM,';
          wSQL = wSQL||                'mov.BDCODCSTPIS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||                'mov.BDALIQPIS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||                'mov.BDCODCSTCOF,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||                'mov.BDALIQCOFINS,';
          wSQL = wSQL||                '(CAST((COALESCE(mov.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||                'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||                'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
                                      /* Sa?das - Transporte (D100) */
          wSQL = wSQL||               'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 16 AS BDCODTP,';
          wSQL = wSQL||                      'mov.BDVALORNOTA AS BDVL_ITEM,';
          wSQL = wSQL||                      'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
          wSQL = wSQL||                      'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS ';
          wSQL = wSQL||               'FROM (';
          wSQL = wSQL||                      'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
          wSQL = wSQL||                      'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||                      'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||                        'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
          wSQL = wSQL||                        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                        'AND s.BDREFLAN = '||:prREFERENCIA;
          wSQL = wSQL||                        'AND ((SELECT first 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                              'FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                              'WHERE p.BDCODEMP = s.BDCODEMP ';
          wSQL = wSQL||                                'AND p.BDREFEMP <= s.BDREFLAN ';
          wSQL = wSQL||                              'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||                      ') mov ';
          wSQL = wSQL||               'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||               'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||               'WHERE d100.BDCHAVE is not null ';

          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = mov.BDCODEMP AND x.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIPAR par on (par.BDCODEMP = mov.BDCODEMP AND par.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||              'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||          ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||        'WHERE (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||               '(COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'a170.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'a170.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||              'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          if (wINCTRIB = 2) then
            wSQL = wSQL||             'AND (s.BDTIPLAN = 0) ';
          wSQL = wSQL||               'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT FIRST 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                     'FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP ';
          wSQL = wSQL||                       'AND e.BDREFEMP <= s.BDREFLAN ';
          wSQL = wSQL||                     'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||                'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                 ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||' )) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVSERITENS i on (mov.BDCODEMP = i.BDCODEMP AND mov.BDCHAVE = i.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TA170 a170 on (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND i.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit on (mov.BDCODSITNF = sit.BDCODSITNF) ';
          wSQL = wSQL||        'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';

          wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
          wSQL = wSQL||               '(pgto.bdvalorpgtopar +';
          wSQL = wSQL||                '(COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                 'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||               'mov.BDCODCSTPIS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||               'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||               'mov.BDCODCSTCOF,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||               'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||               '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS,';
          wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
          wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
          wSQL = wSQL||        'FROM (';
          wSQL = wSQL||              'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.BDNAT_BC_CRED,';
          wSQL = wSQL||                     'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||                     'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
          wSQL = wSQL||              ' WHERE DEM.'||TRIM(:prWHEREEMPRESAS)||' ';

          if (wINCTRIB = 2) then
            wSQL = wSQL||              ' AND (dem.BDIND_OPER <> 1) '; -- Opera??o de Aquisi??o...
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO ';
          wSQL = wSQL||                      'FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = dem.BDCODEMP ';
          wSQL = wSQL||                        'AND e.BDREFEMP <= dem.BDREFLAN ';
          wSQL = wSQL||                      'ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||        'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS INTEGER) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||        'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||        'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||               'WHERE P.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                ' AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||        'WHERE ((mov.BDCODCSTPIS is not null) or (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||          'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||        'union all ';
        END
                           /* Sa?das - Produtos */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, mov.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 2 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'p.BDVLRITEM AS BDVL_ITEM,';
      wSQL = wSQL||               'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS,';
      wSQL = wSQL||               'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                 'AND (s.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||               'AND (s.BDCONDPGTO <> 1) ';
       wSQL = wSQL||                'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 'AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVPROSAI p on (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||        'WHERE (p.BDCODPROD is not null) ';

      wSQL = wSQL||        'union all ';
                           /* Sa?das - Transporte (D100) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 16 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'mov.BDVALORNOTA AS BDVL_ITEM,';
      wSQL = wSQL||               'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
      wSQL = wSQL||               'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      wSQL = wSQL||                 'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                   'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 ' AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'WHERE (d100.BDCHAVE is not null) ';

      wSQL = wSQL||        'union all ';
                           /* Demais documentos - Receita */
      wSQL = wSQL||        'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN AS BDREFERENCIA, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'dem.BDVL_OPER AS BDVL_ITEM,';
      wSQL = wSQL||               'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS,';
      wSQL = wSQL||               'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||        'WHERE DEM.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         ' AND dem.BDREFLAN = '||:prREFERENCIA;
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||        'AND (dem.BDIND_OPER <> 1) '; -- Opera??o de Aquisi??o...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||          'AND (dem.BDCONDPGTO <> 1) ';

      wSQL = wSQL||        ' union all ';
                           /* Servi?os tomados(Emitidos) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'a.BDVL_ITEM, ';
      wSQL = wSQL||               'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS,';
      wSQL = wSQL||               'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM ( ';
      wSQL = wSQL||               'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
      IF (wINCTRIB = 2) THEN
        wSQL = wSQL||                 'AND (s.BDTIPLAN = 0) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                 'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                 ' AND s.BDREFLAN = '||:prREFERENCIA;
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TA170 a on (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||        'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) or (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||        'WHERE (a.BDCODPROD is not null) ';

      wSQL = wSQL||        'union all ';
                           /* C425 - Varias al?quotas */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMICMS AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE,  r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZVARALIQ aliq on (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425ALIQ c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE AND c425.BDORDEMICMS = aliq.BDORDEMICMS) ';

      wSQL = wSQL||        'union all ';
                           /* C425 */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMTOT AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 6 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE, r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425 c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||        'union all ';
                           /* C470 */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c470.BDCHAVE, c470.BDORDEMDOCECF AS BDORDEM, c470.BDORDEMITEM AS BDORDEMPRO, 8 AS BDCODTP, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c470.BDVLRTOTPRO AS BDVL_ITEM,';
      wSQL = wSQL||               'c470.BDCODCSTPIS, c470.BDVL_BC_PIS AS BDBCPIS, c470.BDALIQ_PIS AS BDALIQPIS, c470.BDVLRPIS,';
      wSQL = wSQL||               'c470.BDCODCSTCOF, c470.BDVL_BC_COFINS AS BDBCCOFINS, c470.BDALIQ_COFINS AS BDALIQCOFINS, c470.BDVLRCOFINS,';
      wSQL = wSQL||               'c470.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c470.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c470.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c470.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE, r.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TDOCECF c460 on (c460.BDCODEMP = mov.BDCODEMP AND c460.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TITEMDOCECF c470 on (c470.BDCODEMP = c460.BDCODEMP AND c470.BDCHAVE = c460.BDCHAVE AND c470.BDORDEMDOCECF = c460.BDORDEMDOCECF) ';

      wSQL = wSQL||        'union all ';
                           /* Lan?amento de opera??es imobili?rias(F200) */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, Cast((SubString(i.BDDATAPGTO FROM 1 for 4)||SubString(i.BDDATAPGTO FROM 6 for 2)) AS Integer) AS BDREFERENCIA, ';
      wSQL = wSQL||               'i.BDCHAVE, i.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, ';
      IF (wINCTRIB = 1) THEN
        BEGIN
          wSQL = wSQL||             'iif(((i.BDCODCSTPIS = 1) AND (CAST(i.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)))), 4, null) AS BDCOD_CONT_PIS, ';
          wSQL = wSQL||             'iif(((i.BDCODCSTCOF = 1) AND (CAST(i.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)))), 4, null) AS BDCOD_CONT_COF, ';
        END
      ELSE
      IF (wINCTRIB = 2) THEN
        BEGIN
          wSQL = wSQL||             'iif(((i.BDCODCSTPIS = 1) AND (CAST(i.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)))), 54, null) AS BDCOD_CONT_PIS, ';
          wSQL = wSQL||             'iif(((i.BDCODCSTCOF = 1) AND (CAST(i.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)))), 54, null) AS BDCOD_CONT_COF, ';
        END
      ELSE
      IF (wINCTRIB = 3) THEN
        BEGIN
          wSQL = wSQL||           'CASE i.BDCODCSTPIS ';
          wSQL = wSQL||             'WHEN 1 THEN CASE CAST(i.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 04 ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE null ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'WHEN 5 THEN CASE CAST(i.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE 32 ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'ELSE null ';
          wSQL = wSQL||           'END AS BDCOD_CONT_PIS, ';

          wSQL = wSQL||           'CASE i.BDCODCSTCOF ';
          wSQL = wSQL||             'WHEN 1 THEN CASE CAST(i.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 04 ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE null ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'WHEN 5 THEN CASE CAST(i.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE 32 ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'ELSE null ';
          wSQL = wSQL||           'END AS BDCOD_CONT_COF, ';
        END
      wSQL = wSQL||               'i.BDVLRTOTRECPAR AS BDVL_ITEM,';
      wSQL = wSQL||               'i.BDCODCSTPIS, i.BDBASEPIS AS BDBCPIS, i.BDALIQPIS, i.BDVLRPIS,';
      wSQL = wSQL||               'i.BDCODCSTCOF, i.BDBASECOFINS AS BDBCCOFINS, i.BDALIQCOFINS, i.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT f.BDCODEMP, f.BDCHAVE ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 f ';
      wSQL = wSQL||               'WHERE F.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'WHERE (i.BDDATAPGTO is not null) ';
      wSQL = wSQL||          'AND (Cast((SubString(i.BDDATAPGTO FROM 1 for 4)||SubString(i.BDDATAPGTO FROM 6 for 2)) AS Integer) = '||:prREFERENCIA||') ';

      wSQL = wSQL||        'union all ';
                           /* I100 */
      wSQL = wSQL||        'SELECT i100.BDCODEMP, COALESCE(emp.BDCODMATRIZ, i100.BDCODEMP) as BDCODMATRIZ, i100.BDREFERENCIA, i100.BDCHAVE, NULL as BDORDEM,';
--      wSQL = wSQL||               'NULL as BDORDEMPRO, 9 as BDCODTP, NULL as BDCOD_CONT_PIS, NULL as BDCOD_CONT_COF, (i100.BDVLRREC-i100.BDVLRTOTDEDGER-i100.BDVLRTOTDEDESP) as BDVL_ITEM,';
      wSQL = wSQL||               'NULL as BDORDEMPRO, 9 as BDCODTP, NULL as BDCOD_CONT_PIS, NULL as BDCOD_CONT_COF, i100.BDVLRREC as BDVL_ITEM,';
      wSQL = wSQL||               'i100.BDCODCSTPISCOF as BDCODCSTPIS, i100.BDBASEPIS as BDBCPIS, i100.BDALIQPIS, i100.BDVLRPIS,';
      wSQL = wSQL||               'i100.BDCODCSTPISCOF as BDCODCSTCOF, i100.BDBASECOFINS as BDBCCOFINS, i100.BDALIQCOFINS, i100.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL as BDQUANT_BC_PIS, NULL as BDALIQ_PIS_QUANT, NULL as BDQUANT_BC_COF, NULL as BDALIQ_COF_QUANT ';
      wSQL = wSQL||        'FROM VEF_EMP_TMOVFINI100 i100 ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = i100.BDCODEMP) ';
      wSQL = wSQL||        'WHERE i100.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         ' AND i100.BDREFERENCIA = '||:prREFERENCIA||' ';

      wSQL = wSQL||        ') aux ';
--      wSQL = wSQL||'WHERE ((aux.BDCODCSTPIS in (1,2,3,5)) OR (aux.BDCODCSTCOF in (1,2,3,5))) '; -- CSTs que geram regitros M200/600...

      EXECUTE STATEMENT ( wSQL );

      /* Insere os valores no nas tabelas do M210 e M610, pois j? atingiu o tamanho m?ximo da SP */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX (:prCODEMP, :prREFERENCIA);

    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M210_M610AUX) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCSOCIAL INTEGER;
DECLARE VARIABLE WINDNATPJ INTEGER;
DECLARE VARIABLE WALIQ_PIS_IT_1 VARCHAR(5);
DECLARE VARIABLE WALIQ_COF_IT_1 VARCHAR(5);
DECLARE VARIABLE WALIQ_PIS_IT_2 VARCHAR(5);
DECLARE VARIABLE WALIQ_COF_IT_2 VARCHAR(5);
BEGIN
  /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
  wALIQ_PIS_IT_1 = '1.65';
  wALIQ_COF_IT_1 = '7.60';
  /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
  wALIQ_PIS_IT_2 = '0.65';
  wALIQ_COF_IT_2 = '3.00';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  SELECT BDINDNATPJ FROM VW_VEF_BASE_TEMPPARFED WHERE BDCODEMP = :prCODEMP INTO :wINDNATPJ;

  /* REGISTRO M210: DETALHAMENTO DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER) ';
  wSQL = wSQL||'SELECT 19 as BDCODQUADRO, 7 as BDCODPERIODO, tmp.BDCODEMP, COALESCE(emp.BDCODMATRIZ, tmp.BDCODEMP) as BDCODMATRIZ, tmp.BDREFERENCIA, ';
  wSQL = wSQL||'       (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7) as BDCHAVE, ';
  wSQL = wSQL||'       t435.BDCODCSOCIAL, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDVL_REC_BRT,0)) as BDVL_REC_BRT, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDVL_BC_CONT_PIS,0)) as BDVL_BC_CONT, tmp.BDALIQ_PIS as BDALIQ, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDQUANT_BC_PIS,0)) as BDQUANT_BC, tmp.BDALIQ_QUANT_PIS as BDALIQ_QUANT, ';
  wSQL = wSQL||'       (SUM(IIF(COALESCE(tmp.BDVL_BC_CONT_PIS,0) > 0, tmp.BDVL_BC_CONT_PIS, COALESCE(tmp.BDQUANT_BC_PIS, 0))*IIF(COALESCE(tmp.BDALIQ_PIS,0) > 0, tmp.BDALIQ_PIS, COALESCE(tmp.BDALIQ_QUANT_PIS,1)))) as BDVL_CONT_APUR, ';
  wSQL = wSQL||'       0 as BDVL_AJUS_ACRES, ';
  wSQL = wSQL||'       0 as BDVL_AJUS_REDUC, ';
  wSQL = wSQL||'       0 as BDVL_CONT_DIFER, ';
  wSQL = wSQL||'       0 as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||'       0 as BDVL_CONT_PER ';
  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = tmp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIALEXP = tmp.BDCOD_CONT_PIS) ';
  wSQL = wSQL||'WHERE (((tmp.BDVL_BC_CONT_PIS > 0) or (tmp.BDALIQ_PIS > 0)) or ';
  wSQL = wSQL||'       ((tmp.BDQUANT_BC_PIS > 0) or (tmp.BDALIQ_QUANT_PIS > 0))) ';
  wSQL = wSQL||'  AND (tmp.BDCODCSTPIS in (1,2,3,5)) '; -- CSTs que geram regitros M200/600...
  wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS <> 5) OR ((tmp.BDCODCSTPIS = 5) and ((tmp.BDALIQ_PIS > 0) or (tmp.BDALIQ_QUANT_PIS > 0)))) '; -- CST 05 com al?quota zerada vai no M400/M800...
  wSQL = wSQL||'  AND ((tmp.BDCODTP NOT IN (3,10,11,16)) OR '; -- Lan?amentos de transporte com CST inv?lida, tem inconsist?ncia...
  wSQL = wSQL||'       ((tmp.BDCODTP IN (3,10,11,16)) AND (tmp.BDCODCSTPIS <> (03))) ) ';
  wSQL = wSQL||'  AND (tmp.BDCOD_CONT_PIS IS NOT NULL) ';
  wSQL = wSQL||'  AND (t435.BDCODCSOCIAL IS NOT NULL) ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))) ) ';
     END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) ) ';
     END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Exclusivamente no regime n?o-cumulativo / Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
       wSQL = wSQL||'       ((CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))) OR (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4)))) ) ';
     END
   wSQL = wSQL||'GROUP BY tmp.BDCODEMP, emp.BDCODMATRIZ, tmp.BDREFERENCIA, t435.BDCODCSOCIAL, tmp.BDALIQ_PIS, tmp.BDALIQ_QUANT_PIS; ';

   EXECUTE STATEMENT ( wSQL );

  /* REGISTRO M610: DETALHAMENTO DA CONTRIBUI??O PARA A SEGURIDADE SOCIAL - COFINS DO PER?ODO */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER) ';
  wSQL = wSQL||'SELECT 37 as BDCODQUADRO, 7 as BDCODPERIODO, tmp.BDCODEMP, COALESCE(emp.BDCODMATRIZ, tmp.BDCODEMP) as BDCODMATRIZ, tmp.BDREFERENCIA, ';
  wSQL = wSQL||'      (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7) as BDCHAVE, ';
  wSQL = wSQL||'      t435.BDCODCSOCIAL, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDVL_REC_BRT,0)) as BDVL_REC_BRT, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDVL_BC_CONT_COF,0)) as BDVL_BC_CONT, tmp.BDALIQ_COF as BDALIQ, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDQUANT_BC_COF,0)) as BDQUANT_BC, tmp.BDALIQ_QUANT_COF as BDALIQ_QUANT, ';
  wSQL = wSQL||'      (SUM(IIF(COALESCE(tmp.BDVL_BC_CONT_COF,0) > 0, tmp.BDVL_BC_CONT_COF, COALESCE(tmp.BDQUANT_BC_COF, 0))*IIF(COALESCE(tmp.BDALIQ_COF,0) > 0, tmp.BDALIQ_COF, COALESCE(tmp.BDALIQ_QUANT_COF,1)))) as BDVL_CONT_APUR, ';
  wSQL = wSQL||'      0 as BDVL_AJUS_ACRES, ';
  wSQL = wSQL||'      0 as BDVL_AJUS_REDUC, ';
  wSQL = wSQL||'      0 as BDVL_CONT_DIFER, ';
  wSQL = wSQL||'      0 as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||'      0 as BDVL_CONT_PER ';
  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = tmp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIALEXP = tmp.BDCOD_CONT_COF) ';
  wSQL = wSQL||'WHERE (((tmp.BDVL_BC_CONT_COF > 0) or (tmp.BDALIQ_COF > 0)) or ';
  wSQL = wSQL||'       ((tmp.BDQUANT_BC_COF > 0) or (tmp.BDALIQ_QUANT_COF > 0))) ';
  wSQL = wSQL||'  AND (tmp.BDCODCSTCOF in (1,2,3,5)) '; -- CSTs que geram regitros M200/600...
  wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF <> 5) OR ((tmp.BDCODCSTCOF = 5) and ((tmp.BDALIQ_COF > 0) or (tmp.BDALIQ_QUANT_COF > 0)))) '; -- CST 05 com al?quota zerada vai no M400/M800...
  wSQL = wSQL||'  AND ((tmp.BDCODTP NOT IN (3,10,11,16)) OR '; -- Lan?amentos de transporte com CST inv?lida, tem inconsist?ncia...
  wSQL = wSQL||'       ((tmp.BDCODTP IN (3,10,11,16)) AND (tmp.BDCODCSTCOF <> (03))) ) ';
  wSQL = wSQL||'  AND (tmp.BDCOD_CONT_COF IS NOT NULL) ';
  wSQL = wSQL||'  AND (t435.BDCODCSOCIAL IS NOT NULL) ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(7.60 as NUMERIC(7,4))) ) ';
    END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(3.00 as NUMERIC(7,4))) ) ';
    END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Exclusivamente no regime n?o-cumulativo / Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer al?quota
      wSQL = wSQL||'       ((CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(7.60 as NUMERIC(7,4))) OR (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(3.00 as NUMERIC(7,4)))) ) ';
    END
   wSQL = wSQL||'GROUP BY tmp.BDCODEMP, emp.BDCODMATRIZ, tmp.BDREFERENCIA, t435.BDCODCSOCIAL, tmp.BDALIQ_COF, tmp.BDALIQ_QUANT_COF; ';

  EXECUTE STATEMENT ( wSQL );
   
  /* Atualiza os valores ap?s inserir, n?o faz no insert/select acima para n?o matriciar */
  FOR
      SELECT BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL
      FROM VEF_EMP_TBLOCOM210_M610 x
      WHERE x.BDCODMATRIZ = :prCODEMP
        AND x.BDREFERENCIA = :prREFERENCIA
      INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCODCSOCIAL
  DO
    BEGIN
      /* Verifica o quadros para pegar os campos corretos, PIS ou Cofins */
      /* Quando alterar os Selects dos campos, n?o esquecer de atualizar os Selects do campos 13... */
      UPDATE VEF_EMP_TBLOCOM210_M610 x
      SET -- 04 - VL_BC_CONT - Valor da Base de C?lculo da Contribui??o
          -- Se a empresa for sociedade cooperativa, vai descontar os lan?amentos de ajuste do M211...
          x.BDVL_BC_CONT = IIF(:wINDNATPJ IN (1,4),
--                               (IIF(((COALESCE(x.BDVL_BC_CONT,0) > 0) OR (x.BDCODCSOCIAL = 3)), COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))- -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
                               (x.BDVL_BC_CONT-
                                COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0)+COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0)+COALESCE(m211.BDVLREXCLUBCCOFINS,0) ))
                                          FROM VEF_EMP_TSOCCOOPM211M611 m211
                                          WHERE m211.BDCODEMP = x.BDCODEMP
                                            AND m211.BDREFERENCIA = x.BDREFERENCIA
                                            AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                            AND (((x.BDCODQUADRO = 19) AND (m211.BDALIQPIS = x.BDALIQ)) OR
                                                 ((x.BDCODQUADRO = 37) AND (m211.BDALIQCOFINS = x.BDALIQ)))),0)
                                        ),
--                               IIF(((COALESCE(x.BDVL_BC_CONT,0) > 0) OR (x.BDCODCSOCIAL = 3)), COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))), -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
                               x.BDVL_BC_CONT), -- Contribui??o social 3 ? base de c?lculo por quantidade sempre
          -- 08 - VL_CONT_APUR - Valor total da contribui??o social apurada
          x.BDVL_CONT_APUR = (((IIF(:wINDNATPJ IN (1,4),
                                    (IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))-
                                     COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19),COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) FROM VEF_EMP_TSOCCOOPM211M611 m211
                                     WHERE m211.BDCODEMP = x.BDCODEMP
                                       AND m211.BDREFERENCIA = x.BDREFERENCIA
                                       AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                                 AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT))) OR
                                                      ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))))),0) ),
                                    IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0)))
                                )*IIF(COALESCE(x.BDALIQ,0) > 0, COALESCE(x.BDALIQ,0), COALESCE(x.BDALIQ_QUANT,1)))/IIF(COALESCE(x.BDALIQ,0) > 0, 100, 1)), -- Caso seja por quantidade, multiplica sem al?quota....
          -- 09 - VL_AJUS_ACRES - Valor total dos ajustes de acr?scimo
          x.BDVL_AJUS_ACRES = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 1 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 10 - VL_AJUS_REDUC - Valor total dos ajustes de redu??o
          x.BDVL_AJUS_REDUC = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 0 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 11 - VL_CONT_DIFER - Valor da contribui??o a diferir no per?odo
          x.BDVL_CONT_DIFER = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m230.BDVLRCONDEFPIS,0), COALESCE(m230.BDVLRCONDEFCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 m230 WHERE m230.BDCODEMP = x.BDCODEMP AND m230.BDREFERENCIA = x.BDREFERENCIA AND m230.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m230.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m230.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 12 - VL_CONT_DIFER_ANT - Valor da contribui??o diferida em per?odos anteriores
          x.BDVL_CONT_DIFER_ANT = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), (COALESCE(m300.BDVLRCONTRIPIS,0)-COALESCE(m300.BDVLRCREPIS,0)), (COALESCE(m300.BDVLRCONTRICOFINS,0)-COALESCE(m300.BDVLRCRECOFINS,0)))) FROM VEF_EMP_TINFADIDEFM300M700 m300 WHERE m300.BDCODEMP = x.BDCODEMP AND m300.BDREFERENCIA = x.BDREFERENCIA AND m300.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m300.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m300.BDALIQCOFINS = x.BDALIQ))) ),0)),
          -- 13 - VL_CONT_PER - Valor Total da Contribui??o do Per?odo (08 + 09 ? 10 ? 11 + 12)
          x.BDVL_CONT_PER = (
          /*   08 - VL_CONT_APUR */       (((IIF(:wINDNATPJ IN (1,4),
                                                 (IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))-
                                                  COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19),COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) FROM VEF_EMP_TSOCCOOPM211M611 m211
                                                  WHERE m211.BDCODEMP = x.BDCODEMP
                                                    AND m211.BDREFERENCIA = x.BDREFERENCIA
                                                    AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
                                                              AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT))) OR
                                                                   ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))))),0) ),
                                                 IIF(COALESCE(x.BDVL_BC_CONT,0) > 0, COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0)))
                                             )*IIF(COALESCE(x.BDALIQ,0) > 0, COALESCE(x.BDALIQ,0), COALESCE(x.BDALIQ_QUANT,1)))/IIF(COALESCE(x.BDALIQ,0) > 0, 100, 1)) -- Caso seja por quantidade, multiplica sem al?quota....
          /* + 09 - VL_AJUS_ACRES */     +(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 1 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* ? 10 - VL_AJUS_REDUC */     -(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 WHERE m220.BDCODEMP = x.BDCODEMP AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 0 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* ? 11 - VL_CONT_DIFER */     -(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m230.BDVLRCONDEFPIS,0), COALESCE(m230.BDVLRCONDEFCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 m230 WHERE m230.BDCODEMP = x.BDCODEMP AND m230.BDREFERENCIA = x.BDREFERENCIA AND m230.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m230.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m230.BDALIQCOFINS = x.BDALIQ))) ),0))
          /* + 12 - VL_CONT_DIFER_ANT */ +(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), (COALESCE(m300.BDVLRCONTRIPIS,0)-COALESCE(m300.BDVLRCREPIS,0)), (COALESCE(m300.BDVLRCONTRICOFINS,0)-COALESCE(m300.BDVLRCRECOFINS,0)))) FROM VEF_EMP_TINFADIDEFM300M700 m300 WHERE m300.BDCODEMP = x.BDCODEMP AND m300.BDREFERENCIA = x.BDREFERENCIA AND m300.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m300.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m300.BDALIQCOFINS = x.BDALIQ))) ),0))
                             )
      WHERE x.BDCODPERIODO = :wCODPERIODO
        AND x.BDCODEMP = :wCODEMP
        AND x.BDCODMATRIZ = :wCODMATRIZ
        AND x.BDCODQUADRO = :wCODQUADRO
        AND x.BDREFERENCIA = :wREFERENCIA
        AND x.BDCHAVE = :wCHAVE;

  IF (:wINDNATPJ IN (1,4)) THEN -- Apenas se a empresa for "01 ? Sociedade cooperativa" ou "04 ? Sociedade cooperativa participante de SCP como s?cia ostensiva"
    BEGIN
          /* REGISTRO M211: SOCIEDADES COOPERATIVAS ? COMPOSI??O DA BASE DE CALCULO ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM211_M611 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDTIPOSOCCOOP, BDVL_BC_CONT_ANT_EXC, BDVL_EXC_COOP_GER, BDVL_EXC_ESP_COOP, BDVL_BC_CONT)
      SELECT :wCODPERIODO AS BDCODPERIODO, m211.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m211.BDCODEMP) AS BDCODMATRIZ, :wCODQUADRO AS BDCODQUADRO, m211.BDREFERENCIA, :wCHAVE AS BDCHAVE,
                 (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
                  FROM VEF_EMP_TBLOCOM211_M611 x
                  WHERE x.BDCODPERIODO = :wCODPERIODO
                    AND x.BDCODEMP = :wCODEMP
                    AND x.BDCODMATRIZ = :wCODMATRIZ
                    AND x.BDCODQUADRO = :wCODQUADRO
                    AND x.BDREFERENCIA = :wREFERENCIA
                    AND x.BDCHAVE = :wCHAVE) AS BDORDEM,
             m211.BDTIPOSOCCOOP,
             -- 03 - VL_BC_CONT_ANT_EXC_COOP - Valor da Base de C?lculo da Contribui??o, conforme Registros escriturados nos Blocos A, C, D e F, antes das Exclus?es das Cooperativas.
                 (SELECT ( SUM(x.BDVL_BC_CONT)+
                           -- Como j? abateu as exclus?es no select complementar acima, adiciona esses valores aqui...
                           SUM(IIF((x.BDCODQUADRO = 19), COALESCE(SUM(m211.BDVLREXCLUGERPIS),0)+COALESCE(SUM(m211.BDVLREXCLUBCPIS),0),
                                                         COALESCE(SUM(m211.BDVLREXCLUGERCOFINS),0)+COALESCE(SUM(m211.BDVLREXCLUBCCOFINS),0) )) ) as BDVL_BC_CONT


                  FROM VEF_EMP_TBLOCOM210_M610 x
                  WHERE x.BDCODPERIODO = :wCODPERIODO
                    AND x.BDCODEMP = :wCODEMP
                    AND x.BDCODMATRIZ = :wCODMATRIZ
                    AND x.BDCODQUADRO = :wCODQUADRO
                    AND x.BDREFERENCIA = :wREFERENCIA
                    AND x.BDCHAVE = :wCHAVE
                    AND x.BDCODCSOCIAL = :wCODCSOCIAL
                    AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT)) ) OR
                         ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))) ) ) AS BDVL_BC_CONT_ANT_EXC,
             -- 04 - VL_EXC_COOP_GER - Valor de Exclus?o Especifica das Cooperativas em Geral, decorrente das Sobras Apuradas na DRE, destinadas a constitui??o do Fundo de Reserva e do FATES.
             SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0))) AS BDVL_EXC_COOP_GER,
             -- 05 - VL_EXC_ESP_COOP - Valor das Exclus?es da Base de C?lculo Especifica do Tipo da Sociedade Cooperativa, conforme Campo 02 (IND_TIP_COOP).
             SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) AS BDVL_EXC_ESP_COOP,
             -- 06 - VL_BC_CONT - Valor da Base de C?lculo, Ap?s as Exclus?es Especificas da Sociedade Cooperativa (04 ? 05 ? 06) ? Transportar para M210.
                 /* 03 - VL_BC_CONT_ANT_EXC_COOP */ ( (SELECT SUM(x.BDVL_BC_CONT) as BDVL_BC_CONT
                                                       FROM VEF_EMP_TBLOCOM210_M610 x
                                                       WHERE x.BDCODPERIODO = :wCODPERIODO
                                                         AND x.BDCODEMP = :wCODEMP
                                                         AND x.BDCODMATRIZ = :wCODMATRIZ
                                                         AND x.BDCODQUADRO = :wCODQUADRO
                                                         AND x.BDREFERENCIA = :wREFERENCIA
                                                         AND x.BDCHAVE = :wCHAVE
                                                         AND x.BDCODCSOCIAL = :wCODCSOCIAL)
                 -- J? abateu as exclus?es no select complementar acima...
                 --/* 04 - VL_EXC_COOP_GER */          -SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0)))
                 --/* 05 - VL_EXC_ESP_COOP */          -SUM(IIF((:wCODQUADRO = 19), COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0)))
                                                      ) AS BDVL_BC_CONT
      FROM VEF_EMP_TSOCCOOPM211M611 m211
      LEFT OUTER JOIN TEMPRESAS emp ON (emp.BDCODEMP = m211.BDCODEMP)
      WHERE m211.BDCODEMP = :wCODEMP
        AND m211.BDREFERENCIA = :wREFERENCIA
            AND m211.BDCODCSOCIAL = :wCODCSOCIAL
            AND ( ((:wCODQUADRO = 19) AND ((m211.BDALIQPIS > 0) OR (m211.BDVLREXCLUGERPIS > 0) OR (m211.BDVLREXCLUBCPIS > 0))) OR
                  ((:wCODQUADRO = 37) AND ((m211.BDALIQCOFINS > 0) OR (m211.BDVLREXCLUGERCOFINS > 0) OR (m211.BDVLREXCLUBCCOFINS > 0))) )
            AND (EXISTS(SELECT *
                        FROM VEF_EMP_TBLOCOM210_M610 x
                        WHERE x.BDCODEMP = m211.BDCODEMP
                          AND x.BDREFERENCIA = m211.BDREFERENCIA
                          AND x.BDCODCSOCIAL = m211.BDCODCSOCIAL
                          AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT)) ) OR
                               ((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))) )
                        ))
          GROUP BY m211.BDCODEMP, emp.BDCODMATRIZ, m211.BDREFERENCIA, m211.BDTIPOSOCCOOP, m211.BDALIQPIS, m211.BDALIQCOFINS;
        END

  END
  
  /* Aliquota diferente do padr?o nos lan?amentos do M210 e M610 #Inconsist?ncia# */
  wSQL =       'INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC) ';
  wSQL = wSQL||'SELECT aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = aux.BDCODMATRIZ AND x.BDREFERENCIA = '||:prREFERENCIA||') AS BDCODBLOCOM, ';
  wSQL = wSQL||       'aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODINC ';
  wSQL = wSQL||'FROM ( ';
  -- PIS/PASEP
  wSQL = wSQL||       'SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '       aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 6 AS BDCODINC ';
  wSQL = wSQL||       'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux ';
  wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
  --wSQL = wSQL||       'WHERE (aux.BDCODCSTPIS NOT IN (02,03,05)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||       'WHERE (aux.BDCODCSTPIS IN (01)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||         'AND aux.BDCODEMP in (SELECT ex.BDCODEMP ';
  wSQL = wSQL||                              'FROM TEMPRESAS ex ';
  wSQL = wSQL||                              'WHERE ex.BDCODEMP = '||:prCODEMP||' ';
  wSQL = wSQL||                                 'OR ex.BDCODMATRIZ = '||:prCODEMP||') ';
  wSQL = wSQL||         'AND (aux.BDREFERENCIA = '||:prREFERENCIA||') ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))) ';
     END
   ELSE
   IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
     BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))) ';
     END
   ELSE
   IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
     BEGIN
      wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))) AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)))) ';
     END

  wSQL = wSQL||       'UNION ALL ';
  -- Cofins
  wSQL = wSQL||       'SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '       aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 7 AS BDCODINC ';
  wSQL = wSQL||       'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux ';
  wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
  --wSQL = wSQL||       'WHERE (aux.BDCODCSTCOF NOT IN (02,03,05)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||       'WHERE (aux.BDCODCSTCOF IN (01)) '; -- Para esses CSTs pode ser qualquer al?quota...
  wSQL = wSQL||         'AND aux.BDCODEMP in (SELECT ex.BDCODEMP ';
  wSQL = wSQL||                              'FROM TEMPRESAS ex ';
  wSQL = wSQL||                              'WHERE ex.BDCODEMP = '||:prCODEMP||' ';
  wSQL = wSQL||                                 'OR ex.BDCODMATRIZ = '||:prCODEMP||') ';
  wSQL = wSQL||         'AND (aux.BDREFERENCIA = '||:prREFERENCIA||') ';
  IF (wINCTRIB = 1) THEN /* Incid?ncia tribut?ria 1 - Exclusivamente no regime n?o-cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))) ';
    END
  ELSE
  IF (wINCTRIB = 2) THEN /* Incid?ncia tribut?ria 2 - Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||         'AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))) ';
    END
  ELSE
  IF (wINCTRIB = 3) THEN /* Incid?ncia tribut?ria 3 - Regimes n?o-cumulativo e cumulativo */
    BEGIN
      wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))) AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)))) ';
    END

   wSQL = wSQL||      ') aux ';

   EXECUTE STATEMENT ( wSQL );

  /* CST 03 n?o permitida nos lan?amentos "A100/A170, C600/C601,D200/D201,D300,D600/D601" #Inconsist?ncia# */
  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
  SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
         aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 4 AS BDCODINC
  FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux
  WHERE ((aux.BDCODCSTPIS IN (03)) OR (aux.BDCODCSTCOF IN (03)))
    AND (aux.BDCODTP IN (3,10,11,16))
    AND (aux.BDCODMATRIZ = :prCODEMP)
    AND (aux.BDREFERENCIA = :prREFERENCIA);

  /* CST diferente de 01, a ?nica permitida nos lan?amentos de opera??es imobili?rias  #Inconsist?ncia# */
  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
  SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
         (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
         aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 10 AS BDCODINC
  FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux
  WHERE ((aux.BDCODCSTPIS <> 01) OR (aux.BDCODCSTCOF <> 01))
    AND (aux.BDCODTP IN (14))
    AND (aux.BDCODMATRIZ = :prCODEMP)
    AND (aux.BDREFERENCIA = :prREFERENCIA);

  IF (:wINDNATPJ IN (1,4)) THEN -- Apenas se a empresa for "01 ? Sociedade cooperativa" ou "04 ? Sociedade cooperativa participante de SCP como s?cia ostensiva"
    BEGIN
      /* Registros de M210/M610 sem M211/M611 respectivo #Inconsist?ncia# */
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDREPLACES)
      SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
             NULL as BDCODTP, NULL as BDCHAVE, NULL as BDORDEM, NULL as BDORDEMPRO, 11 AS BDCODINC,
             aux.BDCODCSOCIAL||'?'||CASE WHEN aux.BDCODQUADRO = 19 THEN 'PIS' ELSE 'Cofins' END||'?'||IIF(aux.BDALIQ > 0, aux.BDALIQ, aux.BDALIQ_QUANT) as BDREPLACES
      FROM VEF_EMP_TBLOCOM210_M610 aux
      WHERE (aux.BDCODMATRIZ = :prCODEMP)
        AND (aux.BDREFERENCIA = :prREFERENCIA)
        AND (NOT EXISTS(SELECT *
                        FROM VEF_EMP_TBLOCOM211_M611 m211
                        WHERE m211.BDCODPERIODO = aux.BDCODPERIODO
                          AND m211.BDCODEMP = aux.BDCODEMP
                          AND m211.BDCODMATRIZ = aux.BDCODMATRIZ
                          AND m211.BDCODQUADRO = aux.BDCODQUADRO
                          AND m211.BDREFERENCIA = aux.BDREFERENCIA
                          AND m211.BDCHAVE = aux.BDCHAVE ));
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M220_M620) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M220_M620(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  -- INSERE A COMPET?NCIA DA APURA??O...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT;

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* REGISTRO M220: AJUSTES DA CONTRIBUI??O PARA O PIS/PASEP APURADA */
      INSERT INTO VEF_EMP_TBLOCOM220_M620 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, DESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m220.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m220.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m220.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m220.BDCODEMP AND x.BDREFERENCIA = m220.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) ) as BDORDEM,
             m220.BDCODAJUEFDC, m220.BDTIPOAJUSTE as BDIND_AJ, m220.BDVLRAJUPIS as BDVL_AJ, m220.BDNUMERODOC as BDNUM_DOC, m220.BDDESCRICAO as DESCR_AJ, m220.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TAJUAPUPCM220620 m220
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m220.BDCODEMP)
      WHERE m220.BDVLRAJUPIS > 0
        AND m220.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m220.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m220.BDCODEMP
                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL));

      /* REGISTRO M225: DETALHAMENTO DOS AJUSTES DA CONTRIBUI??O PARA O PIS/PASEP APURADA */
      INSERT INTO VEF_EMP_TBLOCOM225_M625 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM25, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCSTPIS, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m220.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m220.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m220.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m220.BDCODEMP AND x.BDREFERENCIA = m220.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) as BDCHAVE,
             (SELECT FIRST 1 x.BDORDEM
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDNUM_DOC = m220.BDNUMERODOC
                AND x.DESCR_AJ  = m220.BDDESCRICAO
                AND x.BDDT_REF  = m220.BDDATAREF
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL) ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM25)+1, 1)
              FROM VEF_EMP_TBLOCOM225_M625 x
              WHERE x.BDCODEMP = m220.BDCODEMP
                AND x.BDREFERENCIA = m220.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL)
                AND x.BDORDEM = (SELECT FIRST 1 x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM220_M620 x
                                 WHERE x.BDCODEMP = m220.BDCODEMP
                                   AND x.BDREFERENCIA = m220.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDNUM_DOC = m220.BDNUMERODOC
                                   AND x.DESCR_AJ  = m220.BDDESCRICAO
                                   AND x.BDDT_REF  = m220.BDDATAREF
                                   AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                                    FROM VEF_EMP_TBLOCOM210_M610 x
                                                    WHERE x.BDCODEMP = m220.BDCODEMP
                                                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                                                      AND x.BDCODQUADRO = 19
                                                      AND x.BDCODPERIODO = 7
                                                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL)) ) as BDORDEM25,
             m625.BDCODCSTCOF, m625.BDCODPLAPADRAO, m625.BDCODTPLA, m625.BDCODCSTPIS, m625.BDVALORPIS as BDDET_VALOR_AJ, m625.BDBCPIS as BDDET_BC_CRED, m625.BDALIQPIS as BDDET_ALIQ,
             m625.BDDATAOPEPIS as BDDT_OPER_AJ, m625.BDDESCRICAOAJU as BDDESC_AJ, m625.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TAJUAPUPCM220620 m220
      JOIN VEF_EMP_TDETAJUM225625 m625 on (m220.BDCODEMP = m625.BDCODEMP AND m220.BDCHAVE = m625.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m220.BDCODEMP)
      WHERE m220.BDVLRAJUPIS > 0
        AND m220.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m220.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m220.BDCODEMP
                      AND x.BDREFERENCIA = m220.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m220.BDCODCSOCIAL));

      /* REGISTRO M620: AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM220_M620 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, DESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m620.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m620.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m620.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m620.BDCODEMP AND x.BDREFERENCIA = m620.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) ) as BDORDEM,
             m620.BDCODAJUEFDC, m620.BDTIPOAJUSTE as BDIND_AJ, m620.BDVLRAJUCOFINS as BDVL_AJ, m620.BDNUMERODOC as BDNUM_DOC, m620.BDDESCRICAO as DESCR_AJ, m620.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TAJUAPUPCM220620 m620
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m620.BDCODEMP)
      WHERE m620.BDVLRAJUCOFINS > 0
        AND m620.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m620.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m620.BDCODEMP
                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL));

      /* REGISTRO M625: DETALHAMENTO DOS AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM225_M625 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM25, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCSTPIS, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m620.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m620.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m620.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m620.BDCODEMP AND x.BDREFERENCIA = m620.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) as BDCHAVE,
             (SELECT FIRST 1 x.BDORDEM
              FROM VEF_EMP_TBLOCOM220_M620 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDNUM_DOC = m620.BDNUMERODOC
                AND x.DESCR_AJ  = m620.BDDESCRICAO
                AND x.BDDT_REF  = m620.BDDATAREF
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL) ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM25)+1, 1)
              FROM VEF_EMP_TBLOCOM225_M625 x
              WHERE x.BDCODEMP = m620.BDCODEMP
                AND x.BDREFERENCIA = m620.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL)
                AND x.BDORDEM = (SELECT FIRST 1 x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM220_M620 x
                                 WHERE x.BDCODEMP = m620.BDCODEMP
                                   AND x.BDREFERENCIA = m620.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDNUM_DOC = m620.BDNUMERODOC
                                   AND x.DESCR_AJ  = m620.BDDESCRICAO
                                   AND x.BDDT_REF  = m620.BDDATAREF
                                   AND x.BDCHAVE = (SELECT x.BDCHAVE
                                                    FROM VEF_EMP_TBLOCOM210_M610 x
                                                    WHERE x.BDCODEMP = m620.BDCODEMP
                                                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                                                      AND x.BDCODQUADRO = 37
                                                      AND x.BDCODPERIODO = 7
                                                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL)) ) as BDORDEM25,
             m625.BDCODCSTCOF, m625.BDCODPLAPADRAO, m625.BDCODTPLA, m625.BDCODCSTPIS, m625.BDVALORCOFINS as BDDET_VALOR_AJ, m625.BDBCCOFINS as BDDET_BC_CRED, m625.BDALIQCOFINS as BDDET_ALIQ,
             m625.BDDATAOPECOFINS as BDDT_OPER_AJ, m625.BDDESCRICAOAJU as BDDESC_AJ, m625.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TAJUAPUPCM220620 m620
      JOIN VEF_EMP_TDETAJUM225625 m625 on (m620.BDCODEMP = m625.BDCODEMP AND m620.BDCHAVE = m625.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m620.BDCODEMP)
      WHERE m620.BDVLRAJUCOFINS > 0
        AND m620.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = :prCODEMP
                                OR ex.BDCODMATRIZ = :prCODEMP)
        AND m620.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m620.BDCODEMP
                      AND x.BDREFERENCIA = m620.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m620.BDCODCSOCIAL));
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M230_M630) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M230_M630(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  -- INSERE A COMPET?NCIA DA APURA??O...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT;

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* REGISTRO M230: INFORMA??ES ADICIONAIS DE DIFERIMENTO */
      INSERT INTO VEF_EMP_TBLOCOM230_M630 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCRE_4_3_6, BDCNPJ, BDVL_VEND, BDVL_NAO_RECEB, BDVL_CONT_DIF, BDVL_CRED_DIF)
      SELECT 7 as BDCODPERIODO, m230.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m230.BDCODEMP) as BDCODMATRIZ, 19 as BDCODQUADRO, m230.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m230.BDCODEMP AND x.BDREFERENCIA = m230.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM230_M630 x
              WHERE x.BDCODEMP = m230.BDCODEMP
                AND x.BDREFERENCIA = m230.BDREFERENCIA
                AND x.BDCODQUADRO = 19
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m230.BDCODEMP
                                   AND x.BDREFERENCIA = m230.BDREFERENCIA
                                   AND x.BDCODQUADRO = 19
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL) ) as BDORDEM,
             m230.BDCODCRE_4_3_6, m230.BDCNPJPJRELACIONADA as BDCNPJ,
             m230.BDVLRVENDAPIS as BDVL_VEND, m230.BDVLRNRECPIS as BDVL_NAO_RECEB, m230.BDVLRCONDEFPIS as BDVL_CONT_DIF, m230.BDVLRCREDEFPIS as BDVL_CRED_DIF
      FROM VEF_EMP_TINFADIDEFM230630 m230
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m230.BDCODEMP)
      WHERE m230.BDALIQPIS > 0
        AND m230.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m230.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m230.BDCODEMP
                      AND x.BDREFERENCIA = m230.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL));

      /* REGISTRO M630: INFORMA??ES ADICIONAIS DE DIFERIMENTO */
      INSERT INTO VEF_EMP_TBLOCOM230_M630 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCRE_4_3_6, BDCNPJ, BDVL_VEND, BDVL_NAO_RECEB, BDVL_CONT_DIF, BDVL_CRED_DIF)
      SELECT 7 as BDCODPERIODO, m630.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m630.BDCODEMP) as BDCODMATRIZ, 37 as BDCODQUADRO, m630.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m630.BDCODEMP AND x.BDREFERENCIA = m630.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM230_M630 x
              WHERE x.BDCODEMP = m630.BDCODEMP
                AND x.BDREFERENCIA = m630.BDREFERENCIA
                AND x.BDCODQUADRO = 37
                AND x.BDCODPERIODO = 7
                AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 x
                                 WHERE x.BDCODEMP = m630.BDCODEMP
                                   AND x.BDREFERENCIA = m630.BDREFERENCIA
                                   AND x.BDCODQUADRO = 37
                                   AND x.BDCODPERIODO = 7
                                   AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL) ) as BDORDEM,
             m630.BDCODCRE_4_3_6, m630.BDCNPJPJRELACIONADA as BDCNPJ,
             m630.BDVLRVENDACOFINS as BDVL_VEND, m630.BDVLRNRECCOFINS as BDVL_NAO_RECEB, m630.BDVLRCONDEFCOFINS as BDVL_CONT_DIF, m630.BDVLRCREDEPCOFINS as BDVL_CRED_DIF
      FROM VEF_EMP_TINFADIDEFM230630 m630
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m630.BDCODEMP)
      WHERE m630.BDALIQCOFINS > 0
        AND m630.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m630.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = m630.BDCODEMP
                      AND x.BDREFERENCIA = m630.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL));

    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M300_M700) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M300_M700(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  /*
    REGISTRO M300: CONTRIBUI??O DE PIS/PASEP DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO.
    REGISTRO M700: COFINS DIFERIDA EM PER?ODOS ANTERIORES ? VALORES A PAGAR NO PER?ODO
  */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM300_M700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_CONT_APUR_DIFER, BDNAT_CRED_DESC, BDVL_CRED_DESC_DIFER, BDVL_CONT_DIFER_ANT, BDALIQ, BDPER_APUR, BDDT_RECEB) ';
  wSQL = wSQL||'SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) as BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE+1),1) FROM VEF_EMP_TBLOCOM300_M700 x WHERE x.BDCODPERIODO = aux.BDCODPERIODO AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) AND x.BDCODQUADRO = aux.BDCODQUADRO AND x.BDREFERENCIA = aux.BDREFERENCIA) AS BDCHAVE, ';
  wSQL = wSQL||       'aux.BDCODCSOCIAL, aux.BDVL_CONT_APUR_DIFER, aux.BDNAT_CRED_DESC, aux.BDVL_CRED_DESC_DIFER, aux.BDVL_CONT_DIFER_ANT, aux.BDALIQ, aux.BDPER_APUR, aux.BDDT_RECEB ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||      'SELECT 24 as BDCODQUADRO, '; -- M300 - Diferimentos Per?odos Anteriores de PIS/PASEP
  wSQL = wSQL||             '7 as BDCODPERIODO, m300.BDCODEMP, m300.BDREFERENCIA, m300.BDCODCSOCIAL, m300.BDVLRCONTRIPIS as BDVL_CONT_APUR_DIFER, ';
  wSQL = wSQL||             'm300.BDCODNATDEF as BDNAT_CRED_DESC, m300.BDVLRCREPIS as BDVL_CRED_DESC_DIFER, (m300.BDVLRCONTRIPIS-m300.BDVLRCREPIS) as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||             'm300.BDALIQPIS as BDALIQ, m300.BDREFERENCIA as BDPER_APUR, m300.BDDATAREC as BDDT_RECEB ';
  wSQL = wSQL||      'FROM VEF_EMP_TINFADIDEFM300M700 m300 ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 soc ON (soc.BDCODCSOCIAL = m300.BDCODCSOCIAL) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABNATCREDEF nat ON (nat.BDCODNATDEF = m300.BDCODNATDEF) ';
  wSQL = wSQL||      'WHERE m300.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND m300.BDREFERENCIA = '||:prREFERENCIA||' ';
  
  wSQL = wSQL||      ' UNION ALL ';
  
  wSQL = wSQL||      'SELECT 42 as BDCODQUADRO, '; -- M700 - Diferimentos Per?odos Anteriores de Cofins
  wSQL = wSQL||             '7 as BDCODPERIODO, m700.BDCODEMP, m700.BDREFERENCIA, m700.BDCODCSOCIAL, m700.BDVLRCONTRICOFINS as BDVL_CONT_APUR_DIFER, ';
  wSQL = wSQL||             'm700.BDCODNATDEF as BDNAT_CRED_DESC, m700.BDVLRCRECOFINS as BDVL_CRED_DESC_DIFER, (m700.BDVLRCONTRICOFINS-m700.BDVLRCRECOFINS) as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||             'm700.BDALIQCOFINS as BDALIQ, m700.BDREFERENCIA as BDPER_APUR, m700.BDDATAREC as BDDT_RECEB ';
  wSQL = wSQL||      'FROM VEF_EMP_TINFADIDEFM300M700 m700 ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 soc ON (soc.BDCODCSOCIAL = m700.BDCODCSOCIAL) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABNATCREDEF nat ON (nat.BDCODNATDEF = m700.BDCODNATDEF) ';
  wSQL = wSQL||      'WHERE m700.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND m700.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||      ') aux ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP); ';

  EXECUTE STATEMENT wSQL;

  /* REGISTRO M350: PIS/PASEP ? FOLHA DE SAL?RIOS */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M350 (:prCODEMP, :prREFERENCIA);
  
END
^

/* Alter (SP_APURACAO_BLOCOM_M350) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M350(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WALIQ NUMERIC(15,6);
DECLARE VARIABLE WCODIMP INTEGER;
DECLARE VARIABLE WVLRBRUTO NUMERIC(15,2);
DECLARE VARIABLE WVLRPIS NUMERIC(15,2);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT FIRST 1 i.BDCODIMP, i.BDALIQIMPOSTO
  FROM VW_TEMPRESAIMPOSTO e
  LEFT OUTER JOIN TIMPOSTO i ON (i.BDCODIMP = e.BDCODIMP)
  WHERE e.BDCODEMP = :prCODEMP
    AND i.BDCLASSIMP LIKE '01.01.01.04.%' -- "Classifica??o" PIS - Programa integra??o social
    AND i.BDCODSIS = 2 -- "Sistema" Folha
    AND i.BDDOCARRECADACAO = 1 -- "Documento arrecada??o" DARF
    AND i.BDCODTIPIMP = 6 -- "Tipo de imposto" PIS/Pasep
    AND i.BDTIPOIMPDOC = 2 -- "Tipo c?lculo imposto" PIS
    AND i.BDTIPORETENCAO = 1 -- "Reten??o" PIS
  INTO :wCODIMP, :wALIQ;

  IF (wALIQ IS NOT NULL) THEN -- A empresa deve ter o imposto cadastrado na empresa, caso contr?rio, n?o obriga...
    BEGIN
      SELECT --calc.BDCODEMP,calc.BDREFFN,
             SUM(CASE WHEN vr.BDTIPOCODVER = 0 THEN COALESCE(calc.BDVALVFN,0) ELSE 0 END) AS BDVLRBRUTO
             --SUM(CASE WHEN vr.BDPISVER = 'TRUE' THEN calc.BDVALVFN ELSE 0 END) AS BDVLRPIS -- Apenas verbas cadastradas como PIS
      FROM (
            SELECT fn.BDCODEMP, fn.BDCODCOL, fn.BDREFFN, fn.BDCODVER, fn.BDVALVFN
            FROM VRHF_EMP_TVERBAFN fn -- Folha normal
            WHERE fn.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND fn.BDREFFN = :prREFERENCIA
      
            UNION ALL
      
            SELECT rh.BDCODEMP, ad.BDCODCOL, ad.BDREFCOMP, ad.BDCODVER, ad.BDVALVFC
            FROM VRHF_EMP_TVERBAFC ad -- Folha normal complementar
            JOIN VW_VRHF_EMPRESAS_REF_ATUAL rh ON (ad.BDCODEMP = rh.BDCODEMP)
            WHERE (rh.BDCALCFCNAFNEMP <> 'TRUE')
              AND ad.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ad.BDREFCOMP = :prREFERENCIA
      
            UNION ALL
      
            SELECT ft.BDCODEMP, ft.BDCODCOL, ft.BDREFTOMADOR, ft.BDCODVER, ft.BDVALVFT
            FROM VRHF_EMP_TVERBATOMADOR ft -- Folha por tomador
            WHERE ft.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ft.BDREFTOMADOR = :prREFERENCIA
      
            UNION ALL
      
            SELECT ad.BDCODEMP, ad.BDCODCOL, ad.BDREFCOMP, ad.BDCODVER, ad.BDVALVFC
            FROM VRHF_EMP_TVERBAFCTOMADOR ad -- Folha por tomador complementar
            JOIN VW_VRHF_EMPRESAS_REF_ATUAL rh ON (ad.BDCODEMP = rh.BDCODEMP)
            WHERE (rh.BDCALCFCNAFNEMP <> 'TRUE')
              AND ad.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ad.BDREFCOMP = :prREFERENCIA
      
            UNION ALL
      
            SELECT dt.BDCODEMP, dt.BDCODCOL, dt.BDREF13, dt.BDCODVER, dt.BDVALV13
            FROM VRHF_EMP_TVERBA13 dt -- 13?
            WHERE dt.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND dt.BDREF13 = :prREFERENCIA
      
            UNION ALL
      
            SELECT cdt.BDCODEMP, cdt.BDCODCOL, cdt.BDREFC13, cdt.BDCODVER, cdt.BDVALVC13
            FROM VRHF_EMP_TVERBAC13 cdt -- Complemento 13o
            WHERE cdt.BDCODEMP in (SELECT ex.BDCODEMP
                                   FROM TEMPRESAS ex
                                   WHERE ex.BDCODEMP = :prCODEMP
                                      OR ex.BDCODMATRIZ = :prCODEMP)
              AND cdt.BDREF13 = :prREFERENCIA
            ) calc
      JOIN VW_VRH_EMP_TCOLCON_VINC col ON (col.BDCODEMP = calc.BDCODEMP AND col.BDCODCOL = calc.BDCODCOL)
      JOIN VRH_BASE_TCLASSE cla ON (col.BDCODCLA = cla.BDCODCLA)
      JOIN VW_VERBAS_REF_ATUAL vr ON (vr.BDCODVER = calc.BDCODVER)
      --GROUP BY calc.BDCODEMP, calc.BDREFFN
      INTO :wVLRBRUTO;--, :wVLRPIS;

      /* Caso n?o tenha apura??o da folha #Inconsist?ncia# */
      --IF (:wVLRBRUTO IS NULL) THEN
      --  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
      --                        VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA), NULL, NULL, NULL, NULL, 3);

      SELECT SUM(COALESCE(d.BDBASEIMP,0)) as BDBASEIMP
      FROM TDARFPADRAO d
      WHERE d.BDCODIMP = :wCODIMP
        AND d.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND d.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRPIS;

      /* Caso n?o tenha apura??o do Darf PIS #Inconsist?ncia# */
      IF (:wVLRPIS IS NULL) THEN
        INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
                              VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA), NULL, NULL, NULL, NULL, 12);

    END

  IF ((wALIQ IS NULL) OR (wVLRBRUTO IS NULL) OR (wVLRPIS IS NULL)) THEN
    EXIT;

  /* 02 - VL_TOT_FOL - Valor Total da Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 2, :wVLRBRUTO);

  /* 03 - VL_EXC_BC - Valor Total das Exclus?es ? Base de C?lculo */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 3, (:wVLRBRUTO - :wVLRPIS));

  /* 04 - VL_TOT_BC - Valor Total da Base de C?lculo */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 4, :wVLRPIS);

  IF ((wVLRBRUTO = 0) AND (wVLRPIS = 0)) THEN -- Caso venham valores zerados, leva tudo zerado...
    wALIQ = 0;

  /* 05 - ALIQ_PIS_FOL - Al?quota do PIS/PASEP ? Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 5, :wALIQ);

  /* 06 - VL_TOT_CONT_FOL - Valor Total da Contribui??o Social sobre a Folha de Sal?rios */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 6, ((:wVLRPIS*:wALIQ)/100) );

END
^

/* Alter (SP_APURACAO_BLOCOM_M400_M800) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX (:prCODEMP, :prREFERENCIA, :prWHEREEMPRESAS);

      /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM400_M800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODCSTPIS, BDVL_TOT_REC, BDDESC_COMPL)
      SELECT 26 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM400_M800 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 26) AS BDCHAVE,
             tmp.BDCODCSTCOF, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTPIS, SUM(COALESCE(tmp.BDVL_ITEM,0)) AS BDVL_TOT_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTPIS > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

      /* REGISTRO M410: DETALHAMENTO DAS RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM410_M810 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODNATREC, BDVL_REC, BDDESC_COMPL)
      SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 26 AS BDCODQUADRO, tmp.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM400_M800 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                AND x.BDCODQUADRO = 26
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                ) AS BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1,1) FROM VEF_EMP_TBLOCOM410_M810 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 26
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                AND x.BDCHAVE = (SELECT z.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM400_M800 z
                                 WHERE z.BDCODEMP = tmp.BDCODEMP
                                   AND z.BDCODMATRIZ = tmp.BDCODMATRIZ
                                   AND z.BDREFERENCIA = tmp.BDREFERENCIA
                                   AND z.BDCODCSTCOF = tmp.BDCODCSTCOF
                                   AND z.BDCODCSTPIS = tmp.BDCODCSTPIS
                                   AND z.BDCODQUADRO = 26
                                   AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                                   AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
                                   ) AS BDORDEM,
             tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODNATREC, SUM(tmp.BDVL_ITEM) AS BDVL_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTPIS > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM400_M800 x
                    WHERE x.BDCODEMP = tmp.BDCODEMP
                      AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                      AND x.BDREFERENCIA = tmp.BDREFERENCIA
                      AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                      AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                      AND x.BDCODQUADRO = 26
                      AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                      AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))) ))
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODNATREC, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

      /* REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      INSERT INTO VEF_EMP_TBLOCOM400_M800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODCSTCOF, BDVL_TOT_REC, BDDESC_COMPL)
      SELECT 43 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,
             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM400_M800 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 43) AS BDCHAVE,
             tmp.BDCODCSTPIS, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, SUM(COALESCE(tmp.BDVL_ITEM,0)) AS BDVL_TOT_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTCOF > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF;

      /* REGISTRO M810: DETALHAMENTO DAS RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
      INSERT INTO VEF_EMP_TBLOCOM410_M810 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODNATREC, BDVL_REC, BDDESC_COMPL)
      SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 43 AS BDCODQUADRO, tmp.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM400_M800 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                AND x.BDCODQUADRO = 43
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                ) AS BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM)+1,1) FROM VEF_EMP_TBLOCOM410_M810 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 43
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                AND x.BDCHAVE = (SELECT z.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM400_M800 z
                                 WHERE z.BDCODEMP = tmp.BDCODEMP
                                   AND z.BDCODMATRIZ = tmp.BDCODMATRIZ
                                   AND z.BDREFERENCIA = tmp.BDREFERENCIA
                                   AND z.BDCODCSTPIS = tmp.BDCODCSTPIS
                                   AND z.BDCODCSTCOF = tmp.BDCODCSTCOF
                                   AND z.BDCODQUADRO = 43
                                   AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                                   AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
                                   ) AS BDORDEM,
             tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODNATREC, SUM(tmp.BDVL_ITEM) AS BDVL_REC, NULL AS BDDESC_COMPL
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTCOF > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = :prCODEMP
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM400_M800 x
                    WHERE x.BDCODEMP = tmp.BDCODEMP
                      AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                      AND x.BDREFERENCIA = tmp.BDREFERENCIA
                      AND x.BDCODCSTCOF = tmp.BDCODCSTCOF
                      AND x.BDCODCSTPIS = tmp.BDCODCSTPIS
                      AND x.BDCODQUADRO = 26
                      AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                      AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))) ))
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODNATREC, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS;

    END

   /* Lan?amentos sem natureza da base de c?lculo  #Inconsist?ncia# */
   INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
   SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCODBLOCOM, tmp.BDCODTP, tmp.BDCHAVE, tmp.BDORDEM, tmp.BDORDEMPRO, 2 AS BDCODINC
   FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
   WHERE tmp.BDCODNATREC IS NULL
     AND tmp.BDCODMATRIZ = :prCODEMP
     AND tmp.BDREFERENCIA = :prREFERENCIA;

END
^

/* Alter (SP_APURACAO_BLOCOM_M400_M800AUX) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        /* REGISTRO M400: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? PIS/PASEP
           REGISTRO M800: RECEITAS ISENTAS, N?O ALCAN?ADAS PELA INCID?NCIA DA CONTRIBUI??O, SUJEITAS A AL?QUOTA ZERO OU DE VENDAS COM SUSPENS?O ? COFINS */
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR (:prcodemp,  :prREFERENCIA, :prWHEREEMPRESAS);

      wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA) ';

      wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
      wSQL = wSQL||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
      wSQL = wSQL||       'aux.BDCODCSTPIS, aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
      wSQL = wSQL||       'aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
      wSQL = wSQL||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA ';
      wSQL = wSQL||'FROM (';
                          /* Sa?das - Produtos */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 2 AS BDCODTP, ';
      wSQL = wSQL||              'p.BDVLRITEM AS BDVL_ITEM, p.BDCODNATREC, p.BDCODCTA, ';
      wSQL = wSQL||              'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS,';
      wSQL = wSQL||              'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROSAI p ON (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = COALESCE(p.BDCODPLAPADRAO,lan.BDCODPLAPADRAO) and ccl.BDCODTPLA = COALESCE(p.BDCODTPLA,lan.BDCREDITO)) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = COALESCE(p.BDCODPLAPADRAO,lanrat.BDCODPLAPADRAO) and cclrat.BDCODTPLA = COALESCE(p.BDCODTPLA,lanrat.BDCREDITO)) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Sa?das - Transporte (D100) */
      wSQL = wSQL||       'select mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL as BDORDEM,';
      wSQL = wSQL||              'NULL as BDORDEMPRO, 16 as BDCODTP, mov.BDVALORNOTA as BDVL_ITEM, d100.BDCODNATREC, NULL as BDCODCTA,';
      wSQL = wSQL||              'd100.BDCODCSTPIS, d100.BDVL_BC_PIS as BDBCPIS, d100.BDALIQ_PIS as BDALIQPIS, d100.BDVLRPIS,';
      wSQL = wSQL||              'd100.BDCODCSTCOF, d100.BDVL_BC_COF as BDBCCOFINS, d100.BDALIQ_COF as BDALIQCOFINS, d100.BDVLRCOFINS,';
      wSQL = wSQL||              'COALESCE(CCL.BDCODPLAPADRAO, CCLRAT.BDCODPLAPADRAO) as BDCODPLAPADRAO,';
      wSQL = wSQL||              'COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (trim(upper(nat.BDNAOEXPEFDCONT)) <> trim(''TRUE'')))) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Servi?o */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, ';
      wSQL = wSQL||              'a.BDVL_ITEM, a.BDCODNATREC, NULL AS BDCODCTA, ';
      wSQL = wSQL||              'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS,';
      wSQL = wSQL||              'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||              'WHERE s.BDTIPLAN = 0 '; -- Servi?os Emitidos
      wSQL = wSQL||                'AND (s.BDCODSITNF not in (2,3,4,5)) ';
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TA170 a ON (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESER, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSER GROUP BY BDCODEMP, BDCHAVESER, BDORDEM) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESER = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSER GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Demais documentos */
      wSQL = wSQL||       'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, ';
      wSQL = wSQL||              'dem.BDVL_OPER AS BDVL_ITEM, dem.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS, dem.BDVLR_PIS AS BDVLRPIS,';
      wSQL = wSQL||              'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(dem.bdCODPLAPADRAO, lan.bdCODPLAPADRAO) AS bdCODPLAPADRAO, COALESCE(dem.bdCODTPLA, lan.bdCREDITO) AS bdCODTPLA ';
      wSQL = wSQL||       'FROM ( ';
      wSQL = wSQL||               'SELECT dem.BDCODEMP, dem.BDREFLAN, dem.BDCHAVE, dem.bdIND_OPER, dem.BDVL_OPER, dem.BDCODNATREC, dem.bdCODPLAPADRAO, dem.bdCODTPLA, '; -- Caso tenha v?rios lan?amentos na contabiliza??o, vai buscar apenas a primeira conta...
      wSQL = wSQL||                      'dem.BDCODCSTPIS, dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS, ';
      wSQL = wSQL||                      'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||               'WHERE dem.bdIND_OPER IN (2,3) '; -- Opera??o Representativa de Receita
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        wSQL = wSQL||                'AND (dem.BDCONDPGTO <> 1) ';
      wSQL = wSQL||                'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND dem.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||       ' ) dem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT tol.bdCODEMP, tol.bdCHAVEDEMDOC, lan.bdCODPLAPADRAO, MIN(lan.bdDATA) AS bdDATA, MIN(lan.bdREFERENCIA) AS bdREFERENCIA, MIN(lan.bdCREDITO) AS bdCREDITO, MIN(lan.bdDEBITO) AS bdDEBITO ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVDEMAISDOC tol ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = tol.bdCODEMP AND lan.bdCHAVE = tol.bdCHAVE) ';
      wSQL = wSQL||                        'GROUP BY bdCODEMP, bdCHAVEDEMDOC, bdCODPLAPADRAO) lan ON (lan.bdCODEMP = dem.bdCODEMP AND lan.bdCHAVEDEMDOC = dem.bdCHAVE) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* Redu??o Z */
      wSQL = wSQL||       'SELECT redz.BDCODEMP, redz.BDCODMATRIZ, redz.BDREFLAN, redz.BDCHAVE, redz.BDORDEM, redz.BDORDEMPRO, redz.BDCODTP,  ';
      wSQL = wSQL||              'redz.BDVL_ITEM, redz.BDCODNATREC, redz.BDCODCTA,';
      wSQL = wSQL||              'redz.BDCODCSTPIS, redz.BDBCPIS, redz.BDALIQPIS, redz.BDVLRPIS,';
      wSQL = wSQL||              'redz.BDCODCSTCOF, redz.BDBCCOFINS, redz.BDALIQCOFINS, redz.BDVLRCOFINS, ';
      wSQL = wSQL||              'ccl.BDCODPLAPADRAO, ccl.BDCODTPLA ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, c425.BDCHAVE, c425.BDORDEMTOT AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 6 AS BDCODTP, ';
      wSQL = wSQL||                     'c425.BDVLRACU AS BDVL_ITEM, c425.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||                     'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425 c425 ON (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL ';

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, aliq.BDCHAVE, aliq.BDORDEMICMS AS BDORDEM, aliq.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, ';
      wSQL = wSQL||                     'aliq.BDVLRACU AS BDVL_ITEM, aliq.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'aliq.BDCODCSTPIS, aliq.BDVL_BC_PIS AS BDBCPIS, aliq.BDALIQ_PIS AS BDALIQPIS, aliq.BDVLRPIS,';
      wSQL = wSQL||                     'aliq.BDCODCSTCOF, aliq.BDVL_BC_COFINS AS BDBCCOFINS, aliq.BDALIQ_COFINS AS BDALIQCOFINS, aliq.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425ALIQ aliq ON (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL ';

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, i.BDCHAVE, i.BDORDEMDOCECF AS BDORDEM, i.BDORDEMITEM AS BDORDEMPRO, 8 AS BDCODTP, ';
      wSQL = wSQL||                     'i.BDVLRTOTPRO AS BDVL_ITEM, i.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'i.BDCODCSTPIS, i.BDVL_BC_PIS AS BDBCPIS, i.BDALIQ_PIS AS BDALIQPIS, i.BDVLRPIS AS BDVLRPIS,';
      wSQL = wSQL||                     'i.BDCODCSTCOF, i.BDVL_BC_COFINS AS BDBCCOFINS, i.BDALIQ_COFINS AS BDALIQCOFINS, i.BDVLRCOFINS ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TDOCECF doc ON (doc.BDCODEMP = mov.BDCODEMP AND doc.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TITEMDOCECF i ON (i.BDCODEMP = doc.BDCODEMP AND i.BDCHAVE = doc.BDCHAVE AND i.BDORDEMDOCECF = doc.BDORDEMDOCECF) ';
      wSQL = wSQL||            ') redz ';
      wSQL = wSQL||       'LEFT OUTER JOIN (';
      wSQL = wSQL||                         'SELECT v.BDCODEMP, v.BDCHAVECFOP,';
      wSQL = wSQL||                                '(SELECT FIRST 1 x.BDCHAVE FROM TOL_VEF_EMP_TREDZVARCFOP x WHERE x.BDCODEMP = v.BDCODEMP AND x.BDCHAVECFOP = v.BDCHAVECFOP) as BDCHAVE ';
      wSQL = wSQL||                         'FROM TOL_VEF_EMP_TREDZVARCFOP v ';
      wSQL = wSQL||                         'WHERE v.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                         'GROUP BY v.BDCODEMP, v.BDCHAVECFOP ';
      wSQL = wSQL||                         ') tol on (tol.BDCODEMP = redz.BDCODEMP and tol.BDCHAVECFOP = redz.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
                          /* I100 */
      wSQL = wSQL||       'SELECT i100.BDCODEMP, COALESCE(emp.BDCODMATRIZ, i100.BDCODEMP) as BDCODMATRIZ, i100.BDREFERENCIA AS BDREFLAN, i100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 9 AS BDCODTP, ';
      --wSQL = wSQL||              '(i100.BDVLRREC-i100.BDVLRTOTDEDGER-i100.BDVLRTOTDEDESP) AS BDVL_ITEM, i100.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'i100.BDVLRREC AS BDVL_ITEM, i100.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'i100.BDCODCSTPISCOF AS BDCODCSTPIS, i100.BDBASEPIS AS BDBCPIS, i100.BDALIQPIS, i100.BDVLRPIS,';
      wSQL = wSQL||              'i100.BDCODCSTPISCOF AS BDCODCSTCOF, i100.BDBASECOFINS AS BDBCCOFINS, i100.BDALIQCOFINS, i100.BDVLRCOFINS, ';
      wSQL = wSQL||              'i200.BDCODPLAPADRAO, i200.BDCODTPLA ';
      wSQL = wSQL||       'FROM VEF_EMP_TMOVFINI100 i100 ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = i100.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN ( SELECT i.BDCODEMP, i.BDCHAVE, i.BDORDEMI200 as BDORDEMI200, i.BDCODPLAPADRAO, i.BDCODTPLA ';
      wSQL = wSQL||                         'FROM VEF_EMP_TMOVFIN_I200 i ';
      wSQL = wSQL||                         'WHERE i.BDORDEMI200 = (SELECT FIRST 1 x.BDORDEMI200 ';
      wSQL = wSQL||                                                'FROM VEF_EMP_TMOVFIN_I200 x ';
      wSQL = wSQL||                                                'WHERE x.BDCODEMP = i.BDCODEMP ';
      wSQL = wSQL||                                                  'AND x.BDCHAVE = i.BDCHAVE ';
      wSQL = wSQL||                                                  'AND x.BDCODPLAPADRAO IS NOT NULL ';
      wSQL = wSQL||                                                  'AND x.BDCODTPLA IS NOT NULL) ) i200 on (i200.BDCODEMP = i100.BDCODEMP and i200.BDCHAVE = i100.BDCHAVE) ';
      wSQL = wSQL||       'WHERE i100.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND i100.BDREFERENCIA = '||:prREFERENCIA||' ';

      wSQL = wSQL||     ') aux ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
      wSQL = wSQL||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
      wSQL = wSQL||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';

      EXECUTE STATEMENT ( wSQL );

    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M400_M800PAR) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRWHEREEMPRESAS VARCHAR(500))
 AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
DECLARE VARIABLE WMOD_TRANSPORTE VARCHAR(30);
BEGIN
-- Modelos para lan?amento de entrada, faz isso para n?o carregar dados de movimentos errados.
-- Por exemplo: N?o carregar dados dos produtos em notas de transporte, caso tenham produtos lan?ados...
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incid?ncia tribut?ria <> de exclusivamente n?o-cumulativo e crit?rio de escritura??o = Regime de caixa...
        BEGIN
          wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA) ';
          wSQL = wSQL||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
          wSQL = wSQL||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
          wSQL = wSQL||       'aux.BDCODCSTPIS, aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
          wSQL = wSQL||       'aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
          wSQL = wSQL||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA ';
          wSQL = wSQL||'FROM (';
                              /* Sa?das - Produtos */
          wSQL = wSQL||       'SELECT sai.BDCODEMP, COALESCE(emp.BDCODMATRIZ, sai.BDCODEMP) as BDCODMATRIZ, sai.BDREFLAN, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 2 AS BDCODTP, ';
          wSQL = wSQL||              '(CAST(ROUND((';-- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                           '(IIF(qtdepro.BDQTDEPRO < 1, pgto.bdvalorpgtopar,'; -- Caso n?o tenha produtos integral
          wSQL = wSQL||                                                      '((COALESCE(pgto.bdvalorpgtopar,0)*((CAST( COALESCE(movpro.BDVLRITEM,0) AS NUMERIC(15,6))/itens.BDVLRCONTAB)))) ))+';
          wSQL = wSQL||                           '(IIF(qtdepro.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                                                         'COALESCE(pgto.BDVALORRETINSS,0) ),+';
          wSQL = wSQL||                                                     '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                                       '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/itens.BDVLRCONTAB)))) )))';
          wSQL = wSQL||                           ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM,';
          wSQL = wSQL||              'movpro.BDCODNATREC, movpro.BDCODCTA, movpro.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'movpro.BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'movpro.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'movpro.BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') SAI ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = sai.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x ON (sai.BDCODEMP = x.BDCODEMP AND sai.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (sai.BDCODEMP = par.BDCODEMP AND sai.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (sai.BDCODEMP = itens.BDCODEMP AND sai.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, Count(*) AS BDQTDEPRO FROM VEF_EMP_TMOVPROSAI p group by p.BDCODEMP, p.BDCHAVE, p.BDORDEM) qtdepro ON ';
          wSQL = wSQL||                                                    '(qtdepro.BDCODEMP = itens.BDCODEMP AND qtdepro.BDCHAVE = itens.BDCHAVE AND qtdepro.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODNATREC, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||                    'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS, p.BDCODPLAPADRAO, p.BDCODTPLA ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVPROSAI p) movpro ON (itens.BDCODEMP = movpro.BDCODEMP AND itens.BDCHAVE = movpro.BDCHAVE AND itens.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = movpro.BDCODCSTPIS) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = movpro.BDCODCSTCOF) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = COALESCE(movpro.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) and ccl.BDCODTPLA = COALESCE(movpro.BDCODTPLA, lan.BDCREDITO)) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = COALESCE(movpro.BDCODPLAPADRAO, lanrat.BDCODPLAPADRAO) and cclrat.BDCODTPLA = COALESCE(movpro.BDCODTPLA, lanrat.BDCREDITO)) ';
          wSQL = wSQL||       'WHERE ((movpro.BDCODCSTPIS is not null) OR (movpro.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"
          wSQL = wSQL||         'AND ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (movpro.BDALIQPIS = 0)) OR ';
          wSQL = wSQL||              '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (movpro.BDALIQCOFINS = 0))) ';

          wSQL = wSQL||       'UNION ALL ';
                              /* Sa?das - Transporte (D100) */
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, d100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'd100.BDCODNATREC, d100.BDCODCTA, d100.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'd100.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(cast((COALESCE(d100.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'd100.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'd100.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(d100.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que n?o s?o produtos...
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x ON (x.BDCODEMP = mov.BDCODEMP AND x.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TD100SAI d100 ON (mov.BDCODEMP = d100.BDCODEMP AND mov.BDCHAVE = d100.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((d100.BDCODCSTPIS is not null) OR (d100.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, d500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'd500.BDCODNATREC,d500.BDCODCTA,d500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'd500.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'd500.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'd500.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(d500.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS numeric(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5))';
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TD500SAI x ';
          wSQL = wSQL||             'WHERE not exists(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||             ') d500 ON (mov.BDCODEMP = d500.BDCODEMP AND mov.BDCHAVE = d500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((d500.BDCODCSTPIS is not null) OR (d500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, c500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'c500.BDCODNATREC, NULL AS BDCODCTA, c500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(c500.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'c500.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(c500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'c500.BDCODCSTCOF,';
          wSQL = wSQL||              'CAST((COALESCE(c500.BDVL_BC_COF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8)) AS BDBCCOFINS,';
          wSQL = wSQL||              'c500.BDALIQ_COF AS BDALIQCOFINS,';
          wSQL = wSQL||              'CAST((COALESCE(c500.BDVLRCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8)) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||             ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TC500SAI x ';
          wSQL = wSQL||             'WHERE not exists(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||             ') c500 ON (mov.BDCODEMP = C500.BDCODEMP AND mov.BDCHAVE = C500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((C500.BDCODCSTPIS is not null) OR (C500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, f500.BDCHAVE, f500.BDORDEM, f500.BDORDEMF500 AS BDORDEMPRO, 13 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'f500.BDCODNATREC, NULL AS BDCODCTA, f500.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDBASEPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'f500.BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'f500.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDBASECOF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'f500.BDALIQCOF AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(f500.BDVLRCOF,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
          wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
          wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                      'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||              ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSAIPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||       'JOIN (SELECT X.* FROM VEF_EMP_TF500SAI X ';
          wSQL = wSQL||             'WHERE not exists(SELECT Y.BDCODEMP, Y.BDCHAVE FROM VEF_EMP_TMOVPROSAI Y WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCHAVE = Y.BDCHAVE) ';
          wSQL = wSQL||             ') F500 ON (mov.BDCODEMP = F500.BDCODEMP AND mov.BDCHAVE = F500.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESAI = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((F500.BDCODCSTPIS is not null) OR (F500.bdcodcstcof is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';
    
          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'a170.BDCODNATREC, NULL AS BDCODCTA, a170.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'a170.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(a170.BDVL_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100) /COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSERPAR aux group by aux.BDCODEMP, aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSERPAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVSERPARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSERITENS itens ON (mov.BDCODEMP = itens.BDCODEMP AND mov.BDCHAVE = itens.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TA170 a170 ON (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND itens.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit ON (mov.BDCODSITNF = sit.BDCODSITNF) ';

          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVESER, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVSER GROUP BY BDCODEMP, BDCHAVESER, BDORDEM) tol on (tol.BDCODEMP = itens.BDCODEMP and tol.BDCHAVESER = itens.BDCHAVE and tol.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMP and lan.BDCHAVE = tol.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE FROM TOL_VEF_EMP_TMOVRATSER GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat on (tolrat.BDCODEMP = itens.BDCODEMP and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
          wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMP and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
          wSQL = wSQL||       'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||       'UNION ALL ';

          wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, ';
          wSQL = wSQL||              '(pgto.bdvalorpgtopar +(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||              'mov.BDCODNATREC, NULL AS BDCODCTA, mov.BDCODCSTPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||              'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||              'mov.BDCODCSTCOF,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||              'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||              '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||              'ccl.BDCODPLAPADRAO, COALESCE(mov.bdCODTPLA, ccl.bdCODTPLA) as bdCODTPLA ';
          wSQL = wSQL||       'FROM (';
          wSQL = wSQL||             'SELECT dem.BDCODEMP, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.bdCODTPLA, ';
          wSQL = wSQL||                    'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||                    'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||             'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||             'WHERE dem.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||                     'WHERE e.BDCODEMP = dem.BDCODEMP AND e.BDREFEMP <= dem.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X ON (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVF100PAR par ON (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||             'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||               'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto ON (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||       'LEFT OUTER JOIN (SELECT tol.bdCODEMP, tol.bdCHAVEDEMDOC, lan.bdCODPLAPADRAO, MIN(lan.bdDATA) AS bdDATA, MIN(lan.bdREFERENCIA) AS bdREFERENCIA, MIN(lan.bdCREDITO) AS bdCREDITO, MIN(lan.bdDEBITO) AS bdDEBITO ';
          wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVDEMAISDOC tol ';
          wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = tol.bdCODEMP AND lan.bdCHAVE = tol.bdCHAVE) ';
          wSQL = wSQL||                        'GROUP BY bdCODEMP, bdCHAVEDEMDOC, bdCODPLAPADRAO) lan ON (lan.bdCODEMP = mov.bdCODEMP AND lan.bdCHAVEDEMDOC = mov.bdCHAVE) ';

          wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
          wSQL = wSQL||       'WHERE ((mov.BDCODCSTPIS is not null) OR (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||         'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - N?o levar no faturamento caso o tipo seja "Desconto"

         wSQL = wSQL||     ') aux ';
         wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
         wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
         wSQL = wSQL||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
         wSQL = wSQL||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';
   
         EXECUTE STATEMENT ( wSQL );

        END

    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M500) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M500(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WMETODOAPRO INTEGER;
DECLARE VARIABLE WRBNCUMTRIBMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMNTMI NUMERIC(15,4);
DECLARE VARIABLE WRBNCUMEXP NUMERIC(15,4);
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configura??o da empresa na refer?ncia da apura??o...
  SELECT BDINCTRIB+1, -- Incid?ncia tribut?ria
         BDMETODOAPRO+1 -- M?todo de apropria??o
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  /* 34 - Contribui??o n?o cumulativa
     Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 1
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMTRIBMI;

  /* 34 - Contribui??o n?o cumulativa
     N?o Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 2
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMNTMI;

  /* 34 - Contribui??o n?o cumulativa
     Exporta??o */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribui??o n?o cumulativa
    AND BDNUMCAMPO = 3
    AND BDCODEMP = :prCODEMP
    AND BDREFERENCIA = :prREFERENCIA
  INTO :wRBNCUMEXP;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      /* REGISTRO M500: CR?DITO DE COFINS RELATIVO AO PER?ODO */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM100_500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDIND_CRED_ORI, BDVL_BC, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CRED,';
      wSQL = wSQL||                                    'BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CRED_DIF, BDVL_CRED_DISP, BDIND_DESC_CRED, BDVL_CRED_DESC, BDSLD_CRED) ';
      wSQL = wSQL||'SELECT 29 AS BDCODQUADRO, 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7) AS BDCHAVE,';
      wSQL = wSQL||       't436.BDCODCRE_4_3_6, 0 AS BDIND_CRED_ORI, SUM(COALESCE(tmp.BDBCCOFINS,0)) AS BDVL_BC, COALESCE(tmp.BDALIQCOFINS,0) AS BDALIQ,';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC, COALESCE(tmp.BDALIQCOFINS_QUANT,0) AS BDALIQ_QUANT,';
      wSQL = wSQL||       '(((SUM(COALESCE(tmp.BDBCCOFINS,0))*COALESCE(tmp.BDALIQCOFINS,1))/100)+(SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0))*COALESCE(tmp.BDALIQCOFINS_QUANT,1))) AS BDVL_CRED,';
      wSQL = wSQL||       '0 AS BDVL_AJUS_ACRES, 0 AS BDVL_AJUS_REDUC, 0 AS BDVL_CRED_DIF, 0 AS BDVL_CRED_DISP,';
      wSQL = wSQL||       'NULL AS BDIND_DESC_CRED, 0 AS BDVL_CRED_DESC, 0 AS BDSLD_CRED ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED,';
      wSQL = wSQL||             'x.BDALIQCOFINS,';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT,';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT,';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                    -- Rateio
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||             'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED, ';
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||             'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
         wSQL = wSQL||          'x.BDCOD_CRED as BDCOD_CRED, ';
         wSQL = wSQL||          'x.BDBCCOFINS ';
        END
      wSQL = wSQL||             'AS BDBCCOFINS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTCOF and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';

      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCCOFINS > 0) OR (tmp.BDBCCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQCOFINS > 0) OR (tmp.BDALIQCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      --wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, t436.BDCODCRE_4_3_6, tmp.BDALIQCOFINS, tmp.BDALIQCOFINS_QUANT; ';
 
      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M505: DETALHAMENTO DA BASE DE CALCULO DO CR?DITO APURADO NO PER?ODO ? COFINS */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM105_M505 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCSTPIS, BDCODCSTCOF, BDCODNATBC, BDCODCRE_4_3_6,';
      wSQL = wSQL||                                     'BDVL_BC_TOT, BDVL_BC_CUM, BDVL_BC_NC, BDVL_BC, BDQUANT_BC_TOT, BDQUANT_BC, BDDESC_CRED, BDALIQ) ';
      wSQL = wSQL||'SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, 29 AS BDCODQUADRO, tmp.BDREFERENCIA, ';
      wSQL = wSQL||       '(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQCOFINS) OR (x.BDALIQ_QUANT = tmp.BDALIQCOFINS_QUANT))) AS BDCHAVE, ';
      wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDORDEM)+1,1)';
      wSQL = wSQL||        'FROM VEF_EMP_TBLOCOM105_M505 x ';
      wSQL = wSQL||        'WHERE x.BDCODPERIODO = 7 ';
      wSQL = wSQL||          'AND x.BDCODEMP = tmp.BDCODEMP ';
      wSQL = wSQL||          'AND x.BDCODMATRIZ = tmp.BDCODMATRIZ ';
      wSQL = wSQL||          'AND x.BDCODQUADRO = 29 ';
      wSQL = wSQL||          'AND x.BDREFERENCIA = tmp.BDREFERENCIA ';
      wSQL = wSQL||          'AND x.BDCHAVE = (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 29 AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQCOFINS) OR (x.BDALIQ_QUANT = tmp.BDALIQCOFINS_QUANT)))) AS BDORDEM, ';
      wSQL = wSQL||       'tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED AS BDCODNATBC, t436.BDCODCRE_4_3_6, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINSTOTAL,0)) AS BDVL_BC_TOT, 0 AS BDVL_BC_CUM, /*(Campo 04 ? Campo 05)*/SUM(COALESCE(tmp.BDBCCOFINSTOTAL,0)-0) AS BDVL_BC_NC, ';
      wSQL = wSQL||       'SUM(COALESCE(tmp.BDBCCOFINS,0)) AS BDVL_BC, SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC_TOT, SUM(COALESCE(tmp.BDBCCOFINS_QUANT,0)) AS BDQUANT_BC, NULL AS BDDESC_CRED, COALESCE(tmp.BDALIQCOFINS,tmp.BDALIQCOFINS_QUANT) AS BDALIQ ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT, ';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED, ';
      wSQL = wSQL||             'x.BDALIQCOFINS, x.BDBCCOFINS as BDBCCOFINSTOTAL, ';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT, ';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT, ';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso fa?a rateio na CST com c?digo de cr?dito, aqui pega os c?digos de cr?dito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED, ';
                                    -- Caso fa?a rateio na CST com c?digo de cr?dito, faz os rateios das base de c?lculos pelas formulas do registro 0111...
          wSQL = wSQL||             'CASE x.BDCODCSTPIS ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMTRIBMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMNTMI||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (x.BDBCCOFINS*(('||:wRBNCUMEXP||'*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE x.BDBCCOFINS ';
          wSQL = wSQL||             'END ';
        END
      ELSE
        BEGIN
         wSQL = wSQL||          'x.BDCOD_CRED as BDCOD_CRED, ';
         wSQL = wSQL||          'x.BDBCCOFINS ';
        END
      wSQL = wSQL||             'AS BDBCCOFINS ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo / 2 - M?todo de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCSTCOF and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';

      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...
      wSQL = wSQL||'WHERE ((tmp.BDBCCOFINS > 0) OR (tmp.BDBCCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQCOFINS > 0) OR (tmp.BDALIQCOFINS_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lan?amentos de produtos...
      wSQL = wSQL||       '('; -- Fiiltro dos c?digo da base de c?lculo de cr?tido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisi??o de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisi??o de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisi??o de Servi?os Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolu??o de Vendas Sujeitas ? Incid?ncia N?o-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Opera??es com Direito a Cr?dito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- N?o pode levar movimenta??o imobili?ria...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED, t436.BDCODCRE_4_3_6, tmp.BDALIQCOFINS, tmp.BDALIQCOFINS_QUANT; ';
 
      EXECUTE STATEMENT ( wSQL );

      /* REGISTRO M510: AJUSTES DO CR?DITO DE COFINS APURADO */
      INSERT INTO VEF_EMP_TBLOCOM110_M510 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, BDDESCR_AJ, BDDT_REF)
      SELECT 7 as BDCODPERIODO, m.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) as BDCODMATRIZ,  29 as BDCODQUADRO, m.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = m.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP) AND x.BDCODQUADRO = 29 AND x.BDREFERENCIA = m.BDREFERENCIA AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6 AND ((x.BDALIQ = m.BDALIQCOFINS) OR (x.BDALIQ_QUANT = m.BDALIQCOFINS))) as BDCHAVE,
             (SELECT COALESCE(MAX(x.BDORDEM+1),1)
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 29
                AND x.BDCODEMP = m.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                AND x.BDREFERENCIA = m.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM100_500 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDCODEMP = m.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)
                                   AND x.BDREFERENCIA = m.BDREFERENCIA
                                   AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                                   AND ((x.BDALIQ = m.BDALIQCOFINS) OR (x.BDALIQ_QUANT = m.BDALIQCOFINS))) ) as BDORDEM,
             m.BDCODAJUEFDC, m.BDTIPOAJUSTE as BDIND_AJ, SUM(m.BDVLRAJUCOFINS) as BDVL_AJ, m.BDNUMERODOC as BDNUM_DOC, m.BDDESCRICAO as BDDESCR_AJ, m.BDDATAREF as BDDT_REF
      FROM VEF_EMP_TCREDAJU_M110_M510 m
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m.BDCODEMP)
      WHERE m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM100_500 m100
                    WHERE m100.BDCODPERIODO = 7
                      AND m100.BDCODQUADRO = 29
                      AND m100.BDCODEMP = m.BDCODEMP
                      AND m100.BDREFERENCIA = m.BDREFERENCIA
                      AND m100.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND ((m100.BDALIQ = m.BDALIQCOFINS) OR (m100.BDALIQ_QUANT = m.BDALIQCOFINS)) ))
      GROUP BY m.BDCODEMP, emp.BDCODMATRIZ, m.BDREFERENCIA, m.BDCODAJUEFDC, m.BDTIPOAJUSTE, m.BDNUMERODOC, m.BDDESCRICAO, m.BDDATAREF, m.BDCODCRE_4_3_6, m.BDALIQCOFINS;
 
      /* REGISTRO 515: DETALHAMENTO DOS AJUSTES DO CR?DITO DE COFINS APURADO */
      INSERT INTO VEF_EMP_TBLOCOM115_M515 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM15, BDCODCSTCOF, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL)
      SELECT 7 as BDCODPERIODO, m515.BDCODEMP, COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP) as BDCODMATRIZ, 29 as BDCODQUADRO, m510.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDCODQUADRO = 29
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDNUM_DOC = m510.BDNUMERODOC
                AND x.BDDESCR_AJ = m510.BDDESCRICAO
                AND x.BDDT_REF = m510.BDDATAREF ) as BDCHAVE,
             (SELECT x.BDORDEM
              FROM VEF_EMP_TBLOCOM110_M510 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDCODQUADRO = 29
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDNUM_DOC = m510.BDNUMERODOC
                AND x.BDDESCR_AJ = m510.BDDESCRICAO
                AND x.BDDT_REF = m510.BDDATAREF ) as BDORDEM,
             (SELECT COALESCE(MAX(x.BDORDEM15+1),1)
              FROM VEF_EMP_TBLOCOM115_M515 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 29
                AND x.BDCODEMP = m515.BDCODEMP
                AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                AND x.BDREFERENCIA = m510.BDREFERENCIA
                AND x.BDCHAVE = (SELECT x.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF )
                AND x.BDORDEM = (SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF ) ) as BDORDEM15,
             m515.BDCODCSTCOF, m515.BDCODCSTPIS, m515.BDCODPLAPADRAO, m515.BDCODTPLA, SUM(m510.BDVLRAJUCOFINS) as BDDET_VALOR_AJ, SUM(m515.BDBCCOFINS) as BDDET_BC_CRED,
             m515.BDALIQCOFINS as BDDET_ALIQ, m515.BDDATAOPECOFINS as BDDT_OPER_AJ, m515.BDDESCRICAOAJU as BDDESC_AJ, m515.BDINFCOMP as BDINFO_COMPL
      FROM VEF_EMP_TCREDAJU_M110_M510 m510
      JOIN VEF_EMP_TDETAJU_M115_M515 m515 on (m515.BDCODEMP = m510.BDCODEMP AND m515.BDCHAVE = m510.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m510.BDCODEMP)
      WHERE m515.BDCODEMP IS NOT NULL
        AND m515.BDBCCOFINS > 0
        AND m510.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
        AND m510.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT x.BDORDEM
                                 FROM VEF_EMP_TBLOCOM110_M510 x
                                 WHERE x.BDCODPERIODO = 7
                                   AND x.BDCODEMP = m515.BDCODEMP
                                   AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, m515.BDCODEMP)
                                   AND x.BDCODQUADRO = 29
                                   AND x.BDREFERENCIA = m510.BDREFERENCIA
                                   AND x.BDNUM_DOC = m510.BDNUMERODOC
                                   AND x.BDDESCR_AJ = m510.BDDESCRICAO
                                   AND x.BDDT_REF = m510.BDDATAREF ))
      GROUP BY m515.BDCODEMP, emp.BDCODMATRIZ, m510.BDREFERENCIA, m510.BDCODCRE_4_3_6,  m515.BDCODCSTCOF, m515.BDCODCSTPIS, m515.BDCODPLAPADRAO, m515.BDCODTPLA,
               m515.BDALIQCOFINS, m515.BDDATAOPECOFINS, m515.BDDESCRICAOAJU, m515.BDINFCOMP, m510.BDNUMERODOC, m510.BDDESCRICAO, m510.BDDATAREF;
 
    END

END
^

/* Alter (SP_APURACAO_BLOCOM_M600) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_M600(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCREDITOSPERANT VARCHAR(5);
DECLARE VARIABLE WRETPISCOFPERANT VARCHAR(5);
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WVLRAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRUP NUMERIC(15,2);
DECLARE VARIABLE WVLRUPAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRSLD NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT NUMERIC(15,2);
DECLARE VARIABLE WVLRTOTCONT_ORIGINAL NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT NUMERIC(15,2);
DECLARE VARIABLE WVLRCREDPERANT_TOTAL NUMERIC(15,2);
DECLARE VARIABLE WINTAUX INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WPER_APU_CRED INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODCRE_4_3_6 INTEGER;
DECLARE VARIABLE WIND_CRED_ORI INTEGER;
DECLARE VARIABLE WCOD_NAT_REC INTEGER;
DECLARE VARIABLE WCHAVEAUX INTEGER;
DECLARE VARIABLE WORDENACAO INTEGER;
DECLARE VARIABLE WIND_DESC_CRED INTEGER;
BEGIN
  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCREDITOSPERANT, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCREDITOSPERANT, :wRETPISCOFPERANT;

  /* REGISTRO M200: CONSOLIDA??O DA CONTRIBUI??O PARA O PIS/PASEP DO PER?ODO */
  /* 1 - Exclusivamente no regime n?o-cumulativo */
  IF (wINCTRIB IN (1,3)) THEN
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M610, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      wVLRTOTCONT = 0;
      SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR
      FROM VEF_EMP_TBLOCOM210_M610 m
      LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL)
      WHERE (t435.BDCODCSOCIALEXP IN (01,02,03,04,32,71))
        AND (m.BDCODQUADRO = 37) -- M610 - Detalhamento da contribui??o para o Cofins
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRTOTCONT;

      wVLRTOTCONT_ORIGINAL = wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 2, COALESCE(:wVLRTOTCONT,0));

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100)
         Caso esteja configurado para usar saldo do per?odo anterior, deve descontar ele primeiro, antes do cr?dito do per?odo atual... */
      wVLRCREDPERANT = 0;
      wVLRCREDPERANT_TOTAL = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 53) -- 1500 - Controle de cr?ditos fiscais Cofins
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL = wVLRCREDPERANT_TOTAL + wVLR;

                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
              END
          END
        END

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      SELECT COUNT(m.BDCHAVE) as BDQTD
      FROM VEF_EMP_TBLOCOM100_500 m
      WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
        AND m.BDCODMATRIZ = :prCODEMP
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO wQTD;

      IF ((wQTD = 0) OR (wVLRTOTCONT = 0) OR (wVLRTOTCONT IS NULL)) THEN -- Caso n?o tenha dados no M100/M500 ou o valor do cr?dito seja zerado...
        BEGIN
          UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                               VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, 0)
                                             MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
            UPDATE VEF_EMP_TBLOCOM100_500 m
            SET m.BDIND_DESC_CRED = 1,
                m.BDVL_CRED_DESC  = 0,
                m.BDSLD_CRED      = m.BDVL_CRED_DISP
            WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA;
 
            /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
            SELECT COUNT(*)
            FROM VEF_EMP_TBLOCOM1100_1500 m
            WHERE m.BDCODPERIODO = 7
              AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDREFERENCIA = :prREFERENCIA
              AND m.BDPER_APU_CRED = :prREFERENCIA
              AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
              AND m.BDORIG_CRED = :wIND_CRED_ORI
            INTO :wQTD;
  
            IF (:wQTD > 0) THEN
              BEGIN
                /* Caso tenha registros atualiza */
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                    m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                    m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
      ELSE
        BEGIN
                /* Caso n?o tenha lan?amento de saldos insere */
                INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                              VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                      (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA),
                                                      7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
              END
          END
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              GROUP BY m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDIND_CRED_ORI
              INTO :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wIND_CRED_ORI, :wVLR
          DO
          BEGIN
            IF (:wVLRTOTCONT > 0) THEN
              BEGIN
                /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1300. */
                IF (:wVLR < :wVLRTOTCONT) THEN
                  BEGIN
                    wVLRSLD        = 0;
                    wVLRTOTCONT    = wVLRTOTCONT - wVLR;
                    wIND_DESC_CRED = 0; -- 0 ? Utiliza??o do valor total para desconto da contribui??o apurada no per?odo, no Registro M200;
                  END
                ELSE
                  BEGIN
                    /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                    wVLRSLD        = :wVLR - :wVLRTOTCONT;
                    wVLR           = :wVLR - :wVLRSLD;
                    wVLRTOTCONT    = 0;
                    wIND_DESC_CRED = 1; -- 1 ? Utiliza??o de valor parcial para desconto da contribui??o apurada no per?odo, no Registro M200.
                  END
    
                -- Atualiza os cr?ditos descontados do M500...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = :wIND_DESC_CRED,
                    m.BDVL_CRED_DESC  = :wVLR,
                    m.BDSLD_CRED      = :wVLRSLD
                WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDCHAVE = :wCHAVE
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI;

                IF (wVLRSLD > 0) THEN
                  BEGIN
                /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                SELECT COUNT(*)
                FROM VEF_EMP_TBLOCOM1100_1500 m
                WHERE m.BDCODPERIODO = 7
                  AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDPER_APU_CRED = :prREFERENCIA
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI
                INTO :wQTD;
      
                IF (:wQTD > 0) THEN
                  BEGIN
                    /* Caso tenha registros atualiza */
                    UPDATE VEF_EMP_TBLOCOM1100_1500 m
                    SET m.BDVL_CRED_APU      = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO  = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI;
                  END
                ELSE
                  BEGIN
                    /* Caso n?o tenha lan?amento de saldos insere */
                    INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                  VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                              (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                              7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', (:wVLR + :wVLRSLD) /*:wVLR*/, :wVLR/*0*/, :wVLRSLD/*:wVLR*/);
                  END
              END

                wVLRAUX = 0;
                SELECT COALESCE(BDVALOR, 0)
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
                  AND BDREFERENCIA = :prREFERENCIA
                  AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
                  AND BDNUMCAMPO   = 3
                INTO wVLRAUX;
         
                IF (wVLRAUX IS NULL) THEN
                  wVLRAUX = 0;
         
                UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, COALESCE(:wVLR+:wVLRAUX,0))
                                                   MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);

                  END
                ELSE
                  BEGIN
                -- Zera os cr?ditos descontados do M100 e joga tudo pra saldo...
                UPDATE VEF_EMP_TBLOCOM100_500 m
                SET m.BDIND_DESC_CRED = 1,
                    m.BDVL_CRED_DESC  = 0,
                    m.BDSLD_CRED      = m.BDVL_CRED_DISP
                WHERE (m.BDCODQUADRO = 29) -- M500 - Cr?dito de Cofins
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDIND_CRED_ORI = :wIND_CRED_ORI
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :prREFERENCIA
                  AND m.BDCHAVE = :wCHAVE;
          
                    /* Cria lan?amento de implanta??o de saldos, aqui verifica se j? existem lan?amentos de Saldos */
                    SELECT COUNT(*)
                    FROM VEF_EMP_TBLOCOM1100_1500 m
                    WHERE m.BDCODPERIODO = 7
                      AND m.BDCODQUADRO = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                      AND m.BDCODEMP = :wCODEMP
                      AND m.BDCODMATRIZ = :wCODMATRIZ
                      AND m.BDREFERENCIA = :prREFERENCIA
                      AND m.BDPER_APU_CRED = :prREFERENCIA
                      AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                      AND m.BDORIG_CRED = :wIND_CRED_ORI
                    INTO :wQTD;
          
                    IF (:wQTD > 0) THEN
                      BEGIN
                        /* Caso tenha registros atualiza */
                        UPDATE VEF_EMP_TBLOCOM1100_1500 m
                        SET m.BDVL_CRED_APU = m.BDVL_CRED_APU+:wVLR,
                        m.BDVL_CRED_DESC_EFD = m.BDVL_CRED_DESC_EFD,
                        m.BDSLD_CRED_FIM     = m.BDSLD_CRED_FIM+:wVLR
                        WHERE m.BDCODPERIODO = 7
                          AND m.BDCODQUADRO = 53 -- 1500 - Controle de cr?ditos fiscais Cofins
                          AND m.BDCODEMP = :wCODEMP
                          AND m.BDCODMATRIZ = :wCODMATRIZ
                          AND m.BDREFERENCIA = :prREFERENCIA
                          AND m.BDPER_APU_CRED = :prREFERENCIA
                          AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                          AND m.BDORIG_CRED = :wIND_CRED_ORI;
                      END
                    ELSE
                      BEGIN
                        /* Caso n?o tenha lan?amento de saldos insere */
                        INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM)
                                                      VALUES (53, -- 1500 - Controle de cr?ditos fiscais Cofins
                                                          (SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = 53 AND x.BDCODPERIODO = 7 AND x.BDCODEMP = :wCODEMP AND x.BDCODMATRIZ = :wCODMATRIZ AND x.BDREFERENCIA = :prREFERENCIA),
                                                          7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -', :wVLR, 0, :wVLR);
                      END
                          END
                          END
                      END

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      wVLR = 0;
      IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a op??o "Aproveitar o cr?dito de PIS e Cofins de per?odos anteriores" */
        BEGIN
          wVLR = wVLRCREDPERANT_TOTAL;
        END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED,
                     SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM1100_1500 m
              WHERE (m.BDCODQUADRO = 53) -- 1500 - Controle de cr?ditos fiscais Cofins
                AND (m.BDCODMATRIZ = :prCODEMP)
                AND (m.BDREFERENCIA = :prREFERENCIA)
              GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDORIG_CRED
              ORDER BY m.BDPER_APU_CRED
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, wIND_CRED_ORI, :wVLRCREDPERANT
          DO
          BEGIN
            IF ((:wVLRTOTCONT > 0) AND (:wVLRCREDPERANT > 0)) THEN
              BEGIN
                IF (:wVLRTOTCONT < :wVLRCREDPERANT) THEN -- Caso o valor da contribui??o seja menor que o cr?dito anterior, apenas abate esse valor...
                  BEGIN
                    wVLR = :wVLRTOTCONT;
                    wVLRTOTCONT = 0;
                  END
                ELSE
                  BEGIN -- Caso o valor da contribu??o seja maior que o cr?dito, pode abater totalmente...
                    wVLR = :wVLRCREDPERANT;
                    wVLRTOTCONT = wVLRTOTCONT - wVLRCREDPERANT;
                  END

                wVLRCREDPERANT_TOTAL =  wVLRCREDPERANT_TOTAL + wVLR;
    
                UPDATE VEF_EMP_TBLOCOM1100_1500 m
                SET m.BDVL_CRED_DESC_EFD = :wVLR,
                    m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :wVLR
                WHERE m.BDCODPERIODO = :wCODPERIODO
                  AND m.BDCODQUADRO = :wCODQUADRO -- 1500 - Controle de cr?ditos fiscais Cofins
                  AND m.BDCODEMP = :wCODEMP
                  AND m.BDCODMATRIZ = :wCODMATRIZ
                  AND m.BDREFERENCIA = :wREFERENCIA
                  AND m.BDPER_APU_CRED = :wPER_APU_CRED
                  AND m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  AND m.BDORIG_CRED = :wIND_CRED_ORI;
        END
          END

          wVLR = wVLRCREDPERANT_TOTAL;
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 4, COALESCE(:wVLR,0));

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (2))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (3,4))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 5, COALESCE(:wVLR,0));

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 0 '; -- N?o cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1700. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
              AND BDNUMCAMPO   = 6
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRCOFINS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 1 -- 0 - Dedu??o de Natureza N?o Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 7, COALESCE(:wVLR,0));

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR) as BDVALOR, SUM(aux.BDVLRSUB) as BDVALORSUB
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (5))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (6,7))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR, wVLRAUX;

      IF ((wVLR - wVLRAUX) >= 0) THEN -- Se tiver valor de contribbui??o, calcula os campos a somar e subtrair...
        wVLR = (wVLR - wVLRAUX);
      ELSE
      /* Se o valor do campo 5(Valor Total da Contribui??o) menos o valor do campo 6(Valor Retido na Fonte) for menor que zero, ent?o este valor deve ser levado como saldo no registro 1300. */
      IF ((wVLR - wVLRAUX) < 0) THEN -- Se n?o tiver valor de contribbui??o, leva zerado...
        BEGIN
          /* Atualiza o valor do campo 6, Valor Retido na Fonte, s? pode usar aquilo que abater e n?o o total... */
          UPDATE VEF_EMP_TBLOCOMGERREG
          SET BDVALOR = :wVLR
          WHERE BDCODMATRIZ  = :prCODEMP
            AND BDREFERENCIA = :prREFERENCIA
            AND BDCODQUADRO  = 33
            AND BDNUMCAMPO   = 6;

          FOR
              SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, COALESCE(m.BDVL_RET_APU, 0)
              FROM VEF_EMP_TBLOCOM1300_1700 m
              WHERE (m.BDCODQUADRO = 50) -- 1700 - Ficha de reten??o do Cofins
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUP
          DO
            BEGIN
              IF (wVLR > 0) THEN
                BEGIN
                  /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                  IF (:wVLRUP < :wVLR) THEN
                    BEGIN
                      wVLRUPAUX = :wVLRUP;
                      wVLRSLD   = 0;
                      wVLR      = :wVLR-:wVLRUP; /* Cr?dito j? descontado vai ser abatido... */
                    END
                  ELSE
                    BEGIN
                      wVLRUPAUX = :wVLR;
                      wVLRSLD   = :wVLRUP - :wVLR;
                    END
    
                  UPDATE OR INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDVL_RET_DED, BDSLD_RET)
                                                          VALUES (:wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVLRUPAUX  , :wVLRSLD)
                                                        MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE);
                END
            END

          wVLR = 0; -- Se n?o tiver valor de contribbui??o, leva zerado...
        END

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 8, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN
      /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribui??o N?o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 01, 02, 03, 04, 32 e 71) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 2, 0);

      /* 03 - VL_TOT_CRED_DESC - Valor do Cr?dito Descontado, Apurado no Pr?prio Per?odo da Escritura??o (recuperado do campo 14 do Registro M100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 3, 0);

      /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior (recuperado do campo 13 do Registro 1100) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 4, 0);

      /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribui??o N?o Cumulativa Devida (02 ? 03 - 04) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 5, 0);

      /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 6, 0);

      /* 07 - VL_OUT_DED_NC - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 7, 0);

      /* 08 - VL_CONT_NC_REC - Valor da Contribui??o N?o Cumulativa a Recolher/Pagar (05 ? 06 - 07) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 8, 0);
    END

  /* 2 - Exclusivamente no regime cumulativo */
  IF (wINCTRIB IN (2,3)) THEN
    BEGIN
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      wVLRTOTCONT = 0;
      wSQL =        'SELECT SUM(COALESCE(m.BDVL_CONT_PER, 0)) as BDVALOR ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM210_M610 m ';
      wSQL = wSQL|| 'LEFT OUTER JOIN  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.BDCODCSOCIAL =  m.BDCODCSOCIAL) ';
      IF (wINCTRIB IN (3)) THEN -- Quando ? regime n?o-cumulativo e cumulativo, j? considerou algumas contribui??es no campo 2...
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,51,52,53,54,72)) ';
      ELSE
        wSQL = wSQL|| 'WHERE (t435.BDCODCSOCIALEXP IN (31,32,51,52,53,54,72)) ';
      wSQL = wSQL|| '  AND (m.BDCODQUADRO = 37) '; -- M610 - Detalhamento da contribui??o para o Cofins
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :wVLRTOTCONT;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 9, COALESCE(:wVLRTOTCONT,0));

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
      IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQL )
      INTO :WQTD;

      IF ((WQTD = 0) OR ((:wVLRTOTCONT IS NULL) OR (:wVLRTOTCONT = 0)))  THEN
        BEGIN
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                     VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, COALESCE(:wVLR,0));
        END
      ELSE
        BEGIN
      wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de reten??o do Cofins
          IF (wINCTRIB IN (3)) THEN -- Apenas vai considerar o tipo de incid?ncia tribut?ria quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Quando estiver configurada a op??o "Aproveitar as reten??es de PIS e Cofins de per?odos anteriores" vai aproveitar sempre os per?odos anteriores primeiro...
      wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          ELSE -- Caso conter?rio, vai primeiro abater o m?s atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      FOR
          EXECUTE STATEMENT ( wSQL )
              INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
      DO
      BEGIN
        IF (:wVLRTOTCONT > 0) THEN
          BEGIN
            /* Se o valor do cr?dito for maior que o valor do d?bito ent?o este valor deve ser levado como saldo credor no registro 1700. */
            IF (:wVLR < :wVLRTOTCONT) THEN
              BEGIN
                wVLRSLD     = 0;
                wVLRTOTCONT = wVLRTOTCONT - wVLR;
              END
            ELSE
              BEGIN
                /* Caso tenha mais d?bitos que cr?ditos, abate apenas apenas os cr?ditos poss?veis do lan?amento... */
                wVLRSLD     = :wVLR - :wVLRTOTCONT;
                wVLR        = :wVLR - :wVLRSLD;
                wVLRTOTCONT = 0;
              END
    
            /* Caso tenha registros atualiza */
            UPDATE VEF_EMP_TBLOCOM1300_1700 m
            SET m.BDVL_RET_DED = :wVLR,
                m.BDSLD_RET    = :wVLRSLD
            WHERE m.BDCODPERIODO = :wCODPERIODO
              AND m.BDCODEMP = :wCODEMP
              AND m.BDCODMATRIZ = :wCODMATRIZ
              AND m.BDCODQUADRO = :wCODQUADRO
              AND m.BDREFERENCIA = :wREFERENCIA
              AND m.BDCHAVE = :wCHAVE
              AND m.BDCOD_NAT_REC = :wCOD_NAT_REC;
    
            wVLRAUX = 0;
            SELECT COALESCE(BDVALOR, 0)
            FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODMATRIZ  = :prCODEMP
              AND BDREFERENCIA = :prREFERENCIA
              AND BDCODQUADRO  = 33 -- M600 - Consolida??o da contribui??o para o Cofins
                  AND BDNUMCAMPO   = 10
            INTO wVLRAUX;
      
            IF (wVLRAUX IS NULL) THEN
              wVLRAUX = 0;
      
            UPDATE OR INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                                         VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, COALESCE(:wVLR+:wVLRAUX,0))
                                               MATCHING (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO);
          END
      END
        END

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      wVLR = 0;
      SELECT SUM(COALESCE(m.BDVLRCOFINS, 0)) as BDVALOR
      FROM VEF_EMP_TORIDEDF700 m
      WHERE m.BDINDNATDED = 2 -- 1 - Dedu??o de Natureza Cumulativa
        AND m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND m.BDREFERENCIA = :prREFERENCIA
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 11, COALESCE(:wVLR,0));

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      wVLR = 0;
      SELECT SUM(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      FROM (/* Campo a somar */
            SELECT m.BDCODEMP, m.BDREFERENCIA, COALESCE(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (9))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            UNION ALL
            /* Campo a subtrair */
            SELECT m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, COALESCE(m.BDVALOR,0) as BDVLRSUB
            FROM VEF_EMP_TBLOCOMGERREG m
            WHERE (m.BDCODQUADRO = 33)
              AND (m.BDNUMCAMPO in (10,11))
              AND m.BDCODMATRIZ = :prCODEMP
              AND m.BDREFERENCIA = :prREFERENCIA
            ) aux
      INTO :wVLR;

      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 12, COALESCE(:wVLR,0));
    END
  ELSE
    BEGIN -- Joga os valores zerados...
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribui??o Cumulativa do Per?odo (recuperado do campo 13 do Registro M210, quando o campo ?COD_CONT? = 31, 32, 51, 52, 53, 54 e 72) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 9, 0);

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 10, 0);

      /* 11 - VL_OUT_DED_CUM - Outras Dedu??es no Per?odo */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 11, 0);

      /* 12 - VL_CONT_CUM_REC - Valor da Contribui??o Cumulativa a Recolher/Pagar (09 - 10 ? 11) */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 12, 0);
    END

  /* 3 - Regimes n?o-cumulativo e cumulativo */
  /* 13 - VL_TOT_CONT_REC - Valor Total da Contribui??o a Recolher/Pagar no Per?odo (08 + 12) */
  wVLR = 0;
  SELECT SUM(COALESCE(m.BDVALOR,0)) as BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG m
  WHERE (m.BDCODQUADRO = 33)
    AND (m.BDNUMCAMPO in (8,12))
    AND m.BDCODMATRIZ = :prCODEMP
    AND m.BDREFERENCIA = :prREFERENCIA
  INTO :wVLR;

  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR)
                             VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 33, 13, COALESCE(:wVLR,0));

END
^

/* Alter (SP_APURACAO_BLOCOM_ONLINE) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
BEGIN
  -- Limpa a tabela de contabiliza??o do Bloco M
  DELETE FROM TMP_TCONF_CONTAS_ONLINE_TEMP WHERE bdCODMATRIZ = :prCODEMP AND bdREFERENCIA = :prREFERENCIA;

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Incid?ncia tribut?ria
  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;

  IF (:wINCTRIB IN (1,3)) THEN -- 1 - Exclusivamente no regime n?o-cumulativo e 3 - Regimes n?o-cumulativo e cumulativo
    BEGIN
      -- Valida as contas da contabiliza??o da apura??o do Bloco M...
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDAONLINE (:prCODEMP, :prREFERENCIA);
    
      -- Verifica se possui alguma inconsist?ncia de contas online...
      SELECT FIRST 1 i.bdCODINC
      FROM VEF_INCON_BLOCOM i
      WHERE i.bdCODMATRIZ = :prCODEMP
        AND i.bdREFERENCIA = :prREFERENCIA
        -- "Outras Dedu??es" n?o ? um campo obrigat?rio
        AND i.bdCODINC IN (13,/*"Cr?dito" do PIS*/    14,/*"D?bito" do PIS*/    /*15,/*"Outras Dedu??es" do PIS*/    16,/*"Compensa??o" do PIS*/
                           17,/*"Cr?dito" do Cofins*/ 18,/*"D?bito" do Cofins*/ /*19,/*"Outras Dedu??es" do Cofins*/ 20,/*"Compensa??o" do Cofins*/
                           21/*Inconsist?ncias gen?rica da contabiliza??o detalhada*/)
      INTO :wCODINC;
    
      -- Deleta os registros da tabela da contabiliza??o, caso exista algum lan?amento
      DELETE FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
      WHERE t.bdCODMATRIZ = :prCODEMP
        AND t.bdREFERENCIA = :prREFERENCIA;

      IF (:wCODINC IS NULL) THEN
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO (:prCODEMP, :prREFERENCIA);
    END
 
END
^

/* Alter (SP_APURACAO_BLOCOM_ONLINE_CONSO) */
ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO(PRCODEMP INTEGER,
PRREFERENCIA INTEGER)
 AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCONTDETALHADA VARCHAR(5);
BEGIN
  /* PIS */
  /****************************************************************************/
  /********************************** Cr?ditos ********************************/
  -- "Cr?dito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS');
  -- "Cr?dito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 247);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED');
  /********************************** D?bitos *********************************/
  -- "D?bito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS');
  -- "D?bito Detalhado"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 248);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED');

          -- "Outras Dedu??es"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de PIS Outras Dedu??es - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, g.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 249)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
            AND g.bdNUMCAMPO  = 07 -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
            AND g.bdVALOR > 0;

          -- "Compensa??o"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de PIS Compensa??o - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, SUM(g.bdVALOR) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 250)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 15 -- M200 - Consolida??o da contribui??o para o PIS/PASEP
    AND (
         (g.bdNUMCAMPO  = 03) OR -- VL_TOT_CRED_DESC - Valor do Cr?dito Descontado
                 (g.bdNUMCAMPO  = 04) OR -- VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior
                 (g.bdNUMCAMPO  = 06) OR -- VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo
                 (g.bdNUMCAMPO  = 07)    -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
                 )
            AND g.bdVALOR > 0
  GROUP BY g.bdCODMATRIZ, g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdORDENACAO;
  /****************************************************************************/

  /****************************************************************************/
  /********************************** Cr?ditos ********************************/
          /* Cofins */
  -- "Cr?dito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins');
  -- "Cr?dito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 251);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED');
  /********************************** D?bitos *********************************/
  -- "D?bito Principal"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins');
  -- "D?bito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 252);
  -- "Diferen?as de D?bito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB');
  -- "Diferen?as de Cr?dito"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED');

          -- "Outras Dedu??es"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de Cofins Outras Dedu??es - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, g.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 253)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 33 -- M600 - Consolida??o da contribui??o para o Cofins
            AND g.bdNUMCAMPO  = 07 -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
            AND g.bdVALOR > 0;

          -- "Compensa??o"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODTPHI, bdORDENACAO)
          SELECT g.bdCODMATRIZ, g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
                 'Valor de Cofins Compensa??o - Ref:'||substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL,
         NULL as bdDATA, SUM(g.bdVALOR) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, NULL as bdTRANFECHADA, NULL as bdCODTPHI, c.bdORDENACAO
          FROM VEF_EMP_TBLOCOMGERREG g
          JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
          JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 254)
          WHERE g.bdCODMATRIZ = :prCODEMP
            AND g.bdREFERENCIA = :prREFERENCIA
            AND g.bdCODQUADRO = 33 -- M600 - Consolida??o da contribui??o para o Cofins
    AND (
         (g.bdNUMCAMPO  = 03) OR -- VL_TOT_CRED_DESC - Valor do Cr?dito Descontado
                 (g.bdNUMCAMPO  = 04) OR -- VL_TOT_CRED_DESC_ANT - Valor do Cr?dito Descontado, Apurado em Per?odo de Apura??o Anterior
                 (g.bdNUMCAMPO  = 06) OR -- VL_RET_NC - Valor Retido na Fonte Deduzido no Per?odo
                 (g.bdNUMCAMPO  = 07)   -- VL_OUT_DED_NC - Outras Dedu??es no Per?odo
                 )
            AND g.bdVALOR > 0
  GROUP BY g.bdCODMATRIZ, g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdORDENACAO;
  /****************************************************************************/
END
^

/* Alter (SP_APURADOS_VALREF) */
ALTER PROCEDURE SP_APURADOS_VALREF(PRCODEMP VARCHAR(6000),
PRCOLABORADOR VARCHAR(6000),
PRCOMPETENCIA INTEGER,
PRNRVIAS INTEGER)
 RETURNS(BDNRVIA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCONVREF INTEGER,
BDCOMPETENCIA INTEGER,
BDQUANTIDADE INTEGER,
BDTPAPURACAO INTEGER,
BDDTINICIAL DATE,
BDDTFINAL DATE,
BDDESCCONVREF VARCHAR(50),
BDNOMCOL DM_BDNOMCOL,
BDNOMCOLUPPER DM_BDNOMCOL,
BDRGCOL VARCHAR(20),
BDCPFCOL VARCHAR(14),
BDVALUNI NUMERIC(18,6),
BDVALCUSTOEMP NUMERIC(18,6),
BDVALDESCONTO NUMERIC(18,6),
BDQTDCONVENIOREF INTEGER)
 AS
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WVIA INTEGER;
DECLARE VARIABLE WBDCODEMP INTEGER;
DECLARE VARIABLE WBDCODCOL INTEGER;
DECLARE VARIABLE WFECHAVTEMP INTEGER;
DECLARE VARIABLE WBDCODCONVREF INTEGER;
DECLARE VARIABLE WBDCOMPETENCIA INTEGER;
DECLARE VARIABLE WBDQUANTIDADE INTEGER;
DECLARE VARIABLE WBDTAPURACAO INTEGER;
DECLARE VARIABLE WBDDTINICIAL DATE;
DECLARE VARIABLE WBDDTFINAL DATE;
DECLARE VARIABLE WBDDESCCONVREF VARCHAR(50);
DECLARE VARIABLE WBDNOMCOL DM_BDNOMCOL;
DECLARE VARIABLE WBDNOMCOLUPPER DM_BDNOMCOL;
DECLARE VARIABLE WBDRGCOL VARCHAR(20);
DECLARE VARIABLE WBDCPFCOL VARCHAR(30);
DECLARE VARIABLE WBDVALUNI NUMERIC(18,6);
DECLARE VARIABLE WBDVALCUSTOEMP NUMERIC(18,6);
DECLARE VARIABLE WBDVALDESCONTO NUMERIC(18,6);
DECLARE VARIABLE WBDQTDCONVENIOREF INTEGER;
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLDATA VARCHAR(10000);
DECLARE VARIABLE WSQLCUSTOEMP VARCHAR(20000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WBDDATAADMCOL DATE;
DECLARE VARIABLE WBDDATARESCISAO DATE;
BEGIN
  WBDQTDCONVENIOREF = 0;
  WVIA = 1;

  WSQL = 'select ValeRef.*, cast (null as Date) BDDTINICIAL, cast(null as Date) BDDTFINAL, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, DOCREF.BDRGCOL, ColCon.BDCPFCOL, '||
        'Conv.BDVALUNI BDVALUNI, 0 BDVALCUSTOEMP, 0 BDVALDESCONTO, COLCON.BDDATAADMCOL, Resc.BDDATARESCISAO, Conv.BDDESC BDDESCCONVREF '||
        'from VRHF_EMP_TAPVALREF ValeRef '||
        'left outer join VRH_EMP_TCOLCON ColCon on (ColCon.BDCODEMP = ValeRef.BDCODEMP and ColCon.BDCODCOL = ValeRef.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = VALEREF.BDCODEMP and COLCAD.BDCODCOL = VALEREF.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = VALEREF.BDCODEMP and DOCREF.BDCODCOL = VALEREF.BDCODCOL) '||
        'left outer join VRH_EMP_TCOLCON_DOC ColConDoc on (ColConDoc.BDCODEMP = ValeRef.BDCODEMP and ColConDoc.BDCODCOL = ValeRef.BDCODCOL) '||
        'left outer join VW_VRHF_BASE_TCONVREFEICAO_REF Conv on (Conv.BDCODCONVREF = ValeRef.BDCODCONVREF)  '||
        'left outer join VW_RESCISAO Resc on (Resc.BDCODEMP = ValeRef.BDCODEMP and Resc.BDCODCOL = ValeRef.BDCODCOL) ';

  WWHERE = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     BEGIN
      WWHERE = ' where '||PRCODEMP||' ';

      IF (PRCOLABORADOR IS NOT NULL AND PRCOLABORADOR <> '') THEN
         WWHERE = WWHERE||' and '||PRCOLABORADOR||' ';
     END

   IF (PRCOMPETENCIA IS NOT NULL AND PRCOMPETENCIA <> 0) THEN
      BEGIN
        IF (WWHERE = '') THEN
           WWHERE = WWHERE||' where ValeRef.BDCOMPETENCIA = '||PRCOMPETENCIA;
        ELSE
           WWHERE = WWHERE||' and ValeRef.BDCOMPETENCIA = '||PRCOMPETENCIA;
      END

   WSQL = WSQL||WWHERE||' order by ValeRef.BDCODEMP, ValeRef.BDCODCOL, ValeRef.BDCODCONVREF, ValeRef.BDCOMPETENCIA';

   FOR EXECUTE STATEMENT WSQL INTO
     WBDCODEMP,
     WBDCODCOL,
     WBDCODCONVREF,
     WBDCOMPETENCIA,
     WBDQUANTIDADE,
     WBDTAPURACAO,
     WBDDTINICIAL,
     WBDDTFINAL,
     WBDNOMCOL,
     WBDNOMCOLUPPER,
     WBDRGCOL,
     WBDCPFCOL,
     WBDVALUNI,
     WBDVALCUSTOEMP,
     WBDVALDESCONTO,
     WBDDATAADMCOL,
     WBDDATARESCISAO,
     WBDDESCCONVREF
   DO
   BEGIN
     WVIA = 1;
     WHILE (WVIA <= PRNRVIAS) DO
       BEGIN
         BDNRVIA = WVIA;
         BDCODEMP = WBDCODEMP;
         BDCODCOL = WBDCODCOL;
         BDCODCONVREF = WBDCODCONVREF;
         BDCOMPETENCIA = WBDCOMPETENCIA;
         BDQUANTIDADE = WBDQUANTIDADE;
         BDTPAPURACAO = WBDTAPURACAO;

         --Sol. 19620 - Bruno L. R. - 28/07/2017
         EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRCOMPETENCIA);

         WSQLDATA = 'select BDFECHAVTEMP from VW_VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP;
         EXECUTE STATEMENT WSQLDATA INTO WFECHAVTEMP;

         IF (((WFECHAVTEMP > 28) AND (WFECHAVTEMP <> 30)) AND ((WFECHAVTEMP IS NOT NULL) AND (WFECHAVTEMP > 0))) THEN
            BEGIN
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
            END
         ELSE
         IF (WFECHAVTEMP = 30) THEN
            BEGIN
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||', '||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4)||')' INTO WDIA;
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WDIA|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
            END
         ELSE
         IF ((WFECHAVTEMP IS NULL) OR (WFECHAVTEMP = 0)) THEN
            BEGIN
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTFINAL = NULL;
            END
         ELSE
            BEGIN
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTINICIAL = DATEADD(DAY, -30, WBDDTFINAL);
            END
         --Sol. 19620 - Bruno L. R. - 28/07/2017

    
         IF (WBDDTINICIAL < WBDDATAADMCOL) THEN
            BEGIN
              WBDDTINICIAL = WBDDATAADMCOL;
            END
    
         IF (((SUBSTRING(WBDDATARESCISAO FROM 1 FOR 4) || SUBSTRING(WBDDATARESCISAO FROM 6 FOR 2)) = BDCOMPETENCIA) AND (WBDDTFINAL > WBDDATARESCISAO)) THEN
            BEGIN
              WBDDTFINAL = WBDDATARESCISAO;
            END
    
         BDDTINICIAL = WBDDTINICIAL;
         BDDTFINAL = WBDDTFINAL;


         WSQLCUSTOEMP = 'select distinct (ValRef.BDQUANTIDADE * Conv.BDVALUNI) from VRHF_EMP_TAPVALREF ValRef '||
            'left outer join VW_VRHF_BASE_TCONVREFEICAO_REF Conv on (Conv.BDCODCONVREF = ValRef.BDCODCONVREF) '||
            'left outer join VWRH_UNION_FN_FT_MES Val on (Val.BDREFFN = ValRef.BDCOMPETENCIA and Val.BDCODEMP = ValRef.BDCODEMP and Val.BDCODCOL = ValRef.BDCODCOL) '||
            'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = Val.BDCODVER) '||
         'where ValRef.BDCODEMP='||BDCODEMP||' and ValRef.BDCODCOL='||BDCODCOL||' and ValRef.BDCOMPETENCIA='||PRCOMPETENCIA;

         EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP;


         BDNOMCOL = WBDNOMCOL;
         BDNOMCOLUPPER = WBDNOMCOLUPPER;
         BDRGCOL = WBDRGCOL;
         BDCPFCOL = WBDCPFCOL;
         BDVALUNI = WBDVALUNI;
         BDVALCUSTOEMP = WBDVALCUSTOEMP;
         BDVALDESCONTO = WBDVALDESCONTO;
         WBDQTDCONVENIOREF = WBDQTDCONVENIOREF + 1;
         BDQTDCONVENIOREF = WBDQTDCONVENIOREF;
         BDDESCCONVREF = WBDDESCCONVREF;
         WVIA = WVIA + 1;
         SUSPEND;
       END
     END
END
^

/* Alter (SP_APURADOS_VALTRANS) */
ALTER PROCEDURE SP_APURADOS_VALTRANS(PRCODEMP VARCHAR(25000),
PRCOLABORADOR VARCHAR(32700),
PRCOMPETENCIA INTEGER,
PRNRVIAS INTEGER)
 RETURNS(BDNRVIA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODITI INTEGER,
BDCOMPETENCIA INTEGER,
BDQUANTIDADE INTEGER,
BDTPAPURACAO INTEGER,
BDDTINICIAL DATE,
BDDTFINAL DATE,
BDNOMCOL DM_BDNOMCOL,
BDNOMCOLUPPER DM_BDNOMCOL,
BDRGCOL VARCHAR(20),
BDCPFCOL VARCHAR(14),
BDDESCITI VARCHAR(40),
BDLINHAITI VARCHAR(20),
BDVALUNI NUMERIC(18,6),
BDVALCUSTOEMP NUMERIC(18,6),
BDVALDESCONTO NUMERIC(18,6),
BDQTDITINERARIOS INTEGER,
BDFECHAMENTOVT INTEGER,
BDFECHAMENTO INTEGER)
 AS
declare variable WVIA integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDCODITI integer;
declare variable WBDCOMPETENCIA integer;
declare variable WBDQUANTIDADE integer;
declare variable WBDTAPURACAO integer;
declare variable WBDDTINICIAL date;
declare variable WBDDTFINAL date;
declare variable WBDNOMCOL DM_BDNOMCOL;
declare variable WBDNOMCOLUPPER DM_BDNOMCOL;
declare variable WBDRGCOL varchar(20);
declare variable WBDCPFCOL varchar(30);
declare variable WBDDESCITI varchar(50);
declare variable WBDLINHAITI varchar(20);
declare variable WBDVALUNI numeric(18,6);
declare variable WBDVALCUSTOEMP numeric(18,6);
declare variable WBDVALDESCONTO numeric(18,6);
declare variable WBDQTDITINERARIOS integer;
declare variable WSQL varchar(30000);
declare variable WSQLDATA varchar(10000);
declare variable WWHERE varchar(10000);
declare variable WBDDATAADMCOL date;
declare variable WBDDATARESCISAO date;
declare variable WSQLCUSTOEMP varchar(2000);
declare variable WFECHAVTEMP integer;
declare variable WFECHAEMP integer;
declare variable WULTDIA integer;
BEGIN
  WBDQTDITINERARIOS = 0;
  WVIA = 1;

  WSQL = 'select ValeTrans.*, cast (null as Date) BDDTINICIAL, cast(null as Date) BDDTFINAL, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, DOCREF.BDRGCOL, ColCon.BDCPFCOL, Iti.BDDESCITI, '||
        'Iti.BDLINHAITI, Iti.BDVALITI BDVALUNI, 0 BDVALCUSTOEMP, 0 BDVALDESCONTO, ColCon.BDDATAADMCOL, Resc.BDDATARESCISAO '||
        'from VRHF_EMP_TAPVALTRANS ValeTrans '||
        'left outer join VRH_EMP_TCOLCON ColCon on (ColCon.BDCODEMP = ValeTrans.BDCODEMP and ColCon.BDCODCOL = ValeTrans.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = VALETRANS.BDCODEMP and COLCAD.BDCODCOL = VALETRANS.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = VALETRANS.BDCODEMP and DOCREF.BDCODCOL = VALETRANS.BDCODCOL) '||
        'left outer join VRH_EMP_TCOLCON_DOC ColConDoc on (ColConDoc.BDCODEMP = ValeTrans.BDCODEMP and ColConDoc.BDCODCOL = ValeTrans.BDCODCOL) '||
        'left outer join VW_VRHF_BASE_TITINERARIOS_REF Iti on (Iti.BDCODITI = ValeTrans.BDCODITI) '||
        'left outer join VW_RESCISAO Resc on (Resc.BDCODEMP = ValeTrans.BDCODEMP and Resc.BDCODCOL = ValeTrans.BDCODCOL) ';

  WWHERE = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     BEGIN
      WWHERE = ' where '||PRCODEMP||' ';

      IF (PRCOLABORADOR IS NOT NULL AND PRCOLABORADOR <> '') THEN
         WWHERE = WWHERE||' and '||PRCOLABORADOR||' ';
     END

   IF (PRCOMPETENCIA IS NOT NULL AND PRCOMPETENCIA <> 0) THEN
      BEGIN
        IF (WWHERE = '') THEN
           WWHERE = WWHERE||' where ValeTrans.BDCOMPETENCIA = '||PRCOMPETENCIA;
        ELSE
           WWHERE = WWHERE||' and ValeTrans.BDCOMPETENCIA = '||PRCOMPETENCIA;
      END

   WSQL = WSQL||WWHERE||' order by ValeTrans.BDCODEMP, ValeTrans.BDCODCOL, ValeTrans.BDCODITI, ValeTrans.BDCOMPETENCIA';

   EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(prcompetencia FROM 5 FOR 2)||', '||SUBSTRING(prcompetencia FROM 1 FOR 4)||')' INTO :wultdia;

   FOR EXECUTE STATEMENT WSQL INTO
     WBDCODEMP,
     WBDCODCOL,
     WBDCODITI,
     WBDCOMPETENCIA,
     WBDQUANTIDADE,
     WBDTAPURACAO,
     WBDDTINICIAL,
     WBDDTFINAL,
     WBDNOMCOL,
     WBDNOMCOLUPPER,
     WBDRGCOL,
     WBDCPFCOL,
     WBDDESCITI,
     WBDLINHAITI,
     WBDVALUNI,
     WBDVALCUSTOEMP,
     WBDVALDESCONTO,
     WBDDATAADMCOL,
     WBDDATARESCISAO
   DO
   BEGIN
     WVIA = 1;
     BDVALCUSTOEMP = 0;
     WHILE (WVIA <= PRNRVIAS) DO
       BEGIN
         BDNRVIA = WVIA;
         BDCODEMP = WBDCODEMP;
         BDCODCOL = WBDCODCOL;
         BDCODITI = WBDCODITI;
         BDCOMPETENCIA = WBDCOMPETENCIA;
         BDQUANTIDADE = WBDQUANTIDADE;
         BDTPAPURACAO = WBDTAPURACAO;

         --Sol. 19620 - Bruno L. R. - 28/07/2017
         EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRCOMPETENCIA);

         WSQLDATA = 'select BDFECHAVTEMP, BDFECHAMESEMP from VW_VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP;
         WFECHAVTEMP = null;
         EXECUTE STATEMENT WSQLDATA INTO :WFECHAVTEMP, :WFECHAEMP;
    
         BDFECHAMENTOVT = wfechavtemp;
         BDFECHAMENTO   = wfechaemp;

         if ((coalesce(wfechavtemp, 0) = 0) or (wfechavtemp > wultdia)) then
            begin
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);

              if (coalesce(wfechavtemp, 0) = 0) then
                 WBDDTFINAL = null;
              else
                 WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||wultdia|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
            end
         else
            begin
              WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
              WBDDTINICIAL = DATEADD(DAY, 1, DATEADD(MONTH, -1, WBDDTFINAL));
            end
         --Sol. 19620 - Bruno L. R. - 28/07/2017
    
         IF (WBDDTINICIAL < WBDDATAADMCOL) THEN
            BEGIN
              WBDDTINICIAL = WBDDATAADMCOL;
            END
    
         IF (((SUBSTRING(WBDDATARESCISAO FROM 1 FOR 4) || SUBSTRING(WBDDATARESCISAO FROM 6 FOR 2)) = BDCOMPETENCIA) AND (WBDDTFINAL > WBDDATARESCISAO)) THEN
            BEGIN
              WBDDTFINAL = WBDDATARESCISAO;
            END
    
         BDDTINICIAL = WBDDTINICIAL;
         BDDTFINAL = WBDDTFINAL;


         WSQLCUSTOEMP = 'select distinct (ValTrans.BDQUANTIDADE * Iti.BDVALITI) from VRHF_EMP_TAPVALTRANS ValTrans '||
            'left outer join VW_VRHF_BASE_TITINERARIOS_REF Iti on (Iti.BDCODITI = ValTrans.BDCODITI) '||
            'left outer join VWRH_UNION_FN_FT_MES Val on (Val.BDREFFN = ValTrans.BDCOMPETENCIA and Val.BDCODEMP = ValTrans.BDCODEMP and Val.BDCODCOL = ValTrans.BDCODCOL) '||
            'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = Val.BDCODVER) '||
         'where ValTrans.BDCODEMP='||BDCODEMP||' and ValTrans.BDCODCOL='||BDCODCOL||' and ValTrans.BDCOMPETENCIA='||PRCOMPETENCIA;

         FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALCUSTOEMP = BDVALCUSTOEMP + WBDVALCUSTOEMP;
           END

         BDNOMCOL = WBDNOMCOL;
         BDNOMCOLUPPER = WBDNOMCOLUPPER;
         BDRGCOL = WBDRGCOL;
         BDCPFCOL = WBDCPFCOL;
         BDDESCITI = WBDDESCITI;
         BDLINHAITI = WBDLINHAITI;
         BDVALUNI = WBDVALUNI;
         BDVALDESCONTO = WBDVALDESCONTO;
         WBDQTDITINERARIOS = WBDQTDITINERARIOS + 1;
         BDQTDITINERARIOS = WBDQTDITINERARIOS;

         WVIA = WVIA + 1;
         SUSPEND;
         BDVALCUSTOEMP = 0;

       END
   END
END
^

/* Alter (SP_ATU_CAMPOS_GERADOR) */
ALTER PROCEDURE SP_ATU_CAMPOS_GERADOR AS
DECLARE VARIABLE WCODTABELA INTEGER;
DECLARE VARIABLE WTABELA VARCHAR(256);
DECLARE VARIABLE WCAMPO VARCHAR(256);
DECLARE VARIABLE WDESCCAMPO VARCHAR(256);
BEGIN
  /* Procedure Text */
  EXECUTE PROCEDURE sp_seta_competencia(201110,NULL,NULL);

--  suspend;
  FOR SELECT t.bdcodtabger,t.bdtabela FROM ttabelagerador t INTO :wcodtabela,:wtabela DO
    BEGIN
      FOR SELECT rdb$field_name, CAST(rdb$description AS VARCHAR(256)) FROM RDB$RELATION_FIELDS
        WHERE UPPER(rdb$relation_name) = UPPER(:wtabela) INTO :wcampo, :wdesccampo DO
        BEGIN
           UPDATE OR INSERT INTO TCAMPOSGERADOR (BDCODTABGER, BDCODCAMPOGER, BDCAMPO, BDDESCRICAO, BDDESCRICAOAUX, bdfiltro)
                                         VALUES (:wcodtabela, NULL, :wcampo, :wdesccampo, :wdesccampo, 'TRUE')
                                       MATCHING (BDCODTABGER, BDCODCAMPOGER);

        END
    END

END
^

/* Alter (SP_CALC_DEPRECIACAO) */
ALTER PROCEDURE SP_CALC_DEPRECIACAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
PRCORRECAOPERIODO NUMERIC(15,2),
PRVALORCORRIGIDOATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
PRDEPRECIACAOPERIODO NUMERIC(15,2),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
PRVALORRESIDUALCONTABIL NUMERIC(15,2),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,2),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
PRVALORBAIXAREAL NUMERIC(15,2),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2))
 AS
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDTINI DATE;
DECLARE VARIABLE WDTFIM DATE;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIAMES INTEGER;
DECLARE VARIABLE WCONTINUACALCULO VARCHAR(5);
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALDEPACUMUBEM NUMERIC(15,6);
DECLARE VARIABLE WMESESDEPACUMUBEM INTEGER;
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WCODMOEDA INTEGER;
DECLARE VARIABLE WDESCMOEDA VARCHAR(20);
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,2);
DECLARE VARIABLE WVALORBAIXAAUX NUMERIC(15,2);
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WVALORAQUISICAO NUMERIC(15,6);
DECLARE VARIABLE WPOSSUIBAIXA VARCHAR(5);
DECLARE VARIABLE WREFMOEDAINI VARCHAR(10);
DECLARE VARIABLE WREFMOEDAFIM VARCHAR(10);
DECLARE VARIABLE WVALORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPDIASADEPRECIAR INTEGER;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WTOTALMESESDOPERIODO INTEGER;
DECLARE VARIABLE WDATAOFICIALINICIOLCALCULO DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WDATATOTALMESESDEPDIA DATE;
DECLARE VARIABLE WDATATOTALMESESULTIMODIA DATE;
DECLARE VARIABLE WDEPDIAFINAL VARCHAR(5);
DECLARE VARIABLE WDATAATUAL DATE;
DECLARE VARIABLE WDIFERENCAMESES INTEGER;
DECLARE VARIABLE WVALORAQUISICAOMOEDA NUMERIC(15,7);
DECLARE VARIABLE WVALORDEPRECIACAOMENSAL NUMERIC(15,7);
DECLARE VARIABLE WVALORDEPRECIACAODIARIA NUMERIC(15,6);
DECLARE VARIABLE WDATAINICIAL DATE;
DECLARE VARIABLE WDATAFINAL DATE;
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,2);
BEGIN
  /*Stored procedure para calcular a deprecia??o dos bens*/

  --#alt:6598.
  /*Esta stored procedure foi iniciada para calcular de uma forma mais r?pida, mas conseguimos melhorar a rotina anterior.
  Caso a rotina SP_CONS_CALC_DEP volte a dar problema j? tem essa meia encaminhada.
  OBS_1: Est? rotina est? no in?cio, por isso precisa implementar v?rias situa??es e testar muito bem.
  OBS_2: Tem algumas stored procedure que podem ser trocadas por rotinas do pr?prio banco para melhorar o desempenho. 
  Ex: select BDNOVADATA from diminui_meses(:wdatatotalmesesultimodia,1) into wdatatotalmesesultimodia;   --->  wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);
      select bdMESES from DIFERENCA_MESES(:wdatainicial,:wdatafinal) into :wtotalmesesdoperiodo;         --->  wtotalmesesdoperiodo = datediff(month,:wdatainicial,:wdatafinal);                 
  */

  -- Inicializa par?metros
  PRVALORCORRIGIDOANTERIOR        = 0;
  PRCORRECAOPERIODO               = 0;
  PRVALORCORRIGIDOATUAL           = 0;
  PRDEPRECIACAOACUMULADAANTERIOR  = 0;
  PRDEPRECIACAOPERIODO            = 0;
  PRDEPRECIACAOPERIODOMOEDA       = 0;
  PRDEPRECIACAOACUMULADAATUAL     = 0;
  PRDEPRECIACAOACUMULADAATUALMOED = 0;
  PRCORRECAOMONETARIADEPRECIACAO  = 0;
  PRVALORRESIDUALCONTABIL         = 0;
  PRVALORRESIDUALCONTABILMOEDA    = 0;
  PRTOTALMESESDEPRECIACAO         = 0;
  PRMESESDEPRECIADOS              = 0;
  PRMESESDEPRECIAR                = 0;
  PRTAXADEPRECIACAOANUAL          = 0;
  PRDATATAXADEPRECIACAO           = NULL;
  PRVALORBAIXA                    = 0;
  PRDEPRECIACAOBAIXAMOEDA         = 0;
  PRVALORBAIXAREAL                = 0;
  PRVALORMOEDA                    = 0;
  PRDATABAIXA                     = NULL;
  PRVALORAQUISICAOMOEDA           = 0;
  PRVALORCORRIGIDOANTERIORMOEDA   = 0;
  PRVALORAQUISICAOORIGINAL        = 0;
  PRCTADEBITODEPRE                = NULL;
  PRVALORDEPRECIACAODIARIAFIM     = 0;

  wcodbemoriginal            = 0;
  wdataorigaquisicao         = NULL;
  wdepdia                    = 'FALSE';
  wdepmensal                 = 'FALSE';
  wdepmesbaixa               = 'FALSE';
  wdatainiciocalc            = NULL;
  wdatafimcalc               = NULL;
  wdataultimoitemdep         = NULL;
  wvaldepacumubem            = 0;
  wnumdias                   = 0;
  wcodmoeda                  = 0;
  wdescmoeda                 = '';
  wvalormoeda                = 0;

  SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  INTO :wvalorbaixa;

  IF (wvalorbaixa > 0) THEN
    wpossuibaixa = 'TRUE';
  --Tipo 2 somente baixas
  IF ((prtipo = 2) AND (wvalorbaixa = 0)) THEN
    EXIT;

  SELECT tind.bddescind,tbem.bdcodind
  FROM (SELECT COALESCE(tbem.bdcodind,0) bdcodind FROM empresas_tbem tbem
        WHERE (tbem.bdcodemp = :prcodemp)
        AND   (tbem.bdcodbem = :prcodbem)) tbem
  LEFT OUTER JOIN TINDICES tind ON (tind.bdcodind = tbem.bdcodind)
  INTO :wdescmoeda,:wcodmoeda;

  SELECT tbem.bdDATORIAQUIBEM FROM empresas_tbem tbem
  WHERE (tbem.bdcodemp = :prcodemp) AND
        (tbem.bdcodbem = :prcodbem)
  INTO :wdataaquisicao;

  wmes = CAST(SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(EXTRACT(YEAR FROM wdataaquisicao) AS INTEGER);
  SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;

  --wdtini           = wmes||'-01-'||wano;
  wdtini           = wdataaquisicao;
  wdtfim           = wmes||'-'||wultdiames||'-'||wano;
  wrefatu          = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim          = CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER);
  wcontinuacalculo = 'TRUE';
  WHILE ((wrefatu <= wreffim) AND (wcontinuacalculo = 'TRUE')) DO
    BEGIN
      -- Inicializa vari?veis
      wdatainicial               = wdtini;
      wdatafinal                 = wdtfim;
      wdepdiafinal               = 'FALSE';
      wmesesdepacumubem          = 0;
      wvalorbaixa                = 0;
      wvalorbaixaaux             = 0;
      wdatabaixa                 = NULL;
      wvaloraquisicao            = 0;
      wpossuibaixa               = 'FALSE';
      wrefmoedaini               = '';
      wrefmoedafim               = '';
      wdepdiasadepreciar         = 0;
      wtotalmesesdepreciacao     = 0;
      wmesesdepreciados          = 0;
      wmesesdepreciar            = 0;
      wtotalmesesdoperiodo       = 0;
      wdataoficialiniciolcalculo = NULL;
      wdatatotalmeses            = NULL;
      wdatatotalmesesdepdia      = NULL;
      wdatatotalmesesultimodia   = NULL;
      wdataatual                 = wdatafinal;
      wdiferencameses            = NULL;
      wvaloraquisicaomoeda       = 0;
      wvalordepreciacaomensal    = 0;
      wvalordepreciacaodiaria    = 0;
      wdepreciacaoperiodo        = 0;
      wdepreciacaoperiodomoeda   = 0;

      -- Quando o valor da deprecia??o acumulada passou do valor do bem n?o precisa continuar o processo at? chegar na data informada
      IF ((wcontinuacalculo = 'TRUE') AND (prvaloraquisicaooriginal > 0) AND (prdepreciacaoacumuladaatual > COALESCE(prvaloraquisicaooriginal,0))) THEN
        wcontinuacalculo = 'FALSE';

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((prtaxadepreciacaoanual = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        SELECT tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem,
               tbem.bddepmesbaixabem, tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, tdep.bdvaldepacumubem,tdep.bdctadebitodepre, tbem.bdnumdias
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :prtaxadepreciacaoanual, :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,           :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre,       :wnumdias;

      IF ((wvaloraquisicao = 0) AND (prvaloraquisicaooriginal > 0)) THEN
        wvaloraquisicao = prvaloraquisicaooriginal;

      wvalorbaixa = 0;
      IF (wpossuibaixa = 'TRUE') THEN
        BEGIN
          FOR SELECT bddatbai,COALESCE(SUM(bdvalbai),0) AS TotalBaixa FROM empresas_tbai
              WHERE (bdcodemp = :prcodemp) AND (bdcodbem = :prcodbem)
              AND   (bddatbai BETWEEN :wdtini AND :wdtfim) GROUP BY bddatbai
              INTO :wdatabaixa,:wvalorbaixaaux DO
            BEGIN
              wvalorbaixa = wvalorbaixa + wvalorbaixaaux;
            END
        END

      IF (prvaloraquisicaooriginal IS NULL) THEN
        BEGIN
          EXCEPTION ex_date;
          SUSPEND;
          EXIT;
        END

      --if (prdatainicial > wdatafimcalc) then
      --  begin
      --    suspend;
      --    exit;
      --  end

      wvaloraquisicao = (wvaloraquisicao - wvalorbaixa);
    
      IF ((UPPER(wdepmesbaixa) = 'TRUE') AND (wvalorbaixa >= wvaloraquisicao)) THEN
        BEGIN
          wdatafinal = wdatabaixa; -- tinha prdatafinal
    
          IF (CAST((SUBSTRING(wdatabaixa FROM 1 FOR 4)) || (SUBSTRING(wdatabaixa FROM 6 FOR 2)) AS INTEGER) <=
              CAST((SUBSTRING(wdtfim FROM 1 FOR 4)) || (SUBSTRING(wdtfim FROM 6 FOR 2)) AS INTEGER)) THEN
            wdepmesbaixa = 'TRUE';
          ELSE
            wdepmesbaixa = 'FALSE';
        END
      ELSE
        wdepmesbaixa = 'FALSE';
    
      IF (UPPER(wdepmesbaixa) = 'TRUE') THEN
        wvaloraquisicao = (wvaloraquisicao + wvalorbaixa);

      IF ((((wvaloraquisicao IS NULL) OR (wvaloraquisicao <=0))) AND (UPPER(wdepmesbaixa) = 'FALSE')) THEN
        BEGIN
          SUSPEND;
          EXIT;
        END
    
      IF (prtipo = 2) THEN
        BEGIN
          prvaloraquisicaooriginal = wvalorbaixa;
          wvaloraquisicao          = wvalorbaixa;
        END

      -- C?LCULO DE DEPRECIA??O
      prvalorcorrigidoatual = wvaloraquisicao;

      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      IF ((wvalormoeda IS NULL) OR (wvalormoeda = 0) OR (POSITION('UFIR',UPPER(wdescmoeda)) = 0))  THEN
        BEGIN
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
          wrefmoedafim = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
          IF (wdataorigaquisicao IS NOT NULL) THEN
            BEGIN
              wrefmoedaini = SUBSTRING(CAST(:wdataorigaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
              wrefmoedafim = SUBSTRING(CAST(:wdataorigaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
            END
    
          SELECT MAX(tind.bdvalind) FROM tindval tind
                 WHERE (tind.bdcodind = :wcodmoeda) AND
                       (tind.bdrefind BETWEEN :wrefmoedaini AND :wrefmoedafim)
          INTO :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          IF (wvalormoeda IS NULL) THEN
            BEGIN
              SELECT FIRST 1 tind.bdvalind FROM tindval tind
                     WHERE tind.bdcodind = :wcodmoeda AND
                     tind.bdrefind <= :wrefmoedaini
                     ORDER BY tind.bdrefind
              INTO :wvalormoeda;
            END
        END

      -- Deprecia??o di?ria (In?cio)
      IF (UPPER(wdepdia) = 'TRUE' ) THEN
        IF ((SUBSTRING(wdatainiciocalc FROM 9 FOR 2)) = '01') THEN
          wdepdia = 'FALSE';
    
      IF (UPPER(wdepdia) = 'TRUE') THEN
        BEGIN
          wdepdiasadepreciar = (SUBSTRING(wdatainiciocalc FROM 9 FOR 2));
    
          wmes = CAST(SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano = CAST(SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;
    
          IF (wnumdias = 2) THEN
            wdepdiasadepreciar = wultdiames - wdepdiasadepreciar;
          ELSE
            wdepdiasadepreciar = 30 - wdepdiasadepreciar;
        END
      -- Deprecia??o di?ria (Fim)

      IF (prtaxadepreciacaoanual >= 0.1) THEN
        wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
      ELSE
        BEGIN
          prvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / wvalormoeda;
          prvalorresidualcontabil       = wvaloraquisicao;
          prvalorresidualcontabilmoeda  = (wvaloraquisicao / wvalormoeda);
          prdatataxadepreciacao         = wdataultimoitemdep;
          prvalorbaixa                  = wvalorbaixa;
          prvalorbaixareal              = wvalorbaixa;
          prvalormoeda                  = wvalormoeda;
          prdatabaixa                   = wdatabaixa;
          prvaloraquisicaomoeda         = (wvaloraquisicao / wvalormoeda);
    
          SUSPEND;
          EXIT;
        END

      IF (wdatainiciocalc IS NOT NULL) THEN
        wdataoficialiniciolcalculo = wdatainiciocalc;
      ELSE
        wdataoficialiniciolcalculo =  wdataaquisicao;

      IF (wvaloraquisicao = 0) THEN
        EXIT;
      -- Joga para uma vari?vel o numero de meses que j? foi depreciado em outro sistema
      IF (wvaldepacumubem > 0) THEN
        wmesesdepacumubem = ((wvaldepacumubem) / (wvaloraquisicao / wtotalmesesdepreciacao));

      wdatatotalmeses       = addmonth(wdataoficialiniciolcalculo, wtotalmesesdepreciacao-wmesesdepacumubem);
      wdatatotalmesesdepdia = addmonth(wdatatotalmeses, 1);
      -- Transforma no primeiro dia do m?s
      wdatatotalmeses       = SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
      wdataaquisicao        = SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
    
      SELECT bdMESES FROM DIFERENCA_MESES(:wdatatotalmeses,:wdataatual) INTO :wdiferencameses ;
      ---------------wdiferencameses = datediff(month,:wdatatotalmeses,:wdataatual); --------------------
      IF (wdiferencameses-1 > 0) THEN
        BEGIN
         IF (wdepmensal = 'FALSE') THEN
           SELECT BDNOVADATA FROM add_meses(:wdatatotalmeses,1) INTO wdataatual;
         ELSE
           wdataatual = wdatatotalmeses;
        END

      IF ((wdepmensal = 'FALSE') AND
          (CAST(EXTRACT(YEAR FROM wdatainicial) || EXTRACT(MONTH FROM wdatainicial) AS INTEGER) = --
           CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
        BEGIN
        SELECT BDNOVADATA FROM diminui_meses(:wdatafinal,1) INTO wdatafinal; -- tinha prdatafinal ---------------
        ---------------wdatafinal = addmonth(:wdatafinal,-1);
        END
    
      -- Se for relatorio de baixas, a data atual devera ser o do mes da baixa.
      IF ((prtipo = 2) OR ((wdatabaixa IS NOT NULL) AND (wvalorbaixa >= wvaloraquisicao))) THEN
        BEGIN
          wdataatual  = wdatabaixa;
          wdatafinal = wdatabaixa; -- tinha prdatafinal
        END
    
       IF ((wdatafimcalc IS NOT NULL) AND (wdatafimcalc < wdatafinal)) THEN -- tinha prdatafinal
         BEGIN
           wdataatual = wdatafimcalc;
           wdatafinal = wdatafimcalc; -- tinha prdatafinal
         END

      SELECT bdMESES FROM DIFERENCA_MESES(:wdataoficialiniciolcalculo,:wdataatual) INTO :wmesesdepreciados;
      ---------------wmesesdepreciados = datediff(month,:wdataoficialiniciolcalculo,:wdataatual); --------------------
      IF ((wdepmensal = 'FALSE') OR (wvaldepacumubem > 0)) THEN
        wmesesdepreciados = wmesesdepreciados - 1;
    
      -- Adiciona no total de meses depreciados o valor j? depreciado de outro sistema
      IF ((wvaldepacumubem > 0) AND (wmesesdepreciados >= 0)) THEN
        wmesesdepreciados = wmesesdepreciados + ((wvaldepacumubem) / (wvaloraquisicao / wtotalmesesdepreciacao));
    
      IF (wmesesdepreciados > wtotalmesesdepreciacao) THEN
        wmesesdepreciados = wtotalmesesdepreciacao;

      -- Se os meses decreciados for menor que zero, significa que foi informado uma data inferior a data de aquisicao do bem
      IF (wmesesdepreciados > 0) THEN
        BEGIN
          -- Total de meses da diferen?a do periodo de deprecia??o
          wmes = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;
          wdatatotalmesesultimodia = wmes||'-'||wultdiames||'-'||wano;
          IF (wdatafinal > wdatatotalmesesultimodia) THEN -- tinha prdatafinal
            BEGIN
              IF (wdepdia = 'TRUE') THEN
                BEGIN
                  -- Caso seja o ?ltimo m?s para depreciar
                  IF (wmesesdepreciar = 0) THEN
                    wdepdiafinal = 'TRUE';
        
                  wdatatotalmesesultimodia = addmonth(wdatatotalmesesultimodia, 1);
                  wdatatotalmesesultimodia = SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                                             SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
                END
            END
        
          IF (wdatafinal > wdatatotalmeses) THEN -- tinha prdatafinal
            wdatafinal = wdatatotalmeses; -- tinha prdatafinal
        
          IF (wdatainicial < :wdataoficialiniciolcalculo) THEN --
            wdatainicial = wdataoficialiniciolcalculo; --
        
          SELECT bdMESES FROM DIFERENCA_MESES(:wdatainicial,:wdatafinal) INTO :wtotalmesesdoperiodo; -- tinha prdatafinal
          ---------------wtotalmesesdoperiodo = datediff(month,:wdatainicial,:wdatafinal); --------------------
          IF ((wvaldepacumubem > 0) AND (wdatainicial <= wdataorigaquisicao)) THEN --
            wtotalmesesdoperiodo = wtotalmesesdoperiodo-1;
          
          -- Meses ? depreciar
          wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);
          wvaloraquisicaomoeda = (wvaloraquisicao / wvalormoeda);
          -- Deprecia??o do per?odo
          wvalordepreciacaomensal = (wvaloraquisicaomoeda / wtotalmesesdepreciacao);
    
          IF (wdepdiasadepreciar > 0) THEN
            BEGIN
              wvalordepreciacaodiaria     = (wvalordepreciacaomensal * wvalormoeda) / 30 * wdepdiasadepreciar;
              prvalordepreciacaodiariafim = (wvalordepreciacaomensal * wvalormoeda) - wvalordepreciacaodiaria;
            END
        
          IF (wdepdia = 'TRUE') THEN
            BEGIN
              -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
              wmesesdepreciar      = wmesesdepreciar + 1;
              wmesesdepreciados    = wmesesdepreciados - 1;
              wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;
            END
    
          IF (wdatainicial <= :wdataaquisicao) THEN
            BEGIN
              wdepreciacaoperiodo      = ((wvalordepreciacaodiaria) + wvalordepreciacaomensal * wtotalmesesdoperiodo * wvalormoeda);
              wdepreciacaoperiodomoeda = ((wvalordepreciacaodiaria / wvalormoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
            END
          ELSE
          IF (wdepdia = 'TRUE') THEN
            BEGIN
              wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo + 1) * wvalormoeda);
              wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo+1);
            END
          ELSE
            BEGIN
              wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo) * wvalormoeda);
              wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo);
            END
    
          -----------------------------------------------------------------------------------
          IF ((wvalordepreciacaodiaria > 0) AND (wdatainicial <= :wdataaquisicao))  THEN
            BEGIN
              wdepreciacaoacumuladaatual = wvalordepreciacaomensal * wmesesdepreciados;
              wdepreciacaoacumuladaatual = wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * wvalormoeda;
        
              wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
            END
          ELSE
            BEGIN
              wdepreciacaoacumuladaatual = wvalordepreciacaomensal * wmesesdepreciados;
              wdepreciacaoacumuladaatual = wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * wvalormoeda;
        
              IF (wvalordepreciacaodiaria > 0) THEN
                wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
              ELSE
                wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual -  ((wvalordepreciacaomensal * (wtotalmesesdoperiodo) * wvalormoeda)));
            END
    
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            wvalorcorrigidoanterior = wvaloraquisicao;
        
          IF (wdepreciacaoacumuladaanterior < 0) THEN
            wdepreciacaoacumuladaanterior = 0;
    
          wdepreciacaoacumuladaatualmoed = (wvalordepreciacaodiaria/wvalormoeda) + wvalordepreciacaomensal * wmesesdepreciados;
          wcorrecaomonetariadepreciacao  = 0;
          wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          wvalorresidualcontabilmoeda    = wvalorresidualcontabil / wvalormoeda;
          wdepreciacaobaixamoeda         = (wvalorbaixa / wtotalmesesdepreciacao);
          wdepreciacaobaixamoeda         = (wdepreciacaobaixamoeda / wvalormoeda);
    
          IF (prtipo = 2) THEN
            BEGIN
              prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
              prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior) / wvalormoeda;
            END
          ELSE
            BEGIN
              prvalorcorrigidoanterior      = wvalorcorrigidoanterior + wvalorbaixa;
              prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior + wvalorbaixa) / wvalormoeda;
            END
    
          IF ((wdepdia = 'TRUE')  AND (wdepdiafinal = 'TRUE')) THEN
            BEGIN
              IF (wdatainicial <= :wdataaquisicao) THEN
                BEGIN
                  wdepreciacaoperiodo      = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo * wvalormoeda);
                  wdepreciacaoperiodomoeda = (((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) / wvalormoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
        
                  wdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim;
                  wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual / wvalormoeda;
        
                  wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
                  wvalorresidualcontabilmoeda = 0;
        
                  wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
                END
              ELSE
                BEGIN
                  SELECT BDNOVADATA FROM diminui_meses(:wdatatotalmesesultimodia,1) INTO wdatatotalmesesultimodia;
                  ---------------wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);----------------------
        
                  wdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim;
                  wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual / wvalormoeda;
        
                  wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
                  wvalorresidualcontabilmoeda = 0;
        
                  IF (wdatainicial <> :wdatatotalmesesultimodia) THEN
                    BEGIN
                      wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
                      wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaanterior / wvalormoeda);
                    END
        
                  wdepreciacaoperiodo = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;
        
                  IF (wdepreciacaoperiodo <= 0) THEN
                    wdepreciacaoperiodomoeda = 0;
                  ELSE
                    wdepreciacaoperiodomoeda = ((wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior) / wvalormoeda);
                END
        
              wmesesdepreciados = wmesesdepreciados + 1;
              wmesesdepreciar   = 0;
            END
    
          prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;
          prdepreciacaoperiodo            = wdepreciacaoperiodo;
          prdepreciacaoperiodomoeda       = wdepreciacaoperiodomoeda;
          prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
          prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
          prcorrecaomonetariadepreciacao  = wcorrecaomonetariadepreciacao;
          prvalorresidualcontabil         = wvalorresidualcontabil;
          prvalorresidualcontabilmoeda    = wvalorresidualcontabilmoeda;
          prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
          prmesesdepreciados              = wmesesdepreciados;
          prmesesdepreciar                = wmesesdepreciar;
          prdatataxadepreciacao           = wdataultimoitemdep;
          prvalorbaixa                    = wvalorbaixa;
          prdepreciacaobaixamoeda         = wdepreciacaobaixamoeda;
          prvalorbaixareal                = wvalorbaixa;
          prvalormoeda                    = wvalormoeda;
          prdatabaixa                     = wdatabaixa;
          prvaloraquisicaomoeda           = wvaloraquisicaomoeda;
        END

      wdtini  = addmonth(wdtini, 1);
      wmes    = CAST(SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
      wano    = CAST(EXTRACT(YEAR FROM wdtini) AS INTEGER);
      wdtini  = wmes||'-01-'||wano;
      wdtfim  = addmonth(wdtini, 1)-1;
      wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  SUSPEND;
END
^

/* Alter (SP_COMMIT_UNIDADEMEDIDA) */
ALTER PROCEDURE SP_COMMIT_UNIDADEMEDIDA(PRSESSAO INTEGER,
PRCODEMP INTEGER,
PRREF INTEGER)
 AS
DECLARE VARIABLE WCODINCONSISTENCIA INTEGER;
DECLARE VARIABLE wAtuUnidMed VARCHAR(5);
DECLARE VARIABLE wEditChave  INTEGER;
DECLARE VARIABLE wDescUnimed VARCHAR(100);
DECLARE VARIABLE wApeUniMed  VARCHAR(5);
DECLARE VARIABLE wCodTipo    INTEGER;
BEGIN
  wCodInconsistencia = NULL;
  SELECT S.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) S INTO :wCodInconsistencia;

  IF ((:wCodInconsistencia IS NULL) OR (:wCodInconsistencia = 0)) THEN
    SELECT I.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS I WHERE UPPER(I.BDPLANODEFAULT) = 'TRUE' INTO :wCodInconsistencia;

  /* **********************Insere unidades de medida que n?o existem no banco********************** */
  INSERT INTO TUNIDADEMEDIDA(bdcodunimed, bddescunimed, bdapeunimed, bdcodtipo)
  SELECT un.bdeditchave bdcodunimed, un.bddescunimed, un.bdapeunimed, un.bdcodtipo
  FROM TMP_TUNIDADEMEDIDA_TEMP un
  WHERE un.bdsessao = :PRSESSAO
  AND NOT EXISTS(
                 SELECT u.bdcodunimed, u.bddescunimed,
                        u.bdapeunimed, u.bdcodtipo
                 FROM TUNIDADEMEDIDA U
                 WHERE U.BDAPEUNIMED = un.BDAPEUNIMED
                );

  /*Existe plano de inconsistencia no cadastro da empresa ou plano default*/
  IF ((:wCodInconsistencia IS NOT NULL) OR (:wCodInconsistencia > 0)) THEN
    BEGIN
      SELECT COALESCE(UPPER(I.BDATUUNIDMED), 'FALSE') BDATUUNIDMED FROM VEF_BASE_TACOESINCONS I WHERE I.BDCODPLANOINCONS = :wCodInconsistencia INTO :wAtuUnidMed;

      /*Atualiza as unidades de medida*/
      IF (:wAtuUnidMed = 'TRUE') THEN
        BEGIN
          FOR SELECT un.bdeditchave bdcodunimed, un.bddescunimed, un.bdapeunimed, un.bdcodtipo
              FROM TMP_TUNIDADEMEDIDA_TEMP un
              WHERE un.bdsessao = :PRSESSAO
              AND EXISTS(
                         SELECT u.bdcodunimed, u.bddescunimed,
                                u.bdapeunimed, u.bdcodtipo
                         FROM TUNIDADEMEDIDA U
                         WHERE U.BDAPEUNIMED = un.BDAPEUNIMED
                        )
              INTO :wEditChave, :wDescUniMed, :wApeUniMed, :wCodTipo
          DO
            UPDATE TUNIDADEMEDIDA U SET U.BDDESCUNIMED = :wDescUniMed, U.BDAPEUNIMED = :wApeUniMed, U.BDCODTIPO = :wCodTipo WHERE U.BDCODUNIMED = :wEditChave;
        END
    END


END
^

/* Alter (SP_COMP_ACUMULADO_GPS) */
ALTER PROCEDURE SP_COMP_ACUMULADO_GPS(PRCODEMP INTEGER,
PRAGRUPADO INTEGER,
PRCODTPCC INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOFOLHA INTEGER,
PRCHAVEDARF INTEGER = 0,
PRCOMPL13 SMALLINT = 1)
 RETURNS(BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULADO NUMERIC(15,6),
BDACUMULADOTERC NUMERIC(15,6))
 AS
DECLARE VARIABLE WVALACUTER NUMERIC(15,6);
DECLARE VARIABLE WVALACU NUMERIC(15,6);
DECLARE VARIABLE WTOTACUTER NUMERIC(15,6);
DECLARE VARIABLE WTOTACU NUMERIC(15,6);
DECLARE VARIABLE WQUOTA INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WREFUTIMAL INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WAUXCODCENTO VARCHAR(3000);
DECLARE VARIABLE WSQL VARCHAR(3000);
DECLARE VARIABLE WSQLMOVICOL VARCHAR(3000);
DECLARE VARIABLE WCOMPENSACAO NUMERIC(15,6);
DECLARE VARIABLE WINICIOCOMPENSACAO INTEGER;
DECLARE VARIABLE WFIMCOMPENSACAO INTEGER;
DECLARE VARIABLE WBUSCACOMP INTEGER;
DECLARE VARIABLE WACUMULADO NUMERIC(15,6);
DECLARE VARIABLE WACUMULADOTERC NUMERIC(15,6);
DECLARE VARIABLE WCODIMP INTEGER;
DECLARE VARIABLE WAUX1 NUMERIC(15,6);
DECLARE VARIABLE WAUX2 INTEGER;
DECLARE VARIABLE WAUX3 INTEGER;
BEGIN
  /* Procedure Text */
   IF (pranomespag IS NULL) THEN
      pranomespag = pranomes;

   wsql = 'select colcon.bdcodimp from vw_tempresaimpostoref colcon where colcon.bddocarrecadacao = 12 and colcon.bdcodemp = '||prcodemp;
   wcompensacao = 0;
   winiciocompensacao = 999999;
   wfimcompensacao = 0;
   wbuscacomp = 0;
   wacumulado = 0;
   wacumuladoterc = 0;

   IF (wtotacu IS NULL) THEN
      wtotacu = 0;

   IF (wtotacuter IS NULL) THEN
      wtotacuter = 0;

   EXECUTE PROCEDURE sp_seta_competencia(pranomespag);
   FOR EXECUTE STATEMENT wsql INTO : wcodimp DO
     BEGIN
       waux1 = NULL;
       IF (prtipofolha IN (0,1,2)) THEN
          BEGIN
            IF (prcodtpcc IS NULL) THEN
               wsqlmovicol = 'null';
            ELSE
               wsqlmovicol = ''||prcodtpcc;
            wsqlmovicol = 'select sum(comp.BDVALOR),min(comp.BDMESINI),max(comp.BDMESFIM) from vrhf_sp_tcompensacaogps('||wcodimp||','||prcodemp||','||prtipofolha||','||pragrupado||','||wsqlmovicol||','||wbuscacomp||','||pranomespag||','||prchavedarf||') comp';
            EXECUTE STATEMENT wsqlmovicol INTO waux1,waux2,waux3;
          END

       wbuscacomp = 1;
       IF (waux1 IS NOT NULL) THEN
          BEGIN
            IF (waux1 IS NULL) THEN
               waux1 = 0;
            IF (waux2 IS NULL) THEN
               waux2 = 999999;
            IF (waux3 IS NULL) THEN
               waux3 = 0;

            wcompensacao = wcompensacao + waux1;

            IF (waux2 < winiciocompensacao) THEN
               winiciocompensacao = waux2;

            IF (waux3 > wfimcompensacao) THEN
               wfimcompensacao = waux3;
          END

       /*Inicio acumulado*/
       /*****************************************************************************/
       wauxcodcento = '';
       IF (pragrupado = 3) THEN
          BEGIN
            IF (prcodtpcc IS NULL) THEN
               wauxcodcento = 'and x.bdcodtpcc is null';
            ELSE
               wauxcodcento = 'and x.bdcodtpcc = '||prcodtpcc;
          END

       wsqlmovicol = 'select first 1 x.bdchavedarf from tdarfpadrao x '||
                     'where x.bdreferencia = '||pranomes||
                     ' and x.bdcodemp = '||prcodemp||
                     ' and x.bdcodimp = '||wcodimp||
                     ' and x.bdrefpag = '||pranomespag||
                     wauxcodcento||
                     ' and x.BDTIPOIMPOSTO = '||prtipofolha;

       wordem = NULL;
       EXECUTE STATEMENT wsqlmovicol INTO wordem;
       wsqlmovicol = 'select first 1 '||
                     'x.bdreferencia,'||
                     'x.bdordem,'||
                     'x.BDCODPERIODO,'||
                     'x.BDQUOTA from tdarfpadrao x ';

       IF (wordem IS NULL) THEN
          BEGIN
            wsqlmovicol = wsqlmovicol||
                     ' where '||
                     ' x.bdcodemp = '||prcodemp||
                     ' and x.bdcodimp = '||wcodimp||
                     ' and x.bdrefpag <= '||pranomespag||
                     wauxcodcento||
                     ' and x.BDTIPOIMPOSTO = '||prtipofolha;
          END
       ELSE
          BEGIN
            wsqlmovicol = wsqlmovicol||
                      ' where '||
                      ' x.bdcodemp = '||prcodemp||
                      ' and x.bdcodimp = '||wcodimp||
                      ' and ((x.bdrefpag < '||pranomespag||') or (x.bdrefpag = '||pranomespag||' and x.bdordem < '||wordem||'))'||
                      ' and x.bdchavedarf < '||wordem||
                      wauxcodcento;

            IF ((prcompl13 IS NULL) OR (prcompl13 = 0)) THEN
               wsqlmovicol = wsqlmovicol||' and x.BDTIPOIMPOSTO <> 3 ';

          END

       wsqlmovicol = wsqlmovicol||' order by x.bdrefpag desc, x.bdordem desc';
    
       wrefutimal = NULL;
       EXECUTE STATEMENT wsqlmovicol INTO wrefutimal,wordem,wcodperiodo,wquota;

       IF ((wrefutimal IS NOT NULL) AND (wrefutimal > 0)) THEN
          BEGIN
            wsqlmovicol = 'select y.bdvalcampo6,y.bdvalcampo9 from VRHF_SP_HIST_ACUMU_GPS('||''''||'x.bdcodemp = '||prcodemp||' and x.bdcodimp = '||wcodimp||' and x.bdreferencia = '||wrefutimal||
                      ' and x.bdordem = '||wordem||' and x.BDCODPERIODO = '||wcodperiodo||' and x.BDQUOTA = '||wquota||''''||') y';
    
            FOR EXECUTE STATEMENT wsqlmovicol INTO
              : wvalacu,
              : wvalacuter
            DO
              BEGIN
                IF (wvalacu IS NOT NULL) THEN
                   wtotacu = wtotacu + wvalacu;

                IF (wvalacuter IS NOT NULL) THEN
                   wtotacuter = wtotacuter + wvalacuter;
              END
          END

       wacumulado = wtotacu;
       wacumuladoterc = wvalacuter;
       /*****************************************************************************/
       /*Fim acumulado*/
     END

   IF ((wcompensacao = 0) OR (wcompensacao IS NULL)) THEN
      BEGIN
        winiciocompensacao = 0;
        wfimcompensacao = 0;
      END

  bdacumulado = wacumulado;
  bdacumuladoterc = wacumuladoterc;
  bdcompensacao = wcompensacao;
  bdinicomp = winiciocompensacao;
  bdfimcomp = wfimcompensacao;
  SUSPEND;
END
^

/* Alter (SP_CONS_CALC_DEP) */
ALTER PROCEDURE SP_CONS_CALC_DEP(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER,
PRDETALHARTAXADEP INTEGER = 0)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,6),
PRCORRECAOPERIODO NUMERIC(15,6),
PRVALORCORRIGIDOATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6),
PRDEPRECIACAOPERIODO NUMERIC(15,6),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6),
PRVALORRESIDUALCONTABIL NUMERIC(15,6),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,6),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,6),
PRVALORBAIXAREAL NUMERIC(15,6),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,6),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,6),
BDCODEMP INTEGER,
BDCODBEM INTEGER,
PRSOMARDEPRECIACAO INTEGER,
PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDTINI DATE;
DECLARE VARIABLE WDTFIM DATE;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIAMES INTEGER;
DECLARE VARIABLE WCORRECAOPERIODO NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOATUAL NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOSAUX INTEGER;
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,6);
DECLARE VARIABLE WVALORBAIXABEM NUMERIC(15,6);
DECLARE VARIABLE WPOSSUIBAIXA VARCHAR(5);
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,6);
DECLARE VARIABLE WVALORBAIXAREAL NUMERIC(15,6);
DECLARE VARIABLE WVALORAQUISICAOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WTAXAAUX NUMERIC(6,6);
DECLARE VARIABLE WTAXAANT NUMERIC(6,6);
DECLARE VARIABLE WDEPRECIACAOPERIODOAUX NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6);
DECLARE VARIABLE WCODMOEDA INTEGER;
DECLARE VARIABLE WVALORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WREFMOEDAINI VARCHAR(10);
DECLARE VARIABLE WREFMOEDAFIM VARCHAR(10);
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALDEPACUMUBEM NUMERIC(15,6);
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WDEPDIADATA INTEGER;
DECLARE VARIABLE WFIRST VARCHAR(5);
DECLARE VARIABLE WDTBAIXAAUX DATE;
DECLARE VARIABLE WMESESDEPRECIADOSOUTRATAXA INTEGER;
DECLARE VARIABLE WDEPRECIACAOACUMULADA NUMERIC(15,6);
DECLARE VARIABLE WDATAINIMES DATE;
DECLARE VARIABLE WDATAINICIALCALCULO DATE;
DECLARE VARIABLE WDIASDEPRECIADOS INTEGER;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,6);
DECLARE VARIABLE WTIPO INTEGER;
BEGIN
  /*Stored procedure para somar os valores das deprecia??es. Principalmente
  quando houver v?rias deprecia??es cadastradas no bem. O c?lculo da deprecia??o
  ? feito na verdade na sp_cons_calc_dep_correcao*/
  prvalorcorrigidoanterior        = 0;
  prcorrecaoperiodo               = 0;
  prvalorcorrigidoatual           = 0;
  prdepreciacaoacumuladaanterior  = 0;
  prdepreciacaoperiodo            = 0;
  prdepreciacaoperiodomoeda       = 0;
  prdepreciacaoacumuladaatual     = 0;
  prdepreciacaoacumuladaatualmoed = 0;
  prcorrecaomonetariadepreciacao  = 0;
  prvalorresidualcontabil         = 0;
  prvalorresidualcontabilmoeda    = 0;
  prtotalmesesdepreciacao         = 0;
  prmesesdepreciados              = 0;
  prmesesdepreciar                = 0;
  prtaxadepreciacaoanual          = 0;
  prdatataxadepreciacao           = NULL;
  prvalorbaixa                    = 0;
  prdepreciacaobaixamoeda         = 0;
  prvalorbaixareal                = 0;
  prvalormoeda                    = 0;
  prdatabaixa                     = NULL;
  prvaloraquisicaomoeda           = 0;
  prvalorcorrigidoanteriormoeda   = 0;
  prvaloraquisicaooriginal        = 0;
  prctadebitodepre                = 0;
  prvalordepreciacaodiariafim     = 0;

  wdepreciacaoperiodo             = 0;
  wdepreciacaoperiodoaux          = 0;
  wtaxaaux                        = 0;
  wdepreciacaoperiodomoeda        = 0;
  wmesesdepreciadosaux            = 0;
  wdepreciacaoacumuladaanterior   = 0;
  wcodmoeda                       = 0;
  wvalormoeda                     = 0;
  wrefmoedaini                    = '';
  wrefmoedafim                    = '';
  wvalorbaixabem                  = 0;
  wpossuibaixa                    = 'FALSE';
  wcodbemoriginal                 = 0;
  wdataorigaquisicao              = NULL;
  wdepdia                         = 'FALSE';
  wdepmensal                      = 'FALSE';
  wdepmesbaixa                    = 'FALSE';
  wdatainiciocalc                 = NULL;
  wdatafimcalc                    = NULL;
  wdataultimoitemdep              = NULL;
  wvaldepacumubem                 = 0;
  wnumdias                        = 0;
  wdepdiadata                     = 0;
  wfirst                          = 'TRUE';
  wdtbaixaaux                     = NULL;
  wdepreciacaoacumulada           = 0;
  WDATAINIMES                     = NULL;
  WDATAINICIAlCALCULO             = NULL;
  WDEPRECIACAOACUMULADAATUAL      = 0;

  BDCODEMP = PRCODEMP;
  BDCODBEM = PRCODBEM;

  --#alt:85169. Os c?lculos para a op??o de relat?rio 2 devem ser os mesmo da deprecia??o, se n?o os valores ficam incorretos. Ana - 21/06/2018
  WTIPO = PRTIPO;
  if (WTIPO = 2) then
    WTIPO = 0;

  --alt:16006 - 03/11/2016 - Comentado aqui e implementado no SP_CONS_CALC_DEP_CORRECAO, pois deve verificar para cada per?odo se possui baixa. Pedro
  /* In?cio deprecia??o anteriores */
  --Processo para calcular os meses anteriores ao per?odo informado, pois posso ter v?rias
  --deprecia??es cadastradas
  /*SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  AND   (tbai.BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
  INTO :wvalorbaixabem;

  IF (wvalorbaixabem > 0) THEN
    wpossuibaixa = 'TRUE';
  --Tipo 2 somente baixas
  IF ((prtipo = 2) AND (wvalorbaixabem = 0)) THEN
    EXIT;*/
  --alt:16006 - Fim

  SELECT tbem.bdDATORIAQUIBEM FROM empresas_tbem tbem
  WHERE (tbem.bdcodemp = :prcodemp) AND
        (tbem.bdcodbem = :prcodbem)
  INTO :wdataaquisicao;

  --SELECT tind.bddescind,tbem.bdcodind
  SELECT tbem.bdcodind
  FROM (SELECT COALESCE(tbem.bdcodind,0) bdcodind FROM empresas_tbem tbem
        WHERE (tbem.bdcodemp = :prcodemp)
        AND   (tbem.bdcodbem = :prcodbem)) tbem
  LEFT OUTER JOIN TINDICES tind ON (tind.bdcodind = tbem.bdcodind)
  --INTO :wdescmoeda,:wcodmoeda;
  INTO :wcodmoeda;

  --#alt:21384 - Estava sempre pegando o maior valor da moeda do ano da aquisi??o do bem, quando na verdade deve pegar sempre o valor mais pr?ximo ao m?s da aquisi??o. Ana - 13/11/2017
  SELECT FIRST 1 tind.bdvalind FROM tindval tind
         WHERE tind.bdcodind = :wcodmoeda AND
         tind.bddataind <= :wdataaquisicao
         ORDER BY tind.bdrefind DESC
   INTO :wvalormoeda;

  --Converte a moeda para cruzeiros reias
  IF (wdataaquisicao <= '06/30/1994') THEN
    wvalormoeda = wvalormoeda / 1000;

  IF ((wvalormoeda = 0) OR (wvalormoeda IS NULL)) THEN
    wvalormoeda = 0.8287;

  /*wrefmoedaini = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
  wrefmoedafim = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
  SELECT MAX(tind.bdvalind) FROM tindval tind
         WHERE (tind.bdcodind = :wcodmoeda) AND
               (tind.bdrefind BETWEEN :wrefmoedaini AND :wrefmoedafim)
  INTO :wvalormoeda;
  --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
  IF (wvalormoeda IS NULL) THEN
    BEGIN
      SELECT FIRST 1 tind.bdvalind FROM tindval tind
             WHERE tind.bdcodind = :wcodmoeda AND
             tind.bdrefind <= :wrefmoedaini
             ORDER BY tind.bdrefind DESC    --#alt:17142 - Alterado para pegar da ultima referencia. Ana - 02/02/2017
      INTO :wvalormoeda;
    END*/
  --#alt:21384. fim

  wmes = CAST(SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(EXTRACT(YEAR FROM wdataaquisicao) AS INTEGER);--cast(substring(cast(wdataaquisicao as varchar(10)) from 1 for 4) as integer);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultdiames;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultdiames = EXTRACT(DAY FROM (wdataaquisicao - EXTRACT(DAY FROM wdataaquisicao) +
                       32 - EXTRACT(DAY FROM wdataaquisicao - EXTRACT(DAY FROM wdataaquisicao) + 32)));

  wdtini  = wmes||'-01-'||wano;
  wdtfim  = wmes||'-'||wultdiames||'-'||wano;
  wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim = CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER);

  --#alt:18204 - Adicionei a verifica??o da data da aquisi??o com a data final para n?o executar quando n?o pertencer ao per?odo de aquisi??o do bem. Ana - 28/04/2017
  WHILE ((wrefatu < wreffim) AND (prdatafinal >= wdataaquisicao)) DO
    BEGIN
      /* A antiga rotina da deprecia??o estava pegando sempre o valor da moeda do m?s de aquisi??o, por isso
         fiz a busca do valor fora do while das refer?ncias, mas deixei como coment?rio caso seja feito
         para busca o valor da moeda conforme o m?s em que esta calculando
      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      if ((wvalormoeda is null) or (wvalormoeda = 0) or (position('UFIR',upper(wdescmoeda)) = 0))  then
        begin
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'0101';
          wrefmoedafim = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'1231';
    
          select max(tind.bdvalind) from tindval tind
                 where (tind.bdcodind = :wcodmoeda) and
                       (tind.bdrefind between :wrefmoedaini and :wrefmoedafim)
          into :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          if (wvalormoeda is null) then
            begin
              select first 1 tind.bdvalind from tindval tind
                     where tind.bdcodind = :wcodmoeda and
                     tind.bdrefind <= :wrefmoedaini
                     order by tind.bdrefind
              into :wvalormoeda;
            end
        end*/

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((COALESCE(prtaxadepreciacaoanual,0) = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        --#alt:16415 - Alterada a verifica??o do case, pois quando n?o havia nehuma contabiliza??o ele n?o levava o valor do bem. Ana - 05/12/2016
        --Faz o select com o First, pois um bem pode ter mais de uma deprecia??o cadastrada.
        --alt:14255 - 28/06/2016 - Adicionado case para verificar o tipo da contabiliza??o e ver de onde ir? buscar valor da aquisi??o. Pedro
        --SELECT FIRST 1 tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem,
        SELECT FIRST 1 tbem.bdcodorigbem, COALESCE(CASE WHEN ((tdep.BDCONTABILIZACAO = 0) OR (tdep.BDCONTABILIZACAO IS NULL) ) THEN tbem.BDVALAQUIBEM ELSE tdep.BDVALAQUISOC END, 0),
               tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem, tbem.bddepmesbaixabem,
               tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, COALESCE(tdep.bdvaldepacumubem,0),tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        ORDER BY tdep.bddatinicalcbem DESC
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :wtaxaaux,         :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,     :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre, :wnumdias,        :wdepdiadata;

      --alt:13784 - 12/04/2016 - Se tiver trocado de taxa de deprecia??o, precisa levar os meses j? depreciados com a taxa anterior para o c?lculo da pr?xima. Pedro
      IF ((wtaxaant <> 0) AND (wtaxaant <> wtaxaaux)) THEN
        BEGIN
          wmesesdepreciadosoutrataxa = prmesesdepreciados;
          --alt:13784 - 12/04/2016 - Se estiver marcado para detalhar por taxa de deprecia??o, precisa retornar aqui a taxa. Pedro
          IF (prdetalhartaxadep = 1) THEN
            BEGIN
              prmesesdepreciar = prtotalmesesdepreciacao - prmesesdepreciados;
              prsomardepreciacao = 0; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
              SUSPEND;
            END
        END

      wdepreciacaoperiodoaux = COALESCE(wdepreciacaoperiodo,0);
      SELECT prcorrecaoperiodo, prvalorcorrigidoatual, prdepreciacaoperiodo, prmesesdepreciados, prvalorbaixa,
             prdepreciacaoperiodomoeda, prvalorresidualcontabil, prvalorresidualcontabilmoeda,
             prdepreciacaobaixamoeda, prvalorbaixareal, prvaloraquisicaomoeda,
             prdepreciacaoacumuladaanterior, prtaxadepreciacaoanual, prdepreciacaoacumuladaatualmoed,
             prtotalmesesdepreciacao, prvaloraquisicaooriginal, prdatabaixa, prdepreciacaoacumuladaatual
      FROM sp_cons_calc_dep_correcao(:prcodemp, :prcodbem, :wdtini, :wdtfim, :WTIPO /*:prtipo*/, :prcontabilizacao,:wvalormoeda,:wpossuibaixa,:wcodbemoriginal,
                                     :prvaloraquisicaooriginal,:wtaxaaux,:wdataaquisicao,:wdataorigaquisicao,:wdepdia,:wdepmensal,
                                     :wdepmesbaixa,:wdatainiciocalc,:wdatafimcalc,:wdataultimoitemdep,:wvaldepacumubem,:prctadebitodepre,:wnumdias,
                                     :wdepdiadata, :wvalorbaixabem, :wmesesdepreciadosoutrataxa, :wdepreciacaoacumulada)
      INTO :wcorrecaoperiodo, :wvalorcorrigidoatual, :wdepreciacaoperiodo, :wmesesdepreciados, :wvalorbaixa,
           :wdepreciacaoperiodomoeda, :wvalorresidualcontabil, :wvalorresidualcontabilmoeda,
           :wdepreciacaobaixamoeda, :wvalorbaixareal, :wvaloraquisicaomoeda,
           :wdepreciacaoacumuladaanterior, :prtaxadepreciacaoanual, :wdepreciacaoacumuladaatualmoed,
           :prtotalmesesdepreciacao, :prvaloraquisicaooriginal, :prdatabaixa, wdepreciacaoacumulada;

      IF (wcorrecaoperiodo > 0) THEN
        BEGIN
          wcorrecaoperiodo = ABS(wcorrecaoperiodo - prcorrecaoperiodo);
          IF (wcorrecaoperiodo > 0) THEN
            prcorrecaoperiodo = prcorrecaoperiodo + wcorrecaoperiodo;
        END

      IF (wvalorcorrigidoatual > 0) THEN
        BEGIN
          wvalorcorrigidoatual = ABS(wvalorcorrigidoatual - prvalorcorrigidoatual);
          --alt:9013 - Foi retirada a incrementa??o do valor corrigido atual daqui pois estava duplicando a corre??o baseada no valor da baixa. Pedro
          /*if (wvalorcorrigidoatual > 0) then
            prvalorcorrigidoatual = abs(prvalorcorrigidoatual - wvalorcorrigidoatual);*/
        END

      --Feito esse tratamento pois posso ter v?rias taxas cadastradas para o bem. N?o posso utilizar o
      --prdepreciacaoacumuladaanterior pois a rotina calcula como se sempre fosse a taxa do m?s em quest?o
      -- In?cio
      IF ((prdepreciacaoacumuladaanterior = 0) AND (prtaxadepreciacaoanual > 0) AND (wdepreciacaoacumuladaanterior > 0)) THEN
        BEGIN
          wdepreciacaoacumuladaanterior = ABS(wdepreciacaoacumuladaanterior - prdepreciacaoacumuladaanterior);
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoacumuladaanterior;
        END
      ELSE
      IF (wdepreciacaoperiodoaux > 0) THEN
        prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoperiodoaux;

      IF ((prdepreciacaoacumuladaatualmoed = 0) AND (prtaxadepreciacaoanual > 0) AND (wdepreciacaoacumuladaatualmoed > 0)) THEN
        BEGIN
          wdepreciacaoacumuladaatualmoed = ABS(wdepreciacaoacumuladaatualmoed - prdepreciacaoacumuladaatualmoed);
          IF (wdepreciacaoacumuladaatualmoed > 0) THEN
            prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoacumuladaatualmoed;
        END
      ELSE
      IF (wdepreciacaoperiodomoeda > 0) THEN
        prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoperiodomoeda;
      -- Fim

      IF (wvalorresidualcontabil > 0) THEN
        BEGIN
          wvalorresidualcontabil = ABS(wvalorresidualcontabil - prvalorresidualcontabil);
          IF ((prvalorresidualcontabil > 0) AND (wdepreciacaoperiodo > 0) AND (wvalorresidualcontabil <> wdepreciacaoperiodo)) THEN
            wvalorresidualcontabil = wdepreciacaoperiodo;

          IF (wvalorresidualcontabil > 0) THEN
            prvalorresidualcontabil = ABS(prvalorresidualcontabil - wvalorresidualcontabil);
        END

      IF (wvalorresidualcontabilmoeda > 0) THEN
        BEGIN
          wvalorresidualcontabilmoeda = ABS(wvalorresidualcontabilmoeda - prvalorresidualcontabilmoeda);
          IF ((prvalorresidualcontabilmoeda > 0) AND (wdepreciacaoperiodomoeda > 0) AND (wvalorresidualcontabilmoeda <> wdepreciacaoperiodomoeda)) THEN
            wvalorresidualcontabilmoeda = wdepreciacaoperiodomoeda;

          IF (wvalorresidualcontabilmoeda > 0) THEN
            prvalorresidualcontabilmoeda = ABS(prvalorresidualcontabilmoeda - wvalorresidualcontabilmoeda);
        END

      --alt:14761 - 16/06/2016 - Se tiver valor de deprecia??o acumulada (informado no cadastro da deprecia??o)
      --? feito um c?lculo da quantidade de meses j? depreciados e assim precisa retornar eles tamb?m. Pedro
      IF ((wdepreciacaoperiodo > 0) OR (wvaldepacumubem > 0)) THEN
        BEGIN
          IF ((wtaxaaux > 0) AND (wtaxaaux <> prtaxadepreciacaoanual)) THEN
            wmesesdepreciadosaux = wmesesdepreciadosaux + ABS(wmesesdepreciadosaux - prmesesdepreciados);

          IF ((wmesesdepreciados > 0) AND ((prmesesdepreciados = 0) OR (wmesesdepreciados > prmesesdepreciados))) THEN --alt:13784 - 12/04/2016 - Quando trocada a taxa de deprecia??o n?o estava levando os meses depreciados corretamente. Pedro
            prmesesdepreciados = wmesesdepreciados;
          --alt:9013 - Colocada essa valida??o para n?o continuar depreciando depois do total de meses da deprecia??o, isso acontecia quando tinha deprecia??o di?ria. Pedro
          ELSE IF (prmesesdepreciados <> prtotalmesesdepreciacao) THEN
            prmesesdepreciados = prmesesdepreciados + 1;
        END
      --#Alt:5105
      /*if (wvalorbaixa > 0) then
        begin
          wvalorbaixa = ABS(wvalorbaixa - prvalorbaixa);
          if (wvalorbaixa > 0) then
            prvalorbaixa = prvalorbaixa + wvalorbaixa;
        end*/

      IF (wdepreciacaobaixamoeda > 0) THEN
        BEGIN
          wdepreciacaobaixamoeda = ABS(wdepreciacaobaixamoeda - prdepreciacaobaixamoeda);
          IF (wdepreciacaobaixamoeda > 0) THEN
            prdepreciacaobaixamoeda = prdepreciacaobaixamoeda + wdepreciacaobaixamoeda;
        END

      IF (wvalorbaixareal > 0) THEN
        BEGIN
          wvalorbaixareal = ABS(wvalorbaixareal - prvalorbaixareal);
          IF (wvalorbaixareal > 0) THEN
            prvalorbaixareal = prvalorbaixareal + wvalorbaixareal;
        END

      IF (wvaloraquisicaomoeda > 0) THEN
        BEGIN
          wvaloraquisicaomoeda = ABS(wvaloraquisicaomoeda - prvaloraquisicaomoeda);
          IF (wvaloraquisicaomoeda > 0) THEN
            prvaloraquisicaomoeda = ABS(prvaloraquisicaomoeda - wvaloraquisicaomoeda);
        END

      IF (prdatabaixa IS NOT NULL) THEN
        wdtbaixaaux = prdatabaixa;

      wtaxaant = wtaxaaux;
      wtaxaaux = prtaxadepreciacaoanual;
      wdtini   = addmonth(wdtini, 1);
      wdtfim   = addmonth(wdtini, 1)-1;
      wrefatu  = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  --alt:15196 - 09/11/2016 - Alterado para carregar a deprecia??o acumulada da vari?vel que est? somando o valor para cada per?odo. Pedro
  /*IF (wdepreciacaoperiodo > 0) THEN
    prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoperiodo;*/

  prdepreciacaoacumuladaanterior = wdepreciacaoacumulada;

  wtaxaaux = COALESCE(wtaxaaux,0);
  /* Final deprecia??o anteriores */

  wdtini  = prdatainicial;
  wmes    = CAST(SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano    = CAST(EXTRACT(YEAR FROM wdtini) AS INTEGER);--cast(substring(cast(wdtini as varchar(10)) from 1 for 4) as integer);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultdiames;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultdiames = EXTRACT(DAY FROM (wdtini - EXTRACT(DAY FROM wdtini) +
               32 - EXTRACT(DAY FROM wdtini - EXTRACT(DAY FROM wdtini) + 32)));
  wdtfim  = wmes||'-'||wultdiames||'-'||wano;
  IF (wdtfim > prdatafinal) THEN
    wdtfim = prdatafinal;
  wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim = CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER);

  prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior;

  --#alt:18204 - Adicionei a verifica??o da data da aquisi??o com a data final para n?o executar quando n?o pertencer ao per?odo de aquisi??o do bem. Ana - 28/04/2017
  WHILE ((wrefatu <= wreffim) AND (prdatafinal >= wdataaquisicao)) DO
    BEGIN
      /* A antiga rotina da deprecia??o estava pegando sempre o valor da moeda do m?s de aquisi??o, por isso
         fiz a busca do valor fora do while das refer?ncias, mas deixei como coment?rio caso seja feito
         para busca o valor da moeda conforme o m?s em que esta calculando
      --Conforme me explicado a moeda Ufir est? congelada, por isso n?o preciso verifcar o valor dela todos os meses
      if ((wvalormoeda is null) or (wvalormoeda = 0) or (position('UFIR',upper(wdescmoeda)) = 0))  then
        begin
          --Seleciona o valor da moeda da data de aquisi??o ou se o bem j? vier depreciado da data original de aquisi??o
          wrefmoedaini = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'0101';
          wrefmoedafim = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'1231';
    
          select max(tind.bdvalind) from tindval tind
                 where (tind.bdcodind = :wcodmoeda) and
                       (tind.bdrefind between :wrefmoedaini and :wrefmoedafim)
          into :wvalormoeda;
          --caso n?o encontre um valor nesse periodo, o sql a seguir retorna o mais pr?ximo
          if (wvalormoeda is null) then
            begin
              select first 1 tind.bdvalind from tindval tind
                     where tind.bdcodind = :wcodmoeda and
                     tind.bdrefind <= :wrefmoedaini
                     order by tind.bdrefind
              into :wvalormoeda;
            end
        end*/

      --S? faz o select da taxa da depreci??o quando mudar o per?odo
      IF ((COALESCE(prtaxadepreciacaoanual,0) = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        --#alt:16415 - Alterada a verifica??o do case, pois quando n?o havia nehuma contabiliza??o ele n?o levava o valor do bem. Ana - 05/12/2016
        --Faz o select com o First, pois um bem pode ter mais de uma deprecia??o cadastrada.
        --alt:14255 - 28/06/2016 - Adicionado case para verificar o tipo da contabiliza??o e ver de onde ir? buscar valor da aquisi??o. Pedro
        --SELECT FIRST 1 tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem,
        SELECT FIRST 1 tbem.bdcodorigbem, COALESCE(CASE WHEN ((tdep.BDCONTABILIZACAO = 0) OR (tdep.BDCONTABILIZACAO IS NULL) ) THEN tbem.BDVALAQUIBEM ELSE tdep.BDVALAQUISOC END, 0),
               tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem, tbem.bddepmesbaixabem,
               tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, COALESCE(tdep.bdvaldepacumubem,0),tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :wtaxaaux,         :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,     :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre, :wnumdias,        :wdepdiadata;

      --alt:13784 - 12/04/2016 - Se tiver trocado de taxa de deprecia??o, precisa levar os meses j? depreciados com a taxa anterior para o c?lculo da pr?xima. Pedro
      IF ((wtaxaant <> 0) AND (wtaxaant <> wtaxaaux)) THEN
        BEGIN
          wmesesdepreciadosoutrataxa = prmesesdepreciados;
          --alt:13784 - 12/04/2016 - Se estiver marcado para detalhar por taxa de deprecia??o, precisa retornar aqui a taxa. Pedro
          IF (prdetalhartaxadep = 1) THEN
            BEGIN
              prmesesdepreciar = prtotalmesesdepreciacao - prmesesdepreciados;
              prsomardepreciacao = 0; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
              SUSPEND;
            END
        END

      --alt:15793 - 22/09/2016 - Se tiver informa??o de deprecia??o em outra taxa ou valor acumulado, n?o ? o primeiro m?s a depreciar,
      --ent?o precisa mudar o valor desta vari?vel, pois estava calculando incorretamente a deprecia??o acumulada atual nestes casos. Pedro
      wFirst = IIF((wvaldepacumubem = 0) AND (wmesesdepreciadosoutrataxa = 0) AND (wFirst = 'TRUE'), 'TRUE', 'FALSE');

      --#alt:16929 - Quando h? um valor de deprecia??o acumulada cadastrado deve ser substituido pelo valor da deprecia??o acumulada anterior ao per?odo. Ana - 01/02/2017
      wdatainimes = SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                    SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
      wdatainicialcalculo = SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                            SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

      wdiasdepreciados = DATEDIFF(DAY,:wdatainicialcalculo,:wdatainimes);

      IF ((wdiasdepreciados < 30) AND (wdepreciacaoacumuladaanterior > 0) AND ((wdiasdepreciados > -1) OR (prdepreciacaoacumuladaanterior <> wdepreciacaoacumuladaanterior)) )THEN
        prdepreciacaoacumuladaanterior = wvaldepacumubem;
      --#alt:16929. fim

      SELECT prdepreciacaoperiodo, prdepreciacaoperiodomoeda, prcorrecaomonetariadepreciacao,
             prvalorresidualcontabil, prvalorresidualcontabilmoeda, prtotalmesesdepreciacao,
             prmesesdepreciados, prmesesdepreciar, prtaxadepreciacaoanual, prdatataxadepreciacao, prvalorbaixa,
             prdepreciacaobaixamoeda, prvalorbaixareal, prvalormoeda, prdatabaixa, prvaloraquisicaomoeda, prvalorcorrigidoanteriormoeda,
             prvaloraquisicaooriginal, prctadebitodepre, prvalordepreciacaodiariafim, prvalorcorrigidoanterior,
             prvalorcorrigidoatual, prdepreciacaoacumuladaanterior, prdepreciacaoacumuladaatualmoed, prdepreciacaoacumuladaatual, prcompensacaobaixaperanterior
      FROM sp_cons_calc_dep_correcao(:prcodemp, :prcodbem, :wdtini, :wdtfim, :prtipo, :prcontabilizacao,:wvalormoeda,:wpossuibaixa,:wcodbemoriginal,
                                     :prvaloraquisicaooriginal,:wtaxaaux,:wdataaquisicao,:wdataorigaquisicao,:wdepdia,:wdepmensal,
                                     :wdepmesbaixa,:wdatainiciocalc,:wdatafimcalc,:wdataultimoitemdep,:wvaldepacumubem,:prctadebitodepre,:wnumdias,
                                     :wdepdiadata, :wvalorbaixabem, :wmesesdepreciadosoutrataxa, :prdepreciacaoacumuladaatual)
      INTO   :wdepreciacaoperiodo, :wdepreciacaoperiodomoeda, :wcorrecaomonetariadepreciacao,
             :wvalorresidualcontabil, :wvalorresidualcontabilmoeda, :prtotalmesesdepreciacao,
             :wmesesdepreciados, :prmesesdepreciar, :prtaxadepreciacaoanual, :prdatataxadepreciacao, :wvalorbaixa, 
             :wdepreciacaobaixamoeda, :wvalorbaixareal, :prvalormoeda, :prdatabaixa, :wvaloraquisicaomoeda, :wvalorcorrigidoanteriormoeda, 
             :prvaloraquisicaooriginal, :prctadebitodepre, :prvalordepreciacaodiariafim, :wvalorcorrigidoanterior,
             :wvalorcorrigidoatual, :wdepreciacaoacumuladaanterior, :wdepreciacaoacumuladaatualmoed, :wdepreciacaoacumuladaatual, :prcompensacaobaixaperanterior;

      --#alt:16929 - Alterada verifica??o para substituir o valor da deprecia??o acumuludada anterior.
      -- Quando h? uma deprecia??o acumulada anterior cadastrada na taxa de deprecia??o, ent?o esta deve ser substituida. Ana - 31/01/2017
      --#Alt:5105 -> Acrescentado a vari?vel wfirst
      IF ((prdepreciacaoacumuladaanterior = 0)  AND (wdepreciacaoacumuladaanterior > 0) AND (wvaldepacumubem <> 0) /*AND (wfirst = 'TRUE')*/) THEN
        BEGIN
          wdepreciacaoacumuladaanterior = ABS(wdepreciacaoacumuladaanterior - prdepreciacaoacumuladaanterior);
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoacumuladaanterior;

          IF (wfirst = 'TRUE') THEN
          prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior;
        END
      wfirst = 'FALSE';

      IF (((wtaxaaux = prtaxadepreciacaoanual) OR (wtaxaaux = 0)) AND (prdepreciacaoacumuladaatualmoed = 0)) THEN
        BEGIN
          wdepreciacaoacumuladaatualmoed = ABS(wdepreciacaoacumuladaatualmoed - wdepreciacaoperiodomoeda);
          IF (wdepreciacaoacumuladaatualmoed > 0) THEN
            prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoacumuladaatualmoed;
        END

      IF ((wvalorcorrigidoanterior > 0) AND (prvalorcorrigidoanterior = 0)) THEN
        prvalorcorrigidoanterior = wvalorcorrigidoanterior;

      IF ((wvalorcorrigidoanteriormoeda > 0) AND (prvalorcorrigidoanteriormoeda = 0)) THEN
        prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;

      prdepreciacaoperiodo            = prdepreciacaoperiodo + COALESCE(wdepreciacaoperiodo,0);
      prdepreciacaoperiodomoeda       = prdepreciacaoperiodomoeda + COALESCE(wdepreciacaoperiodomoeda,0);
      prcorrecaomonetariadepreciacao  = prcorrecaomonetariadepreciacao + COALESCE(wcorrecaomonetariadepreciacao,0);

      --alt:14761 - 20/06/2016 - Quando h? baixa, pode n?o haver deprecia??o no per?odo, ent?o estava sendo calculado incorretamente. Pedro
      --alt:14624 - 14/06/2016 - Aparentemente estava somando novamente a deprecia??o do per?odo porque vinha
      --errado do sp_cons_calc_dep_correcao, por?m agora vem certo e estava somando valor de um m?s a mais. Pedro
      --prdepreciacaoacumuladaatual     = prdepreciacaoacumuladaatual + COALESCE(wdepreciacaoperiodo,0);
      --prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + COALESCE(wdepreciacaoperiodomoeda,0);
      --prdepreciacaoacumuladaatual     = prdepreciacaoacumuladaanterior + COALESCE(wdepreciacaoperiodo,0);
      --prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatual / COALESCE(wvalormoeda,0);

      --#alt:18200 - Comentado pois foram feitas altera??es na sp_cons_calc_dep_correcao que n?o h? mais necessidade de fazer esta verifica??o. Ana - 04/05/2017
      --alt:16006 - 03/11/2016 - S? deve carregar o saldo anterior no caso de ter baixa e n?o depreciar neste m?s, caso contrario, se estiver calculando mais de um m?s de uma vez, o saldo anterior vem incorreto. Pedro
      /*if ((wdepmesbaixa <> 'TRUE') and (wvalorbaixa > 0)) then
        prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;  */
      --alt:14624 - Fim

      --#alt:16852 - Quando n?o tiver uma taxa cadastrada ent?o deve levar o valor correto do valo residual que ? o valor original do bem - o total de baixas. Ana - 01/02/2017
      IF (prtotalmesesdepreciacao = 0) THEN
        prvalorresidualcontabil = wvalorresidualcontabil;
      ELSE
      IF (wvalorresidualcontabil > 0) THEN
        BEGIN
          wvalorresidualcontabil = ABS(wvalorresidualcontabil - prvalorresidualcontabil);
          --alt:16006 - 23/11/2016 - Corrigido para trazer o valor residual considerando quando houver baixa. Pedro
          --IF ((prvalorresidualcontabil > 0) AND (wdepreciacaoperiodo > 0) AND (wvalorresidualcontabil <> wdepreciacaoperiodo)) THEN
          --  wvalorresidualcontabil = wdepreciacaoperiodo;

          IF (wvalorresidualcontabil > 0) THEN
            prvalorresidualcontabil = ABS(prvalorresidualcontabil - wvalorresidualcontabil);
        END

      --#alt:16852 - Quando o valor da aquisi??o for o mesmo do valor residual o valor residual moeda ja vem correto da sp. Ana - 10/02/2017
      IF (prvaloraquisicaooriginal = prvalorresidualcontabil) THEN
        prvalorresidualcontabilmoeda = wvalorresidualcontabilmoeda;
      ELSE
      IF (wvalorresidualcontabilmoeda > 0) THEN
        BEGIN
          wvalorresidualcontabilmoeda = ABS(wvalorresidualcontabilmoeda - prvalorresidualcontabilmoeda);
          --alt:16006 - 23/11/2016 - Corrigido para trazer o valor residual considerando quando houver baixa. Pedro
          --IF ((prvalorresidualcontabilmoeda > 0) AND (wdepreciacaoperiodomoeda > 0) AND (wvalorresidualcontabilmoeda <> wdepreciacaoperiodomoeda)) THEN
          --  wvalorresidualcontabilmoeda = wdepreciacaoperiodomoeda;

          IF (wvalorresidualcontabilmoeda > 0) THEN
            prvalorresidualcontabilmoeda = ABS(prvalorresidualcontabilmoeda - wvalorresidualcontabilmoeda);
        END

      --alt:14761 - 20/06/2016 - Se tiver baixa no per?odo tamb?m precisa retornar os meses depreciados. Pedro
      --alt:14761 - 16/06/2016 - Se tiver valor de deprecia??o acumulada (informado no cadastro da deprecia??o)
      --? feito um c?lculo da quantidade de meses j? depreciados e assim precisa retornar eles tamb?m. Pedro
      IF ((wdepreciacaoperiodo > 0) OR (wvaldepacumubem > 0) OR (wvalorbaixa > 0)) THEN
        BEGIN
          IF ((wtaxaaux > 0) AND (wtaxaaux <> prtaxadepreciacaoanual)) THEN
            wmesesdepreciadosaux = wmesesdepreciadosaux + ABS(wmesesdepreciadosaux - prmesesdepreciados);

          IF ((wmesesdepreciados > 0) AND ((prmesesdepreciados = 0) OR (wmesesdepreciados > prmesesdepreciados))) THEN --alt:13784 - 12/04/2016 - Quando trocada a taxa de deprecia??o n?o estava levando os meses depreciados corretamente. Pedro
            prmesesdepreciados = wmesesdepreciados;
          --alt:9013 - Comentado pois essa valida??o n?o faz sentido quando ? deprecia??o di?ria. Pedro
          /*else
            if (not prmesesdepreciados = prtotalmesesdepreciacao) then
               prmesesdepreciados = prmesesdepreciados + 1; */
        END

      IF (wvalorbaixa > 0) THEN
        BEGIN
          --#alt:18200 - Comentado pois desta forma estava calculando o valor da baixa incorretamente. Ana - 04/05/2017
          --wvalorbaixa = ABS(wvalorbaixa - prvalorbaixa);
          IF (wvalorbaixa > 0) THEN
            prvalorbaixa = prvalorbaixa + wvalorbaixa;
        END

      IF (wdepreciacaobaixamoeda > 0) THEN
        BEGIN
          wdepreciacaobaixamoeda = ABS(wdepreciacaobaixamoeda - prdepreciacaobaixamoeda);
          IF (wdepreciacaobaixamoeda > 0) THEN
            prdepreciacaobaixamoeda = prdepreciacaobaixamoeda + wdepreciacaobaixamoeda;
        END

      IF (wvalorbaixareal > 0) THEN
        BEGIN
          wvalorbaixareal = ABS(wvalorbaixareal - prvalorbaixareal);
          IF (wvalorbaixareal > 0) THEN
            prvalorbaixareal = prvalorbaixareal + wvalorbaixareal;
        END

      IF (wvaloraquisicaomoeda > 0) THEN
        BEGIN
          wvaloraquisicaomoeda = ABS(wvaloraquisicaomoeda - prvaloraquisicaomoeda);
          IF (wvaloraquisicaomoeda > 0) THEN
            prvaloraquisicaomoeda = ABS(prvaloraquisicaomoeda - wvaloraquisicaomoeda);
        END

      IF (wvalorcorrigidoatual > 0) THEN
        BEGIN
          --#alt:18200 - O valor ja vem correto da sp_cons_calc_dep_correcao com as novas altera??es. Ana - 02/05/2017
          prvalorcorrigidoatual = wvalorcorrigidoatual;
          /*wvalorcorrigidoatual = ABS(wvalorcorrigidoatual - prvalorcorrigidoatual);
          IF (wvalorcorrigidoatual > 0) THEN
            prvalorcorrigidoatual = ABS(prvalorcorrigidoatual - wvalorcorrigidoatual);*/
          --#alt:18200. fim
        END

      --#alt:19501 - Foi feito o tratamento na sp de corre??o para quando o bem estiver totalmente baixado e n?o for o m?s da baixa total, ent?o todos os saldos devem ser zerados. Ana - 22/09/2017
      IF ((wdepreciacaoperiodo = 0) AND (wdepreciacaoacumuladaatual = 0) AND (prdepreciacaoacumuladaanterior <> 0) AND (prvalorbaixa = 0) ) THEN
        BEGIN
          prdepreciacaoacumuladaanterior = 0;
          prdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * wvalormoeda);
          --se n?o tiver baixa no per?odo da consulta, ent?o o bem ja foi totalmente baixado. Com isso o saldo anterior, valor residual e valor residual moeda devem ir zerados
          IF (wpossuibaixa = 'FALSE') THEN
            BEGIN
              prdepreciacaoacumuladaatual  = 0;
              prvalorresidualcontabil      = 0;
              prvalorresidualcontabilmoeda = 0;
            END
        END
      ELSE
        IF ((prdepreciacaoacumuladaatual = 0) OR (wdepreciacaoacumuladaatual <> 0)) THEN
        BEGIN
          --antes o valor de retorno da sp era setado direto na vari?vel de retorno, mas n?o deve substituir sempre
          prdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual;
        END
      --#alt:19501. fim

      IF (prdatabaixa IS NOT NULL) THEN
        BEGIN
          wdtbaixaaux = prdatabaixa;
          --#alt:19501 - Atribui ? vari?vel o valor true quando possuir alguma baixa no per?odo. Colocando como true n?o interfere na sp da corre??o, pois la dentro ? refeita esta verifica??o. Ana - 22/09/2017'
          wpossuibaixa = 'TRUE';
        END

      wtaxaant = wtaxaaux;
      wtaxaaux = COALESCE(prtaxadepreciacaoanual,0);
      wdtini   = addmonth(wdtini, 1);
      wdtfim   = addmonth(wdtini, 1)-1;
      IF (wdtfim > prdatafinal) THEN
        wdtfim = prdatafinal;
      wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  --#alt:18200 - Alterada forma de c?lculo do valor corrigido atual (valor corrigido anterior + corre??o do per?odo - valor de baixas do per?odo). Ana - 02/05/2017
  prvalorcorrigidoatual = (prvalorcorrigidoanterior + prcorrecaoperiodo - prvalorbaixa);

  --#alt:19501 - Se o valor corrigido atual for zero, ent?o o bem ja foi totalmente depreciado/baixado. Ana - 22/09/2017
  IF (prvalorcorrigidoatual = 0) THEN
    BEGIN
      prcorrecaomonetariadepreciacao = 0;
      prvalorresidualcontabil        = 0;
      prvalorresidualcontabilmoeda   = 0;
    END

  prtotalmesesdepreciacao = prtotalmesesdepreciacao + wmesesdepreciadosaux;
  --alt:11609 - 21/10/2015 - Corrigido, estava retornando o valor incorreto para o meses a depreciar. H? um outro c?lculo 
  --que ? feito na vari?vel wmesesdepreciados que n?o estava sendo propagado por pegar o valor do prmesesdepreciados. Pedro
  prmesesdepreciar        = prtotalmesesdepreciacao - prmesesdepreciados; --alt:13978 - 06/04/2016 - Voltado como era antes, corrigido o tratamento dos campos. Pedro
  --prmesesdepreciar        = prtotalmesesdepreciacao - wmesesdepreciados;

  --#alt:16929 - Estava trazendo a quantidade de meses depreciados maior que o total de meses de deprecia??o e os meses a depreciar negativo. Ana - 01/02/2017
  IF (prmesesdepreciados > prtotalmesesdepreciacao) THEN
    BEGIN
      prmesesdepreciados = prtotalmesesdepreciacao;
      prmesesdepreciar   = 0;
    END

  --#alt:16852 - Quando n?o tiver uma taxa cadastrada ent?o deve levar o valor correto do valor residual. Quando o valor residual for 0 o residual moeda tamb?m deve ser. Ana - 08/02/2017
  IF (((prtotalmesesdepreciacao = prmesesdepreciados) AND (prtotalmesesdepreciacao > 0)) OR (prvalorresidualcontabil = 0)) THEN
    BEGIN
      prcorrecaomonetariadepreciacao = 0;
      prvalorresidualcontabil        = 0;
      prvalorresidualcontabilmoeda   = 0;
    END

  --#alt:17098 - Com um per?odo maior do que a data da baixa estava retornando null, ent?o se teve alguma baixa durante o per?odo selecionado deve retornar essa data. Ana - 19/05/2017
  IF ((prdatabaixa IS NULL) AND (wdtbaixaaux IS NOT NULL))THEN
    prdatabaixa = wdtbaixaaux;

  --alt:9581 - Joga o valor para a vari?vel de retorno, antes no ?ltimo m?s em alguns casos n?o retornava nada. Pedro
  --prmesesdepreciados = wmesesdepreciados; --alt:13978 - 06/04/2016 - Agora o retorno est? correto acima, e se jogar o valor aqui, mata outro tratamento acima. Pedro

  --#Alt:5105
  IF (prvaloraquisicaooriginal = wvalorbaixabem) THEN
    BEGIN
      prvalorresidualcontabil      = 0;
      prvalorresidualcontabilmoeda = 0;

      IF ((wdepmesbaixa = 'TRUE') AND
          (wreffim > CAST((SUBSTRING(wdtbaixaaux FROM 1 FOR 4)) || (SUBSTRING(wdtbaixaaux FROM 6 FOR 2)) AS INTEGER))) THEN
        BEGIN
          prvalorcorrigidoanterior        = 0;
          prcorrecaoperiodo               = 0;
          prvalorcorrigidoatual           = 0;
          prvalorbaixa                    = 0;
          prdepreciacaoacumuladaanterior  = 0;
          prdepreciacaoperiodo            = 0;
          prdepreciacaoperiodomoeda       = 0;
          prdepreciacaoacumuladaatual     = 0;
          prdepreciacaoacumuladaatualmoed = 0;
          prcorrecaomonetariadepreciacao  = 0;
          prtotalmesesdepreciacao         = 0;
          prmesesdepreciados              = 0;
          prmesesdepreciar                = 0;
        END
    END

  prsomardepreciacao = 1; --alt:13784 - 03/05/2016 - S? deve somar nos totais do relat?rio quando for a ?nica taxa ou a ?ltima (caso esteja detalhando por taxa de deprecia??o). Pedro
  SUSPEND;
END
^

/* Alter (SP_CONS_CALC_DEP_CORRECAO) */
ALTER PROCEDURE SP_CONS_CALC_DEP_CORRECAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER,
PRVLRMOEDA NUMERIC(15,6),
PRPOSSUIBAIXA VARCHAR(5),
PRCODBEMORIGINAL INTEGER,
PRVALORAQUISICAO NUMERIC(15,6),
PRTAXADEPANUAL NUMERIC(6,6),
PRDATAAQUISICAO DATE,
PRDATAORIGAQUISICAO DATE,
PRDEPDIA VARCHAR(5),
PRDEPMENSAL VARCHAR(5),
PRDEPMESBAIXA VARCHAR(5),
PRDATAINICIOCALC DATE,
PRDATAFIMCALC DATE,
PRDATAULTIMOITEMDEP DATE,
PRVALDEPACUMUBEM NUMERIC(15,6),
PRCTADEBDEPRE INTEGER,
PRNUMDIAS INTEGER,
PRDEPDIADATA INTEGER,
PRVALORBAIXABEM NUMERIC(15,6),
PRMESESDEPRECIADOSOUTRATAXA INTEGER,
PRVALORACUMULADOANTERIOR NUMERIC(15,6))
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,6),
PRCORRECAOPERIODO NUMERIC(15,6),
PRVALORCORRIGIDOATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6),
PRDEPRECIACAOPERIODO NUMERIC(15,6),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6),
PRVALORRESIDUALCONTABIL NUMERIC(15,6),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,6),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,6),
PRVALORBAIXAREAL NUMERIC(15,6),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,6),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,6),
PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOPERIODO DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED DOUBLE PRECISION;
DECLARE VARIABLE WVALORRESIDUALCONTABIL DOUBLE PRECISION;
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WDIASDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WVALORAQUISICAO DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOAUX DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOORIGINAL DOUBLE PRECISION;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAATUAL DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALORBAIXA DOUBLE PRECISION;
DECLARE VARIABLE WVALORBAIXAAUX DOUBLE PRECISION;
DECLARE VARIABLE WVALORBAIXAPER DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPDIASADEPRECIAR INTEGER;
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WTOTALMESESDOPERIODO INTEGER;
DECLARE VARIABLE WVALORDEPRECIACAOMENSAL DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPRECIACAODIARIA DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPRECIACAODIARIABAIXA DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDIFERENCAMESES INTEGER;
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WVALDEPACUMUBEM DOUBLE PRECISION;
DECLARE VARIABLE WMESESDEPACUMUBEM INTEGER;
DECLARE VARIABLE WDATAOFICIALINICIOLCALCULO DATE;
DECLARE VARIABLE WDATAINICIALINICIOCALCULO DATE;
DECLARE VARIABLE WULTIMODIADOMES SMALLINT;
DECLARE VARIABLE WDIA SMALLINT;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WDEPDIADATA INTEGER;
DECLARE VARIABLE WDATAINICIALOFICIAL DATE;
DECLARE VARIABLE WDEPDIAFINAL VARCHAR(5);
DECLARE VARIABLE WDATATOTALMESESULTIMODIA DATE;
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATATOTALMESESDEPDIA DATE;
DECLARE VARIABLE WVALORCORRIGIDOANTERIORMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WVERIFICAMESINTEIRO INTEGER;
DECLARE VARIABLE WDIASDEPDIARIA DOUBLE PRECISION;
DECLARE VARIABLE WMESESDEPDIARIA DOUBLE PRECISION;
DECLARE VARIABLE WDATAINICIOCALCAUX DATE;
BEGIN
  /*Stored procedure para calcular a deprecia??o dos bens*/
  -- Inicializa par?metros
  PRVALORCORRIGIDOANTERIOR        = 0;
  PRCORRECAOPERIODO               = 0;
  PRVALORCORRIGIDOATUAL           = 0;
  PRDEPRECIACAOACUMULADAANTERIOR  = 0;
  PRDEPRECIACAOPERIODO            = 0;
  PRDEPRECIACAOPERIODOMOEDA       = 0;
  PRDEPRECIACAOACUMULADAATUAL     = 0;
  PRDEPRECIACAOACUMULADAATUALMOED = 0;
  PRCORRECAOMONETARIADEPRECIACAO  = 0;
  PRVALORRESIDUALCONTABIL         = 0;
  PRVALORRESIDUALCONTABILMOEDA    = 0;
  PRTOTALMESESDEPRECIACAO         = 0;
  PRMESESDEPRECIADOS              = 0;
  PRMESESDEPRECIAR                = 0;
  PRTAXADEPRECIACAOANUAL          = 0;
  PRDATATAXADEPRECIACAO           = NULL;
  PRVALORBAIXA                    = 0;
  PRDEPRECIACAOBAIXAMOEDA         = 0;
  PRVALORBAIXAREAL                = 0;
  PRVALORMOEDA                    = 0;
  PRDATABAIXA                     = NULL;
  PRVALORAQUISICAOMOEDA           = 0;
  PRVALORCORRIGIDOANTERIORMOEDA   = 0;
  PRVALORAQUISICAOORIGINAL        = 0;
  PRCTADEBITODEPRE                = NULL;
  PRVALORDEPRECIACAODIARIAFIM     = 0;

  -- Inicializa vari?veis
  wdatainicialoficial            = prdatainicial;
  wdepdiafinal                   = 'FALSE';
  wnumdias                       = 0;
  wdepdiadata                    = 0;
  wultimodiadomes                = 0;
  wdepdiasadepreciar             = 0;
  wvalordepreciacaodiaria        = 0;
  wvalordepreciacaodiariabaixa   = 0;
  wvaloraquisicaomoeda           = 0;
  wvalorcorrigidoanterior        = 0;
  wdepreciacaoacumuladaanterior  = 0;
  wdepreciacaoperiodo            = 0;
  wdepreciacaoperiodomoeda       = 0;
  wdepreciacaoacumuladaatual     = 0;
  wdepreciacaoacumuladaatualmoed = 0;
  wvalorresidualcontabil         = 0;
  wvalorresidualcontabilmoeda    = 0;
  wtotalmesesdepreciacao         = 0;
  wmesesdepreciados              = 0;
  wdiasdepreciados               = 0;
  wmesesdepreciar                = 0;
  wvaloraquisicao                = 0;
  wvaloraquisicaoaux             = 0;
  wvaloraquisicaooriginal       = 0;
  wdataaquisicao                 = NULL;
  wdatainiciocalc                = NULL;
  wdatafimcalc                   = NULL;
  wdataatual                     = :prdatafinal;
  wdatatotalmeses                = NULL;
  wdatatotalmesesdepdia          = NULL;
  wdatatotalmesesultimodia       = NULL;
  wdataultimoitemdep             = NULL;
  wvalorbaixa                    = 0;
  wvalorbaixaaux                 = 0;
  wvalorbaixaper                 = 0;
  wvaldepacumubem                = 0;
  wmesesdepacumubem              = 0;
  wdataoficialiniciolcalculo     = NULL;
  wdatainicialiniciocalculo      = NULL;
  --alt:16494 - 25/11/2016 - Inicializar a vari?vel, ficava null quando calculava um per?odo antes do in?cio
  --da deprecia??o, assim os meses que deveriam depreciar concatenava com null e ficava sempre null. Pedro
  prvaloracumuladoanterior       = COALESCE(prvaloracumuladoanterior, 0);

  -- Para melhorar o desempenho da rotina esse select foi jogado na Stored Procedure SP_CONS_CALC_DEP para ser chamada apenas quando
  -- for necess?ria. As informa??es do select est?o sendo passadas por par?metro
  /*select tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem,
         tbem.bddepmesbaixabem, tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, tdep.bdvaldepacumubem,tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata
  from empresas_tbem tbem
  left outer join empresas_tdepreciacao tdep on ((tbem.bdcodemp = tdep.bdcodemp) and (tbem.bdcodbem = tdep.bdcodbem) and
                                                 (tdep.bdcontabilizacao = :prcontabilizacao) and
                                                 (Cast((substring(tdep.bddatinicalcbem from 1 for 4)) || (substring(tdep.bddatinicalcbem from 6 for 2)) as integer) <=
                                                  Cast((substring(:prdatainicial from 1 for 4)) || (substring(:prdatainicial from 6 for 2)) as integer)) and
                                                 ((Cast((substring(tdep.bddatfimcalcbem from 1 for 4)) || (substring(tdep.bddatfimcalcbem from 6 for 2)) as integer) >=
                                                   Cast((substring(:prdatafinal from 1 for 4)) || (substring(:prdatafinal from 6 for 2)) as integer)) or (tdep.bddatfimcalcbem is null)))
  where (tbem.bdcodemp = :prcodemp) and
        (tbem.bdcodbem = :prcodbem)
  into :wcodbemoriginal, :wvaloraquisicao,    :prtaxadepreciacaoanual,
       :wdataaquisicao,  :wdataorigaquisicao, :wdepdia,            :wdepmensal, : wdepmesbaixa,
       :wdatainiciocalc, :wdatafimcalc,       :wdataultimoitemdep, :wvaldepacumubem, :prctadebitodepre, :wnumdias, :wdepdiadata;*/
  --wcodbemoriginal        = prcodbemoriginal;
  wvaloraquisicao        = prvaloraquisicao;
  wvaloraquisicaooriginal= wvaloraquisicao;
  prtaxadepreciacaoanual = prtaxadepanual;
  wdataaquisicao         = prdataaquisicao;
  wdataorigaquisicao     = prdataorigaquisicao;
  wdepdia                = prdepdia;
  wdepmensal             = prdepmensal;
  wdepmesbaixa           = prdepmesbaixa;
  wdatainiciocalc        = prdatainiciocalc;
  wdatafimcalc           = prdatafimcalc;
  wdataultimoitemdep     = prdataultimoitemdep;
  wvaldepacumubem        = prvaldepacumubem;
  prctadebitodepre       = prctadebdepre;
  wnumdias               = prnumdias;
  wdepdiadata            = prdepdiadata;
  wdepreciacaoacumuladaatual = prvaloracumuladoanterior;

  IF (wvaloraquisicao IS NULL) THEN
     BEGIN
       EXCEPTION ex_date;
       SUSPEND;
       EXIT;
     END

   IF (prdatainicial > wdatafimcalc) THEN
     EXIT;

  --alt:16006 - 03/11/2016 - Implementado aqui o c?lculo da baixa de todos os per?odos. Pedro
  --Processo para calcular os meses anteriores ao per?odo informado, pois posso ter v?rias deprecia??es cadastradas
  SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  AND   (tbai.BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
  INTO :wvalorbaixa;
  IF (wvalorbaixa > 0) THEN
    prpossuibaixa = 'TRUE';

  --#alt:85169. Deve fazer os outros c?lculos. Ana - 20/06/2018
  --Tipo 2 somente baixas
  /*IF ((prtipo = 2) AND (wvalorbaixa = 0)) THEN
    EXIT;*/
  --alt:16006 - Fim

  prvaloraquisicaooriginal = wvaloraquisicao;
  /*#Alt:5105. Conforme visto com o Celso quando o bem tem alguma baixa parcial o sistema calcula a depreci??o desde o in?cio levando em conta
  a baixa, e n?o apenas no m?s da baixa pra frente.*/
  --wvalorbaixa = 0;
  --wvalorbaixa = prvalorbaixabem; --alt:16006 - Calcula aqui o valor da baixa. Pedro
  IF (prpossuibaixa = 'TRUE') THEN
    BEGIN
      FOR SELECT bddatbai,COALESCE(SUM(bdvalbai),0) AS TotalBaixa FROM empresas_tbai
          WHERE (bdcodemp = :prcodemp) AND (bdcodbem = :prcodbem) AND (BDCONTABILIZACAO = :prContabilizacao) --alt:14256 - 04/07/2016 - Adicionado campo da contabiliza??o. Pedro
          AND   (bddatbai BETWEEN :prdatainicial AND :prdatafinal) GROUP BY bddatbai
          INTO :wdatabaixa,:wvalorbaixaaux DO
        BEGIN
          --#Alt:5105
          --wvalorbaixa = wvalorbaixa + wvalorbaixaaux;
          wvalorbaixaper = wvalorbaixaper + wvalorbaixaaux;
        END
    END
  wvaloraquisicao = (wvaloraquisicao - wvalorbaixa);

  --alt:8005 - Foi removida esta valida??o porque n?o faz sentido e fazia com que n?o funcionasse corretamente em alguns casos. Pedro
  IF ((UPPER(wdepmesbaixa) = 'TRUE') /*and (wvalorbaixa >= wvaloraquisicao)*/) THEN
    BEGIN
      --alt:8005 - Foi removido porque n?o faz sentido setar um ano igual ao outro sendo que vai comparar os dois depois, isso fazia com que n?o funcionasse corretamente em alguns casos. Pedro
      --prdatafinal = wdatabaixa;

      --alt:8005 - Estava ocorrendo um erro no m?s da baixa, por isso foi adicionada a valida??o do "wdatabaixa is null".
      --Mas isso gerou outro problema agora e aparentemente o problema que acontecia antes n?o ocorreu mais, ent?o retirei. Pedro
      IF ((CAST((SUBSTRING(wdatabaixa FROM 1 FOR 4)) || (SUBSTRING(wdatabaixa FROM 6 FOR 2)) AS INTEGER) <=
          CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER))) THEN
        wdepmesbaixa = 'TRUE';
      ELSE
        wdepmesbaixa = 'FALSE';
    END
  ELSE
    wdepmesbaixa = 'FALSE';

  --alt:9013 - Foi colocado aqui o c?lculo do valor corrigido atual, pois precisava ser antes de juntar novamente o valor da baixa ao valor da aquisi??o. Pedro
  -- C?LCULO DE DEPRECIA??O
  prcorrecaoperiodo     = 0;

  --#alt:18200. Desta forma que estava retornando o valor n?o estava correta. Ana - 02/05/2017
  --#alt:16852 - Adicionada verifica??o para retornar o valor da baixa do per?odo quando tiver taxa cadastrada, pois estava calculando errado o valor residual. Ana - 01/02/2017
  /*if (prtaxadepanual <> 0) then
    prvalorcorrigidoatual = wvalorbaixaper;
  else
    prvalorcorrigidoatual = wvalorbaixa;*/

  --alt:9581 - Foi alterado para jogar devolta apenas a baixa do per?odo, n?o a baixa de todos os per?odos,
  --pois quando tinha mais de uma baixa e estava marcada a op??o calcular deprecia??o do m?s da baixa ele trazia o valor original para a deprecia??o do m?s,
  --sendo que deveria ser o valor original menos baixas que tenham ocorrido em per?odo anterior. Pedro
  IF ((UPPER(wdepmesbaixa) = 'TRUE') /*and (wdatabaixa is null)*/) THEN
    --wvaloraquisicao = (wvaloraquisicao + wvalorbaixa);
    wvaloraquisicao = (wvaloraquisicao + wvalorbaixaper);

  --alt:9581 - Implementado aqui, pois se cair no exit precisa retornar a quantidade de meses depreciados. Pedro
  IF (wdatainiciocalc IS NOT NULL) THEN
    wdataoficialiniciolcalculo = wdatainiciocalc;
  ELSE
    wdataoficialiniciolcalculo =  wdataaquisicao;

  -- Meses j? depreciados
  wmesesdepreciados = DATEDIFF(MONTH,:wdataoficialiniciolcalculo,:wdataatual);
  IF (wmesesdepreciados < 0) THEN
    wmesesdepreciados = 0;

  --#alt:16929 - Adicionada verifica??o para atribuir o valor do campo cadastrado na depreci??o acumulada, pois estava ignorando este campo e fazendo os calculos errados. Ana - 31/01/2017
  wdatainicialoficial = SUBSTRING(CAST(prdatainicial AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                        SUBSTRING(CAST(prdatainicial AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
  wdatainicialiniciocalculo = SUBSTRING(CAST(wdataoficialiniciolcalculo AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdataoficialiniciolcalculo AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

  wdiasdepreciados = DATEDIFF(DAY,:wdatainicialiniciocalculo,:wdatainicialoficial);
  IF ((wvaldepacumubem <> 0) AND ((wdiasdepreciados < 30) AND ((wvaldepacumubem <> prdepreciacaoacumuladaanterior) OR (wdiasdepreciados > -1)))) THEN
    wdepreciacaoacumuladaatual = wVALDEPACUMUBEM;
  wdatainicialoficial = prdatainicial;
  --#alt:16929. fim

  --alt:13784 - 12/04/2016 - Implementado para contar corretamente no caso de ter duas taxas de deprecia??o distintas. Pedro
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) /*>*/=
      CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER)) THEN
    wmesesdepreciados = wmesesdepreciados + 1;

  IF (prmesesdepreciadosoutrataxa > 0) THEN --alt:13784 - 12/04/2016 - Se j? tiver depreciado algum m?s com a taxa anterior, precisa somar esses meses tamb?m. Pedro
    wmesesdepreciados = wmesesdepreciados + prmesesdepreciadosoutrataxa;
  --alt:13784 - Fim

  prmesesdepreciados = wmesesdepreciados;
  --alt:9581 - Fim

  IF ((((wvaloraquisicao IS NULL) OR (wvaloraquisicao <= 0))) AND (UPPER(wdepmesbaixa) = 'FALSE')) THEN
     BEGIN
       --alt:14624 - 27/05/2016 - Se tiver baixa no per?odo, precisa calcular o valor depreciado at? ent?o. Pedro
       --alt:14761 - 20/06/2016 - Adicionados par?metros remanescentes. Pedro
       --alt:15375 - 12/08/2016 - Adicionada verifica??o do valor da aquisi??o, este processo ? executado no cadastro de deprecia??o
       --para verificar se h? valor depreciado anterior a ele, e como n?o possui valor da aquisi??o ainda, ocorre erro. Pedro
       ------- if ((wvaloraquisicao is not null) and (wvaloraquisicao > 0)) then  **** Essa regra estava dando problema. Foi comentado porque n?o conseguiram explicar a raz?o dela (Solicita??o.: 15605)
       --#alt:15259 - Quando o valor vinha zerado gerava um erro. Ana - 16/09/2016
       IF ( prtaxadepreciacaoanual <> 0) THEN
         BEGIN
           wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
           wvalordepreciacaomensal = (prvaloraquisicao / wtotalmesesdepreciacao);
         END

       --#alt:19501 - Se o bem ja foi totalmente baixado ent?o n?o deve possuir deprecia??o acumulada anterior e nem deprecia??o no per?odo, quando consultado em um per?odo ap?s a baixa total. Ana - 21/09/2017
       IF ((wvalorbaixa >= wvaloraquisicaooriginal) AND (wvalorbaixa <> wvalorbaixaper) AND (wvalorbaixaper = 0)) THEN
         BEGIN
           prdepreciacaoacumuladaanterior = 0;
           wdepreciacaoacumuladaatual = wvaloraquisicao;
           wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual;
         END
       ELSE
         BEGIN
           IF ((wvalordepreciacaodiaria > 0) AND (wdatainicialoficial <= :wdataaquisicao))  THEN
             BEGIN
               --alt:16006 - 03/11/2016 - Alterado para carregar o valor acumulado depreciado de uma vari?vel que calcula m?s a m?s, pois quando na aquisi??o utilizava a deprecia??o di?ria, nos meses seguintes desconsiderava este valor. Pedro
               --wdepreciacaoacumuladaatual     = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wmesesdepreciados);
               wdepreciacaoacumuladaatual     = (wvalordepreciacaodiaria + wvalordepreciacaomensal + wdepreciacaoacumuladaatual);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
             END
           ELSE
             BEGIN
               --alt:16006 - 03/11/2016 - Alterado para carregar o valor acumulado depreciado de uma vari?vel que calcula m?s a m?s, pois quando na aquisi??o utilizava a deprecia??o di?ria, nos meses seguintes desconsiderava este valor. Pedro
               --wdepreciacaoacumuladaatual     = (wvalordepreciacaomensal * wmesesdepreciados);
               wdepreciacaoacumuladaatual     = (wvalordepreciacaomensal + wdepreciacaoacumuladaatual);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
             END
    
           --#Alt:5105
           IF (wvalorbaixaper > 0) THEN
             BEGIN
               prdatabaixa  = wdatabaixa;
               prvalorbaixa = wvalorbaixaper;
               wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual - wvalordepreciacaomensal);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
               prdepreciacaoacumuladaanterior = wdepreciacaoacumuladaatual;
    
               --#Alt:16327 (In?cio) - Precisa ser setado o valor corrigido anterior mesmo que o valor do bem j? tenha baixado totalmente. E o
               --valor ? jogado para uma vari?vel local do tipo Double Precision e depois para a de sa?da,
               --pois pode gerar um erro de "Aritmethic Overflow" por calcular um valor grande demais.
               wvalorcorrigidoanterior  = (wvaloraquisicao + wvalorbaixaper);
               prvalorcorrigidoanterior = wvalorcorrigidoanterior;
    
               wvalorcorrigidoanteriormoeda  = (wvaloraquisicao + wvalorbaixaper) / prvlrmoeda;
               prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;
               --#Alt:16327 (Fim)
             END
           ELSE
             prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaatual - wvalordepreciacaomensal;
         END

       prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
       prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
       prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
       --alt:14624 - Fim
       --alt:14761 - Fim
       prcompensacaobaixaperanterior = wdepreciacaoacumuladaatual; --alt:16006 - 24/11/2016 - Tratado para retornar o valor da deprecia??o acumulada para quando tem baixa total. Pedro

       --alt:15196 - 24/11/2016 - Adapta??o para zerar o valor residual da deprecia??o. Pedro
       IF ((prdepreciacaoacumuladaanterior + wtotalmesesdepreciacao) > wvaloraquisicao) THEN
         BEGIN
           IF (prdepreciacaoacumuladaanterior < wvaloraquisicao) THEN
             BEGIN
               wtotalmesesdepreciacao = wvaloraquisicao - prdepreciacaoacumuladaanterior;
               prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior + wtotalmesesdepreciacao;
             END
           ELSE
             BEGIN
               wtotalmesesdepreciacao = 0;
               --#alt:19501 - N?o deve assumir o valor da aquisi??o, pois mesmo que o bem ja tenha sido totalmente baixado ainda h? como depreciar o valor acumulado anterior. Ana - 21/09/2017
               --prdepreciacaoacumuladaatual = wvaloraquisicao;
             END
    
           prdepreciacaoperiodomoeda = wtotalmesesdepreciacao * prvlrmoeda;
           prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatual * prvlrmoeda;
           prdepreciacaoperiodo = wtotalmesesdepreciacao;
         END

       SUSPEND;
       EXIT;
     END

  IF (prtipo = 2) THEN
    BEGIN
      --#alt:85169. Ana - 20/06/2018
      wvaloraquisicaoaux       = wvaloraquisicao;
      if ((wvalorbaixaper > 0) and (wvalorbaixa > 0)) then
        begin
          wvaloraquisicao          = wvalorbaixa;
          --prvaloraquisicaooriginal = wvalorbaixa;
        end
      --#alt:85169. fim
    END

  --alt:9013 - Foi retirado daqui e colocado mais acima, pois quando chegava aqui o valor estava incorreto, baseado no valor original da aquisi??o, desconsiderando a baixa. Pedro
  -- C?LCULO DE DEPRECIA??O
  /*prcorrecaoperiodo     = 0;
  prvalorcorrigidoatual = wvaloraquisicao;*/

  -- Deprecia??o di?ria (In?cio)
  --#alt:19501 - Alterada verifica??o da vari?vel "wNumDias". Ana - 24/10/2017
  --#alt:18200 - N?o estava fazendo a deprecia??o di?ria quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
  --alt:15196 - 24/11/2016 - Adicionada valida??o do "wNumDias", caso esteja selecionado para iniciar a deprecia??o no
  --dia seguinte ? aquisi??o, ter? um dia a menos para depreciar, e n?o ser? mais deprecia??o mensal nesta regra. Pedro
  --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
  --IF ((UPPER(wdepdia) = 'TRUE' ) AND ((SUBSTRING(wdatainiciocalc FROM 9 FOR 2)) = '01')) THEN
  IF ((UPPER(wdepdia) = 'TRUE') AND (wnumdias <= 2) AND
      (((EXTRACT(DAY FROM wdatainiciocalc) = 1) AND (wdatainiciocalc BETWEEN prdatainicial AND prdatafinal)) OR
       ((wdatabaixa BETWEEN prdatainicial AND prdatafinal) AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0)))) THEN
    wdepdia = 'FALSE';

  IF (UPPER(wdepdia) = 'TRUE') THEN
    BEGIN
      --#alt:18200 - Adicionei a verifica??o da diferen?a de meses da baixa para a aquisi??o do bem, pois n?o estava fazendo a deprecia??o di?ria corretamente
      --             quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
      --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
      IF ((wdatabaixa BETWEEN prdatainicial AND prdatafinal) AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0)) THEN
        BEGIN
          --alt:16006 - 03/11/2016 - Se n?o for uma baixa total, ent?o deve dividir o m?s em duas partes para calcular a deprecia??o sobre o valor do bem antes e depois da baixa. Pedro
          IF (wvaloraquisicao <= 0) THEN
            wdepdiasadepreciar = EXTRACT(DAY FROM wdatabaixa);
          ELSE
            wdepdiasadepreciar = EXTRACT(DAY FROM wdatabaixa) -1;
        END
      ELSE
        BEGIN
          -- Total de meses para a deprecia??o
          IF (prtaxadepreciacaoanual >= 0.1) THEN
            wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);

          --#alt:19501 - N?o estava considerando os dias a depreciar quando tem deprecia??o acumulada informada. Ana - 24/10/2017
          IF ((wvaldepacumubem <> 0) AND (wtotalmesesdepreciacao <> 0)) THEN
            BEGIN
              wmesesdepdiaria = (wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
              wverificamesinteiro = (TRUNC(wmesesdepdiaria));
              wdiasdepdiaria = (wmesesdepdiaria - wverificamesinteiro);
              IF (wdiasdepdiaria > 0) THEN
                BEGIN
                  --#alt:21342 - Quando a quantidade de dias depreciados for igual a 0.01 significa que h? um valor de depreci??o di?ria mas n?o fecha em um dia completo.
                  --             para isso truncamos o valor em 0.04 que j? equivale a um dia para conseguir fazer os calculos. Ana - 09/11/2017
                  IF (wdiasdepdiaria < 0.04) THEN
                    wdiasdepdiaria = 0.04;

                  wmes = (ABS((TRUNC((((wmesesdepdiaria)/12) - TRUNC((wmesesdepdiaria)/12)) * 12)-12)+1));
                  wano = (EXTRACT(YEAR FROM wdatainiciocalc));
                  wano = (wano - TRUNC(wverificamesinteiro/12));

                  --#alt:21342 - Tenho que considerar a quantidade de dia de cada m?s e n?o deixar fixo 30 dias. Ana - 13/11/2017
                  SELECT ULTDIA FROM ULTIMO_DIA_MES(:wmes, :wano)
                  INTO :wUltimoDiaDoMes;
                  IF (wUltimoDiaDoMes > 0) THEN
                    wdepdiasadepreciar = (TRUNC(wdiasdepdiaria * wUltimoDiaDoMes));

                  --#alt:21342 - Adicionei a verifica??o dos dias para n?o ocorrer erro na conver??o. Ana - 09/11/2017
                  IF ((wdepdiasadepreciar > 0) AND (wano > 0) AND (wmes > 0) )THEN
                    wdatainiciocalcaux = (CAST(wano AS VARCHAR(4)) ||'-'|| CAST(wmes AS VARCHAR(2)) ||'-'|| CAST(wdepdiasadepreciar AS VARCHAR(2)));
                END
            END
          ELSE
            BEGIN
          wdepdiasadepreciar = EXTRACT(DAY FROM wdatainiciocalc);
              wdatainiciocalcaux = wdatainiciocalc;
            END

          -- C?lculo que retorna o ?ltimo dia do m?s
          --alt:18200 - 22/05/2017 - Corrigido, j? reduz um dia a mais quando ? pra depreciar apenas no dia seguinte. Pedro
          --#alt:18200 - Quando for dia 31 deve considerar como 30 dias e depreciar apenas um dia. Ana - 19/05/2017
          IF (wnumdias = 2) THEN
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatainiciocalcaux - EXTRACT(DAY FROM wdatainiciocalcaux) +
                                                32 - EXTRACT(DAY FROM wdatainiciocalcaux - EXTRACT(DAY FROM wdatainiciocalcaux) + 32)));
          ELSE
            wUltimoDiaDoMes = 30;

          --alt:8005 - Adicionado um dia a mais, pois sempre faltava um dia no c?lculo di?rio. Pedro
          --IF (wnumdias = 2) THEN
          IF (wvaldepacumubem = 0) THEN
            wdepdiasadepreciar = (wultimodiadomes + 1) - wdepdiasadepreciar;
          ELSE
            BEGIN
              --#alt:18204 - Quando o mes tinha 31 dias estava desconciderando o ultimo dia para depreciar. Ana - 28/04/2017
              /*IF (wultimodiadomes = 31) THEN
                wdepdiasadepreciar = (32) - wdepdiasadepreciar;
              ELSE*/
                wdepdiasadepreciar = (30 + 1) - wdepdiasadepreciar;
            END
          --alt:8005 - Fim
          -- Caso a op??o Dia seguinte a aquisi??o esteja selecionada preciso diminuir um dia no
          -- n?mero de dias a depreciar, pois a wdepdiasadepreciar veio calculada conforme
          -- a data de aquisi??o
          IF (wdepdiadata = 2) THEN
            wdepdiasadepreciar = wdepdiasadepreciar - 1;
          IF (wdepdiasadepreciar < 0) THEN
            wdepdiasadepreciar = 0;
        END
      --alt:13156 - Fim
    END
  -- Deprecia??o di?ria (Fim)

  -- Total de meses para a deprecia??o
  IF (prtaxadepreciacaoanual >= 0.1) THEN
    wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
  ELSE
    BEGIN
      --#Alt:16327 - Tamb?m precisamos setar o valor corrigido anterior quando o bem n?o possui taxa de deprecia??o
      wvalorcorrigidoanterior  = (wvaloraquisicao + wvalorbaixaper);
      prvalorcorrigidoanterior = wvalorcorrigidoanterior;

      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / prvlrmoeda;
      --wvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / prvlrmoeda; #Alt:16327 - Alterado a vari?vel "wvalorbaixa" para a "wvalorbaixaper"
      wvalorcorrigidoanteriormoeda  = (wvaloraquisicao + wvalorbaixaper) / prvlrmoeda;
      prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;

      prvalorresidualcontabil       = wvaloraquisicao;

      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvalorresidualcontabilmoeda  = wvaloraquisicao / prvlrmoeda;
      wvalorresidualcontabilmoeda = wvaloraquisicao / prvlrmoeda;
      prvalorresidualcontabilmoeda = wvalorresidualcontabilmoeda;
      
      prdatataxadepreciacao         = wdataultimoitemdep;
      --#Alt:5105
      --prvalorbaixa                  = wvalorbaixa;
      prvalorbaixa                  = wvalorbaixaper;
      prvalorbaixareal              = wvalorbaixa;
      prvalormoeda                  = prvlrmoeda;
      prdatabaixa                   = wdatabaixa;
      
      --alt:10543 - Alterado para jogar o valor para vari?vel local e depois para a de sa?da,
      --e o tipo da vari?vel local foi alterado para Double Precision,
      --pois antes gerava um Aritmethic Overflow por calcular um valor grande demais. Pedro
      --prvaloraquisicaomoeda         = (wvaloraquisicao / prvlrmoeda);
      wvaloraquisicaomoeda = (wvaloraquisicao / prvlrmoeda);
      prvaloraquisicaomoeda = wvaloraquisicaomoeda;
    
      SUSPEND;
      EXIT;
    END

  IF (wdatainiciocalc IS NOT NULL) THEN
    wdataoficialiniciolcalculo = wdatainiciocalc;
  ELSE
    wdataoficialiniciolcalculo =  wdataaquisicao;

  IF (wvaloraquisicao = 0) THEN
     EXIT;

  -- Joga para vari?vel o n?mero de meses que j? foi depreciado em outro sistema
  IF (prmesesdepreciadosoutrataxa > 0) THEN --alt:13784 - 12/04/2016 - Se j? tiver meses depreciados anteriormente com outras taxas, precisa buscar esses meses. Pedro
    wmesesdepacumubem = prmesesdepreciadosoutrataxa;
  ELSE IF (wvaldepacumubem > 0) THEN
    --#alt:16911 - Alterada formula para o calculo dos meses de deprecia??o acumulada. Ana - 26/01/2016
    --wmesesdepacumubem = (wvaldepacumubem / ( wvaloraquisicao / wtotalmesesdepreciacao ));
    wmesesdepacumubem = (wvaldepacumubem / ( wvaloraquisicaooriginal / wtotalmesesdepreciacao ));

  --wmesesdepacumubem= 24311;
  wdatatotalmeses       = addmonth(wdataoficialiniciolcalculo, wtotalmesesdepreciacao-wmesesdepacumubem);
  wdatatotalmesesdepdia = addmonth(wdatatotalmeses, 1);
  wdatatotalmeses       = SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                          SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
  -- Transforma no primeiro dia do m?s
  wdataaquisicao = SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                   SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

  wdiferencameses = DATEDIFF(MONTH,:wdatatotalmeses,:wdataatual);
  IF (wdiferencameses < 0) THEN
    wdiferencameses = 0;
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >=
      CAST((SUBSTRING(wdataaquisicao FROM 1 FOR 4)) || (SUBSTRING(wdataaquisicao FROM 6 FOR 2)) AS INTEGER)) THEN
    wdiferencameses = wdiferencameses + 1;

  IF (wdiferencameses-1 > 0) THEN
    BEGIN
     IF (wdepmensal = 'FALSE') THEN
       BEGIN
         wdataatual = addmonth(:wdatatotalmeses,1);
         wmes       = CAST(SUBSTRING(CAST(wdataatual AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
         wano       = CAST(SUBSTRING(CAST(wdataatual AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
         wdataatual = wmes||'-01-'||wano;
       END
     ELSE
       wdataatual = wdatatotalmeses;
    END

  IF ((wdepmensal = 'FALSE') AND
      (CAST(EXTRACT(YEAR FROM :prdatainicial) || EXTRACT(MONTH FROM :prdatainicial) AS INTEGER) = CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
    BEGIN
      prdatafinal = addmonth(:prdatafinal,-1);
      wmes       = CAST(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
      wano       = CAST(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
      prdatafinal = wmes||'-01-'||wano;
    END

  -- Se for relatorio de baixas, a data atual devera ser o do mes da baixa.
  --if ((prtipo = 2) or (wdatabaixa is not null)) then
  IF ((prtipo = 2) AND (wdatabaixa IS NOT NULL)) THEN
    BEGIN
      wdataatual  = wdatabaixa;
      prdatafinal = wdatabaixa;
    END

   IF ((wdatafimcalc IS NOT NULL) AND (wdatafimcalc < prdatafinal)) THEN
     BEGIN
       wdataatual  = wdatafimcalc;
       prdatafinal = wdatafimcalc;
     END

  -- Meses j? depreciados
  wmesesdepreciados = DATEDIFF(MONTH,:wdataoficialiniciolcalculo,:wdataatual);
  IF (wmesesdepreciados < 0) THEN
    wmesesdepreciados = 0;


  --#alt:19501 - Devo considerar a deprecia??o di?ria no m?s da aquisi??o, que n?o s?o considerados como m?s cheio e por isso est?o informados nas casas ap?s
  --             a v?rgula. Esta deprecia??o di?ria era desconsiderada para os c?lculos. Ana - 18/10/2017
  IF (wdepdia = 'TRUE') THEN
    BEGIN
  wverificamesinteiro = TRUNC(wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
      wdiasdepdiaria = ((wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao)) - wverificamesinteiro);
    END
  ELSE
    BEGIN
      wverificamesinteiro = TRUNC(wdepreciacaoacumuladaatual/(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
      wdiasdepdiaria = ((wdepreciacaoacumuladaatual /(wvaloraquisicaooriginal / wtotalmesesdepreciacao)) - wverificamesinteiro);
    END

  --#alt:19501 - N?o deve considerar um m?s a mais na deprecia??o di?ria. E verifico o par?metro, pois a vari?vel sofre altera??o. Ana - 23/10/2017
  IF (prdepdia = 'FALSE') THEN
    BEGIN
      IF ((wdepmensal = 'TRUE') AND (wvaldepacumubem <> 0) AND (wdiasdepdiaria > 0)) THEN
    wmesesdepreciados = wmesesdepreciados + 1;
  ELSE
  --#alt:19501. Apenas somando este m?s altera bastante os c?culos da deprecia??o. Para somar este m?s s? em situa??es bem espec?ficas. Ana - 18/10/2017
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (((CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >
           CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER))) OR
     ((CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) =
       CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER)) AND
          ((wvaldepacumubem <> 0) OR (wdepmensal = 'TRUE'))) ) THEN
    wmesesdepreciados = wmesesdepreciados + 1;
    END

  --alt:14761 - 16/06/2016 - Retirada valida??o do wvaldepacumubem, sen?o no m?s inicial sem deprecia??o nele e com valor depreciado anteriormente cadastrado, estava retornando um m?s a mais como depreciado. Pedro
  --alt:14624 - 06/06/2016 - Precisa verificar tamb?m se o campo "wvaldepacumubem" est? nulo; estava incorreta a condi??o da data > ou = (o m?s retorna sem o zero, ex: 20158, assim n?o atendia a condi??o). Pedro
  --alt:13784 - 12/04/2016 - S? deve descontar um m?s se a data inicial for de m?s igual ou posterior a data de aquisi??o, n?o levando em considera??o apenas se h? valor j? depreciado. Pedro
  --IF ((wdepmensal = 'FALSE') OR (wvaldepacumubem > 0)) THEN
  --if ((wdepmensal = 'FALSE') AND (wvaldepacumubem = 0) and
  --   (CAST(EXTRACT(YEAR FROM :prdatainicial) || EXTRACT(MONTH FROM :prdatainicial) AS INTEGER) >= CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
  --if ((wdepmensal = 'FALSE') and (coalesce(wvaldepacumubem, 0) = 0) and
  IF ((wdepmensal = 'FALSE') AND
     ((EXTRACT(YEAR FROM :prdatainicial) > EXTRACT(YEAR FROM wdataorigaquisicao)) OR
      ((EXTRACT(YEAR FROM :prdatainicial) = EXTRACT(YEAR FROM wdataorigaquisicao)) AND (EXTRACT(MONTH FROM :prdatainicial) >= EXTRACT(MONTH FROM wdataorigaquisicao))))) THEN
    wmesesdepreciados = wmesesdepreciados - 1;

  --alt:13784 - 12/04/2016 - Se j? tiver depreciado meses com outra taxa, deve somar esse per?odo. Pedro
  IF (prmesesdepreciadosoutrataxa > 0) THEN
    wmesesdepreciados = wmesesdepreciados + prmesesdepreciadosoutrataxa;

  -- Adiciona no total de meses depreciados o valor j? depreciado de outro sistema
  IF ((wvaldepacumubem > 0) AND (wmesesdepreciados >=0)) THEN
     --#alt:18200 - Alterado para pegar o valor original da aquisi??o e n?o o valor ja corrigido. Ana - 03/05/2017
     --wmesesdepreciados = wmesesdepreciados + (wvaldepacumubem / (wvaloraquisicao / wtotalmesesdepreciacao));
     wmesesdepreciados = wmesesdepreciados + (wvaldepacumubem / (wvaloraquisicaooriginal / wtotalmesesdepreciacao));

  --#alt:19501 - Antes os c?lculos da deprecia??o do per?odo estavam incorretos quando o bem possuia baixa parcial, ent?o o total de meses depreciados sempre foi suficiente. Por?m, com
  --             estas altera??es, a quantidade de meses depreciados pode ser com um m?s a mais para fazer o c?lculo de compensa??o de baixa do per?odo anterior corretamente. Ana - 19/10/2017
  IF (((wmesesdepreciados > (wtotalmesesdepreciacao + 1)) AND (wdepmesbaixa = 'FALSE')) OR
      ((wmesesdepreciados > (wtotalmesesdepreciacao))     AND (wdepmesbaixa = 'TRUE')) ) THEN
     wmesesdepreciados = wtotalmesesdepreciacao;

  --#alt:19501 - Quando o bem possui deprecia??o no m?s da aquisi??o e deprecia??o di?ria, e for no m?s da aquisi??o, n?o vai considerar a deprecia??o deste m?s da aquisi??o.
  --             Essa deprecia??o ocorrer? no final do per?odo. Ana - 23/10/2017
  -- Se os meses decreciados for menor que zero, significa que foi informado uma data inferior a data de aquisicao do bem
  /*IF (wmesesdepreciados <= 0) THEN
    BEGIN
      SUSPEND;
      EXIT;
    END*/

  --#alt:19501 - Adicionada a atribui??o aqui, pois preciso dela para controle da vari?vel wdepdiafinal. Ana - 17/10/2017
  -- Meses ? depreciar
  wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);

  -- Total de meses da diferen?a do periodo de deprecia??o
  wmes = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultimodiadomes;
  -- C?lculo que retorna o ?ltimo dia do m?s
  wultimodiadomes = EXTRACT(DAY FROM (wdatatotalmesesdepdia - EXTRACT(DAY FROM wdatatotalmesesdepdia) +
                                      32 - EXTRACT(DAY FROM wdatatotalmesesdepdia - EXTRACT(DAY FROM wdatatotalmesesdepdia) + 32)));
  wdatatotalmesesultimodia = wmes||'-'||wultimodiadomes||'-'||wano;
  IF ((:prdatafinal > wdatatotalmesesultimodia) AND (wdepdia = 'TRUE')) THEN
    BEGIN
      -- Caso seja o ?ltimo m?s para depreciar
      IF (wmesesdepreciar = 0) THEN
        wdepdiafinal = 'TRUE';

      wdatatotalmesesultimodia = addmonth(wdatatotalmesesultimodia, 1);
      wdatatotalmesesultimodia = SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                                 SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
    END
  ELSE
    BEGIN
      --alt:8005 - Foi adicionada excess?o "else" e esta valida??o porque se tiver terminado a quantidade de dias a depreciar deve calcular o final da deprecia??o (os restos). Pedro
      IF (wmesesdepreciar = 0) THEN
        wdepdiafinal = 'TRUE';
    END

  IF (:prdatafinal > wdatatotalmeses) THEN
     prdatafinal = wdatatotalmeses;

  IF (:prdatainicial < :wdataoficialiniciolcalculo) THEN
      prdatainicial = wdataoficialiniciolcalculo;

  wtotalmesesdoperiodo = DATEDIFF(MONTH,:prdatainicial,:prdatafinal);
  IF (wtotalmesesdoperiodo < 0) THEN
    wtotalmesesdoperiodo = 0;
  -- A rotina "datediff" n?o conta se as duas data est?o no mesmo m?s, por isso verifico se a refer?ncia da data atual
  -- ? a mesma da data de aquisi??o para somar 1
  IF (CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
      CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER)) THEN
    wtotalmesesdoperiodo = wtotalmesesdoperiodo + 1;

  --#alt:18204 - Quando a data for igual a data origem de aquisi??o ent?o n?o deve ser calculado. Ana - 28/04/2017
  IF ((wvaldepacumubem > 0) AND (prdatainicial </*=*/ wdataorigaquisicao)) THEN
    wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;

  --#alt:6151. - Carlos Mello(08/11/2013)
  IF (((wtotalmesesdoperiodo > 0) AND
       ((CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) >
         CAST((SUBSTRING(wdatatotalmeses FROM 1 FOR 4)) || (SUBSTRING(wdatatotalmeses FROM 6 FOR 2)) AS INTEGER)) OR
        ((wdepmensal = 'TRUE') AND
         (CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
          CAST((SUBSTRING(wdatatotalmeses FROM 1 FOR 4)) || (SUBSTRING(wdatatotalmeses FROM 6 FOR 2)) AS INTEGER))))) OR
      (wtotalmesesdoperiodo < 0) ) THEN
    wtotalmesesdoperiodo = 0;

  --#alt:19501 - Movi essa atribui??o para cima, pois h? verifica??es com esta vari?vel. Ana - 17/10/2017
  -- Meses ? depreciar
  --wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);
  wvaloraquisicaomoeda = wvaloraquisicao / prvlrmoeda;
  -- Deprecia??o do per?odo
  --wvalordepreciacaomensal = (wvaloraquisicaomoeda / wtotalmesesdepreciacao); --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro

  --#alt:85169. O valor da aquisi??o deve ser o original para calcular a deprecia??o correta e n?o influenciar nos outro valores. Ana- 20/06/2018
  --wvalordepreciacaomensal = (wvaloraquisicao / wtotalmesesdepreciacao);
  IF (prtipo = 2) THEN
    wvalordepreciacaomensal = (wvaloraquisicaoaux / wtotalmesesdepreciacao);
  ELSE
    wvalordepreciacaomensal = (wvaloraquisicao / wtotalmesesdepreciacao);

  --#alt:19501 - Quando tenho deprecia??o acumulada anterior cadastrada devo considerar os meses pertinentes a essa deprecia??o, independente da deprecia??o di?ria. Ana - 17/10/2017
  IF ((wdepdia = 'TRUE') /*AND ((wvaldepacumubem = 0) AND (wvaldepacumubem = wdepreciacaoacumuladaatual))*/) THEN
    BEGIN
      -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
      wmesesdepreciar      = wmesesdepreciar + 1;
      wmesesdepreciados    = wmesesdepreciados - 1;
      wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;
    END

  --alt:15196 - 09/11/2016 - Se depreciou no m?s da aquisi??o, ir? terminar a deprecia??o um m?s antes. Pedro
  IF (wdepmensal = 'TRUE') THEN
    wdatatotalmeses = AddMonth(wdatatotalmeses, -1);

  IF (wdepdiasadepreciar > 0) THEN
    BEGIN
      --#alt:5105. - Carlos Mello(27/11/2013)
      IF (wnumdias = 2) THEN
        BEGIN
          -- C?lculo que retorna o ?ltimo dia do m?s
          --alt:13156 - 17/02/2016 - Alterado para depreciar por dia tamb?m na data da baixa, caso esteja marcado o par?metro. Pedro
          IF (wdatabaixa BETWEEN prdatainicial AND prdatafinal) THEN
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) +
                                                32 - EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32)));
          ELSE
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatainiciocalc - EXTRACT(DAY FROM wdatainiciocalc) +
                                                32 - EXTRACT(DAY FROM wdatainiciocalc - EXTRACT(DAY FROM wdatainiciocalc) + 32)));

          --alt:13156 - Fim
          --alt:16006 - 03/11/2016 - Alterado para dividir o valor da daprecia??o antes e depois da baixa, no caso da baixa parcial. Pedro
          --wvalordepreciacaodiaria  = (wvalordepreciacaomensal * prvlrmoeda) / wultimodiadomes * wdepdiasadepreciar;
          wvalordepreciacaodiaria = (prvaloraquisicaooriginal / wtotalmesesdepreciacao) / wultimodiadomes * wdepdiasadepreciar;
          wvalordepreciacaodiariabaixa = (wvalordepreciacaomensal / wultimodiadomes) * (wultimodiadomes - wdepdiasadepreciar);
          wDia = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32 -
                                   EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32))) - EXTRACT(DAY FROM wdatainiciocalc);
          prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados -1 + (CAST(wdepdiasadepreciar + wDia AS FLOAT) / wUltimoDiaDoMes));
        END
      ELSE
        BEGIN
          --alt:16006 - 03/11/2016 - Alterado para dividir o valor da daprecia??o antes e depois da baixa, no caso da baixa parcial. Pedro
          --wvalordepreciacaodiaria  = (wvalordepreciacaomensal * prvlrmoeda) / 30 * wdepdiasadepreciar;
          wvalordepreciacaodiaria = (prvaloraquisicaooriginal / wtotalmesesdepreciacao) / 30 * wdepdiasadepreciar;
          wvalordepreciacaodiariabaixa = (wvalordepreciacaomensal / 30) * (30 - wdepdiasadepreciar);
          wDia = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32 -
                                   EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32))) - EXTRACT(DAY FROM wdatainiciocalc);
          prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados -1 + (CAST(wdepdiasadepreciar + wDia AS FLOAT) / 30));
        END
      --alt:16006 - Fim

      --alt:15196 - 09/11/2016 - Esta nova vari?vel calcula corretamente o valor a ser compensado no final da deprecia??o. Pedro
      --prvalordepreciacaodiariafim = (wvalordepreciacaomensal * prvlrmoeda) - wvalordepreciacaodiaria;
      prvalordepreciacaodiariafim = wvalordepreciacaodiariabaixa;
    END
  ELSE
    --#alt:19501 - Adicionei o valor pertinente a deprecia??o di?ria no m?s da aquisi??o. Ana - 24/10/2017
    --alt:15196 - 09/11/2016 - Calcula o valor a ser compensado ap?s a baixa para bens SEM deprecia??o di?ria. Pedro
    prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * ((wmesesdepreciados + wdiasdepdiaria) - IIF(wdepmesbaixa = 'TRUE', 0, 1));

  --#alt:18200 - Adicionei a verifica??o da diferen?a de meses da baixa para a aquisi??o do bem, pois n?o estava fazendo a deprecia??o di?ria corretamente
  --             quando havia uma baixa no mesmo m?s da aquisi??o do bem. Ana - 03/05/2017
  --alt:16006 - 03/11/2016 - Separado o c?lculo para per?odo com baixa do per?odo depreciado em outro sistema,
  --pois precisa utilizar o valor da deprecia??o acumulada do c?lculo m?s a m?s, caso contr?rio, caso o primeiro
  --m?s tenha sido depreciado diariamente, estava desconsiderando este valor para os meses seguintes. Pedro
  --alt:13156 - 17/02/2016 - Na baixa tamb?m deve descontar o valor proporcional ao n?mero de dias, se o par?metro estiver marcado. Pedro
  IF ((wdatabaixa BETWEEN prdatainicial AND prdatafinal)  AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0))THEN
    BEGIN
      wdepreciacaoperiodo = (wvalordepreciacaodiaria + wvalordepreciacaodiariabaixa) + (wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  --#alt:19501 - Quando for deprecia??o di?ria e tiver valor de deprecia??o acumulada anterior informada, deve ignorar qualquer c?lculo feito anteriormente. Ana - 17/10/2017
  ELSE IF ((wdatainicialoficial <= :wdataaquisicao) AND
          (((wdepdia = 'TRUE') AND (wvaldepacumubem = 0) OR ((wdepdia = 'FALSE') AND (wvaldepacumubem <> 0))) AND
          (wvaldepacumubem = wdepreciacaoacumuladaatual))) THEN
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo) / prvlrmoeda;
      wdepreciacaoperiodo      = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  ELSE
  IF (wdepdia = 'TRUE') THEN
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo +1) * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * (wtotalmesesdoperiodo+1));
      wdepreciacaoperiodo      = wvalordepreciacaomensal * (wtotalmesesdoperiodo +1);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  ELSE
    BEGIN
      --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
      --wdepreciacaoperiodo      = (wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
      --wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodo      = wvalordepreciacaomensal * wtotalmesesdoperiodo;
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END

  --#alt:19501 - Quando ? informado um valor de deprecia??o acumulada anterior, deve ignorar o qualquer calculo feito anteriormente(deprecia??o diaria) e permanecer com o valor informado. Ana - 17/10/2017
  IF ((prvaloracumuladoanterior = 0) AND (wvaldepacumubem <> 0) AND (wvaldepacumubem = wdepreciacaoacumuladaatual)) THEN
    BEGIN
      wdepreciacaoacumuladaatual    = (wdepreciacaoperiodo + wdepreciacaoacumuladaatual);
      wdepreciacaoacumuladaanterior = (wvaldepacumubem);
    END
  ELSE
   IF ((wvalordepreciacaodiaria > 0) AND (wdatainicialoficial <= :wdataaquisicao))  THEN
     BEGIN
       --alt:16006 - 03/11/2016 - Utiliza o valor da deprecia??o acumulado na vari?vel. Pedro
       --wdepreciacaoacumuladaatual    = (wvalordepreciacaomensal * wmesesdepreciados);
       wdepreciacaoacumuladaatual    = (wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * prvlrmoeda);
       wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
     END
   ELSE
     BEGIN
       --alt:16006 - 03/11/2016 - Utiliza o valor da deprecia??o acumulado na vari?vel. Pedro
       --wdepreciacaoacumuladaatual = (wvalordepreciacaomensal * wmesesdepreciados);
       --wdepreciacaoacumuladaatual = (wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * prvlrmoeda);
       wdepreciacaoacumuladaatual = wdepreciacaoperiodo + wdepreciacaoacumuladaatual;
      
       IF (wvalordepreciacaodiaria > 0) THEN
         wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
       ELSE
         BEGIN
          --#alt:19501 - Na deprecia??o di?ria devo considerar um m?s a mais no total de meses do per?odo. Ana - 25/10/2017 
           --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
           --alt:9013 - Dividido em duas partes porque calculando tudo de uma s? vez estava ocorrendo um over flow. Pedro
           --wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda;
          IF (wdepdia = 'TRUE') THEN
            wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * (wtotalmesesdoperiodo +1);
          ELSE
           wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * wtotalmesesdoperiodo;
           wdepreciacaoacumuladaanterior = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;
           --wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual -  (wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda));
           --alt:9013 - Fim
         END
     END

  --#alt:18200 - N?o precisa fazer esta verifica??o, pois o valor corrigido anterior sempre deve ser em rela??o ao valor da aquisi??o. Ana - 02/05/2017
  --IF (wdepreciacaoacumuladaanterior > 0) THEN
  wvalorcorrigidoanterior = wvaloraquisicao;

  IF (wdepreciacaoacumuladaanterior < 0) THEN
    wdepreciacaoacumuladaanterior = 0;

  --#alt:18200 - S? vai considerar a compensa??o da baixa do per?odo anterior se tiver deprecia??o acumulada anterior ou se o m?s da baixa n?o for o mesmo da aquisi??o.
  --             Deve ser o valor da aquisi??o original pois o valor da aquisi??o ? diminuido conforme os valores das baixas. Ana - 04/05/2017
  --alt:16006 - 03/11/2016 - Caso esteja deprecia??o diariamente e seja um m?s com baixa, deduz o valor dos meses anteriores que foram depreciados calculando valor inteiro do bem (sem baixa). Pedro
  --IF ((wvalorbaixaper > 0) AND (wvalorbaixa < wvaloraquisicao)) THEN
  IF ((wvalorbaixaper > 0) AND (wvalorbaixa < wvaloraquisicaooriginal) AND ((wdepreciacaoacumuladaanterior <> 0) OR (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0))) THEN
    wdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual - prcompensacaobaixaperanterior;
  ELSE IF (wvalorbaixa = wvaloraquisicao) THEN
    prcompensacaobaixaperanterior = wdepreciacaoacumuladaatual;

  --alt:15196 - 09/11/2016 - Agora o valor da deprecia??o mensal vem sem a moeda, ent?o precisa converter. Pedro
  --wdepreciacaoacumuladaatualmoed = ((wvalordepreciacaodiaria / prvlrmoeda) + wvalordepreciacaomensal * wmesesdepreciados);
  wdepreciacaoacumuladaatualmoed = (wvalordepreciacaodiaria + (wvalordepreciacaomensal * wmesesdepreciados)) / prvlrmoeda;
  wdepreciacaobaixamoeda         = (wvalorbaixa / wtotalmesesdepreciacao);
  wdepreciacaobaixamoeda         = (wdepreciacaobaixamoeda / prvlrmoeda);

  IF (prtipo = 2) THEN
    BEGIN
      prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
      prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior / prvlrmoeda);
    END
  ELSE
    BEGIN
      --#alt:18200 - N?o estava calculando certo. Atribuia o valor da aquisi??o menos todas as baixas e somava todas as baixas aqui novamente, mas s? deve somar as baixas que ja foram efetuadas. Ana - 02/05/2017
      /*prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + wvalorbaixa);
      prvalorcorrigidoanteriormoeda = ((wvalorcorrigidoanterior + wvalorbaixa) / prvlrmoeda);  */
      prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + (wvalorbaixaper));
      prvalorcorrigidoanteriormoeda = ((wvalorcorrigidoanterior + (wvalorbaixaper)) / prvlrmoeda);

      --#alt:19501 - Quando ? deprecia??o no mes da baixa, n?o deve considerar os valores de baixa no per?odo para c?lculo do valor corrigido anterior(Estes valores ja est?o inclusos). Ana - 16/10/2017
      --#alt:18200 - Apenas se o valor for maior deve substituir. Ana - 02/05/2017
      IF ((prvalorcorrigidoanterior >/*=*/ prvaloraquisicaooriginal) OR (UPPER(wdepmesbaixa) = 'TRUE') ) THEN
        BEGIN
          prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
          prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior / prvlrmoeda);
        END
    END

  --#alt:19501 - O calculo deve ser em cima do valor corrigido atual e n?o do valor da aquisi??o, quando possuir valor. Ana - 16/10/2017
  IF (prvalorcorrigidoanterior > 0) THEN
    wvalorresidualcontabil         = (((prvalorcorrigidoanterior + prcorrecaoperiodo) - wvalorbaixaper) - wdepreciacaoacumuladaatual);
  ELSE
    wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
  wvalorresidualcontabilmoeda    = (wvalorresidualcontabil / prvlrmoeda);
  --#alt:19501. fim

  IF ((wdepdia = 'TRUE') AND (wdepdiafinal = 'TRUE')) THEN
    BEGIN
      --alt:8005 - Alterado para n?o entrar aqui caso as datas sejam iguais, pois se entrar aqui ele mata a deprecia??o di?ria. Pedro
      --if (wdatainicialoficial <= :wdataaquisicao) then
      IF (wdatainicialoficial < :wdataaquisicao) THEN
        BEGIN
          --alt:15196 - 09/11/2016 - Aqui deveria estar utilizando a vari?vel normal, n?o a com valor moeda. Pedro
          --wdepreciacaoperiodo            = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo * prvlrmoeda);
          --wdepreciacaoperiodomoeda       = (((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) / prvlrmoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
          wdepreciacaoperiodo            = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
          wdepreciacaoperiodomoeda       = wdepreciacaoperiodo / prvlrmoeda;
          wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim);
          wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual / prvlrmoeda);
          wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          wvalorresidualcontabilmoeda    = 0;
          wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
        END
      ELSE
        --#alt:19501 - Se o bem ja foi totalmente depreciado, n?o deve mais executar esta parte. Estava retornando a deprecia??o errada. Ana - 25/10/2017
       IF ((CAST(wvalorcorrigidoanterior AS NUMERIC(15,0)) <> CAST(wdepreciacaoacumuladaatual AS NUMERIC(15,0))) AND
            (CAST(wvalorcorrigidoanterior AS NUMERIC(15,1)) <> CAST(wdepreciacaoacumuladaatual AS NUMERIC(15,1))) OR
           ((wmesesdepreciados + 1) < wtotalmesesdepreciacao)) THEN
        BEGIN
          wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);
          wmes                     = CAST(SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano                     = CAST(SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          wdatatotalmesesultimodia = wmes||'-01-'||wano;

          --alt:14256 - 14/07/2016 - Alterada valida??o, n?o estava trazendo o valor da deprecia??o di?ria nos meses subsequentes ao t?rmino da deprecia??o. Pedro
          --alt:9013 - Retirado pois estava trazendo depreciacao anterior a mais do que devia quando usava deprecia??o di?ria. Pedro
          --IF (wdatatotalmesesultimodia BETWEEN PRDATAINICIAL AND PRDATAFINAL) THEN
          IF (wdatatotalmesesultimodia <= prdatainicial) THEN
             wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim);

          wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual / prvlrmoeda);

          wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          --#alt:16852 - Comentado pois n?o h? necessidade de zerar e estava fazendo com que o valor fosse errado. Ana - 10/02/2017
          --wvalorresidualcontabilmoeda = 0;

          IF (wdatainicialoficial <> :wdatatotalmesesultimodia) THEN
            BEGIN
              wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
              wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaanterior / prvlrmoeda);
            END

          wdepreciacaoperiodo = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;

          IF (wdepreciacaoperiodo <= 0) THEN
            wdepreciacaoperiodomoeda = 0;
          ELSE
            wdepreciacaoperiodomoeda = ((wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior) / prvlrmoeda);
        END

      --alt:9013 - Retirado pois sempre trazia um m?s a mais de deprecia??o quando ? di?ria. Pedro
      /*wmesesdepreciados = wmesesdepreciados + 1;
      wmesesdepreciar   = 0;*/
    END

  --#alt:18200 - Alterada forma de c?lculo do valor corrigido atual (valor corrigido anterior + corre??o do per?odo - valor de baixas do per?odo). Ana - 02/05/2017
  --prvalorcorrigidoatual = (prvalorcorrigidoanterior + prcorrecaoperiodo - wvalorbaixaper);

  --alt:15196 - 24/11/2016 - Adapta??o para zerar o valor residual da deprecia??o. Pedro
  IF ((wdepreciacaoacumuladaanterior + wdepreciacaoperiodo) > wvaloraquisicao) THEN
    BEGIN
      IF (wdepreciacaoacumuladaanterior < wvaloraquisicao) THEN
        BEGIN
          wdepreciacaoperiodo = wvaloraquisicao - wdepreciacaoacumuladaanterior;
          wdepreciacaoacumuladaatual = wdepreciacaoacumuladaanterior + wdepreciacaoperiodo;
        END

      wdepreciacaoperiodomoeda = wdepreciacaoperiodo * prvlrmoeda;
      wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual * prvlrmoeda;
    END

  IF ((wdepdia = 'TRUE')) THEN
    BEGIN
      -- Quer dizer que ? o primeiro m?s e esse m?s n?o vai contar j? que e parcial, o restante estara no ?ltimo m?s a depreciar
      wmesesdepreciar      = wmesesdepreciar - 1;
      wmesesdepreciados    = wmesesdepreciados + 1;
      wtotalmesesdoperiodo = wtotalmesesdoperiodo +1;
    END

  prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;
  prdepreciacaoperiodo            = wdepreciacaoperiodo;
  prdepreciacaoperiodomoeda       = wdepreciacaoperiodomoeda;
  prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
  prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
  prcorrecaomonetariadepreciacao  = 0;
  prvalorresidualcontabil         = wvalorresidualcontabil;
  prvalorresidualcontabilmoeda    = wvalorresidualcontabilmoeda;
  prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
  prmesesdepreciados              = wmesesdepreciados;
  prmesesdepreciar                = wmesesdepreciar;
  prdatataxadepreciacao           = wdataultimoitemdep;
  --#Alt:5105
  --prvalorbaixa                    = wvalorbaixa;
  prvalorbaixa                    = wvalorbaixaper;
  prdepreciacaobaixamoeda         = wdepreciacaobaixamoeda;
  prvalorbaixareal                = wvalorbaixa;
  prvalormoeda                    = prvlrmoeda;
  prdatabaixa                     = wdatabaixa;
  prvaloraquisicaomoeda           = wvaloraquisicaomoeda;

  SUSPEND;
END
^

/* Alter (SP_CONS_CALC_INTERMITENTE) */
ALTER PROCEDURE SP_CONS_CALC_INTERMITENTE(PRCODEMP INTEGER = null,
PRCODCOL INTEGER = null,
PRCODCONTRATO INTEGER = null,
PRDATAINICIAL DATE = null,
PRDATAFINAL DATE = null)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRGCOL VARCHAR(13),
BDCODCONTTI INTEGER,
BDDESCCONTRATOTI VARCHAR(2000),
BDDATACONVTI DATE,
BDHORACONVTI TIME,
BDDATAINISERVTI DATE,
BDDATAFIMSERVTI DATE,
BDDATAPAGTI DATE,
BDLIQUIDO NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDDATAPGTOFN DATE,
BDFGTSFN NUMERIC(18,6),
BDFGTS13FN NUMERIC(18,6),
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(18,6),
BDREFAUXVFN NUMERIC(18,6),
BDVALVFN NUMERIC(18,6),
BDVALIFN NUMERIC(18,6),
BDDESCVER VARCHAR(40),
BDTIPOCODVER INTEGER,
BDORDEMVER INTEGER)
 AS
declare variable WSQL varchar(10000);
declare variable WWHERE varchar(500);
declare variable WSQL2 varchar(5000);
declare variable WWHERE2 varchar(500);
begin
    --<Local aonde deve ser zerado as vari?veis>--
    wSQL   = ' ';
    wWhere = ' ';

    /**************************************************************************/
    /*                      In?cio da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL = wSQL ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL = wSQL ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    --<Contrato>--
    wSQL = wSQL ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAPAGTI,'           || ASCII_CHAR(13);
    --<C?lculo>--
    wSQL = wSQL ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDATAPGTOFN,'                  || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFVFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALIFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDTIPOCODVER,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDORDEMVER'                    || ASCII_CHAR(13);
    wSQL = wSQL ||' FROM (SELECT'                             || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDCODCONTTI,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDLIQUIDO,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDBINSSFN,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDDATAPGTOFN,'       || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTSFN,'           || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTS13FN,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODEMP,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODCOL,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODVER,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDDESCVER,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDORDEMVER,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_DESCVERB.BDTIPOCODVER,'     || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFFN,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFVFN,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFAUXVFN,'    || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALVFN,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALIFN'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       FROM VRHF_EMP_TFOLHAINT XF_CALCULO' || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VRHF_EMP_TVERBAINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP    = XLF_VERBASCALC.BDCODEMP AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCOL    = XLF_VERBASCALC.BDCODCOL AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCONTTI = XLF_VERBASCALC.BDCODCONTTI AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDREFFN     = XLF_VERBASCALC.BDREFFN)'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB      ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'         || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB  ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'        || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    if (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere = wWhere || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

            wWhere = wWhere || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END

    IF (wWhere <> '') THEN
        BEGIN
            wWhere = ' WHERE ' || ASCII_CHAR(13) || wWhere;
        END

    wSQL = wSQL || wWhere || ASCII_CHAR(13);

    wSQL = wSQL || ') F_CALC ' || ASCII_CHAR(13);
    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL = wSQL ||'           JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP)'           || ASCII_CHAR(13);
    wSQL = wSQL ||'           JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP)'               || ASCII_CHAR(13);
    wSQL = wSQL ||'           JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP     AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL     AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI)'    || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          J_CONTRATO_INT.BDCODCOL = LF_REFCOL.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL          AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLCAD.BDREFCOL)'            || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL         AND'|| ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLDOC2.BDREFCOL)'           || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wWhere = ' ';
    if ((prDataInicial is not null) AND ( prDataFinal is not null)) THEN
        BEGIN
            wWhere = wWhere || 'J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN' || prDataInicial || ' AND ' || prDataFinal;
        END



    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/

    --<Local aonde deve ser zerado as vari?veis>--
    wSQL2   = ' ';
    wWhere2 = ' ';

    /**************************************************************************/
    /*                      In?cio da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL2 = wSQL2 ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL2 = wSQL2 ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    --<Contrato>--
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAPAGTI,'           || ASCII_CHAR(13);
    --<C?lculo>--
    wSQL2 = wSQL2 ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDATAPGTOFN,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFVFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALIFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDTIPOCODVER,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDORDEMVER'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||' FROM (SELECT'                                             || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'        XF_CALCULO.BDCODCONTTI,'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'SUM(XF_CALCULO.BDLIQUIDO) AS BDLIQUIDO,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDBINSSFT) AS BDBINSSFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPGTOFT AS BDDATAPGTOFN,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTSFT) AS BDFGTSFN,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTS13FT) AS BDFGTS13FN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'                         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'                        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR AS BDREFFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDREFVFT) AS BDREFVFN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFAUXVFT AS BDREFAUXVFN,'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALVFT) AS BDVALVFN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALIFT) AS BDVALIFN'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       FROM VRHF_EMP_TFOLHATOMINT XF_CALCULO'              || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VRHF_EMP_TVERBATOMINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP     = XLF_VERBASCALC.BDCODEMP AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCOL     = XLF_VERBASCALC.BDCODCOL AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCONTTI  = XLF_VERBASCALC.BDCODCONTTI AND'  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDREFTOMADOR = XLF_VERBASCALC.BDREFTOMADOR AND' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDORDEM      = XLF_VERBASCALC.BDORDEM)'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB         ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB     ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'          || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    if (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

             wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END

    IF (wWhere2 <> '') THEN
        BEGIN
            wWhere2 = ' WHERE ' || ASCII_CHAR(13) || wWhere2;
        END

    wSQL2 = wSQL2 || wWhere2 || ASCII_CHAR(13);

    wSQL2 = wSQL2 ||'       GROUP BY'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDCODCONTTI,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPGTOFT,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR,'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFAUXVFT'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||') F_CALC'                                   || ASCII_CHAR(13);

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL2 = wSQL2 ||'           JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP)'               || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI)'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          J_CONTRATO_INT.BDCODCOL = LF_REFCOL.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLCAD.BDREFCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          LF_REFCOL.BDREFCOL      = LF_COLDOC2.BDREFCOL)'           || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wWhere2 = ' ';
    if ((prDataInicial is not null) AND ( prDataFinal is not null)) THEN
        BEGIN
            wWhere2 = wWhere2 || 'J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN' || prDataInicial || ' AND ' || prDataFinal;
        END



    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/
    
    wSQL = wSQL    || ASCII_CHAR(13) ||
           'UNION' || ASCII_CHAR(13) ||
           wSQL2;

    /*Seta a compet?ncia para o banco*/
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(201806);

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDNOMEMP,
        :BDCNPJEMP,
        :BDLOGREMP,
        :BDENDEMP,
        :BDNUMEMP,
        :BDCODCID,
        :BDNOMCID,
        :BDNOMCOL,
        :BDCPFCOL,
        :BDPISCOL,
        :BDRGCOL,
        :BDCODCONTTI,
        :BDDESCCONTRATOTI,
        :BDDATACONVTI,
        :BDHORACONVTI,
        :BDDATAINISERVTI,
        :BDDATAFIMSERVTI,
        :BDDATAPAGTI,
        :BDLIQUIDO,
        :BDBINSSFN,
        :BDDATAPGTOFN,
        :BDFGTSFN,
        :BDFGTS13FN,
        :BDCODCOL,
        :BDCODVER,
        :BDREFFN,
        :BDREFVFN,
        :BDREFAUXVFN,
        :BDVALVFN,
        :BDVALIFN,
        :BDDESCVER,
        :BDTIPOCODVER,
        :BDORDEMVER
    DO
        SUSPEND;
end
^

/* Alter (SP_CONS_FERIAS_PER_AQUIS_ESCALA) */
ALTER PROCEDURE SP_CONS_FERIAS_PER_AQUIS_ESCALA(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PRPRIDIA DATE,
PRULTDIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDABONOFE NUMERIC(18,6),
BDQTDGOZOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDNOMEMP VARCHAR(100),
BDNOMCOL VARCHAR(70),
BDSALDOFINALSINDFE NUMERIC(18,6),
BDFERIADOSFE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WEMPRESA INTEGER;
DECLARE VARIABLE WCOLABORADOR INTEGER;
DECLARE VARIABLE WPERAQUIS DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WINIPERAQUISFE DATE;
DECLARE VARIABLE WCODFE INTEGER;
DECLARE VARIABLE WINIPERGOZOFE DATE;
DECLARE VARIABLE WFIMPERAQUISFE DATE;
DECLARE VARIABLE WFIMPERGOZOFE DATE;
DECLARE VARIABLE WDATAPAGFE DATE;
DECLARE VARIABLE WQTDGOZOFE NUMERIC(18,6);
DECLARE VARIABLE WQTDABONOFE NUMERIC(18,6);
DECLARE VARIABLE WSALDOINIFE NUMERIC(15,6);
DECLARE VARIABLE WSALDOFIMFE NUMERIC(15,6);
DECLARE VARIABLE WBASEIRFE NUMERIC(15,6);
DECLARE VARIABLE WALIQIRFE NUMERIC(15,6);
DECLARE VARIABLE WVALORIRFE NUMERIC(15,6);
DECLARE VARIABLE WBASEINSSFE NUMERIC(15,6);
DECLARE VARIABLE WALIQINSSFE NUMERIC(15,6);
DECLARE VARIABLE WVALORINSSFE NUMERIC(15,6);
DECLARE VARIABLE WDEPFE NUMERIC(15,6);
DECLARE VARIABLE WSALBASEFE NUMERIC(15,6);
DECLARE VARIABLE WSALBASEHEFE NUMERIC(15,6);
DECLARE VARIABLE WDATABAIXAFE DATE;
DECLARE VARIABLE WCOLETIVASFE VARCHAR(5);
DECLARE VARIABLE WREFPAGABOFE INTEGER;
DECLARE VARIABLE WFALTASFE NUMERIC(15,6);
DECLARE VARIABLE WNOMEMP DM_BDNOMEMP;
DECLARE VARIABLE WNOMCOL DM_BDNOMCOL;
DECLARE VARIABLE WSALDOFINALSINDFE NUMERIC(18,6);
DECLARE VARIABLE WFERIADOSFE INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref,  NULL, NULL);

  wsql = 'select FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE, FER.BDINIPERGOZOFE, FER.BDFIMPERAQUISFE, '||
                'FER.BDFIMPERGOZOFE, FER.BDDATAPAGFE, FER.BDQTDGOZOFE, FER.BDQTDABONOFE, FER.BDSALDOINIFE, '||
                'FER.BDSALDOFIMFE, FER.BDBASEIRFE, FER.BDALIQIRFE, FER.BDVALORIRFE, FER.BDBASEINSSFE, FER.BDALIQINSSFE, '||
                'FER.BDVALORINSSFE, FER.BDDEPFE, FER.BDSALBASEFE, FER.BDSALBASEHEFE, FER.BDDATABAIXAFE, FER.BDCOLETIVASFE, '||
                'FER.BDREFPAGABOFE, FER.BDFALTASFE, EMP.BDNOMEMP, COLCAD.BDNOMCOL, FER.BDSALDOFINALSINDFE, FER.BDFERIADOSFE ';

  wsql = wsql || 'from VRH_EMP_TFERIAS FER '||
                 'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
                    'on (EMP.BDCODEMP = FER.BDCODEMP) '||
                 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD '||
                    'on (COLCAD.BDCODEMP = FER.BDCODEMP and COLCAD.BDCODCOL = FER.BDCODCOL) ';

  wwhere = 'coalesce(coalesce(fer.BDDATAPAGFE,fer.BDINIPERGOZOFE),'||
           'cast(case when ((fer.bdrefpagabofe is null) or (fer.bdrefpagabofe = 0)) '||
           'then null else substring(cast(fer.bdrefpagabofe as varchar(6)) from 5 for 2)||'||
           ''''||'/01/'||''''||
           '||substring(cast(fer.bdrefpagabofe as varchar(6)) from 1 for 4) end as date))';

  wwhere = ' where '||wwhere||' <= '''||prultdia||''' ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wwhere;

  wsql = wsql||' order by FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE';

  wEmpresa = 0;
  wColaborador = 0;
  FOR EXECUTE STATEMENT wsql
  INTO :WCODEMP, :WCODCOL, :WINIPERAQUISFE, :WCODFE, :WINIPERGOZOFE, :WFIMPERAQUISFE,
       :WFIMPERGOZOFE, :WDATAPAGFE, :WQTDGOZOFE, :WQTDABONOFE, :WSALDOINIFE,
       :WSALDOFIMFE, :WBASEIRFE, :WALIQIRFE, :WVALORIRFE, :WBASEINSSFE, :WALIQINSSFE,
       :WVALORINSSFE, :WDEPFE, :WSALBASEFE, :WSALBASEHEFE, :WDATABAIXAFE, :WCOLETIVASFE,
       :WREFPAGABOFE, :WFALTASFE, :WNOMEMP, :WNOMCOL, :WSALDOFINALSINDFE, :WFERIADOSFE DO
    BEGIN

      IF ((wEmpresa <> WCODEMP) OR (wColaborador <> WCODCOL) OR (wPerAquis <> WINIPERAQUISFE)) THEN
        BEGIN
          IF (wEmpresa <> 0) THEN
            SUSPEND;

          wEmpresa = WCODEMP;
          wColaborador = WCODCOL;
          wPerAquis = WINIPERAQUISFE;
          BDQTDGOZOFE = 0;
          BDQTDABONOFE = 0;
          BDSALDOINIFE = 0;
        END

      BDCODEMP = WCODEMP;
      BDCODCOL = WCODCOL;
      BDINIPERAQUISFE = WINIPERAQUISFE;
      BDCODFE = WCODFE;
      BDINIPERGOZOFE = WINIPERGOZOFE;
      BDFIMPERAQUISFE = WFIMPERAQUISFE;
      BDFIMPERGOZOFE = WFIMPERGOZOFE;
      BDDATAPAGFE = NULL;     --WDATAPAGFE;
      BDQTDGOZOFE = COALESCE(BDQTDGOZOFE, 0) + COALESCE(WQTDGOZOFE, 0);
      BDQTDABONOFE = COALESCE(BDQTDABONOFE, 0) + COALESCE(WQTDABONOFE, 0);

      IF (WCODFE = 1) THEN
        BDSALDOINIFE = WSALDOINIFE;

      BDSALDOFIMFE = WSALDOFIMFE;
      BDBASEIRFE = WBASEIRFE;
      BDALIQIRFE = WALIQIRFE;
      BDVALORIRFE = WVALORIRFE;
      BDBASEINSSFE = WBASEINSSFE;
      BDALIQINSSFE = WALIQINSSFE;
      BDVALORINSSFE = WVALORINSSFE;
      BDDEPFE = WDEPFE;
      BDSALBASEFE = WSALBASEFE;
      BDSALBASEHEFE = WSALBASEHEFE;
      BDDATABAIXAFE = WDATABAIXAFE;
      BDCOLETIVASFE = WCOLETIVASFE;
      BDREFPAGABOFE = WREFPAGABOFE;
      BDFALTASFE = WFALTASFE;
      BDNOMEMP = WNOMEMP;
      BDNOMCOL = WNOMCOL;
      BDSALDOFINALSINDFE = wsaldofinalsindfe;
      BDFERIADOSFE = wferiadosfe;
    END

  SUSPEND;

END
^

/* Alter (SP_CONSULTA_COL_POR_REF) */
ALTER PROCEDURE SP_CONSULTA_COL_POR_REF(PREMP INTEGER,
PRCOL INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDREFCOL INTEGER)
 AS
BEGIN
   IF (prrefmicro IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);


       SELECT MAX(Y.BDREFCOL)
       FROM VRH_EMP_TCOLCON_REF Y
       WHERE Y.BDCODEMP = :premp AND
             Y.BDCODCOL = :prcol AND
             CAST(Y.BDREFCOL AS VARCHAR(6)) <=
                (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                 FROM rdb$database
                )
       GROUP BY Y.BDCODEMP, Y.bdcodcol

  INTO
    :BDREFCOL;


  IF ((BDREFCOL IS NULL) OR (BDREFCOL = 0)) THEN
    BEGIN
      SELECT FIRST 1 Y.BDREFCOL
      FROM VRH_EMP_TCOLCON_REF Y
      WHERE Y.BDCODEMP = :premp AND
            Y.BDCODCOL = :prcol
      ORDER BY y.bdrefcol
      INTO
        :BDREFCOL;
    END

  SUSPEND;
END
^

/* Alter (SP_CONSULTA_EMP_POR_REF) */
ALTER PROCEDURE SP_CONSULTA_EMP_POR_REF(PREMP INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER)
 AS
DECLARE VARIABLE wref INTEGER;
BEGIN
   IF (prrefmicro IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

   SELECT Y.BDCODEMP, MAX(Y.BDREFEMP)
          FROM TEMPRESAS_REF Y
          WHERE Y.BDCODEMP = :PREMP AND
                CAST(Y.BDREFEMP AS VARCHAR(6)) <=
                   (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                    FROM rdb$database
                   )
          GROUP BY Y.BDCODEMP
  INTO
    :BDCODEMP,
    :BDREFEMP;


  IF ((BDREFEMP IS NULL) OR (BDREFEMP = 0)) THEN
    BEGIN
      SELECT FIRST 1 Y.BDCODEMP, Y.BDREFEMP
      FROM TEMPRESAS_REF Y
      WHERE Y.BDCODEMP = :PREMP
      ORDER BY y.bdrefemp
      INTO
        :BDCODEMP,
        :BDREFEMP;
    END

  SUSPEND;
END
^

/* Alter (SP_CONSULTA_TERCEIRO) */
ALTER PROCEDURE SP_CONSULTA_TERCEIRO(PRCODTER INTEGER,
PRREF INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER DM_BDENDERECO,
BDNUMTER VARCHAR(10),
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER VARCHAR(60),
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDORGAOPUBLICO VARCHAR(5),
BDCODTIPO INTEGER,
BDCODIBGE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

    wSql = ' select ';
    wSql = wSql || 'TER.BDCODTER, ';
    wSql = wSql || 'TER.BDCODPLAPADRAO, ';
    wSql = wSql || 'TER.BDCODTPLA, ';
    wSql = wSql || 'TER.BDCGCTER, ';
    wSql = wSql || 'TER.BDREFEMP, ';
    wSql = wSql || 'TER.BDAPELIDOTER, ';
    wSql = wSql || 'TER.BDNOMETER, ';
    wSql = wSql || 'TER.BDLOGRTER, ';
    wSql = wSql || 'TER.BDENDTER, ';
    wSql = wSql || 'TER.BDNUMTER, ';
    wSql = wSql || 'TER.BDCOMPTER, ';
    wSql = wSql || 'TER.BDCEPTER, ';
    wSql = wSql || 'TER.BDBAITER, ';
    wSql = wSql || 'TER.BDDDDTER, ';
    wSql = wSql || 'TER.BDFONETER, ';
    wSql = wSql || 'TER.BDFAXTER, ';
    wSql = wSql || 'TER.BDEMAILTER, ';
    wSql = wSql || 'TER.BDIETER, ';
    wSql = wSql || 'TER.BDDATACADTER, ';
    wSql = wSql || 'TER.BDIMTER, ';
    wSql = wSql || 'TER.BDPRURALTER, ';
    wSql = wSql || 'TER.BDENQSIMPLESFEDTER, ';
    wSql = wSql || 'TER.BDINSCSUFRAMATER, ';
    wSql = wSql || 'TER.BDCODGPS, ';
    wSql = wSql || 'TER.BDCODCID, ';
    wSql = wSql || 'TER.BDCODPAIS, ';
    wSql = wSql || 'TER.BDDESCPAIS, ';
    wSql = wSql || 'TER.BDDDDFAXTER, ';
    wSql = wSql || 'CID.BDCODUF, ';
    wSql = wSql || 'UF.BDSIGLAUF, ';
    wsql = wsql || 'CID.BDNOMCID,';
    wsql = wsql || 'TER.BDORGAOPUBLICO,';
    wsql = wsql || 'TER.BDCODTIPO,';
    wsql = wsql || 'CID.BDCODIBGE';
 
    wSql = wsql || ' FROM vw_tterceiro TER ';

    wSql = wsql || ' left outer join tcidade CID';
    wSql = wsql || ' on (TER.BDCODCID = CID.bdCODCID)';
    wSql = wsql || ' left outer join tuf UF';
    wSql = wsql || ' on (CID.BDCODUF = UF.bdCODUF)';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' TER.bdcodTER = '||prcodter;

  IF (prwhereTER IS NOT NULL AND prwhereTER <> '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereTER;
    END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TER.bdcodTER';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODTER,
    :BDCODPLAPADRAO,
    :BDCODTPLA,
    :BDCGCTER,
    :BDREFEMP,
    :BDAPELIDOTER,
    :BDNOMETER, 
    :BDLOGRTER, 
    :BDENDTER, 
    :BDNUMTER, 
    :BDCOMPTER,
    :BDCEPTER, 
    :BDBAITER, 
    :BDDDDTER, 
    :BDFONETER,
    :BDFAXTER,
    :BDEMAILTER,
    :BDIETER,
    :BDDATACADTER,
    :BDIMTER,
    :BDPRURALTER,
    :BDENQSIMPLESFEDTER,
    :BDINSCSUFRAMATER,
    :BDCODGPS,
    :BDCODCID,
    :BDCODPAIS,
    :bddescpais, 
    :BDDDDFAXTER,
    :BDCODUF,
    :BDSIGLAUF,
    :bdnomcid,
    :BDORGAOPUBLICO,
    :BDCODTIPO,
 :BDCODIBGE
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONSULTACLIENTES) */
ALTER PROCEDURE SP_CONSULTACLIENTES(PRREFMICRO INTEGER,
PRCODCLI VARCHAR(10240),
PRCODSITCLI INTEGER)
 RETURNS(BDCODCLI INTEGER,
BDCODESC INTEGER,
BDCODPRESER INTEGER,
BDCODCLIMATRIZ INTEGER,
BDCNPJCLI VARCHAR(18),
BDDATAINIATIVCLI DATE,
BDDATAFIMATIVCLI DATE,
BDORGAOCLI VARCHAR(20),
BDNUMREGCLI VARCHAR(40),
BDNOMECARTORIO VARCHAR(100),
BDDATAREGCLI DATE,
BDLIVROREG VARCHAR(15),
BDFOLHAREG VARCHAR(15),
BDDOCAUXREG VARCHAR(18),
BDCODTIPOCLI INTEGER,
BDDATACADCLI DATE,
BDCODCID INTEGER,
BDCODCNAE INTEGER,
BDCODNATJUR INTEGER,
BDDESCPLASITFIN VARCHAR(50),
BDCODPLASITFIN INTEGER,
BDAPECLI DM_BDAPEMP,
BDNOMCLI DM_BDNOMEMP,
BDNOMREDUZCLI DM_BDNOMREDUZEMP,
BDCEPCLI VARCHAR(9),
BDLOGRCLI VARCHAR(15),
BDENDCLI DM_BDENDERECO,
BDNUMCLI INTEGER,
BDCOMPLCLI DM_BDCOMPENDERECO,
BDBAICLI DM_BDBAIRRO,
BDDDDCLI INTEGER,
BDFONECLI DM_BDTELEFONE,
BDDDDFAXCLI INTEGER,
BDFONEFAXCLI DM_BDTELEFONE,
BDDDDCELCLI INTEGER,
BDCELCLI DM_BDTELEFONE,
BDCXPCLI DM_CXPOSTAL,
BDIECLI VARCHAR(20),
BDIMCLI VARCHAR(20),
BDEMAILCLI DM_BDEMAIL,
BDCAPITALSOC DM_NUMERIC_15_2,
BDORGAOPUBLICO DM_BOOLEAN,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCCNAE VARCHAR(200),
BDDESCNAT VARCHAR(100),
BDNUMFUN INTEGER,
BDCODPLATRIB INTEGER,
BDINATIVO DM_BOOLEAN,
BDDESCPLATRIB VARCHAR(50),
BDCODIBGECID INTEGER,
BDCODFEDCID INTEGER,
BDCODSPEDPAIS INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'cli.BDCODCLI, cli.BDCODESC, cli.BDCODPRESER, cli.BDCODCLIMATRIZ, ';
  wSql = wSql||'cli.BDCNPJCLI, cli.BDDATAINIATIVCLI, cli.BDDATAFIMATIVCLI, ';
  wSql = wSql||'cli.BDORGAOCLI, cli.BDNUMREGCLI, cli.BDNOMECARTORIO, cli.BDDATAREGCLI, ';
  wSql = wSql||'cli.BDLIVROREG, cli.BDFOLHAREG, cli.BDDOCAUXREG, cli.BDCODTIPOCLI, cli.BDDATACADCLI, ';
  wSql = wSql||'refcli.BDCODCID, refcli.BDCODCNAE, refcli.BDCODNATJUR, ';
  wSql = wSql||'/*refcli.BDCODSITCLI,*/ refcli.BDAPECLI, refcli.BDNOMCLI, ';
  wSql = wSql||'refcli.BDNOMREDUZCLI, refcli.BDCEPCLI, refcli.BDLOGRCLI, ';
  wSql = wSql||'refcli.BDENDCLI, refcli.BDNUMCLI, refcli.BDCOMPLCLI, ';
  wSql = wSql||'refcli.BDBAICLI, refcli.BDDDDCLI, refcli.BDFONECLI, ';
  wSql = wSql||'refcli.BDDDDFAXCLI, refcli.BDFONEFAXCLI, refcli.BDDDDCELCLI, ';
  wSql = wSql||'refcli.BDCELCLI, refcli.BDCXPCLI,refcli.BDIECLI, refcli.BDIMCLI, ';
  wSql = wSql||'refcli.BDEMAILCLI, refcli.BDCAPITALSOC, refcli.BDORGAOPUBLICO, ';
  wSql = wSql||'/*refcli.BDDATAENTRADA, refcli.BDDATASAIDA,*/ refcli.bdnumfun, refcli.bdinativo, refcli.bdcodplatrib, ';
  wSql = wSql||'refcli.BDCODPLANOONLINE, refcli.BDCODPLAPADRAO, refcli.BDCODHIST, ';
  wSql = wsql||'cid.bdnomcid, uf.bdsiglauf, ';
  wSql = wSql||'/*sitcli.bddescsitcli,*/ cnae.BDDESCCNAE, natjur.bddescnat, tplatrib.bddescplatrib, ';
  wSql = wSql||'cid.bdcodibge bdcodibgecid, cid.bdcodfed bdcodfedcid, pais.bdcodsped bdcodspedpais, ';
  wSql = wSql||'refcli.BDCODPLASITFIN, plasit.BDDESCPLASITFIN ';
  wSql = wSql||' from VFIN_BASE_TCLIENTE cli ';
  wSql = wSql||' join vw_vfin_clientes_ref refcli on (refcli.bdcodcli = cli.bdcodcli) ';
  wSql = wSql||' left outer join tcidade cid on (cid.bdcodcid = refcli.bdcodcid)  ';
  wSql = wSql||' left outer join tpais pais on pais.bdcodpais = cid.bdcodpais ';
  wSql = wSql||' left outer join tuf uf on (uf.bdcoduf = cid.bdcoduf) ';
  /*wSql = wSql||' left outer join vfin_base_ttabsitcli sitcli on (sitcli.bdcodsitcli = refcli.bdcodsitcli) ';*/
  wSql = wSql||' left outer join VFIN_BASE_TPLANOSITFIN plasit on (plasit.bdcodplasitfin = refcli.bdcodplasitfin) ';
  wSql = wSql||' left outer join tcnae cnae on (cnae.bdcodcnae = refcli.bdcodcnae) ';
  wSql = wSql||' left outer join tnatjur natjur on (natjur.bdcodnatjur = refcli.bdcodnatjur) ';
  wSql = wSql||' left outer join VCT_PLANO_TRIBUTARIO tplatrib on (tplatrib.bdcodplatrib = refcli.bdcodplatrib) ';

  wwhere = '';

  IF ((prcodcli IS NOT NULL) AND (prcodcli <> '0') AND (prcodcli <> '')) THEN
     BEGIN
       SELECT POSITION('=', :prcodcli) FROM RDB$DATABASE INTO wpos;

       IF (wPos = 0) THEN
          SELECT POSITION(' in (', :prcodcli) FROM RDB$DATABASE INTO :wpos;

       IF (wPos = 0) THEN
          SELECT POSITION(' between ', :prcodcli) FROM RDB$DATABASE INTO :wpos;

       IF (wpos > 0) THEN
          wwhere = wwhere||' ('||prcodcli||') ';
       ELSE
          wwhere = wwhere||' cli.bdcodcli = '||prcodcli;
     END

  /*Comentado pois n?o existe mais o campo BDCODSITCLI na tabela de clientes*/
  /* filra situa??o do cliente*/
  /*if (PRCODSITCLI is not null and PRCODSITCLI <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wWhere = 'ref.bdCODSITCLI = '||prCODSITCLI;
     end*/

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By cli.BDCODCLI';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    /*BDCODSITCLI,*/
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    /*BDDATAENTRADA,
    BDDATASAIDA,*/
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDNOMCID,
    BDSIGLAUF,
    /*BDDESCSITCLI,*/
    BDDESCCNAE,
    BDDESCNAT,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODPLASITFIN,
    BDDESCPLASITFIN
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONSULTACLIENTES_SIS) */
ALTER PROCEDURE SP_CONSULTACLIENTES_SIS(PRREFMICRO INTEGER,
PRCODCLI INTEGER,
PRCODSITCLI INTEGER)
 RETURNS(BDCODCLI INTEGER,
BDCODESC INTEGER,
BDCODPRESER INTEGER,
BDCODCLIMATRIZ INTEGER,
BDCNPJCLI VARCHAR(18),
BDDATAINIATIVCLI DATE,
BDDATAFIMATIVCLI DATE,
BDORGAOCLI VARCHAR(20),
BDNUMREGCLI VARCHAR(40),
BDNOMECARTORIO VARCHAR(100),
BDDATAREGCLI DATE,
BDLIVROREG VARCHAR(15),
BDFOLHAREG VARCHAR(15),
BDDOCAUXREG VARCHAR(18),
BDCODTIPOCLI INTEGER,
BDDATACADCLI DATE,
BDCODCID INTEGER,
BDCODCNAE INTEGER,
BDCODNATJUR INTEGER,
BDAPECLI DM_BDAPEMP,
BDNOMCLI DM_BDNOMEMP,
BDNOMREDUZCLI DM_BDNOMREDUZEMP,
BDCEPCLI VARCHAR(9),
BDLOGRCLI VARCHAR(15),
BDENDCLI DM_BDENDERECO,
BDNUMCLI INTEGER,
BDCOMPLCLI DM_BDCOMPENDERECO,
BDBAICLI DM_BDBAIRRO,
BDDDDCLI INTEGER,
BDFONECLI DM_BDTELEFONE,
BDDDDFAXCLI INTEGER,
BDFONEFAXCLI DM_BDTELEFONE,
BDDDDCELCLI INTEGER,
BDCELCLI DM_BDTELEFONE,
BDCXPCLI DM_CXPOSTAL,
BDIECLI VARCHAR(20),
BDIMCLI VARCHAR(20),
BDEMAILCLI DM_BDEMAIL,
BDCAPITALSOC DM_NUMERIC_15_2,
BDORGAOPUBLICO DM_BOOLEAN,
BDDATAENTRADA DATE,
BDDATASAIDA DATE,
BDCODCONT INTEGER,
BDCONTATO VARCHAR(60),
BDPROFISCONTATO VARCHAR(60),
BDDATANASCCON DATE,
BDCPFCON VARCHAR(18),
BDCODCIDETI INTEGER,
BDNOMENDETI DM_BDNOMEMP,
BDLOGRETI VARCHAR(15),
BDENDERECOETI DM_BDENDERECO,
BDNUMEROETI INTEGER,
BDCOMPLETI DM_BDCOMPENDERECO,
BDBAIRROETI DM_BDBAIRRO,
BDCEPETI VARCHAR(9),
BDCXPETI DM_CXPOSTAL,
BDNOMCIDETI VARCHAR(40),
BDSIGLAUFETI VARCHAR(2),
BDCODENQFED INTEGER,
BDCOMERCIO DM_BOOLEAN,
BDINDUSTRIA DM_BOOLEAN,
BDSERVICO DM_BOOLEAN,
BDANEXOIII DM_BOOLEAN,
BDANEXOIV DM_BOOLEAN,
BDANEXOV DM_BOOLEAN,
BDANEXOVI DM_BOOLEAN,
BDPERINSS DM_NUMERIC_7_4_ALIQ,
BDDEDINSSNF DM_BOOLEAN,
BDUSARPERISS INTEGER,
BDRETIR DM_BOOLEAN,
BDRETCSLL DM_BOOLEAN,
BDRETCOF DM_BOOLEAN,
BDRETPIS DM_BOOLEAN,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCSITCLI VARCHAR(100),
BDDESCCNAE VARCHAR(200),
BDDESCNAT VARCHAR(100),
BDNUMFUN INTEGER,
BDINATIVO DM_BOOLEAN,
BDCODPLATRIB INTEGER,
BDDESCPLATRIB VARCHAR(50),
BDCODIBGECID INTEGER,
BDCODFEDCID INTEGER,
BDCODSPEDPAIS INTEGER,
BDINCENTCULT DM_BOOLEAN,
BDCODIBGECIDETI INTEGER,
BDCODFEDCIDETI INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODSITESP INTEGER,
BDCODPLASITFIN INTEGER,
BDDESCPLASITFIN VARCHAR(50),
BDCODHIST INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'ref.BDCODCLI, ';
  wSql = wSql||'ref.BDCODESC, ';
  wSql = wSql||'ref.BDCODPRESER, ';
  wSql = wSql||'ref.BDCODCLIMATRIZ, ';
  wSql = wSql||'ref.BDCNPJCLI, ';
  wSql = wSql||'ref.BDDATAINIATIVCLI, ';
  wSql = wSql||'ref.BDDATAFIMATIVCLI, ';
  wSql = wSql||'ref.BDORGAOCLI, ';
  wSql = wSql||'ref.BDNUMREGCLI, ';
  wSql = wSql||'ref.BDNOMECARTORIO, ';
  wSql = wSql||'ref.BDDATAREGCLI, ';
  wSql = wSql||'ref.BDLIVROREG, ';
  wSql = wSql||'ref.BDFOLHAREG, ';
  wSql = wSql||'ref.BDDOCAUXREG, ';
  wSql = wSql||'ref.BDCODTIPOCLI, ';
  wSql = wSql||'ref.BDDATACADCLI, ';
  wSql = wSql||'ref.BDCODCID, ';
  wSql = wSql||'ref.BDCODCNAE, ';
  wSql = wSql||'ref.BDCODNATJUR, ';
  /*wSql = wSql||'ref.BDCODSITCLI, ';*/
  wSql = wSql||'ref.BDAPECLI, ';
  wSql = wSql||'ref.BDNOMCLI, ';
  wSql = wSql||'ref.BDNOMREDUZCLI, ';
  wSql = wSql||'ref.BDCEPCLI, ';
  wSql = wSql||'ref.BDLOGRCLI, ';
  wSql = wSql||'ref.BDENDCLI, ';
  wSql = wSql||'ref.BDNUMCLI, ';
  wSql = wSql||'ref.BDCOMPLCLI, ';
  wSql = wSql||'ref.BDBAICLI, ';
  wSql = wSql||'ref.BDDDDCLI, ';
  wSql = wSql||'ref.BDFONECLI, ';
  wSql = wSql||'ref.BDDDDFAXCLI, ';
  wSql = wSql||'ref.BDFONEFAXCLI, ';
  wSql = wSql||'ref.BDDDDCELCLI, ';
  wSql = wSql||'ref.BDCELCLI, ';
  wSql = wSql||'ref.BDCXPCLI, ';
  wSql = wSql||'ref.BDIECLI, ';
  wSql = wSql||'ref.BDIMCLI, ';
  wSql = wSql||'ref.BDEMAILCLI, ';
  wSql = wSql||'ref.BDCAPITALSOC, ';
  wSql = wSql||'ref.BDORGAOPUBLICO, ';
  /*wSql = wSql||'ref.BDDATAENTRADA, ';
  wSql = wSql||'ref.BDDATASAIDA, ';*/
  wSql = wSql||'ref.bdnomcid, ';
  wSql = wSql||'ref.bdsiglauf, ';
  /*wSql = wSql||'ref.bddescsitcli, ';*/
  wSql = wSql||'ref.bddesccnae, ';
  wSql = wSql||'ref.bddescnat, ';
  wSql = wSql||'ref.bdnumfun, ';
  wSql = wSql||'ref.bdinativo, ';
  wSql = wSql||'ref.bdcodplatrib, ';
  wSql = wSql||'ref.bddescplatrib, ';
  wSql = wSql||'ref.bdcodibgecid, ';
  wSql = wSql||'ref.bdcodfedcid, ';
  wSql = wSql||'ref.bdcodspedpais, ';
  wSql = wSql||'ref.BDCODPLANOONLINE, ';
  wSql = wSql||'ref.BDCODPLAPADRAO, ';
  wSql = wSql||'ref.BDCODHIST, ';
  wSql = wSql||'reftot.BDCODCONT, ';
  wSql = wSql||'reftot.BDCONTATO, ';
  wSql = wSql||'reftot.BDPROFISCONTATO, ';
  wSql = wSql||'reftot.BDDATANASCCON, ';
  wSql = wSql||'reftot.BDCPFCON, ';
  wSql = wSql||'reftot.BDCODCIDETI, ';
  wSql = wSql||'reftot.BDNOMENDETI, ';
  wSql = wSql||'reftot.BDLOGRETI, ';
  wSql = wSql||'reftot.BDENDERECOETI, ';
  wSql = wSql||'reftot.BDNUMEROETI, ';
  wSql = wSql||'reftot.BDCOMPLETI, ';
  wSql = wSql||'reftot.BDBAIRROETI, ';
  wSql = wSql||'reftot.BDCEPETI, ';
  wSql = wSql||'reftot.BDCXPETI, ';
  wSql = wSql||'reftot.BDNOMCIDETI, ';
  wSql = wSql||'reftot.BDSIGLAUFETI, ';
  wSql = wSql||'reftot.BDCODENQFED, ';
  wSql = wSql||'reftot.BDCOMERCIO, ';
  wSql = wSql||'reftot.BDINDUSTRIA, ';
  wSql = wSql||'reftot.BDSERVICO, ';
  wSql = wSql||'reftot.BDANEXOIII, ';
  wSql = wSql||'reftot.BDANEXOIV, ';
  wSql = wSql||'reftot.BDANEXOV, ';
  wSql = wSql||'reftot.BDANEXOVI, ';
  wSql = wSql||'reftot.BDPERINSS, ';
  wSql = wSql||'reftot.BDDEDINSSNF, ';
  wSql = wSql||'reftot.BDUSARPERISS, ';
  wSql = wSql||'reftot.BDRETIR, ';
  wSql = wSql||'reftot.BDRETCSLL, ';
  wSql = wSql||'reftot.BDRETCOF, ';
  wSql = wSql||'reftot.BDRETPIS, ';
  wSql = wSql||'reftot.BDINCENTCULT, ';
  wSql = wSql||'reftot.BDCODIBGECIDETI, ';
  wSql = wSql||'reftot.BDCODFEDCIDETI, ';
  wSql = wSql||'reftot.BDCODSITESP, ';
  wSql = wSql||'ref.BDCODPLASITFIN, ';
  wSql = wSql||'ref.BDDESCPLASITFIN ';


  WPAR = 'from sp_consultaclientes('||prrefmicro;
  IF (prcodcli IS NOT NULL AND prcodcli <> 0) THEN
    wpar = wpar||','||prcodcli||',';
  ELSE
    wpar = wpar||',null,';

  IF (PRCODSITCLI IS NULL) THEN
    wpar = wpar||'0) ref';
  ELSE
    wpar = wpar||PRCODSITCLI||') ref';

  wSql = wsql || wpar;

  wSql = wsql || ' left outer join VW_VFIN_BASE_TCLIENTE_REF_TOTAL reftot on (reftot.bdcodcli = ref.bdcodcli) ';

  wwhere = '';

  IF (prcodcli IS NOT NULL AND prcodcli <> 0) THEN
     wwhere = wwhere || ' ref.bdcodcli = '||prcodcli;

  /*Comentado pois n?o existe mais o campo BDCODSITCLI na tabela de clientes*/
  /* filra empresas inativas */
  /*IF (prcodsitcli IS NOT NULL AND prcodsitcli <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'ref.BDCODSITCLI) = '||prcodsitcli;
     END*/

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By ref.BDCODCLI';


  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    /*BDCODSITCLI,*/
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    /*BDDATAENTRADA,
    BDDATASAIDA,*/
    BDNOMCID,
    BDSIGLAUF,
    /*BDDESCSITCLI,*/
    BDDESCCNAE,
    BDDESCNAT,
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCONT,
    BDCONTATO,
    BDPROFISCONTATO,
    BDDATANASCCON,
    BDCPFCON,
    BDCODCIDETI,
    BDNOMENDETI,
    BDLOGRETI,
    BDENDERECOETI,
    BDNUMEROETI,
    BDCOMPLETI,
    BDBAIRROETI,
    BDCEPETI,
    BDCXPETI,
    BDNOMCIDETI,
    BDSIGLAUFETI,
    BDCODENQFED,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDPERINSS,
    BDDEDINSSNF,
    BDUSARPERISS,
    BDRETIR,
    BDRETCSLL,
    BDRETCOF,
    BDRETPIS,
    BDINCENTCULT,
    BDCODIBGECIDETI,
    BDCODFEDCIDETI,
    BDCODSITESP,
    BDCODPLASITFIN,
    BDDESCPLASITFIN
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONSULTADESPESAS) */
ALTER PROCEDURE SP_CONSULTADESPESAS(PRREFDESP INTEGER,
PRCODDESP INTEGER)
 RETURNS(BDCODDESP INTEGER,
BDCLASSDESP DM_CLASSCONTAS,
BDDESCDESP VARCHAR(100),
BDSABDOMFER INTEGER,
BDDIAVENC INTEGER,
BDTIPODESP INTEGER,
BDVALORDESP DM_NUMERIC_15_2)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefdesp, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'desp.BDCODDESP, ';
  wSql = wSql||'desp.BDCLASSDESP, ';
  wSql = wSql||'desp.BDDESCDESP, ';
  wSql = wSql||'refdesp.BDSABDOMFER, ';
  wSql = wSql||'refdesp.BDDIAVENC, ';
  wSql = wSql||'desp.BDTIPODESP, ';
  wSql = wSql||'refdesp.BDVALORDESP ';
  wSql = wSql||'from VFIN_BASE_TDESPESA desp ';
  wSql = wsql||'left outer join VW_VFIN_BASE_TDESPESA_REF refdesp on (refdesp.bdcoddesp = desp.bdcoddesp) ';

  wwhere = '';

  IF (prcoddesp IS NOT NULL AND prcoddesp <> 0) THEN
     wwhere = wwhere || ' desp.bdcoddesp = '||prcoddesp;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By desp.BDCODDESP';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODDESP,
    BDCLASSDESP,
    BDDESCDESP,
    BDSABDOMFER,
    BDDIAVENC,
    BDTIPODESP,
    bdvalordesp
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONSULTAEMPRESAS_SEARCH) */
ALTER PROCEDURE SP_CONSULTAEMPRESAS_SEARCH(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDAPEEMP VARCHAR(20),
BDIEEMP VARCHAR(20))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);


  wSql = ' select TEMP.BDCODEMP, TEMP.BDCNPJEMP, TREF.bdapeemp, '||
                 'tref.BDIEEMP '||
      ' from TEMPRESAS TEMP'||
      ' left outer join vw_tempresas_ref tref  on (tref.bdcodemp = temp.bdcodemp)';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' TEMP.bdcodemp = '||prcodemp;

  /* filra empresas inativas */
  IF (prinativas IS NOT NULL AND prinativas <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'UPPER(tref.BDSITEMP) = '''||'FALSE''';
     END


  /*
  for select BDCODUSU from sp_get_usuario
  into
    :wcodusu
  do

   filtra as empresas por usuario
  if (wcodusu is not null and wcodusu <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TEMP.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     end   */

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TEMP.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCNPJEMP,
    :BDAPEEMP,
    :BDIEEMP
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONSULTAEMPRESAS_SIS) */
ALTER PROCEDURE SP_CONSULTAEMPRESAS_SIS(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDDATAINIATIVEMP DATE,
BDORGAOEMP VARCHAR(8),
BDDATAREGEMP DATE,
BDDATACONSTEMP DATE,
BDDESCCARTEMP VARCHAR(40),
BDDATAFIMATIVEMP DATE,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCODCENTROS INTEGER,
BDCODCID INTEGER,
BDCODCONT INTEGER,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDNOMREDUZEMP DM_BDNOMREDUZEMP,
BDAPEEMP DM_BDAPEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP INTEGER,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDFAXEMP DM_BDTELEFONE,
BDDDDCELULAREMP INTEGER,
BDCELULAREMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDLOGREMP VARCHAR(15),
BDIEEMP VARCHAR(20),
BDIMEMP VARCHAR(20),
BDSITEMP VARCHAR(5),
BDDDDFAXEMP INTEGER,
BDNOMCID VARCHAR(40),
BDCODUF INTEGER,
BDNOMECONT VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDDESCUF VARCHAR(40),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODCONFATIVO INTEGER,
BDSUFRAMA VARCHAR(9),
BDCODACESSOSN VARCHAR(12),
BDPERFILSPED INTEGER,
BDATIVIDADESPED INTEGER,
BDCODCONFIPI INTEGER,
BDCODCONFIRLP INTEGER,
BDCODCONFDIMESC INTEGER,
BDCODPORTEEMP INTEGER,
BDCODAPUCON INTEGER,
BDCODESCCONT INTEGER,
BDCODREGAPU INTEGER,
BDCONTPRODEC VARCHAR(5),
BDNRPARPRODEC INTEGER,
BDLANBCICMSVALCONT VARCHAR(5),
BDLANBCICMSISEOUT INTEGER,
BDLANCLISAISER VARCHAR(5),
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDMOVSER VARCHAR(5),
BDPERCISS NUMERIC(15,6),
BDREDPERCISS NUMERIC(15,6),
BDMOVIRRF VARCHAR(5),
BDALIQIRRF NUMERIC(15,6),
BDISENTOIRRF NUMERIC(15,6),
BDEMPINATIVA VARCHAR(5),
BDEMPDIFPAPEL VARCHAR(5),
BDEMPBARREST VARCHAR(5),
BDVERIFICARNOTASJALAN INTEGER,
BDCODPLANOONLINE INTEGER,
BDLRISSSN NUMERIC(15,6),
BDCOMERCIO VARCHAR(5),
BDINDUSTRIA VARCHAR(5),
BDSERVICO VARCHAR(5),
BDANEXOIII VARCHAR(5),
BDANEXOIV VARCHAR(5),
BDANEXOV VARCHAR(5),
BDCODENQFED INTEGER,
BDSUBSTRIB INTEGER,
BDCODCONFDACON INTEGER,
BDCODCONFICMSSPED INTEGER,
BDCODCONFCIAP INTEGER,
BDREDBCICMSENT NUMERIC(15,6),
BDREDBCICMSSAI NUMERIC(15,6),
BDCODCONFDASN INTEGER,
BDRETPARPIS VARCHAR(5),
BDRETPARCOFINS VARCHAR(5),
BDRETPARCSLL VARCHAR(5),
BDRETPARIRRF VARCHAR(5),
BDRETPARISSQN VARCHAR(5),
BDRETPARINSS VARCHAR(5),
BDRETPARFUNRURAL VARCHAR(5),
BDTIPOAPURACAO INTEGER,
BDSOMFREBASEICMS VARCHAR(5),
BDSOMFREVLRCONTAB VARCHAR(5),
BDCODPLATROCA INTEGER,
BDCODPLACFOP INTEGER,
BDCODCONFBLOCOP INTEGER,
BDCREDPRESUMIDO VARCHAR(5),
BDTERMOACEITE VARCHAR(5),
BDANTECIPAIMPOSTO VARCHAR(5),
BDTIPODECLARANTEDMED INTEGER,
BDREGISTROANSDMED INTEGER,
BDNUMEROCNESDMED INTEGER,
BDDTOBRIGSPEDCONT DATE,
BDTIPOAPURACAORET INTEGER,
BDTIPOAPURACAORETIR INTEGER,
BDDTOBRIGSPEDICMS DATE,
BDCODCONTEF INTEGER,
BDLIVRO VARCHAR(15),
BDFOLHA VARCHAR(15),
BDNOMECARTORIO VARCHAR(100),
BDLANCAPARCELAAUTO VARCHAR(5),
BDCODIGOPLA INTEGER,
BDINDATIV INTEGER,
BDTRANMANUAL VARCHAR(5),
BDIMPORTARVALORESICMSSN DM_BOOLEAN,
BDDIFALIQ VARCHAR(5),
BDDIFALIQBASEEM INTEGER,
BDANEXOVI DM_BOOLEAN,
BDCODPLATRIB INTEGER,
BDCODPLAPADRAOREF INTEGER,
BDINDNATPJ INTEGER,
BDCODIBGE INTEGER,
BDFORMATRIBUTACAO INTEGER,
BDSOMAPISCOFVLRCONT DM_BOOLEAN,
BDSOMAIIVLRCONT DM_BOOLEAN,
BDMANTERPARCELAS DM_BOOLEAN,
BDCODPLANOINCONS INTEGER,
BDABRIRRATEIO DM_BOOLEAN,
BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
BDINTEGRANET DM_BOOLEAN,
BDSOMAIPIPROD DM_BOOLEAN,
BDSOMAICMSVLRCONT DM_BOOLEAN,
BDCODPLAE115 INTEGER,
BDDATACADEMP DATE,
BDCODCLATRI INTEGER,
BDDATAOBRIGREINF DATE,
BDSOMASTPROD DM_BOOLEAN,
BDCALCANTICMS VARCHAR(5),
BDCONSIPIBC VARCHAR(5),
BDIMPICMSST VARCHAR(5),
BDANEXOIII_2018 VARCHAR(5),
BDANEXOIV_2018 VARCHAR(5),
BDANEXOV_2018 VARCHAR(5),
BDSTATUSEMP INTEGER,
BDQTDBACKUPEMP INTEGER,
BDIMPORTARISS VARCHAR(5),
BDINCORPORADORAS DM_BOOLEAN)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);
    wSql = ' select ';
    wSql = wsql || 'Tref.BDCODEMP, ';
    wSql = wsql || 'tref.BDCODMATRIZ, ';
    wSql = wsql || 'tref.BDCNPJEMP, ';
    wSql = wsql || 'tref.BDDATAINIATIVEMP, ';
    wSql = wsql || 'tref.BDORGAOEMP, ';
    wSql = wsql || 'tref.BDDATAREGEMP, ';
    wSql = wsql || 'tref.BDDATACONSTEMP, ';  --alt:14844 - Adicionado campo BDDATACONSTEMP na consulta. Ana - 05/08/2016
    wSql = wsql || 'tref.BDDESCCARTEMP, ';
    wSql = wsql || 'tref.BDDATAFIMATIVEMP, ';
    wSql = wsql || 'tref.BDCODPLAPADRAO, ';
    wSql = wsql || 'tref.BDCODHIST, ';
    wSql = wsql || 'tref.BDCODCENTROS, ';
    wSql = wsql || 'tref.BDCODCID, ';
    wSql = wsql || 'tref.BDCODCONT, ';
    wSql = wsql || 'tref.BDCODNATJUR, ';
    wSql = wsql || 'tref.BDCODCNAE, ';
    wSql = wsql || 'tref.BDNOMEMP, ';
    wSql = wsql || 'tref.BDNOMREDUZEMP, ';
    wSql = wsql || 'tref.BDAPEEMP, ';
    wSql = wsql || 'tref.BDENDEMP, ';
    wSql = wsql || 'tref.BDNUMEMP, ';
    wSql = wsql || 'tref.BDBAIEMP, ';
    wSql = wsql || 'tref.BDCEPEMP, ';
    wSql = wsql || 'tref.BDDDDEMP, ';
    wSql = wsql || 'tref.BDFONEEMP, ';
    wSql = wsql || 'tref.BDFAXEMP, ';
    wSql = wsql || 'tref.BDDDDCELULAREMP, ';
    wSql = wsql || 'tref.BDCELULAREMP, ';
    wSql = wsql || 'tref.BDEMAILEMP, ';
    wSql = wsql || 'tref.BDCOMPLEMP, ';
    wSql = wsql || 'tref.BDLOGREMP, ';
    wSql = wsql || 'tref.BDIEEMP, ';
    wSql = wsql || 'tref.BDIMEMP, ';
    wSql = wsql || 'tref.BDSITEMP, ';
    wSql = wsql || 'tref.BDDDDFAXEMP, ';
    wSql = wsql || 'Tref.BDNOMCID, ';
    wSql = wsql || 'Tref.BDCODUF, ';
    wSql = wsql || 'Tref.BDNOMECONT, ';
    wSql = wsql || 'tref.BDSIGLAUF, ';
    wSql = wsql || 'tref.BDDESCUF, ';
    wSql = wsql || 'tref.BDTRANMANUAL, ';
    wSQL = wsql || 'tref.BDDATACADEMP, ';

    wSql = wsql || 'trefsis.bdretinss, ';
    wSql = wsql || 'trefsis.bdvlrmininss, ';
    wSql = wsql || 'trefsis.bdSUFRAMA, ';
    wSql = wsql || 'trefsis.bdcodacessosn, ';
    wSql = wsql || 'trefsis.bdperfilsped, ';
    wSql = wsql || 'trefsis.bdatividadesped, ';
    wSql = wsql || 'trefsis.BDCODCONFIPI, ';
    wSql = wsql || 'trefsis.BDCODCONFIRLP, ';
    wSql = wsql || 'trefsis.BDCODCONFDIMESC, ';
    wSql = wsql || 'trefsis.BDCODPORTEEMP, ';
    wSql = wsql || 'trefsis.BDCODAPUCON, ';
    wSql = wsql || 'trefsis.BDCODESCCONT, ';
    wSql = wsql || 'trefsis.BDCODREGAPU, ';
    wSql = wsql || 'trefsis.BDCONTPRODEC, ';
    wSql = wsql || 'trefsis.BDNRPARPRODEC, ';
    --wSql = wsql || 'trefsis.BDDIAVCTOEMPSC, ';
    wSql = wsql || 'trefsis.BDCODCONFATIVO, ';
    --harry 17-02-2011
    wSql = wsql || 'trefsis.BDLANBCICMSVALCONT, ';
    wSql = wsql || 'trefsis.BDLANBCICMSISEOUT, ';
    wSql = wsql || 'trefsis.BDLANCLISAISER, ';
    wSql = wsql || 'trefsis.BDLANPROENT, ';
    wSql = wsql || 'trefsis.BDLANPROSAI, ';
    wSql = wsql || 'trefsis.BDMOVSER, ';
    wSql = wsql || 'trefsis.BDPERCISS, ';
    wSql = wsql || 'trefsis.BDREDPERCISS, ';
    wSql = wsql || 'trefsis.BDMOVIRRF, ';
    wSql = wsql || 'trefsis.BDALIQIRRF, ';
    wSql = wsql || 'trefsis.BDISENTOIRRF, ';
    wSql = wsql || 'trefsis.BDEMPINATIVA, ';
    wSql = wsql || 'trefsis.BDEMPDIFPAPEL, ';
    wSql = wsql || 'trefsis.BDEMPBARREST, ';
    wSql = wsql || 'trefsis.BDVERIFICARNOTASJALAN, ';

    wSql = wsql || 'tref.bdcodplanoonline, ';

    wSql = wsql || 'trefsis.bdlrisssn, ';
    wSql = wsql || 'trefsis.bdcomercio, ';
    wSql = wsql || 'trefsis.bdindustria, ';
    wSql = wsql || 'trefsis.bdservico, ';
    wSql = wsql || 'trefsis.bdanexoiii, ';
    wSql = wsql || 'trefsis.bdanexoiv, ';
    wSql = wsql || 'trefsis.bdanexov, ';
    wSql = wsql || 'enq.BDCODENQFED, ';
    wSql = wsql || 'case when (not (enq.BDFORMATRIBUTACAO is null)) then enq.BDFORMATRIBUTACAO else tref.BDFORMATRIBUTACAO end, ';
    wSql = wsql || 'TREFSIS.BDSUBSTRIB, ';
    wSql = wsql || 'TREFSIS.bdcodconfdacon, ';
    wSql = wsql || 'TREFSIS.bdcodconficmssped, ';
    wSql = wsql || 'TREFSIS.BDCODCONFCIAP, ';
    wSql = wsql || 'TREFSIS.BDREDBCICMSENT, ';
    wSql = wsql || 'TREFSIS.BDREDBCICMSSAI, ';
    wSql = wsql || 'TREFSIS.BDCODCONFDASN, ';

    wSql = wsql || 'TREFSIS.BDRETPARPIS, ';
    wSql = wsql || 'TREFSIS.BDRETPARCOFINS, ';
    wSql = wsql || 'TREFSIS.BDRETPARCSLL, ';
    wSql = wsql || 'TREFSIS.BDRETPARIRRF, ';
    wSql = wsql || 'TREFSIS.BDRETPARISSQN, ';
    wSql = wsql || 'TREFSIS.BDRETPARINSS, ';
    wSql = wsql || 'TREFSIS.BDRETPARFUNRURAL, ';
    wSql = wsql || 'TREFSIS.bdtipoapuracao, ';
    wSql = wsql || 'TREFSIS.BDSOMFREVLRCONTAB, ';
    wSql = wsql || 'TREFSIS.BDSOMFREBASEICMS, ';
    wSql = wsql || 'TREFSIS.BDCODPLATROCA, ';
    wSql = wsql || 'TREFSIS.bdcodplacfop, ';
    wSql = wsql || 'TREFSIS.bdcodconfblocop, ';
    wSql = wSql || 'TREFSIS.bdcredpresumido, ';
    wSql = wSql || 'TREFSIS.bdTERMOACEITE, '; --#Alt:84445 (04/06/2018) Patr?cio H. Lehn
    wSql = wSql || 'TREFSIS.bdantecipaimposto, ';
    wSql = wsql || 'TREFSIS.BDTIPODECLARANTEDMED, ';
    wSql = wsql || 'TREFSIS.BDREGISTROANSDMED, ';
    wSql = wsql || 'TREFSIS.BDNUMEROCNESDMED, ';
    wSql = wsql || 'TREFSIS.BDDTOBRIGSPEDCONT, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORET, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORETIR, ';
    wSql = wSql || 'TREFSIS.BDDTOBRIGSPEDICMS, ';
    wsql = wsql || 'TREF.BDCODCONTEF, ';
    wsql = wsql || 'TREF.BDLIVRO, ';
    wsql = wsql || 'TREF.BDFOLHA, ';
    wsql = wsql || 'TREF.BDNOMECARTORIO, ';
    wsql = wsql || 'TREFSIS.BDLANCAPARCELAAUTO, ';
    wsql = wsql || 'TREFSIS.BDCODIGOPLA, ';
    wSql = wsql || 'TREFSIS.BDINDATIV, ';
    wSql = wSql || 'parinteg.BDIMPORTARVALORESICMSSN, ';
    wSql = wSql || 'parinteg.BDDIFALIQ, ';
    wSql = wSql || 'parinteg.BDDIFALIQBASEEM, ';
    wSql = wSql || 'TREFSIS.BDANEXOVI, ';
    wsql = wsql || 'tref.bdcodplatrib, ';
    wSQL = wSQL || 'TREF.BDCODPLAPADRAOREF, '; --alt:11108 - Adicionado novo campo na tabela e na SP. Pedro
    wSql = wsql || 'TREFSIS.BDINDNATPJ, ';
    wSql = wsql || 'TREF.BDCODIBGE, '; --Sol: 11334 Patrick T. S? 03/07/2015. Traz o c?digo do IBGE para verificar o tipo de ISS da empresa
     /*
      Sol: 11439 Patrick T. S? 03/07/2015. Retorna campos para verificar
      se ? para somar ou n?o o imposto de importa??o(II). Parametros incluidos no cadastro de empresas.
    */
    wSql = wSql || 'parinteg.BDSOMAPISCOFVLRCONT, ';
    wSql = wSql || 'parinteg.BDSOMAIIVLRCONT, ';
    wsql = wsql || 'TREFSIS.BDMANTERPARCELAS, ';
    wsql = wsql || 'TREFSIS.BDCODPLANOINCONS, ';
    wSQL = wSQL || 'tref.BDABRIRRATEIO, '; --alt:13677 - 15/03/2016 - Adicionados par?metros. Pedro
    wSQL = wSQL || 'tref.BDNAOPERMITERATEIOGRUPO, '; --alt:13677 - 15/03/2016 - Adicionados par?metros. Pedro
    wSQL = wSQL || 'tref.BDINTEGRANET, '; --alt:14035 - Adicionado par?metro para o IntegraNet. Everton
    wSQL = wSQL || 'parinteg.BDSOMAIPIPROD, ';
    wSql = wSql || 'parinteg.BDSOMAICMSVLRCONT, ';
    wSql = wSql || 'parinteg.BDCODPLAE115, ';
    wSql = wSql || 'tesocial.BDCODCLATRI, ';
    wSql = wSql || 'tref.BDDATAOBRIGREINF, ';
    wSQL = wSQL || 'parinteg.BDSOMASTPROD, ';
    wSql = wSql || 'parinteg.BDCALCANTICMS, ';
    wSql = wSql || 'parinteg.BDCONSIPIBC, ';
    WSQL = WSQL || 'parinteg.BDIMPICMSST, ';
    wSql = wsql || 'trefsis.bdanexoiii_2018, ';
    wSql = wsql || 'trefsis.bdanexoiv_2018, ';
    wSql = wsql || 'trefsis.bdanexov_2018, ';
    wSQL = wsql || 'tref.BDSTATUSEMP, ';   --#Alt:16965 - Carlos Mello (06/10/2017)
    wSQL = wsql || 'tref.BDQTDBACKUPEMP, '; --#Alt:16965 - Carlos Mello (06/10/2017)
    wSql = wSql || 'parinteg.BDIMPORTARISS, ';
    wSql = wsql || 'tref.BDINCORPORADORAS ';
/*
       parger.BDLANBCICMSVALCONT,
       parger.BDLANBCICMSISEOUT,
       parger.BDLANCLISAISER,
       parger.BDLANPROENT,
       parger.BDLANPROSAI,
       parger.BDMOVSER,
       parger.BDPERCISS,
       parger.BDREDPERCISS,
       parger.BDMOVIRRF,
       parger.BDALIQIRRF,
       parger.BDISENTOIRRF,
       parger.BDEMPINATIVA,
       parger.BDEMPDIFPAPEL,
       parger.BDEMPBARREST,
       parger.BDVERIFICARNOTASJALAN
*/

  WPAR = 'from sp_consultaempresas('||prrefmicro;
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wpar = wpar||','||prcodemp||',';
  ELSE
    wpar = wpar||',null,';

  IF (prinativas IS NULL) THEN
    wpar = wpar||'0) tref';
  ELSE
    wpar = wpar||prinativas||') tref';

--  if (prinativas is null) then
--     wSql = wsql || ' from sp_consultaempresas('||prrefmicro||','||PRCODEMP||',0) tref';
--  else
--     wSql = wsql || ' from sp_consultaempresas('||prrefmicro||','||PRCODEMP||','||PRINATIVAS||') tref';

    wSql = wsql || wpar;

    wSql = wsql || ' left outer join vw_emp_ref_TOTAL TREFSIS on (TREFSIS.bdcodemp = tref.bdcodemp) ';
    wSql = wsql || ' left outer join VW_TENQFED Enq  on (Enq.bdcodemp = tref.bdcodemp) ';
    wSql = wSql || ' left outer join VW_VEF_BASE_TEMPPARINTEG parinteg on ( parinteg.bdCodEmp = tref.bdCodEmp ) and ( parinteg.bdRefEmp = trefsis.bdRefEmp ) ';
    wSql = wSql || ' left outer join VW_VRHF_BASE_TEMPESOCIAL tesocial on ( tesocial.bdcodemp = tref.bdcodemp) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' tref.bdcodemp = '||prcodemp;

  /* filra empresas inativas */
  IF (prinativas IS NOT NULL AND prinativas <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'UPPER(tref.BDSITEMP) = '''||'FALSE''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By tref.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODMATRIZ,
    :BDCNPJEMP,
    :BDDATAINIATIVEMP,
    :BDORGAOEMP,
    :BDDATAREGEMP,
    :BDDATACONSTEMP, --alt:14844 - Novo campo no cadastro de empresa. Ana - 05/08/2016
    :BDDESCCARTEMP,
    :BDDATAFIMATIVEMP,
    :BDCODPLAPADRAO,
    :BDCODHIST,
    :BDCODCENTROS,
    :BDCODCID,
    :BDCODCONT,
    :BDCODNATJUR,
    :BDCODCNAE,
    :BDNOMEMP,
    :BDNOMREDUZEMP,
    :BDAPEEMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDFAXEMP,
    :bddddcelularemp,
    :bdcelularemp,
    :BDEMAILEMP,
    :BDCOMPLEMP,
    :BDLOGREMP,
    :BDIEEMP,
    :BDIMEMP,
    :BDSITEMP,
    :BDDDDFAXEMP,
    :BDNOMCID,
    :BDCODUF,
    :BDNOMECONT,
    :BDSIGLAUF,
    :BDDESCUF,
    :BDTRANMANUAL,
    :BDDATACADEMP, 

    :bdretinss,
    :bdvlrmininss,
    :BDSUFRAMA,
    :bdcodacessosn,
    :bdperfilsped,
    :bdatividadesped,

    :BDCODCONFIPI,
    :BDCODCONFIRLP,
    :BDCODCONFDIMESC,
    :BDCODPORTEEMP,
    :BDCODAPUCON,
    :BDCODESCCONT ,
    :BDCODREGAPU ,
    :BDCONTPRODEC ,
    :BDNRPARPRODEC ,
    --:BDDIAVCTOEMPSC,
    :BDCODCONFATIVO,

    --harry 17-02-2011
    :bdlanbcicmsvalcont,
    :bdlanbcicmsiseout,
    :bdlanclisaiser,
    :bdlanproent,
    :bdlanprosai,
    :bdmovser,
    :bdperciss,
    :bdredperciss,
    :bdmovirrf,
    :bdaliqirrf ,
    :bdisentoirrf,
    :bdempinativa ,
    :bdempdifpapel,
    :bdempbarrest,
    :bdverificarnotasjalan,
    :bdcodplanoonline,
    :bdlrisssn,
    :bdcomercio,
    :bdindustria,
    :bdservico,
    :bdanexoiii,
    :bdanexoiv,
    :bdanexov,
    :BDCODENQFED,
    :BDFORMATRIBUTACAO,
    :BDSUBSTRIB,
    :bdcodconfdacon,
    :bdcodconficmssped,
    :BDCODCONFCIAP,
    :BDREDBCICMSENT,
    :BDREDBCICMSSAI,
    :BDCODCONFDASN,

    :BDRETPARPIS,
    :BDRETPARCOFINS,
    :BDRETPARCSLL,
    :BDRETPARIRRF,
    :BDRETPARISSQN,
    :BDRETPARINSS,
    :BDRETPARFUNRURAL,
    :bdtipoapuracao,
    :bdsomfrevlrcontab,
    :bdsomfrebaseicms,
    :bdcodplatroca,
    :bdcodplacfop,
    :bdcodconfblocop,
    :bdcredpresumido,
    :bdtermoaceite,
    :bdantecipaimposto,
    :BDTIPODECLARANTEDMED,
    :BDREGISTROANSDMED,
    :BDNUMEROCNESDMED,
    :BDDTOBRIGSPEDCONT,
    :BDTIPOAPURACAORET,
    :BDTIPOAPURACAORETIR,
    :BDDTOBRIGSPEDICMS,
    :BDCODCONTEF,
    :BDLIVRO,
    :BDFOLHA,
    :BDNOMECARTORIO,
    :BDLANCAPARCELAAUTO,
    :BDCODIGOPLA,
    :BDINDATIV,
    :BDIMPORTARVALORESICMSSN,
    :BDDIFALIQ,
    :BDDIFALIQBASEEM,
    :BDANEXOVI,
    :BDCODPLATRIB,
    :BDCODPLAPADRAOREF,
    :BDINDNATPJ,
    :BDCODIBGE,
    :BDSOMAPISCOFVLRCONT,
    :BDSOMAIIVLRCONT,
    :BDMANTERPARCELAS,
    :bdcodplanoincons,
    :BDABRIRRATEIO,
    :BDNAOPERMITERATEIOGRUPO,
    :BDINTEGRANET,
    :BDSOMAIPIPROD,
    :BDSOMAICMSVLRCONT,
    :BDCODPLAE115,
    :BDCODCLATRI,
    :BDDATAOBRIGREINF,
    :BDSOMASTPROD,
    :BDCALCANTICMS,
    :BDCONSIPIBC,
    :BDIMPICMSST,
    :BDANEXOIII_2018,
    :BDANEXOIV_2018,
    :BDANEXOV_2018,
    :BDSTATUSEMP,
    :BDQTDBACKUPEMP,
    :BDIMPORTARISS,
    :BDINCORPORADORAS
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CONSULTASERVICOS) */
ALTER PROCEDURE SP_CONSULTASERVICOS(PRREFSER INTEGER,
PRCODOBRSER INTEGER)
 RETURNS(BDCODOBRSER INTEGER,
BDCHAVE INTEGER,
BDCLASSIFICACAO VARCHAR(60),
BDDESCRICAO VARCHAR(100),
BDPERIODICIDADE INTEGER,
BDDIA INTEGER,
BDANTECIPAR VARCHAR(5),
BDVENCE INTEGER,
BDALERTA INTEGER,
BDCRIACAO DATE,
BDEXTINTO DATE,
BDSITEGOVERNO VARCHAR(255),
BDPREVHORAS VARCHAR(6),
BDTIPO SMALLINT,
BDPREVDIAS INTEGER,
BDCODSIS INTEGER,
BDMESVENCE INTEGER,
BDENTREGA INTEGER,
BDTEMPOESTIMADO INTEGER,
BDSABDOMFER INTEGER,
BDPERISS NUMERIC(15,4),
BDPERIRRF NUMERIC(15,4),
BDPERCSLL NUMERIC(15,4),
BDPERCOF NUMERIC(15,4),
BDPERPIS NUMERIC(15,4),
BDDEDISS VARCHAR(5),
BDDEDIRRF VARCHAR(5),
BDDEDCSLL VARCHAR(5),
BDDEDCOFINS VARCHAR(5),
BDDEDPIS VARCHAR(5),
BDTIPSERV INTEGER,
BDCALCINSS VARCHAR(5),
BDSOFREREAJ VARCHAR(5),
BDDESCONTO VARCHAR(5),
BDVALORPADRAO DM_NUMERIC_15_2,
BDCODCOBSERV INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefser, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'ser.BDCODOBRSER, ';
  wSql = wSql||'ser.BDCHAVE, ';
  wSql = wSql||'ser.BDCLASSIFICACAO, ';
  wSql = wSql||'ser.BDDESCRICAO, ';
  wSql = wSql||'ser.BDPERIODICIDADE, ';
  wSql = wSql||'ser.BDDIA, ';
  wSql = wSql||'ser.BDANTECIPAR, ';
  wSql = wSql||'ser.BDVENCE, ';
  wSql = wSql||'ser.BDALERTA, ';
  wSql = wSql||'ser.BDCRIACAO, ';
  wSql = wSql||'ser.BDEXTINTO, ';
  wSql = wSql||'ser.BDSITEGOVERNO, ';
  wSql = wSql||'ser.BDPREVHORAS, ';
  wSql = wSql||'ser.BDTIPO, ';
  wSql = wSql||'ser.BDPREVDIAS, ';
  wSql = wSql||'ser.BDCODSIS, ';
  wSql = wSql||'ser.BDMESVENCE, ';
  wSql = wSql||'ser.BDENTREGA, ';
  wSql = wSql||'ser.BDTEMPOESTIMADO, ';
  wSql = wSql||'ser.BDSABDOMFER, ';
  wSql = wSql||'ser.BDPERISS, ';
  wSql = wSql||'ser.BDPERIRRF, ';
  wSql = wSql||'ser.BDPERCSLL, ';
  wSql = wSql||'ser.BDPERCOF, ';
  wSql = wSql||'ser.BDPERPIS, ';
  wSql = wSql||'ser.BDDEDISS, ';
  wSql = wSql||'ser.BDDEDIRRF, ';
  wSql = wSql||'ser.BDDEDCSLL, ';
  wSql = wSql||'ser.BDDEDCOFINS, ';
  wSql = wSql||'ser.BDDEDPIS, ';
  wSql = wSql||'ser.BDTIPSERV, ';
  wSql = wSql||'ser.BDCALCINSS, ';
  wSql = wSql||'ser.BDSOFREREAJ, ';
  wSql = wSql||'ser.BDDESCONTO, ';
  wSql = wSql||'refser.BDVALORPADRAO, ';
  wSql = wSql||'ser.BDCODCOBSERV ';
  wSql = wSql||'from VCT_BASE_SERVICO ser ';
  wSql = wsql||'left outer join VW_VCT_BASE_SERVICO_REF refser on (refser.bdcodobrser = ser.bdcodobrser) ';

  wwhere = '';

  IF (prcodobrser IS NOT NULL AND prcodobrser <> 0) THEN
     wwhere = wwhere || ' ser.bdcodobrser = '||prcodobrser;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By ser.BDCODOBRSER';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODOBRSER,
    BDCHAVE,
    BDCLASSIFICACAO,
    BDDESCRICAO,
    BDPERIODICIDADE,
    BDDIA,
    BDANTECIPAR,
    BDVENCE,
    BDALERTA,
    BDCRIACAO,
    BDEXTINTO,
    BDSITEGOVERNO,
    BDPREVHORAS,
    BDTIPO,
    BDPREVDIAS,
    BDCODSIS,
    BDMESVENCE,
    BDENTREGA,
    BDTEMPOESTIMADO,
    BDSABDOMFER,
    BDPERISS,
    BDPERIRRF,
    BDPERCSLL,
    BDPERCOF,
    BDPERPIS,
    BDDEDISS,
    BDDEDIRRF,
    BDDEDCSLL,
    BDDEDCOFINS,
    BDDEDPIS,
    BDTIPSERV,
    BDCALCINSS,
    BDSOFREREAJ,
    BDDESCONTO,
    BDVALORPADRAO,
    BDCODCOBSERV
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_CRIA_DADOSCALC_BAIXA) */
ALTER PROCEDURE SP_CRIA_DADOSCALC_BAIXA AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WLIQUIDO NUMERIC(18,6);
DECLARE VARIABLE WREFCOMP INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WDATAAUX DATE;
BEGIN
  /* Procedure Text */
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdcodemp IS NOT NULL;

  /* 1 - Terceiros */
  FOR SELECT bdcodemp,bdcodter,bdcodserv,bdliquido FROM vrhf_base_calc_terc
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp, wcodcol, wreferencia,NULL,1,NULL,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 2 - 13? salario */
  FOR SELECT bdcodemp,bdcodcol,bdref13,bdliquido FROM vrhf_emp_t13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,2,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 3 -  ad 13? */
  FOR SELECT bdcodemp,bdcodcol,bdrefa13,bdliquido FROM vrhf_emp_ta13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,3,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 4 -  ad sal */
  FOR SELECT bdcodemp,bdcodcol,BDDATAAD,bdliquido FROM vrhf_emp_tadsal
   INTO
     :wcodemp,
     :wcodcol,
     :wdata,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,4,NULL,wdata,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 5 -  c 13? */
  FOR SELECT bdcodemp,bdcodcol,bdrefc13,bdref13,bdliquido FROM vrhf_emp_tc13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wrefcomp,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,5,wreferencia,NULL,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 6 - folha normal*/
  FOR SELECT bdcodemp,bdcodcol,bdreffn,bdliquido FROM vrhf_emp_tfolhanormal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,6,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 7 - folha normal tomador */
  FOR SELECT bdcodemp,bdcodcol,bdreftomador,bdliquido FROM vrhf_emp_tfolhatomador
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,7,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 8 -  fc */
  FOR SELECT bdcodemp,bdcodcol,bdreffn,bdrefcomp,bdliquido,bddatapagfc FROM vrhf_emp_tfolhacomp
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wrefcomp,
     :wliquido,
     :wdata
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,8,wreferencia,wdata,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 9 -  fct */
  FOR SELECT x.bdcodemp,x.bdcodcol,x.bdreftomador,x.bdliquido,x.bdrefcomp,x.bddatapagfc FROM vrhf_emp_tfoltomcomp x
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido,
     :wrefcomp,
     :wdata
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,9,wreferencia,wdata,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 10 -  f?rias */
  FOR SELECT x.bdcodemp,x.bdcodcol,x.bdliquido,x.bdiniperaquisfe,x.bdcodfe,x.bdiniperaquisfe,x.bdrefpagabofe FROM VRH_EMP_TFERIAS x
   INTO
     :wcodemp,
     :wcodcol,
     :wliquido,
     :wdata,
     :wreferencia,
     :wdataaux,
     :wrefcomp
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,10,NULL,NULL,NULL,wdata,wreferencia,wliquido,wdataaux,wrefcomp);
  END
END
^

/* Alter (SP_EXP_SEFIP) */
ALTER PROCEDURE SP_EXP_SEFIP(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRDATARECFGTS DATE,
PRDATARECINSS DATE,
PRTIPOFOLHA INTEGER,
PRMODALIDADE VARCHAR(1),
PRINDRECFGST VARCHAR(1),
PRINDRECINSS VARCHAR(1))
 RETURNS(BDARQ INTEGER,
BDREG VARCHAR(360),
BDORDEM VARCHAR(70),
BDINC VARCHAR(32000),
BDCONTADOR INTEGER,
BDCODREC INTEGER,
BDMODALIDADE VARCHAR(1))
 AS
DECLARE VARIABLE windrecinss VARCHAR(1);
DECLARE VARIABLE windrecfgts VARCHAR(1);
DECLARE VARIABLE wmodalidade VARCHAR(1);
DECLARE VARIABLE wsqlcalc VARCHAR(32000);
DECLARE VARIABLE wparsqlcalc VARCHAR(32000);
DECLARE VARIABLE wsqlemp VARCHAR(32000);
DECLARE VARIABLE wempatu INTEGER;
DECLARE VARIABLE wcodrecatu INTEGER;
DECLARE VARIABLE wcodrecsqlatu INTEGER;
DECLARE VARIABLE wwhereemp VARCHAR(32000);
BEGIN
  /* Procedure Text */
  /* prtipoFolha
     0 = normal
     1 = folha complementar
     2 = 13 sal
  */
  wmodalidade = prmodalidade;

  windrecfgts = prindrecfgst;
  windrecinss = prindrecinss;

  IF (windrecfgts IS NULL) THEN
     windrecfgts = '1';

  IF (windrecinss IS NULL) THEN
     windrecinss  = '1';

  IF (prtipofolha IS NULL) THEN
     prtipofolha = 0;

  rdb$set_context('USER_TRANSACTION', 'W_TIPOFOLHA', :prtipofolha);

  rdb$set_context('USER_TRANSACTION', 'W_MODALIDADE', :wmodalidade);

  rdb$set_context('USER_TRANSACTION', 'W_INDRECFGTS', :windrecfgts);
  rdb$set_context('USER_TRANSACTION', 'W_INDRECINSS', :windrecinss);

  IF (prdatarecfgts IS NOT NULL) THEN
     rdb$set_context('USER_TRANSACTION', 'W_DATARECFGTS', :prdatarecfgts );

  IF (prdatarecinss IS NOT NULL) THEN
     rdb$set_context('USER_TRANSACTION', 'W_DATARECINSS', :prdatarecinss);

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  rdb$set_context('USER_TRANSACTION', 'W_ANOMESPAG', :pranomespag);

  WPARSQLCALC = '';

  wsqlemp = 'select colcon.bdcodemp,case when colcon.bdcodsefipemp is null then 115 else colcon.bdcodsefipemp end from VW_VRHF_BASE_TEMPSEFIP colcon ';
  IF (prcodemp IS NOT NULL) THEN
     wsqlemp = wsqlemp||' where '||prcodemp;

  wsqlemp = wsqlemp||' order by colcon.bdcodsefipemp, colcon.bdcodemp';

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  IF (prtipofolha IS NULL) THEN
     prtipofolha = 0;

  wcodrecsqlatu = -1;
  wwhereemp = '';
  FOR EXECUTE STATEMENT wsqlemp
  INTO
    : wempatu,
    : wcodrecatu
  DO
    BEGIN
      IF ((wcodrecatu IS NULL) OR (wcodrecatu = 0) ) THEN
         wcodrecatu = 115;

      IF ((wcodrecatu = wcodrecsqlatu) OR (wcodrecsqlatu = -1)) THEN
         BEGIN
           wcodrecsqlatu = wcodrecatu;
           IF (CHAR_LENGTH(wwhereemp)>0) THEN
              wwhereemp = wwhereemp||',';
           wwhereemp = wwhereemp||CAST(wempatu AS VARCHAR(10));
         END
      ELSE
         BEGIN
           WPARSQLCALC = ''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';
           wsqlcalc = 'select bdarq,bdreg,bdinc,bdordem,bdcontador,bdcodrec,bdmodalidade from sp_exp_sefip_codrec(';
           wparsqlcalc = wparsqlcalc||',';
           IF (prcodcol IS NULL) THEN
              wparsqlcalc = wparsqlcalc||'null';
           ELSE
              wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
           wparsqlcalc = wparsqlcalc||','||CAST(wcodrecsqlatu AS VARCHAR(10));

           wsqlcalc = wsqlcalc||wparsqlcalc||')';

           FOR EXECUTE STATEMENT wsqlcalc
           INTO
             : bdarq,
             : bdreg,
             : bdinc,
             : bdordem,
             : bdcontador,
             : bdcodrec,
             : bdmodalidade
           DO
             SUSPEND;

           /*proximo sql*/
           wcodrecsqlatu = wcodrecatu;
           wwhereemp = CAST(wempatu AS VARCHAR(10));
         END
    END

   WPARSQLCALC = ''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';

   wsqlcalc = 'select bdarq,bdreg,bdinc,bdordem,bdcontador,bdcodrec,bdmodalidade from sp_exp_sefip_codrec(';
   wparsqlcalc = wparsqlcalc||',';
   IF (prcodcol IS NULL) THEN
       wparsqlcalc = wparsqlcalc||'null';
   ELSE
       wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
   wparsqlcalc = wparsqlcalc||','||CAST(wcodrecsqlatu AS VARCHAR(10));

   wsqlcalc = wsqlcalc||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsqlcalc
   INTO
     : bdarq,
     : bdreg,
     : bdinc,
     : bdordem,
     : bdcontador,
     : bdcodrec,
     : bdmodalidade
   DO
     SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL,NULL,NULL);

  DELETE FROM VRHF_EXP_SEFIP;
END
^

/* Alter (SP_EXP_SEFIP_MOVIMENTACAO_COL) */
ALTER PROCEDURE SP_EXP_SEFIP_MOVIMENTACAO_COL(PRREFINI INTEGER = 0,
PRREFFIM INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA DATE,
BDDATASTR VARCHAR(10),
BDMOTIVO VARCHAR(5),
BDINDFGTS INTEGER,
BDCODMFG INTEGER,
BDDATAFIM DATE,
BDINSSINTSIT DM_BOOLEAN)
 AS
DECLARE VARIABLE WOK INTEGER;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WSQLQ1 VARCHAR(3000);
DECLARE VARIABLE WSQLAUX VARCHAR(1000);
DECLARE VARIABLE WSQLAUX2 VARCHAR(1000);
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WCOL INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WDATASTR VARCHAR(10);
DECLARE VARIABLE WMOTIVO VARCHAR(5);
DECLARE VARIABLE WCODMFG INTEGER;
DECLARE VARIABLE WCODSIT INTEGER;
DECLARE VARIABLE WPROJECAO DATE;
DECLARE VARIABLE WDATAFIMSIT DATE;
DECLARE VARIABLE WCODSIT2 INTEGER;
DECLARE VARIABLE WINSSINTSIT VARCHAR(5);
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wcodemp;
  IF (wcodemp IS NULL) THEN
     wcodemp = 0;

  SELECT rdb$get_context('USER_TRANSACTION', 'W_COLSEFIP') FROM rdb$database INTO wcodcol;
  IF (wcodcol IS NULL) THEN
     wcodcol = 0;

  IF (COALESCE(prrefini, 0) > 0 AND COALESCE(prreffim, 0) > 0) THEN
     BEGIN
       wanomes = prrefini;
       wdataini = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
     
       wanomes = prreffim;
       wmes = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5) AS SMALLINT);
       wano = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
       SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;
     
       wdatafim = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/'||
                  waux||
                  '/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
     END
  ELSE
     BEGIN
  SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;
  IF (wanomes IS NULL) THEN
     wanomes = 99999;
     
  wmes = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;
     
  wdataini = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
  wdatafim = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/'||
             waux||
             '/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
     END

  /* entrada em situacao */
  wsql = ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,'||
         '        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,'||
         '        sit.bdcodsit, sit.bddatafimsit '||
         ' from vrh_emp_tsitcol sit '||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol) '||
         ' where (((sit.bddatainisefip - 1)  between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)) or '||
         '(sit.bddatafimsit between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)))';

  IF (wcodemp > 0) THEN
     wsql = wsql||' and sit.bdcodemp = '||wcodemp;

  IF (wcodcol > 0) THEN
     wsql = wsql||' and sit.bdcodcol = '||wcodcol;
    
  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit DO
    BEGIN
      wdata = wdata + 1;
      wsqlq1 = 'select '||
                 'STD2.BDCODMFGENT, '||
                 'mot.BDCODSEFMFG, '||
                 'STD2.BDINSSINTSIT '||
               'from ( '||
                 'select BDCODSIT, MAX(BDDATASTD) BDDATASTD '||
                 'from vrh_base_tprepsit_dia '||
                 'where BDCODSIT = '||wcodsit||' and BDDATASTD <= '''||wdata||''' '||
                 'group by BDCODSIT '||
               ') STD '||
               'join vrh_base_tprepsit_dia STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD) '||
               'join vrh_base_tmotfgts mot on (mot.bdcodmfg = STD2.BDCODMFGENT) ';

      wdata = wdata -1;
      FOR EXECUTE STATEMENT wsqlq1 INTO :wcodmfg,:wmotivo,:winssintsit DO
        BEGIN
          -- Deve incluir a movimentacao Q1
          IF (UPPER(wmotivo) = 'Q2') THEN
             BEGIN
               BDINDFGTS  = NULL;
               wsqlaux = 'select first 1 SIT.BDCODEMP, SIT.BDCODCOL, '||
                                 'case '||
                                   'when (SIT.BDDATAINISEFIP - 1) < COL.BDDATAADMCOL then COL.BDDATAADMCOL '||
                                   'else (SIT.BDDATAINISEFIP - 1) '||
                                 'end BDDATAINISEFIP, '||
                                 '(select X.BDDDMMAAAA '||
                                  'from DDMMAAAA(case '||
                                                  'when (SIT.BDDATAINISEFIP - 1) < COL.BDDATAADMCOL then COL.BDDATAADMCOL '||
                                                  'else (SIT.BDDATAINISEFIP - 1) '||
                                                'end) X) DATA, SIT.BDCODSIT, SIT.BDDATAFIMSIT '||
                          'from VRH_EMP_TSITCOL SIT '||
                          'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = SIT.BDCODEMP) and (COL.BDCODCOL = SIT.BDCODCOL) '||
                          'where SIT.BDDATAFIMSIT <= '''||wdata||''' and '||
                                'SIT.BDCODEMP = '||wemp||' and '||
                                'SIT.BDCODCOL = '||wcol||' and '||
                                'SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 7) <= SUBSTRING(CAST('''||wdata||''' AS VARCHAR(10)) FROM 1 FOR 7) '||
                          'order by SIT.BDDATAINISEFIP DESC ';

               FOR EXECUTE STATEMENT wsqlaux INTO :bdcodemp, :bdcodcol, :bddata, :bddatastr, :wcodsit2, :bddatafim DO
                 BEGIN
                   IF (SUBSTRING(CAST(bddatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bddatafim AS VARCHAR(10)) FROM 6 FOR 2) < prrefini) THEN
                      BEGIN
                        wsqlaux2 = 'select STD2.BDCODMFGENT, MOT.BDCODSEFMFG, STD2.BDINSSINTSIT '||
                                   'from (select BDCODSIT, max(BDDATASTD) BDDATASTD '||
                                         'from VRH_BASE_TPREPSIT_DIA '||
                                         'where BDCODSIT = '||wcodsit2||' and '||
                                               'BDDATASTD <= '''||bddata||''' '||
                                         'group by BDCODSIT) STD '||
                                   'join VRH_BASE_TPREPSIT_DIA STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD) '||
                                   'join VRH_BASE_TMOTFGTS MOT on (MOT.BDCODMFG = STD2.BDCODMFGENT) '||
                                   'where MOT.BDCODSEFMFG = ''Q1''';
                        FOR EXECUTE STATEMENT wsqlaux2 INTO :bdcodmfg, :bdmotivo, :winssintsit DO
                          SUSPEND;
                      END
                 END
             END

          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = NULL;
          BDINSSINTSIT = winssintsit;
          SUSPEND;
        END
    END


  wsql = '';
    

  /* o mes todo em situacao */
  wsql = wsql||
         ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,'||
         '        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,'||
         '        sit.bdcodsit, sit.bddatafimsit '||
         ' from vrh_emp_tsitcol sit '||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol) '||
         ' where (sit.bddatainisefip - 1) < cast('||''''||wdataini||''''||' as date) and ((sit.bddatafimsit > cast('||''''||wdatafim||''''||' as date) or (sit.bddatafimsit is null))) ';

  IF (wcodemp > 0) THEN
     wsql = wsql||' and sit.bdcodemp = '||wcodemp;

  IF (wcodcol > 0) THEN
     wsql = wsql||' and sit.bdcodcol = '||wcodcol;
    
  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit DO
    BEGIN
      wdata = wdata + 1;
      wsqlq1 = 'select '||
                 'STD2.BDCODMFGENT, '||
                 'mot.BDCODSEFMFG, '||
                 'STD2.BDINSSINTSIT '||
               'from ( '||
                 'select BDCODSIT, MAX(BDDATASTD) BDDATASTD '||
                 'from vrh_base_tprepsit_dia '||
                 'where BDCODSIT = '||wcodsit||' and BDDATASTD <= '''||wdata||''' '||
                 'group by BDCODSIT '||
               ') STD '||
               'join vrh_base_tprepsit_dia STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD) '||
               'join vrh_base_tmotfgts mot on (mot.bdcodmfg = STD2.BDCODMFGENT) ';

      wdata = wdata -1;
      FOR EXECUTE STATEMENT wsqlq1 INTO :wcodmfg,:wmotivo,:winssintsit DO
        BEGIN
          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = NULL;
          BDINSSINTSIT = winssintsit;
          SUSPEND;
        END
    END


  wsql = '';
    

  /* saida de situacao */
  wsql = wsql||' select sit.bdcodemp,sit.bdcodcol,sit.bddatafimsit, (select x.bdddmmaaaa from ddmmaaaa(sit.bddatafimsit) x), sit.bdcodsit, sit.bddatafimsit '||
          ' from vrh_emp_tsitcol sit'||
          ' where sit.bddatafimsit between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

   IF (wcodemp > 0) THEN
      wsql = wsql||' and sit.bdcodemp = '||wcodemp;

   IF (wcodcol > 0) THEN
      wsql = wsql||' and sit.bdcodcol = '||wcodcol;

  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit DO
    BEGIN
      wdata = wdata + 1;
      wsqlq1 = 'select '||
                 'STD2.BDCODMFGENT, '||
                 'mot.BDCODSEFMFG, '||
                 'STD2.BDINSSINTSIT '||
               'from ( '||
                 'select BDCODSIT, MAX(BDDATASTD) BDDATASTD '||
                 'from vrh_base_tprepsit_dia '||
                 'where BDCODSIT = '||wcodsit||' and BDDATASTD <= '''||wdata||''' '||
                 'group by BDCODSIT '||
               ') STD '||
               'join vrh_base_tprepsit_dia STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD) '||
               'join vrh_base_tmotfgts mot on (mot.bdcodmfg = STD2.BDCODMFGSAI) ';

      wdata = wdata -1;
      FOR EXECUTE STATEMENT wsqlq1 INTO :wcodmfg,:wmotivo,:winssintsit DO
        BEGIN
          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = wdatafimsit;
          BDINSSINTSIT = winssintsit;
          SUSPEND;
        END
    END


  wsql = '';

  BDDATAFIM = NULL;

  /* rescisao */
  wsql = wsql||'SELECT res.bdcodemp,res.bdcodcol,res.bddatarescisao, (SELECT x.bdddmmaaaa FROM ddmmaaaa(res.bddatarescisao) x) Data,'||
         '       mot.bdcodsefmfg CodMovi, pres.bdgrrfpres, mot.BDCODMFG, res.bdprojecaoaviso '||
         ' FROM vrh_emp_trescisao res, vrh_base_tprepresc pres, VRH_BASE_TMOTFGTS mot'||
         ' where (pres.bdcodpres = res.bdcodpres)'||
         ' and (pres.bdcodmfg = mot.bdcodmfg)'||
--         ' FROM vrh_emp_trescisao res'||
--         ' INNER JOIN vrh_base_tprepresc pres ON (pres.bdcodpres = res.bdcodpres)'||
--         ' INNER JOIN VRH_BASE_TMOTFGTS mot ON (pres.bdcodmfg = mot.bdcodmfg)'||
--         ' where res.bddatarescisao between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)'||
         ' and ((res.bddatarescisao between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)) or '||
         ' (res.bdprojecaoaviso between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date))) ';

   IF (wcodemp > 0) THEN
      wsql = wsql||' and res.bdcodemp = '||wcodemp;

   IF (wcodcol > 0) THEN
      wsql = wsql||' and res.bdcodcol = '||wcodcol;


  wsql = wsql||' union all ';

  /* transferencia de entrada */
  wsql = wsql||'select tra.bdcodempdest,tra.bdcodcoldest,tra.bddatatrf, (select x.bdddmmaaaa from ddmmaaaa(tra.bddatatrf) x), '||''''||'N3'||''''||' CodMovi, null indfgts, mot.BDCODMFG, CAST(null as DATE) bdprojecaoaviso '||
               ' from vrh_emp_ttranscol tra, vrh_base_tprepRESc ptra, VRH_BASE_TMOTFGTS mot '||
               ' where  (ptra.bdcodpres = tra.bdcodptran)'||
               ' and (ptra.bdcodmfgent = mot.bdcodmfg)'||
--         '       from vrh_emp_ttranscol tra'||
--         ' inner join vrh_base_tpreptran ptra on (ptra.bdcodptran = tra.bdcodptran)'||
--         ' inner join VRH_BASE_TMOTFGTS mot on (ptra.bdcodmfg = mot.bdcodmfg)'||
--         ' where tra.bddatatrf between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)'||
         ' and tra.bddatatrf between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

  IF (wcodemp > 0) THEN
     wsql = wsql||' and tra.bdcodempdest = '||wcodemp;

  IF (wcodcol > 0) THEN
     wsql = wsql||' and tra.bdcodcoldest = '||wcodcol;

--  wsql = wsql||' union ';

  /* transferencia de saida */ /* vai estar na rescisao */
/*  wsql = wsql||'select tra.bddatatrf, (select x.bdddmmaaaa from ddmmaaaa(tra.bddatatrf) x), mot.bdcodsefmfg CodMovi, null indfgts'||
         '       from vrh_emp_ttranscol tra'||
         ' inner join vrh_base_tpreptran ptra on (ptra.bdcodptran = tra.bdcodptran)'||
         ' inner join VRH_BASE_TMOTFGTS mot on (ptra.bdcodmfg = mot.bdcodmfg)'||
         ' where tra.bddatatrf between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)'||
         ' and tra.bdcodempdest = '||wcodemp||
         ' and tra.bdcodcoldest = '||wcodcol;*/

  FOR EXECUTE STATEMENT wsql INTO
      : bdcodemp,
      : bdcodcol,
      : bddata,
      : bddatastr,
      : bdmotivo,
      : bdindfgts,
      : bdcodmfg,
      : wprojecao
    DO
  BEGIN
    wok = 1;

    IF (wprojecao IS NOT NULL) THEN
       BEGIN
         IF (wprojecao >= CAST(wdataini AS DATE) AND wprojecao <= CAST(wdatafim AS DATE) AND bddata < CAST(wdataini AS DATE)) THEN
            BEGIN
              bddata    = wprojecao;
              bddatastr = SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
                          SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                          SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 1 FOR 4);
            END
       END


    IF ((bdmotivo = 'Q2') AND (bddata <= wdataini)) THEN
       BEGIN
         -- Se movimentacao Q2 for iniciada em mes diferente ou no primeira dia do mes atual precisa buscar a ultima situacao Q1 existente para o colaborador
         SUSPEND;

         wsqlq1 = ' select first 1 sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,'||
                  '        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,'||
                  '        mot.bdcodsefmfg codmovi, null indfgts, mot.bdcodmfg, sit.bddatafimsit '||
                  ' from vrh_emp_tsitcol sit, vrh_base_tprepsit psit, vrh_base_tmotfgts mot, vrh_emp_tcolcon col '||
                  ' where (psit.bdcodsit = sit.bdcodsit) and (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol) and '||
                  '       (psit.bdcodmfgent = mot.bdcodmfg) and upper(mot.bdcodsefmfg) = '||''''||'Q1'||''''||
                  ' and (sit.bddatainisefip - 1) < cast('||''''||bddata||''''||' as date) ';
         wsqlq1 = wsqlq1||' and sit.bdcodemp = '||bdcodemp;
         wsqlq1 = wsqlq1||' and sit.bdcodcol = '||bdcodcol;
         wsqlq1 = wsqlq1||' order by bddatainisefip desc ';

         FOR EXECUTE STATEMENT wsqlq1 INTO : bdcodemp, : bdcodcol, : bddata, : bddatastr, : bdmotivo, : bdindfgts, : bdcodmfg, :bddatafim, :bdinssintsit DO
           SUSPEND;

         wok = 0;
       END

    IF (wok = 1) THEN
      SUSPEND;
  END
END
^

/* Alter (SP_EXPORTA_BLOCOC_CONTRIBUICOES) */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_CONTRIBUICOES(PRCODEMP VARCHAR(500),
PRCODPLAPADRAOREF INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100))
 AS
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WARQUIVOEMP VARCHAR(100);
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  PRCODEMP = PRCODEMP||',';
  WHILE (CHAR_LENGTH(:PRCODEMP) > 0) DO
    BEGIN
      wEmpAtu = TRIM(SUBSTRING(:PRCODEMP FROM 1 FOR POSITION(',', :PRCODEMP)-1));

      /*Cria arquivo da empresa que vai ser exportada*/
      wArquivoEmp = REPLACE(:PRARQUIVO, '.tmp', '_e='||:wEmpAtu||'.tmp');
      NEWFILE(:wArquivoEmp);

      /*SA?DA*/
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(:wEmpAtu, :PRCODPLAPADRAOREF, :PRDTINI, :PRDTFIM, :wArquivoEmp);

      PRCODEMP = SUBSTRING(:PRCODEMP FROM POSITION(',', :PRCODEMP)+1 FOR CHAR_LENGTH(:PRCODEMP));

      /*****************************************************************************
       *                           EXPORTANDO ARQUIVO                              *
       ****************************************************************************/
    
      OPENARQ(:wArquivoEmp);
    
      FOR SELECT E.BDLINHA
          FROM TEXPORTACAO_SPED E
          WHERE E.BDID = :wArquivoEmp
          ORDER BY E.BDCHAVEREG
          INTO :wLinha
      DO
        BEGIN
          WRITELNOA(:wLinha);
        END
    
      CLOSEARQ(:wArquivoEmp);
    END
END
^

/* Alter (SP_EXPORTA_BLOCOC_SAI_SPEDCONTR) */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(PRCODEMP INTEGER,
PRCODPLAPADRAOREF INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100))
 AS
/*DECLARE VARIABLE WCNPJEMP VARCHAR(18);*/
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WMIN INTEGER;
DECLARE VARIABLE WMAX INTEGER;
DECLARE VARIABLE WCHAVEREG VARCHAR(80);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WALIQPIS NUMERIC(15,6);
DECLARE VARIABLE WALIQCOFINS NUMERIC(15,6);
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
BEGIN
  --Pega da matriz
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));  
  
  SELECT FIRST 1 SPED.BDINCTRIB, SPED.BDCODCRIT
  FROM (
        SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ
        FROM vw_tempresas_ref tbem
        JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP)
        WHERE TBEM.BDCODEMP = :PRCODEMP
        GROUP BY BDCODMATRIZ
       ) EMP
  JOIN VW_INT_SPEDPISCOFINS_REF SPED ON(SPED.BDCODEMP = EMP.BDCODMATRIZ AND SPED.BDREFERENCIA <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')))
  ORDER BY SPED.BDREFERENCIA DESC
  INTO :wIncTrib, :wCodCrit;

  IF (NOT((:wIncTrib = 1) AND (:wCodCrit IN(1, 2)))) THEN
    BEGIN
      /*****************************************************************************
       *                                   C860                                    *
       ****************************************************************************/
      /*Salva os n?meros de documento menores e maiores por data de emissao e modelo na DLL, na hora de montar o registro busca os dados na DLL*/
      FREEANDNIL_C800(0);
      FOR SELECT S.BDDATAEMISSAO, MIN(S.BDNUMDOCINI) BDMIN, MAX(S.BDNUMDOCINI) BDMAX
          FROM VEF_EMP_TMOVSAI S
          WHERE S.BDCODEMP = :PRCODEMP
          AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
          AND S.BDMODELO = 59
          AND S.BDCODSITNF NOT IN(2, 3, 4, 5)
          GROUP BY S.BDDATAEMISSAO, S.BDMODELO
          INTO :wData, :wMin, :wMax
      DO
        BEGIN
          SETNUMDOC_C800(:wData, 59, :wMin, :wMax);
        END
    
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO, 'C860.'||(MOV.BDCODEMP||'_'||COALESCE(MOV.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO),
             'C860' BDREG,
             '|C860|59'||
             '|'||COALESCE(MOV.BDNRSERIE, '')|| --NR_SAT
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||MOV.BDNUMDOCINI|| --DOC_INI
             '|'||MOV.BDNUMDOCFIM|| --DOC_FIM
             '|'
      FROM (
            SELECT M.BDCODEMP, M.BDDATAEMISSAO,
                   GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) BDNUMDOCINI,
                   GETNUMDOC_C800_MAX(M.BDDATAEMISSAO, 59) BDNUMDOCFIM,
                   EQ.BDNRSERIE
            FROM VEF_EMP_TMOVSAI M
            LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = M.BDCODEMP AND EQ.BDCODEQUIPSAT = M.BDCODEQUIPSAT)
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND M.BDMODELO = 59
            AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
            GROUP BY M.BDCODEMP, M.BDDATAEMISSAO, BDNUMDOCINI, BDNUMDOCFIM, EQ.BDNRSERIE
           ) MOV;
    
      /*****************************************************************************
       *                                   C870                                    *
       ****************************************************************************/
      /*Grava os dados cfop, al?quota pis, al?quota cofins na DLL*/
      FOR SELECT 'C860.'||(MOV.BDCODEMP||'_'||COALESCE(EQ.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||MOV.BDNUMDOCINI||'_'||COALESCE(PRO.BDCODPROD, '')||'_'||LPAD(COALESCE(PIS.BDCSTPIS, ''), 3, '0')||'_'||LPAD(COALESCE(COF.BDCSTCOF, ''), 3, '0')||'_'||LPAD(COALESCE(PRO.BDCODPLAPADRAO, ''), 9, '0')||'_'||LPAD(COALESCE(PRO.BDCODTPLA, ''), 9, '0')) BDCHAVEREG,
                 MOV.BDCODNAT, PRO.BDALIQPIS, PRO.BDALIQCOFINS, MOV.BDCHAVE, MOV.BDORDEM
          FROM (
                SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODEQUIPSAT,
                       SAI.BDDATAEMISSAO, I.BDCODNAT, SAI.BDNUMDOCINI
                FROM (
                      SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEQUIPSAT,
                             MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI
                      FROM (
                            SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODEQUIPSAT, M.BDDATAEMISSAO,
                                   (SELECT GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) FROM RDB$DATABASE) BDNUMDOCINI
                            FROM VEF_EMP_TMOVSAI M
                            WHERE M.BDCODEMP = :PRCODEMP
                            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                            AND M.BDMODELO = 59
                            AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                           ) MOV
                     ) SAI
                JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
               ) MOV
          LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = MOV.BDCODEMP AND EQ.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT)
          LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
          LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
          LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
          INTO :wChaveReg, :wCodNat, :wAliqPIS, :wAliqCofins, :wChave, :wOrdem
      DO
        BEGIN
          SET_C870(:wChaveReg, :wAliqPIS, :wAliqCofins, :wCodNat, :wChave, :wOrdem);
        END

      DELETE FROM TMP_TOL_VEF_EMP_TMOVSAI;
    
      INSERT INTO TMP_TOL_VEF_EMP_TMOVSAI(BDCHAVESAI, BDORDEM, BDCHAVE, BDCODEMP)
      SELECT T.BDCHAVESAI, T.BDORDEM, MIN(T.BDCHAVE) BDCHAVE, T.BDCODEMP
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDMODELO = 59
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
           ) S
      JOIN TOL_VEF_EMP_TMOVSAI T ON(T.BDCODEMP = S.BDCODEMP AND T.BDCHAVESAI = S.BDCHAVE)
      GROUP BY T.BDCHAVESAI, T.BDORDEM, T.BDCODEMP;

      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCHAVE, BDCODEMP)
      SELECT :PRARQUIVO, MOV.BDCHAVEREG,
             'C870' BDREG,
             '|C870'||
             '|'||COALESCE(IIF(COALESCE(PRO_VINC.BDCODSAIDA, '') = '', PRO_VINC.BDCODPROD, PRO_VINC.BDCODSAIDA), '')|| --COD_ITEM
             '|'||COALESCE(SUBSTRING(GETCFOP_C870(MOV.BDCHAVEREG) FROM 1 FOR 4), '')|| --CFOP
             '|'||REPLACE(MOV.BDVLRITEM, '.', ',')|| --VL_ITEM
             '|'||REPLACE(MOV.BDVLRDESC, '.', ',')|| --VL_DESC
             '|'||COALESCE(LPAD(MOV.BDCSTPIS, 2, '0'), '')|| --CST_PIS
             '|'||REPLACE(MOV.BDBCPIS, '.', ',')|| --VL_BC_PIS
             '|'||COALESCE(REPLACE(CAST(IIF(MOV.BDALIQPIS = '', '0', MOV.BDALIQPIS) AS NUMERIC(8, 4)), '.', ','), '')|| --ALIQ_PIS
             '|'||REPLACE(MOV.BDVLRPIS, '.', ',')|| --VL_PIS
             '|'||COALESCE(LPAD(MOV.BDCSTCOF, 2, '0'), '')|| --CST_COFINS
             '|'||REPLACE(MOV.BDBCCOFINS, '.', ',')|| --VL_BC_COFINS
             '|'||COALESCE(REPLACE(CAST(IIF(MOV.BDALIQCOFINS = '', '0', MOV.BDALIQCOFINS) AS NUMERIC(8, 4)), '.', ','), '')|| --ALIQ_COFINS
             '|'||REPLACE(MOV.BDVLRCOFINS, '.', ',')|| --VL_COFINS
             '|'||COALESCE(COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON), '')|| --COD_CTA
             '|', PRO_VINC.BDCODPROD, COALESCE(ccl.bdcodtpla,cclrat.bdcodtpla) bdcredito, (SELECT BDDATA FROM SP_PARSE_DATE(LAN.BDDATA, 'YYYY')) bdanocredito,
                  COALESCE(MOV.bdcodplapadrao, lan.bdcodplapadrao) bdcodplapadrao, COALESCE(cclep.BDCODTPLAREF, ccderatp.BDCODTPLAREF) bdcreditoref,
                  COALESCE(cclep.BDCODPLAPADRAOREF, ccderatp.BDCODPLAPADRAOREF) bdcreditoplapadraoref, COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON,
                  MOV.BDCHAVE, MOV.BDCODEMP
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, MOV.BDCODPROD, MOV.BDCSTPIS, MOV.BDCSTCOF, MOV.BDCODPLAPADRAO, MOV.BDCODTPLA,
                   GETCHAVE_C870(MOV.BDCHAVEREG) BDCHAVE, GETORDEM_C870(MOV.BDCHAVEREG) BDORDEM, MOV.BDCHAVEREG, MOV.BDVLRITEM, MOV.BDVLRDESC, MOV.BDBCPIS, MOV.BDVLRPIS,
                   MOV.BDBCCOFINS, MOV.BDVLRCOFINS, GETALIQPIS_C870(MOV.BDCHAVEREG) BDALIQPIS, GETALIQCOFINS_C870(MOV.BDCHAVEREG) BDALIQCOFINS
            FROM (
                  SELECT MOV.BDCODEMP, EQ.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, PRO.BDCODPROD, PIS.BDCSTPIS, COF.BDCSTCOF, PRO.BDCODPLAPADRAO, PRO.BDCODTPLA,
                         ('C860.'||MOV.BDCODEMP||'_'||COALESCE(EQ.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||MOV.BDNUMDOCINI||'_'||COALESCE(PRO.BDCODPROD, '')||'_'||LPAD(COALESCE(PIS.BDCSTPIS, ''), 3, '0')||'_'||LPAD(COALESCE(COF.BDCSTCOF, ''), 3, '0')||'_'||LPAD(COALESCE(PRO.BDCODPLAPADRAO, ''), 9, '0')||'_'||LPAD(COALESCE(PRO.BDCODTPLA, ''), 9, '0')) BDCHAVEREG,
                         SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                         SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                         SUM(COALESCE(PRO.BDBCPIS, 0)) BDBCPIS,
                         SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPIS,
                         SUM(COALESCE(PRO.BDBCCOFINS, 0)) BDBCCOFINS,
                         SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINS
                  FROM (
                        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODEQUIPSAT,
                               SAI.BDDATAEMISSAO, SAI.BDNUMDOCINI
                        FROM (
                              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEQUIPSAT,
                                     MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI
                              FROM (
                                     SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODEQUIPSAT, M.BDDATAEMISSAO,
                                           (SELECT GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) FROM RDB$DATABASE) BDNUMDOCINI
                                    FROM VEF_EMP_TMOVSAI M
                                    WHERE M.BDCODEMP = :PRCODEMP
                                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                                    AND M.BDMODELO = 59
                                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                                   ) MOV
                             ) SAI
                        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                       ) MOV
                  LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = MOV.BDCODEMP AND EQ.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT)
                  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                  LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
                  LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
                  GROUP BY MOV.BDCODEMP, EQ.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, PRO.BDCODPROD, PIS.BDCSTPIS, COF.BDCSTCOF, PRO.BDCODPLAPADRAO, PRO.BDCODTPLA
                 ) MOV
           ) MOV
      JOIN TCADPRO_VINC PRO_VINC ON(PRO_VINC.BDCODEMP = MOV.BDCODEMP AND PRO_VINC.BDCODPROD = MOV.BDCODPROD)
      LEFT OUTER JOIN TMP_TOL_VEF_EMP_TMOVSAI TOL ON(TOL.BDCHAVESAI = MOV.BDCHAVE AND TOL.BDORDEM = MOV.BDORDEM)
      LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.BDCODEMP = tol.bdcodemp AND lan.bdchave = tol.BDCHAVE)
      LEFT OUTER JOIN planos_tpla ccl ON (COALESCE(MOV.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) = ccl.bdcodplapadrao AND COALESCE(MOV.bdcodtpla, lan.bdcredito) = ccl.bdcodtpla)
      LEFT OUTER JOIN PLANOS_TPLA_ECF ccle ON (ccle.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                               AND ccle.bdano = (SELECT FIRST 1 BDANO
                                                                 FROM PLANOS_TPLA_ECF
                                                                 WHERE CAST(BDANO || '01' AS INTEGER) <= lan.bdreferencia
                                                                 AND BDCODTPLAREF IS NOT NULL
                                                                 AND CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                 AND CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                 AND CCLE.BDCODTPLA = BDCODTPLA
                                                                 ORDER BY BDANO DESC
                                                                )
                                               AND ccle.bdcodplapadrao = ccl.bdcodplapadrao AND ccle.bdcodtpla = ccl.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cclep ON (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF AND ccle.BDCODTPLAREF = cclep.BDCODTPLAREF)
     LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) tolrat ON (tolrat.bdcodemp = mov.bdcodemp AND tolrat.bdchavelan = mov.bdchave AND tolrat.bdordem = mov.bdordem)
     LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.BDCODEMP = tolrat.bdcodemp AND lanrat.bdchave = tolrat.BDCHAVE)
     LEFT OUTER JOIN planos_tpla cclrat ON (lanrat.BDCODPLAPADRAO = cclrat.bdcodplapadrao AND lanrat.bdcredito = cclrat.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON (CCDERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                                 CCDERAT.bdano =(SELECT FIRST 1 BDANO 
                                                                 FROM PLANOS_TPLA_ECF 
                                                                 WHERE CAST(BDANO || '01' AS INTEGER) <= lanrat.bdreferencia AND 
                                                                   BDCODTPLAREF IS NOT NULL AND 
                                                                   CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                                   CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                                   CCDERAT.BDCODTPLA = BDCODTPLA 
                                                                 ORDER BY BDANO DESC
                                                                ) AND
                                                 ccderat.bdcodplapadrao = cclrat.bdcodplapadrao AND ccderat.bdcodtpla = cclrat.bdcodtpla)
     LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO ccderatp ON (ccderat.BDCODPLAPADRAOref = ccderatp.BDCODPLAPADRAOREF AND ccderat.BDCODTPLAREF = ccderatp.BDCODTPLAREF);

      /*****************************************************************************
       *                                   C890                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO, MOV.BDCHAVEREG,
             'C890' BDREG,
             '|C890'||
             '|'||COALESCE(MOV.BDNUMPROC, '')|| --NUM_PROC
             '|'||COALESCE(MOV.BDINDORIG, '')||  --IND_PROC
             '|'
      FROM (
            SELECT ('C860.'||MOV.BDCODEMP||'_'||COALESCE(MOV.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||'99999999_'||'99999999_'||'999_'||'999_999999999_999999999.C890.'||C890.BDNUMPROC||'_'||IND.BDINDORIG) BDCHAVEREG,
                   C890.BDNUMPROC, IND.BDINDORIG
            FROM (
                  SELECT M.BDCODEMP, M.BDDATAEMISSAO,
                         GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) BDNUMDOCINI,
                         GETNUMDOC_C800_MAX(M.BDDATAEMISSAO, 59) BDNUMDOCFIM,
                         EQ.BDNRSERIE,
                         EQ.BDCODEQUIPSAT
                  FROM VEF_EMP_TMOVSAI M
                  LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = M.BDCODEMP AND EQ.BDCODEQUIPSAT = M.BDCODEQUIPSAT)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDMODELO = 59
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                  GROUP BY M.BDCODEMP, M.BDDATAEMISSAO, M.BDCODEQUIPSAT, BDNUMDOCINI, BDNUMDOCFIM, EQ.BDNRSERIE, EQ.BDCODEQUIPSAT
                 ) MOV
            JOIN VEF_EMP_TPROCREFC890 C890 ON (C890.BDCODEMP = MOV.BDCODEMP AND C890.BDCHAVE = (SELECT FIRST 1 C.BDCHAVE
                                                                                                FROM VEF_EMP_TPROCREFC890 C
                                                                                                WHERE c.BDCODEMP = mov.BDCODEMP
                                                                                                AND c.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT
                                                                                                AND c.BDDTINIVIG <= mov.BDDATAEMISSAO
                                                                                                AND ((c.BDDTFINVIG IS NULL) OR (c.BDDTFINVIG >= mov.BDDATAEMISSAO))
                                                                                                ORDER BY C.BDDTINIVIG))
            LEFT OUTER JOIN VEF_BASE_TTABINDORIG IND ON (IND.BDORDEMINDORIG = C890.BDORDEMINDORIG)
           ) MOV;

      /*Destruindo a lista da DLL*/
--      FREEANDNIL_C800(0);
      DELETE FROM TMP_TOL_VEF_EMP_TMOVSAI;
    END
END
^

/* Alter (SP_EXPORTA_ISS_CURITIBA) */
ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRTIPOLANC INTEGER,
PRRETIFICADORA INTEGER,
PRARQUIVO VARCHAR(100))
 AS
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200 CHARACTER SET UTF8;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- REGISTRO HEADER ? ?H?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, r.bdCODEMP, 1, '000000',                                   -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                      OBSERVA??ES
--SELECT :prARQUIVO, r.bdCODEMP, 1, r.bdCODEMP,                                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                      OBSERVA??ES
         'H'||                                                                  -- H.01     1 -   1  Caracter(1)   C?digo do registro ?H?                                                         Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                  (COALESCE(r.bdIMEMP,''))), 10, '0')||         -- H.02     2 -  11  Num?rico(10)  N?mero da Inscri??o Municipal do Declarante                                    Formato: 9999999999 Exemplo: 65985-1 No arquivo ficar?: 0000659851 Campo N?o Obrigat?rio.
         LPAD(IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,'')))) >= 14,
                  (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,''))),
                  ''), 14, '0')||                                               -- H.03    12 -  25  Num?rico(14)  N?mero do CNPJ do Declarante no caso de pessoa jur?dica                        Formato: 99999999999999 Campo Obrigat?rio quando o campo H.02 ou H.04 n?o for preenchido
         LPAD(IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,'')))) < 14,
                  (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,''))),
                  ''), 11, '0')||                                               -- H.04    26 -  36  Num?rico(11)  N?mero do CPF do Declarante no caso de pessoa f?sica                           Obs.: Se o campo H.02 ou H.03 n?o for informado, ent?o este campo ser? obrigat?rio Formato: 99999999999
         RPAD(COALESCE(r.bdNOMEMP,''), 100, ' ')||                              -- H.05    37 - 136  Caracter(100) Nome/Raz?o Social do Declarante                                                Campo Obrigat?rio.
         'N'||                                                                  -- H.06   137 - 137  Caracter(1)   Tipo do Arquivo enviado para a Prefeitura, podendo ser: N ? normal, T ? Teste  Campo Obrigat?rio.
         SUBSTRING(:prREFERENCIA FROM 5 FOR 2)||                                -- H.07   138 - 139  Num?rico (2)  M?s de refer?ncia dos documentos declarados                                    Campo Obrigat?rio.
         SUBSTRING(:prREFERENCIA FROM 1 FOR 4)||                                -- H.08   140 - 143  Num?rico(4)   Ano de refer?ncia dos documentos declarados                                    Campo Obrigat?rio.
         RPAD('', 252, ' ')||                                                   -- H.09   144 - 395  Caracter(252) Brancos ? reservado para futuro                                                Campo Obrigat?rio.
         '.'                                                                    -- H.10   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                      Campo obrigat?rio que indica o final do registro.
  FROM VW_EMPRESAS_REF_ATUAL r
  WHERE r.bdCODEMP = :prCODEMP;

  -- REGISTRO DOCUMENTOS EMITIDOS CANCELADOS ? ?C?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, s.bdCODEMP, 2, LPAD(COALESCE((SELECT COUNT(*)              -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                        OBSERVA??ES
                                                   FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, s.bdCODEMP, 2, s.bdCODEMP||'.'||s.bdCHAVE,                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                        OBSERVA??ES
         'C'||                                                                  -- C.01     1 -   1  Caracter(1)   C?digo do registro ?C?                           Campo Obrigat?rio
         COALESCE((SUBSTRING(s.bdDATACANC FROM 9 FOR 2)||
                   SUBSTRING(s.bdDATACANC FROM 6 FOR 2)||
                   SUBSTRING(s.bdDATACANC FROM 1 FOR 4)),'00000000')||          -- C.02     2 -   9  Num?rico(8)   Data do cancelamento  da nota fiscal emitida.    Campo Obrigat?rio Formato: DDMMAAAAA
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCINI,'') FROM 1 FOR 8), 8, '0')||     -- C.03    10 -  17  Num?rico(8)   N?mero da nota fiscal inicial cancelada          Campo Obrigat?rio
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCFIM,'') FROM 1 FOR 8), 8, '0')||     -- C.04    18 -  25  Num?rico(8)   N?mero da nota fiscal final cancelada            Dever? ser informado somente quando houver um agrupamento de notas canceladas.
         RPAD(SUBSTRING(COALESCE(s.bdSERIE,'') FROM 1 FOR 3), 3, ' ')||         -- C.05    26 -  28  Caracter(3)   S?rie da Nota Fiscal cancelada                   Campo Obrigat?rio
         RPAD('', 361, ' ')||                                                   -- C.06    29 - 389  Caracter(361) Reservado para futuro
         LPAD(COALESCE((SELECT COUNT(*)
                        FROM TEXPORTACAO_ISS_CURITIBA),1), 6, '0')||            -- C.07   390 - 395  Num?rico(6)   N?mero seq?encial do registro dentro do arquivo. Campo Obrigat?rio.
         '.'                                                                    -- C.08   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                        Campo obrigat?rio que indica o final do registro.
  FROM VEF_EMP_TMOVSER s
  WHERE s.bdCODEMP = :prCODEMP
    AND s.bdTIPLAN = 0 -- Apenas servi?os Emitidos
    AND s.bdCODSITNF IN (2,3,4,5) -- Notas canceladas
    AND s.bdDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM;

  -- REGISTRO DOCUMENTOS EMITIDOS DECLARADOS ? ?E?
  IF (:prTIPOLANC IN (0,1)) THEN -- 0 = Ambos (emitidos/recebidos) / 1 = Somente emitidos
    EXECUTE PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (:prCODEMP, :prREFERENCIA, :prDTINI, :prDTFIM, :prTIPOLANC, :prRETIFICADORA, :prARQUIVO, 0);

  -- REGISTRO DOCUMENTOS RECEBIDOS DECLARADOS ? ?R?
  IF (:prTIPOLANC IN (0,2)) THEN -- 0 = Ambos (emitidos/recebidos) / 2 = Somente recebidos
    EXECUTE PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (:prCODEMP, :prREFERENCIA, :prDTINI, :prDTFIM, :prTIPOLANC, :prRETIFICADORA, :prARQUIVO, 1);

  -- REGISTRO HEADER ? ?T?
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, c.bdCODEMP, 5, LPAD(COALESCE((SELECT COUNT(*)              -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                                                                        OBSERVA??ES
                                                   FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, c.bdCODEMP, 5, c.bdCODEMP,                                 -- CAMPOS  POSI??ES  TIPO/TAMANHO  DESCRI??O                                                                                                                        OBSERVA??ES
         'T'||                                                                  -- T.01     1 -   1  Caracter(1)   C?digo do registro ?T?                                                                                                           Campo Obrigat?rio
         LPAD(COUNT(*)+1, 8, '0')||                                             -- T.02     2 -   9  Num?rico(8)   Quantidade total de registros do arquivo, incluindo o header (H) e trailler (T)                                                  Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLREMIT,0)))), 15, '0')||        -- T.03    10 -  24  Num?rico(15)  Valor Total dos Documentos emitidos  pelo Prestador de Servi?os. Soma de todos os valores descritos nos campos E.11              Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRDEDEMIT,0)))), 15, '0')||     -- T.04    25 -  39  Num?rico(15)  Valor Total das Dedu??es dos Documentos emitidos pelo Prestador de Servi?os. Soma de todos os valores descritos nos campos E.12  Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRRECEB,0)))), 15, '0')||       -- T.05    40 -  54  Num?rico(15)  Valor Total dos Documentos recebidos  pelo tomador de Servi?os. Soma de todos os valores descritos nos campos R.11               Campo Obrigat?rio
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRDEDRECEB,0)))), 15, '0')||    -- T.06    55 -  69  Num?rico(15)  Valor Total das Dedu??es dos Documentos recebidos  pelo tomador de Servi?os. Soma de todos os valores descritos nos campos R.12  Campo Obrigat?rio
         RPAD('', 326, ' ')||                                                   -- T.07    70 - 395  Caracter(326) Brancos ? reservado para futuro
         '.'                                                                    -- T.08   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                                                                        Campo obrigat?rio que indica o final do registro.
  FROM TEXPORTACAO_ISS_CURITIBA c
  WHERE c.bdCODEMP = :prCODEMP
  GROUP BY c.bdCODEMP;

  -- Exporta arquivo...
  OPENARQ(:prARQUIVO);

  FOR
    SELECT e.bdLINHA
    FROM TEXPORTACAO_ISS_CURITIBA E
    WHERE e.bdID = :prARQUIVO
    ORDER BY e.bdORDEMREG, e.bdORDEM
    INTO :wLINHA
  DO
    BEGIN
      WRITELNOA(:WLINHA);
    END

  CLOSEARQ(:prARQUIVO);

  DELETE FROM TEXPORTACAO_ISS_CURITIBA;

END
^

/* Alter (SP_FERIADO_EMPRESA) */
ALTER PROCEDURE SP_FERIADO_EMPRESA(PRCODEMP INTEGER,
PRDATA DATE,
PRREFERENCIA INTEGER = 0,
PRSINDICATO INTEGER = 0)
 RETURNS(BDFERIADO VARCHAR(5))
 AS
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WCIDFER INTEGER;
DECLARE VARIABLE WUFFER INTEGER;
DECLARE VARIABLE WSINDFER INTEGER;
DECLARE VARIABLE WRETURN VARCHAR(5);
BEGIN
  IF ((prreferencia IS NULL) OR (prreferencia = 0)) THEN
     wref = CAST((SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     wref = prreferencia;

  wcodcid = NULL;
  wcoduf  = NULL;
  EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
  SELECT EMP.BDCODCID, CID.BDCODUF FROM VW_TEMPRESAS_REF EMP LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) WHERE EMP.BDCODEMP = :prcodemp INTO :wcodcid,:wcoduf;
  wreturn = 'FALSE';
  FOR SELECT BDCODSINTRAB,BDCODCID,BDCODUF FROM sp_tferiados(:wref, :wref) WHERE BDDATAFER = :prdata INTO :wsindfer,:wcidfer,wuffer DO
    BEGIN
      IF (wsindfer IS NULL AND wcidfer IS NULL AND wuffer IS NULL) THEN  -- Feriado nacional
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wcidfer IS NOT NULL AND wcodcid IS NOT NULL AND wcidfer = wcodcid) THEN  -- Feriado municipal
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wcidfer IS NULL AND wcoduf IS NOT NULL AND wuffer = wcoduf) THEN  -- Feriado estadual
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wsindfer IS NOT NULL AND prsindicato IS NOT NULL AND wsindfer = prsindicato) THEN  -- Feriado sindical
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
    END

  bdferiado = wreturn;
  SUSPEND;
END
^

/* Alter (SP_FICHA_REGISTROS_SALARIOS) */
ALTER PROCEDURE SP_FICHA_REGISTROS_SALARIOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRREF INTEGER,
PRRETORNAVAZIO INTEGER,
PRTRAZERSALINI INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDSALINICOL NUMERIC(18,6),
BDDATACOL DATE,
BDSALBASECOL NUMERIC(18,6),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODTFUC INTEGER,
BDCODSHE INTEGER,
BDDESCSHE VARCHAR(50),
BDSALBASEANT NUMERIC(18,6))
 AS
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATAADMCOL date;
declare variable WSALINICOL numeric(18,6);
declare variable WDATACOL date;
declare variable WSALBASECOL numeric(18,6);
declare variable WCODMAS integer;
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(30000);
declare variable WCONT integer;
declare variable WDESCMAS varchar(50);
declare variable WCODTFUC integer;
declare variable WCODSHE integer;
declare variable WTIPOCOL integer;
declare variable WDESCSHE varchar(50);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WWHERE varchar(500);
BEGIN
  BDSALBASEANT = 0;

  IF (PRRETORNAVAZIO = 1) THEN
     BEGIN
       EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);
       WSQL = ' select BDCODEMP, BDCODCOL, BDTIPOCOL from VW_VRHF_EMP_TCOL_CALC COL ';

       -- 14269 - Marcelo B. M. - 23/06/2016: Ajustado para aceitar mais de uma empresa e/ou colaborador
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
             WSQL = WSQL || ' where '||prcodemp;
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' and '||PRCODCOL;
          END
       ELSE
          BEGIN
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' where '||PRCODCOL;
          END

       FOR EXECUTE STATEMENT wsql INTO
         WCODEMP,
         WCODCOL,
         WTIPOCOL
       DO
       BEGIN
         --Sol. 17643 - Bruno L. R. - 01/08/2017
         IF (WTIPOCOL = 4) THEN
            BEGIN
              WSQL2 = 'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, SHE.BDSALSHE bdsalinicol, SHE.BDDATASHE BDDATACOL, SHE.BDSALSHE BDSALBASECOL, SHE.bdcodshe bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe,  CAST(null as varchar(50)) BDDESCSHE  ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_SHE SHE on (SHE.bdcodemp = COL.bdcodemp and SHE.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = SHE.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = SHE.bdcodemp and VINCDIA.bdcodcol = SHE.bdcodcol and VINCDIA.BDDATACOL = SHE.BDDATASHE) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              WSQL2 = WSQL2 || ' union select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, '||
                      ' HIST.BDSALBASEHAUMHE,  HIST.bdcodshe bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = col.bdcodemp and VINCDIA.bdcodcol = col.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUMHE) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              /*
              WCAMPOSSHE = ' HIST.BDSALBASEANTHAUMHE bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, HIST.BDSALBASEHAUMHE BDSALBASECOL, HIST.bdcodmas, MAUMSAL.BDDESCMAS,'||
                           ' VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE ';
              WJOINSHE = ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) '||
                         ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = HIST.bdcodmas) '||
                         ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WCAMPODATA = 'HIST.BDDATAHAUMHE';      */
            END
          ELSE
            BEGIN
              WSQL2 = 'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, CALC.BDDATACOL, CALC.BDSALBASECOL, CALC.bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOLCON_CALCDIA CALC on (CALC.bdcodemp = COL.bdcodemp and CALC.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = CALC.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = CALC.bdcodemp and VINCDIA.bdcodcol = CALC.bdcodcol and VINCDIA.BDDATACOL = CALC.BDDATACOL) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              WSQL2 = WSQL2 || ' union select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUM BDDATACOL, HIST.BDSALBASEHAUM, '||
                      ' HIST.bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUM HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = COL.bdcodemp and VINCDIA.bdcodcol = COL.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUM) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;
            END
         --Sol. 17643 - Bruno L. R. - 01/08/2017

           wempatu = 0;
           wcolatu = 0;

           WCONT = 0;
           FOR EXECUTE STATEMENT WSQL2 INTO
             WCODEMP,
             WCODCOL,
             WDATAADMCOL,
             WSALINICOL,
             WDATACOL,
             WSALBASECOL,
             WCODMAS,
             WDESCMAS,
             WCODTFUC,
             WCODSHE,
             WDESCSHE
           DO
           BEGIN
             IF (wcont = 0) THEN
                BEGIN
                   BDCODEMP = WCODEMP;
                   BDCODCOL = WCODCOL;
                   BDDATAADMCOL = WDATAADMCOL;
                   IF (WSALINICOL IS NULL) THEN
                      BDSALINICOL = 0;
                   ELSE
                      BDSALINICOL = WSALINICOL;
                   BDDATACOL = WDATACOL;
                   BDSALBASEANT = NULL;   --Sol. 17798 - Bruno L. R. - 05/04/2017
                   BDSALBASECOL = WSALBASECOL;

                   IF ((WDATACOL = WDATAADMCOL) OR (BDSALBASEANT IS NULL)) THEN   --Sol. 18509 - Bruno L. R. - 26/07/2017
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admiss?o';

                        --IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                          -- BDSALBASECOL = BDSALINICOL;

                       -- IF (BDSALBASECOL IS NOT NULL) THEN
                         --  BDSALINICOL = BDSALBASECOL;
                      END
                   ELSE
                     BEGIN
                       BDCODMAS = WCODMAS;
                       BDDESCMAS = WDESCMAS;
                     END

                   IF (BDDATACOL IS NULL) THEN
                      BDDATACOL = BDDATAADMCOL;

                   IF (BDSALBASEANT = BDSALINICOL) THEN
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admiss?o';
                        BDDATACOL = WDATAADMCOL;
                      END

                   BDCODSHE = WCODSHE;
                   BDDESCSHE = WDESCSHE;
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL = BDSALINICOL) AND (WTIPOCOL = 4))) THEN
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL <> BDSALINICOL) OR (BDSALBASECOL IS NULL))) THEN
                   IF ((PRTRAZERSALINI = 1) AND (BDSALINICOL <> 0)) THEN
                      begin
                        if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                           begin
                             wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                      ' and BDREFCOL <= '||prref||
                                      ' order by BDREFCOL DESC';
                             execute statement wwhere into :BDNOMCOL;
           
                             wempatu = wcodemp;
                             wcolatu = wcolatu;
                           end

                        SUSPEND;
                      end
                END
             ELSE
                BEGIN
                --  IF ((BDCODEMP <> WCODEMP) OR (BDCODCOL <> WCODCOL) OR (BDSALBASECOL <> WSALBASECOL) OR (BDCODMAS <> WCODMAS)) THEN   --Sol. 18509 - Bruno L. R. - 03/07/2017
                 -- BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        BDDATAADMCOL = WDATAADMCOL;
                        IF (WSALINICOL IS NULL) THEN
                           BDSALINICOL = 0;
                        ELSE
                           BDSALINICOL = WSALINICOL;
                        BDDATACOL = WDATACOL;
                        BDSALBASEANT = BDSALBASECOL;     --Sol. 17798 - Bruno L. R. - 04/04/2017
                        BDSALBASECOL = WSALBASECOL;

                       IF ((WDATACOL = WDATAADMCOL) OR (BDSALBASEANT IS NULL)) THEN    --Sol. 18509 - Bruno L. R. - 10/07/2017
                          BEGIN
                            BDCODMAS = 0;
                            BDDESCMAS = 'Admiss?o';

                         --   IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                           --    BDSALBASECOL = BDSALINICOL;
                          END
                       ELSE
                         BEGIN
                           BDCODMAS = WCODMAS;
                           BDDESCMAS = WDESCMAS;
                         END

                        BDCODTFUC = WCODTFUC;
                        BDCODSHE = WCODSHE;
                        BDDESCSHE = WDESCSHE;

                        IF (BDDATACOL IS NULL) THEN
                           BDDATACOL = BDDATAADMCOL;

                        IF (BDSALBASEANT = BDSALINICOL) THEN
                           BEGIN
                             BDCODMAS = 0;
                             BDDESCMAS = 'Admiss?o';
                       --      BDDATACOL = WDATAADMCOL;
                           END

                        IF (BDSALBASEANT <> BDSALBASECOL) THEN
                           BEGIN
                             BDCODMAS = WCODMAS;
                             BDDESCMAS = WDESCMAS;
                           END

                       IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND ((BDSALBASECOL <> BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR
                          ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN
                          begin
                            if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                               begin
                                 wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                          ' and BDREFCOL <= '||prref||
                                          ' order by BDREFCOL DESC';
                                 execute statement wwhere into :BDNOMCOL;
               
                                 wempatu = wcodemp;
                                 wcolatu = wcolatu;
                               end

                            SUSPEND;
                          end
                   --  END
                END
    
             WCONT = 1;
           END
       END
     END
   ELSE
     SUSPEND;
END
^

/* Alter (SP_FUNCOES_PLANO_EMP) */
ALTER PROCEDURE SP_FUNCOES_PLANO_EMP(PRCODEMP INTEGER,
PRCODPLAFUC INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODCBO INTEGER,
BDDESCCBO VARCHAR(150),
BDDESCTFUC VARCHAR(40),
BDCODCBOTSIN INTEGER,
BDDESCFUNCDET VARCHAR(100),
BDINATIVA VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FUC.BDCODTFUC, '||
                'FUC.bdcodplafuc, '||
                'FUC.BDCODCBO, '||
                'FUC.BDCODCBOTSIN, '||
                'case when (CBO.BDDESCCBOTSIN <> '''||''||''') and (CBO.BDDESCCBOTSIN is not null) then CBO.BDDESCCBOTSIN else CBOO.BDDESCCBO end BDDESCCBO, '||
                'FUC.BDDESCTFUC, '||
                'FUC.BDDESCFUNCDET, '||
                'FUC.BDINATIVA '||
         'from VRH_FUNCOES_TFUC FUC '||
         'left outer join VRH_BASE_TCBO CBOO on (CBOO.BDCODCBO = FUC.BDCODCBO) '||
         'left outer join VRH_BASE_CBO_TSIN CBO '||
           'on (CBO.BDCODCBO = FUC.BDCODCBO and CBO.BDCODCBOTSIN = FUC.BDCODCBOTSIN) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> 0) THEN
     BEGIN
       wsql = wsql||'join VW_EMPRESAS_REF_ATUAL Y '||
                      'on (Y.BDCODEMP = '||prcodemp||' and Y.BDCODPLAFUC = FUC.BDCODPLAFUC) '||
                    'where Y.BDCODEMP = '||prcodemp;
     END
  ELSE
     BEGIN
       IF (PRCODPLAFUC IS NOT NULL AND PRCODPLAFUC <> 0) THEN
          wsql = wsql||'where FUC.BDCODPLAFUC = '||PRCODPLAFUC;
     END

  FOR EXECUTE STATEMENT wSql
    INTO
      :BDCODTFUC,
      :BDCODPLAFUC,
      :BDCODCBO,
      :BDCODCBOTSIN,
      :BDDESCCBO,
      :BDDESCTFUC,
      :BDDESCFUNCDET,
      :BDINATIVA
    DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Alter (SP_GERAR_INCON_TCADPRO) */
ALTER PROCEDURE SP_GERAR_INCON_TCADPRO(PRSESSAO INTEGER,
PRCODEMP INTEGER,
PRCODPLANOINCO INTEGER,
PRREF INTEGER,
PRIDTERMINAL INTEGER)
 AS
DECLARE VARIABLE WSESSAOUNIMED INTEGER;
DECLARE VARIABLE WNCMINVALIDO DM_BOOLEAN;
DECLARE VARIABLE WISINDUSTRIA DM_BOOLEAN;
DECLARE VARIABLE WNCMPADRAO INTEGER;
DECLARE VARIABLE WCODUNIMEDPADRAO INTEGER;
DECLARE VARIABLE WAPEUNIMEDPADRAO VARCHAR(5);
BEGIN
  DELETE FROM VEF_INCON_TCADPRO WHERE BDSESSAO = :PRSESSAO;

  SELECT I.BDPRODNCMVAZIO, I.BDNCMPROD, I.BDCODUNIMED
  FROM VEF_BASE_TACOESINCONS I
  WHERE I.BDCODPLANOINCONS = :PRCODPLANOINCO
  INTO :wNcmInvalido, :wNcmPadrao, :wCodUnimedPadrao;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREF);
  /*Faz esse select pra ver se a empresa n?o ? industria*/
  SELECT IIF(((a.bdcodconficmssped > 0) AND (a.BDATIVIDADESPED = 0) AND (a.bddtobrigspedcont IS NOT NULL) AND (a.BDINDATIV = 1)), 'TRUE', 'FALSE') BDISINDUSTRIA
  FROM VW_VEF_BASE_TEMPPARFED a
  WHERE a.bdcodemp = :PRCODEMP
  INTO :wIsIndustria;

  /*Transforma ncm's inv?lidas para vazio*/
  IF (:wNcmInvalido = 'TRUE') THEN
    BEGIN
      /*Verifica se a empresa n?o ? Ind?stria, industria deve ter ncm v?lido, sen?o tiver ? inconsistente*/
      IF (:wIsIndustria = 'FALSE') THEN
        BEGIN
          /*Altera na tabela TMP*/
          UPDATE TMP_TCADPRO P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );

          /*Altera na tabela TEMP*/
          UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );
        END
    END

  /*Muda as ncm's inv?lidas para ncm padr?o, se a empresa for ind?stria principalmente(obrigat?rio)*/
  IF ((:wNcmPadrao IS NOT NULL) OR (:wNcmPadrao > 0)) THEN
    BEGIN
      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se j? alterou, n?o vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se j? alterou, n?o vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );
    END

  /*Se tiver uma unidade de medida padr?o, coloca ela nos produtos que n?o tem unidade de medida*/
  IF ((:wCodUnimedPadrao IS NOT NULL) OR (:wCodUnimedPadrao > 0)) THEN
    BEGIN
      /*Busca apelido, apenas para mostrar na grid*/
      SELECT U.BDAPEUNIMED FROM TUNIDADEMEDIDA U WHERE U.BDCODUNIMED = :wCodUnimedPadrao INTO :wApeUnimedPadrao;

      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDCODUNIMED IS NULL) OR (P.BDCODUNIMED = 0))
      AND P.BDCODUNIMED <> :wCodUnimedPadrao; /*Se j? alterou, n?o vai alterar denovo*/

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDALTCODUNIMED = :wCodUnimedPadrao, P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0))
      AND P.BDALTCODUNIMED <> :wCodUnimedPadrao;
    END

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TUNIDADEMEDIDA_TEMP'
  INTO :wSessaoUniMed;

  /*49 - C?digo de unidade de medida n?o cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 49 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TUNIDADEMEDIDA U ON(U.BDCODUNIMED = P.BDALTCODUNIMED)
  LEFT OUTER JOIN TMP_TUNIDADEMEDIDA_TEMP T ON(T.BDEDITCHAVE = P.BDALTCODUNIMED AND T.BDSESSAO = :wSessaoUniMed)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDALTCODUNIMED IS NOT NULL) AND (P.BDALTCODUNIMED > 0))
  AND (U.BDCODUNIMED IS NULL) AND (T.BDCODUNIMED IS NULL);

  /*77 - O campo Unidade de medida n?o pode ficar em branco caso a empresa tenha Sped!*/
  IF (:wIsIndustria = 'TRUE') THEN
    BEGIN
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 77 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/  
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0));

      /*50 - C?digo de NCM n?o cadastrado*/
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/  
      AND ((P.BDNCMPROD IS NULL) OR ((P.BDNCMPROD IS NOT NULL) AND (N.BDNCMPROD IS NULL)));
    END

  /*50 - C?digo de NCM n?o cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
  WHERE P.BDSESSAO = :PRSESSAO
--  AND P.BDCODTIPOSER <> 10 /*Servi?os, n?o deve obrigar ncm*/
  AND P.BDNCMPROD IS NOT NULL
  AND N.BDNCMPROD IS NULL;

  /*73 - Situa??o como N?o relacionado(Est? inconsistencia n?o aparece para o usu?rio, ? somente para o controle de commit's)*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 73 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDSITUACAO IS NULL) OR (P.BDSITUACAO = 0));

  /*63 - Descri??o do produto n?o pode estar vazia*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 63 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDDESCPROD IS NULL) OR (P.BDDESCPROD = ''));

  /*62 - Apelido do produto n?o pode estar vazio*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 62 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDAPEPROD IS NULL) OR (P.BDAPEPROD = ''));

  /*118 - NCM n?o possui o c?digo de exce??o.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 118 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TCODEXTIPI EX ON(EX.BDNCMPROD = P.BDNCMPROD AND EX.BDCODTIPI = P.BDCODTIPI)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDCODTIPI IS NOT NULL) AND (P.BDCODTIPI > 0))
  AND EX.BDCODTIPI IS NULL;
END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOC_ENT for: SP_GET_CODPARTICIPANTEEXP */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_ENT(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOC_SAI for: SP_GET_CODPARTICIPANTEEXP */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOD_ENT for: SP_GET_CODPARTICIPANTEEXP */
ALTER PROCEDURE SP_EXPORTA_BLOCOD_ENT(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER)
 AS
 BEGIN EXIT; END
^

/* empty dependent procedure body */
/* Clear: SP_EXPORTA_BLOCOD_SAI for: SP_GET_CODPARTICIPANTEEXP */
ALTER PROCEDURE SP_EXPORTA_BLOCOD_SAI(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
 BEGIN EXIT; END
^

/* Alter (SP_GET_CODPARTICIPANTEEXP) */
ALTER PROCEDURE SP_GET_CODPARTICIPANTEEXP(PRTIPOEXPCODPART INTEGER,
PRCODTER INTEGER,
PRCGCTER VARCHAR(18),
PRIETER VARCHAR(20),
PRCODIGOARQUIVO VARCHAR(60))
 RETURNS(BDRETORNO VARCHAR(60))
 AS
DECLARE VARIABLE WI INTEGER;
BEGIN

  IF (:PRTIPOEXPCODPART = 0) THEN
    BDRETORNO = :PRCODTER;
  ELSE
  IF (:PRTIPOEXPCODPART = 1) THEN
    BEGIN
      SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:PRIETER) INTO :PRIETER;
      SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:PRCGCTER) INTO :PRCGCTER;

      PRIETER = TRIM(COALESCE(:PRIETER, ''));
      PRCGCTER = TRIM(COALESCE(:PRCGCTER, ''));

      BDRETORNO = :PRCGCTER;

      wI = 0;
      WHILE (wI <= 9) DO
        BEGIN
          IF (:PRCGCTER = LPAD('', CHAR_LENGTH(:PRCGCTER), wI)) THEN
            BEGIN
              BDRETORNO = '';
              BREAK;
            END
          wI = wI + 1;
        END

      IF (:PRIETER <> '') THEN
        BDRETORNO = :BDRETORNO || '_' || :PRIETER;
    END
  ELSE
  IF (:PRTIPOEXPCODPART = 3) THEN
    BDRETORNO = :PRCODIGOARQUIVO;
  ELSE
    BEGIN
      SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:PRCGCTER) INTO :PRCGCTER;
      PRCGCTER = TRIM(COALESCE(:PRCGCTER, ''));

      BDRETORNO = :PRCGCTER;

      wI = 0;
      WHILE (wI <= 9) DO
        BEGIN
          IF (:PRCGCTER = LPAD('', CHAR_LENGTH(:PRCGCTER), wI)) THEN
            BEGIN
              BDRETORNO = '';
              BREAK;
            END
          wI = wI + 1;
        END
    END

  IF (:BDRETORNO = '') THEN
    BDRETORNO = :PRCODTER;

  BDRETORNO = TRIM(COALESCE(BDRETORNO, ''));

  SUSPEND;
END
^

/* Alter (SP_IMPOSTO_EMPRESA) */
ALTER PROCEDURE SP_IMPOSTO_EMPRESA(PRCODEMP INTEGER,
PRCODSIS INTEGER,
PRTIPORETENCAO INTEGER,
PRREF INTEGER,
PRQTD INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER,
BDCODSIS INTEGER)
 AS
DECLARE VARIABLE WPRIDIA DATE;
DECLARE VARIABLE WULTDIA DATE;
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select ';

  EXECUTE PROCEDURE sp_seta_competencia(:prref,NULL,NULL);

  IF (prqtd IS NOT NULL AND prqtd <> 0) THEN
     wsql = wsql||'first '||prqtd||' ';

  wsql = wsql|| 'BDCODEMP, '||
                'BDREFEMP, '||
                'BDREFFIMIMP, '||
                'BDCODIMP, '||
                'BDDESCIMP, '||
                'BDDATACRIACAO, '||
                'BDDATAEXTINTO, '||
                'BDCOMPETENCIA, '||
                'BDDOCARRECADACAO, '||
                'BDPERAPURACAO, '||
                'BDDIAVENCTO, '||
                'BDANTECIPA, '||
                'BDMESVENCTO, '||
                'BDJUROSDIA, '||
                'BDVLRJUROS, '||
                'BDJUROSDIAMES, '||
                'BDMULTADIA, '||
                'BDVLRMULTA, '||
                'BDMULTADIAMES, '||
                'BDVLRMAXMULTA, '||
                'COALESCE(BDALIQIMPOSTO, 0.0) BDALIQIMPOSTO, '||
                'BDLIMITEISENCAO, '||
                'BDTIPORETENCAO, '||
                'BDCODREC, '||
                'BDCODIND, '||
                'BDRETBCCALCULOIMP, '||
                'BDDESCREC, '||
                'BDTIPOIMPOSTO, '||
                'BDCODSIS ';
  wsql = wsql||'from VW_TEMPRESAIMPOSTOREF ';


  wwhere = '';

  IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
       wpridia = CAST((SUBSTRING(prref FROM 5 FOR 2)||'-01-'||SUBSTRING(prref FROM 1 FOR 4)) AS DATE);
       wultdia = wpridia - EXTRACT(DAY FROM wpridia) + 32 - EXTRACT(DAY FROM wpridia - EXTRACT(DAY FROM wpridia) + 32);

       wwhere = wwhere||'BDREFEMP <= '||prref||' ';

       wwhere = wwhere||' and (';

       wwhere = wwhere||'(BDDATACRIACAO is null) or (BDDATACRIACAO <= '''||wpridia||''') and ';
       wwhere = wwhere||'(BDDATAEXTINTO is null) or (BDDATAEXTINTO > '''||wultdia||''')';

       wwhere = wwhere||') ';
     END

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdcodemp = '||prcodemp;
     END

  IF (prcodsis IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdcodsis = '||prcodsis;
     END

  IF (prtiporetencao IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdtiporetencao = '||prtiporetencao;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFEMP,
    :BDREFFIMIMP,
    :BDCODIMP,
    :BDDESCIMP,
    :BDDATACRIACAO,
    :BDDATAEXTINTO,
    :BDCOMPETENCIA,
    :BDDOCARRECADACAO,
    :BDPERAPURACAO,
    :BDDIAVENCTO,
    :BDANTECIPA,
    :BDMESVENCTO,
    :BDJUROSDIA,
    :BDVLRJUROS,
    :BDJUROSDIAMES,
    :BDMULTADIA,
    :BDVLRMULTA,
    :BDMULTADIAMES,
    :BDVLRMAXMULTA,
    :BDALIQIMPOSTO,
    :BDLIMITEISENCAO,
    :BDTIPORETENCAO,
    :BDCODREC,
    :BDCODIND,
    :BDRETBCCALCULOIMP,
    :BDDESCREC,
    :BDTIPOIMPOSTO,
    :BDCODSIS
  DO
  SUSPEND;
END
^

/* Alter (SP_NOME_TERCEIRO) */
ALTER PROCEDURE SP_NOME_TERCEIRO(PRREF INTEGER,
PRTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDNOME VARCHAR(200))
 AS
BEGIN
  /* Procedure Text */
  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  bdcodter = prter;

  SELECT ter.bdnome FROM vw_tterceiro_simples ter WHERE ter.bdcodter = :prter INTO bdnome;

  SUSPEND;
END
^

/* Alter (SP_PBM) */
ALTER PROCEDURE SP_PBM(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDEMP INTEGER,
BDREF INTEGER,
BDOK INTEGER)
 AS
BEGIN
  /* Procedure Text */
  /* BDOK */
  bdemp = premp;
  bdref = prref;

  EXECUTE PROCEDURE sp_seta_competencia(prref);
  bdok = 0;

  FOR SELECT COALESCE(BDCODCONFBLOCOP,0) FROM VW_VEF_BASE_TEMPPARGER WHERE bdcodemp = :premp INTO bdok DO
    BEGIN
    END

  IF (bdok <> 0) THEN
     bdok = 1;

  SUSPEND;
END
^

/* Alter (SP_PERC_GORJETA) */
ALTER PROCEDURE SP_PERC_GORJETA(PRCODEMP VARCHAR(2000),
PRCODCOL VARCHAR(2000),
PRREF INTEGER)
 RETURNS(BDREFCOL VARCHAR(10),
BDPERCGORJ NUMERIC(18,6),
BDNOMCOL VARCHAR(200),
BDCODCOL INTEGER,
BDCODEMP INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WNOMCOL VARCHAR(200);
DECLARE VARIABLE WPERCGORJ NUMERIC(18,6);
DECLARE VARIABLE WREFCOL INTEGER;
DECLARE VARIABLE WSQL VARCHAR(20000);
DECLARE VARIABLE WSQL2 VARCHAR(20000);
DECLARE VARIABLE WCOUNT INTEGER;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);

  WSQL = ' select BDCODEMP, BDCODCOL from VW_VRHF_EMP_TCOL_CALC COL ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       WSQL = WSQL || ' where '||prcodemp;
       IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
          WSQL = WSQL || ' and '||PRCODCOL;
     END
  ELSE
     BEGIN
       IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
          WSQL = WSQL || ' where '||PRCODCOL;
     END

  FOR EXECUTE STATEMENT WSQL INTO
    WCODEMP,
    WCODCOL
  DO
  BEGIN
    WCOUNT = 0;
    WSQL2 = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDNOMCOL, CALC.BDPERCGORJ, CALC.BDREFCOL '||
                'from VW_VRH_EMP_TCOLCON_CAD COL '||
                'left outer join VRHF_EMP_TCOL_CALC CALC on (CALC.BDCODEMP = COL.BDCODEMP and CALC.BDCODCOL = COL.BDCODCOL) '||
                'where CALC.BDPERCGORJ is not null and COL.BDCODEMP='||WCODEMP||' and COL.BDCODCOL='||WCODCOL||' '||
                'order by COL.BDCODEMP, COL.BDCODCOL, CALC.BDREFCOL ';

    FOR EXECUTE STATEMENT WSQL2 INTO
      WCODEMP,
      WCODCOL,
      WNOMCOL,
      WPERCGORJ,
      WREFCOL
    DO
      BEGIN
        IF (WCOUNT = 0) THEN
           BEGIN
             BDCODEMP = WCODEMP;
             BDCODCOL = WCODCOL;
             BDNOMCOL = WNOMCOL;
             BDPERCGORJ = WPERCGORJ;
             BDREFCOL = SUBSTRING(WREFCOL FROM 5 FOR 2)||'/'||SUBSTRING(WREFCOL FROM 1 FOR 4);
             SUSPEND;
           END
        ELSE
           BEGIN
             IF (BDPERCGORJ <> WPERCGORJ) THEN
                BEGIN
                  BDCODEMP = WCODEMP;
                  BDCODCOL = WCODCOL;
                  BDNOMCOL = WNOMCOL;
                  BDPERCGORJ = WPERCGORJ;
                  BDREFCOL = SUBSTRING(WREFCOL FROM 5 FOR 2)||'/'||SUBSTRING(WREFCOL FROM 1 FOR 4);
                  SUSPEND;
                END
           END

        WCOUNT = WCOUNT + 1;
      END
  END
END
^

/* Alter (SP_PRAZO_EXPERIENCIA_SITUACAO) */
ALTER PROCEDURE SP_PRAZO_EXPERIENCIA_SITUACAO(PRCODEMP VARCHAR(30000),
PRCODCOL VARCHAR(30000),
PRDIASPRAZO1COL INTEGER,
PRDIASPRAZO2COL INTEGER,
PRCODSIT INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE)
 AS
DECLARE VARIABLE WWHERE VARCHAR(200);
DECLARE VARIABLE WDATAINISIT DATE;
DECLARE VARIABLE WDATAADMCOL DATE;
DECLARE VARIABLE WDATAULTIMASAIDAAFASTAMENTO DATE;
DECLARE VARIABLE WDATAINICIOPRAZO DATE;
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDIASPRAZO1COL INTEGER;
DECLARE VARIABLE WDIASPRAZO2COL INTEGER;
DECLARE VARIABLE WQDEDIASRESTANTES INTEGER;
DECLARE VARIABLE WQDEDIASAFASTADO INTEGER;
DECLARE VARIABLE WDIASSIT INTEGER;
DECLARE VARIABLE WCONTINUAR CHAR(1);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WMESCOMZERO VARCHAR(2);
DECLARE VARIABLE WSQL2 VARCHAR(1000);
DECLARE VARIABLE WSQL3 VARCHAR(1000);
DECLARE VARIABLE WCOUNTSITUACAO INTEGER;
DECLARE VARIABLE WSQL4 VARCHAR(1000);
DECLARE VARIABLE WINIDATAULTSIT DATE;
DECLARE VARIABLE WFIMDATAPRISIT DATE;
DECLARE VARIABLE WQDIASENTRESIT INTEGER;
DECLARE VARIABLE WPRORROGACONTRATO VARCHAR(5);
DECLARE VARIABLE WCODSIT INTEGER;
DECLARE VARIABLE WCOUNTPRORROGA INTEGER;
DECLARE VARIABLE WDATAINIPRISIT DATE;
DECLARE VARIABLE WCOUNTQTDDIAS INTEGER;
DECLARE VARIABLE WQTDDIAS INTEGER;
BEGIN
--    prcodemp = trim(prcodemp);
--    prcodcol = trim(prcodcol);
--    prdiasprazo2col = coalesce(prdiasprazo2col, 0);

  /*
     Essa primeira parte verifica somente os colaboradores que estao ou estiveram em situacao dentro do periodo de experiencia
   */

  wsql = 'select ADM.BDCODEMP, ADM.BDCODCOL, COL2.BDDATAADMCOL, ';

  IF (prdiasprazo1col IS NOT NULL ) THEN
     wsql = wsql||:prdiasprazo1col||' ';
  ELSE
     wsql = wsql||'coalesce(ADM.BDDIASPRAZO1COL, 0) ';

  wsql = wsql||' bdprazo1, ';

  IF (prdiasprazo2col IS NOT NULL ) THEN
     wsql = wsql||:prdiasprazo2col||' ';
  ELSE
     wsql = wsql||'coalesce(ADM.BDDIASPRAZO2COL, 0) ';

  wsql = wsql||' bdprazo2 ';

  wsql = wsql||
         'from ('||
            'select BDCODEMP, BDCODCOL, BDDIASPRAZO1COL, BDDIASPRAZO2COL, BDDATAFIMPRAZO1COL, BDDATAFIMPRAZO2COL from VRH_EMP_TCOL_ADM ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' where '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and ';
       ELSE
          wsql = wsql||' where ';

       wsql = wsql||prcodcol;
     END

  wsql = wsql||
         ') ADM '||
         'join VRH_EMP_TCOLCON COL2 on (COL2.BDCODEMP = ADM.BDCODEMP and COL2.BDCODCOL = ADM.BDCODCOL) '||
         'join vrh_emp_tsitcol sit on (sit.bdcodemp = adm.bdcodemp and sit.bdcodcol = adm.bdcodcol) '||
         'join vrh_base_tprepsit psit on (psit.bdcodsit = sit.bdcodsit and UPPER(psit.bdprorrogacontrato) = '''||'TRUE'||''') '||
         'where ((adm.bddiasprazo1col > 0 and sit.bddatainisit <= adm.bddatafimprazo1col) or (adm.bddiasprazo2col > 0 and sit.bddatainisit <= adm.bddatafimprazo2col)) ';

  wsql = wSql||' group by ADM.BDCODEMP, ADM.BDCODCOL, COL2.BDDATAADMCOL,bdprazo1,bdprazo2';

  wcountprorroga = 0; -- Sol 19715 - Marcelo B. M. - 25/08/2017
  wcountqtddias = 0;  -- Sol 18917 - Marcelo B. M. - 28/08/2017

    FOR EXECUTE STATEMENT WSQL INTO
        :bdcodemp, :bdcodcol, :wdataadmcol, :wdiasprazo1col, :wdiasprazo2col
    DO
        BEGIN
            wdiasprazo1col = wdiasprazo1col - 1;
            wqdediasrestantes = wdiasprazo1col;
            bddatafimprazo1col = NULL;
            bddatafimprazo2col = NULL;

            wcontinuar = 'S';
            IF (wdiasprazo1col > 0) THEN
                BEGIN
                    wdatainicioprazo = wdataadmcol;
        
                    WHILE (wcontinuar = 'S') DO
                        BEGIN
                            wqdediasafastado = 0;
                            bddatafimprazo1col = wdatainicioprazo + wdiasprazo1col;
        
        
                            wsql2 = 'select sit.BDDATAINISIT, coalesce(sit.BDDIASSIT, 0) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                        ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo1col||''')';

                            -- Sol 18917 - Se tem duas situacoes dentro do periodo de experiencia, considera os dias entre o fim de uma e o comeco de outra como trabalhados
                            wsql3 = 'select count(sit.BDDATAINISIT) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                    ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo1col||''')';

                            wqdiasentresit = 0;

                            IF (wsql3 IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                            BEGIN
                            FOR EXECUTE STATEMENT wsql3 INTO
                                :wcountsituacao
                            DO
                                BEGIN
                                  IF (wcountsituacao = 2) THEN
                                     BEGIN
                                       wsql4 = 'select max(sit.BDDATAINISIT), min(sit.BDDATAFIMSIT) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                               ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo1col||''')';

                                       IF (wsql4 IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                                       BEGIN
                                       FOR EXECUTE STATEMENT wsql4 INTO
                                           :winidataultsit, :wfimdataprisit
                                       DO
                                           wqdiasentresit = TRUNC(winidataultsit - wfimdataprisit) - 1;
                                       END
                                     END
                                END
                            END
                            -- Sol 18917 - Fim

                            wcontinuar = 'N';

                            IF (wsql2 IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                            BEGIN
                            FOR EXECUTE STATEMENT wsql2 INTO
                                :wdatainisit, :wdiassit
                            DO
                                BEGIN
                                    wcontinuar = 'S';
        
                                    IF (wdiassit > 0) THEN
                                        wqdediasafastado = wqdediasafastado + wdiassit;
                                    ELSE
                                        BEGIN
                                            wmes = CAST(SUBSTRING(CAST(wdatainisit AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
                                            wano = CAST(SUBSTRING(CAST(wdatainisit AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
                                            SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;
                                            SELECT str FROM strzero(:wmes,  2) INTO :wmescomzero;
                                            wqdediasafastado = wqdediasafastado + (CAST(:wmescomzero||'/'||:wdia||'/'||:wano AS DATE) - wdatainisit) + 1;
                                        END
                
                                    wqdediasrestantes = wqdediasrestantes - TRUNC(wdatainisit - wdatainicioprazo) + COALESCE(wqdiasentresit,0); -- Sol 18917 - Somando os dias entre as situacoes
                                    wdataultimasaidaafastamento = wdatainisit + wqdediasafastado;

                                    wqdiasentresit = 0; -- Sol 18917 - Deve somar somente uma vez
                                END
                           END
        
                           wdatainicioprazo = wdataultimasaidaafastamento;
                           wdiasprazo1col = wqdediasrestantes;
        
                        END
        
        -- Encontra os afastamenstos do primeiro prazo, encontra os afastamentos do prazo prorrogado prorroga o prazo 2 encontra os afastamentos do prazo 2 prorrogado

                    IF (wdiasprazo2col > 0) THEN
                        BEGIN
                            bddatafimprazo2col = bddatafimprazo1col;
                            wqdediasrestantes = wdiasprazo2col;
                            wdatainicioprazo = bddatafimprazo2col;
                            wcontinuar = 'S';
                            WHILE (wcontinuar = 'S') DO
                                BEGIN
                                    wqdediasafastado = 0;
                                    bddatafimprazo2col = wdatainicioprazo + wdiasprazo2col;
        
                                    wsql = 'select sit.BDDATAINISIT, coalesce(sit.BDDIASSIT, 0) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                                ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo2col||''')';
                                    
                                    wcontinuar = 'N';

                                    IF (wsql IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                                    BEGIN
                                    FOR EXECUTE STATEMENT wsql INTO
                                        :wdatainisit, :wdiassit
                                    DO
                                        BEGIN
                                            wcontinuar = 'S';

                                            -- Sol 19715 - Caso a situacao tenha o parametro 'prorroga contrato de experiencia' desmarcado, nao deve somar os dias
                                            IF (prcodsit <> 0) THEN
                                                BEGIN
                                                    wsql3 = 'select first 1 BDPRORROGACONTRATO from VRH_BASE_TPREPSIT_DIA where BDCODSIT = '||:prcodsit||' order by BDDATASTD desc';

                                                    IF (wsql3 IS NOT NULL) THEN -- Sol 18917 - Marcelo B. M. - 21/08/2017
                                                    BEGIN
                                                    FOR EXECUTE STATEMENT wsql3 INTO
                                                        :wprorrogacontrato
                                                    DO
                                                        BEGIN
                                                            IF (wprorrogacontrato = 'FALSE') THEN
                                                                wcontinuar = 'N';

                                                            -- Sol 19715 - Marcelo B. M. - 25/08/2017 - Se penultima situacao prorroga deve somar esses dias
                                                            wsql4 = 'select first 1 SIT1.BDCODSIT from VRH_EMP_TSITCOL SIT1 where SIT1.BDCODEMP = '||:bdcodemp||' and SIT1.BDCODCOL = '||:bdcodcol||
                                                                    ' and SIT1.BDDATAINISIT <> (select first 1 SIT2.BDDATAINISIT from VRH_EMP_TSITCOL SIT2 where SIT2.BDCODEMP = '||:bdcodemp||' and SIT2.BDCODCOL = '||:bdcodcol||
                                                                    ' order by SIT2.BDDATAINISIT desc) order by SIT1.BDDATAINISIT desc';

                                                            IF (wsql4 IS NOT NULL) THEN
                                                                EXECUTE STATEMENT wsql4 INTO :wcodsit;

                                                            wsql3 = 'select first 1 BDPRORROGACONTRATO from VRH_BASE_TPREPSIT_DIA where BDCODSIT = '||:wcodsit||' order by BDDATASTD desc';

                                                            IF (wsql3 IS NOT NULL) THEN
                                                            BEGIN
                                                            FOR EXECUTE STATEMENT wsql3 INTO
                                                                :wprorrogacontrato
                                                            DO
                                                                BEGIN
                                                                    IF (wprorrogacontrato = 'TRUE') THEN
                                                                        BEGIN
                                                                            wcountprorroga = wcountprorroga + 1;

                                                                            IF (wcountprorroga = 1) THEN -- Sol 19715 - Marcelo B. M. - 25/08/2017 - Soma os dias da penultima situacao apenas uma vez
                                                                                wcontinuar = 'S';
                                                        END
                                                    END
                                                END
                                                        END
                                                    END
                                                END
                                            -- Sol 19715 - Fim
                
                                            IF (wdiassit > 0) THEN
                                                wqdediasafastado = wqdediasafastado + wdiassit;
                                            ELSE
                                                BEGIN
                                                    wmes = CAST(SUBSTRING(CAST(wdatainisit AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
                                                    wano = CAST(SUBSTRING(CAST(wdatainisit AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
                                                    SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;
                                                    SELECT str FROM strzero(:wmes,  2) INTO :wmescomzero;
                                                    wqdediasafastado = wqdediasafastado + (CAST(:wmescomzero||'/'||:wdia||'/'||:wano AS DATE) - wdatainisit) + 1;
                                                END
                        
                                            -- Sol 18917 - Marcelo B. M. - 28/08/2017 - Deve considerar os dias entre o fim do prazo da experiencia e o comeco da primeira situacao
                                            wsql3 = 'select count(sit.BDDATAINISIT) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                                    ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo2col||''')';
--
                                            IF (wsql3 IS NOT NULL) THEN
                                            BEGIN
                                                FOR EXECUTE STATEMENT wsql3 INTO
                                                    :wcountsituacao
                                                DO
                                                    BEGIN
                                                        IF (wcountsituacao = 2) THEN
                                                            BEGIN
                                                                wsql4 = 'select max(sit.BDDATAINISIT), min(sit.BDDATAFIMSIT) from VRH_EMP_TSITCOL sit where (sit.BDCODEMP = '||:bdcodemp||') and (sit.BDCODCOL = '||:bdcodcol||
                                                                        ') and (sit.BDDATAINISIT between '''||:wdatainicioprazo||''' and '''||:bddatafimprazo2col||''')';

                                                            IF (wsql4 IS NOT NULL) THEN
                                                                BEGIN
                                                                    FOR EXECUTE STATEMENT wsql4 INTO
                                                                        :winidataultsit, :wfimdataprisit
                                                                    DO
                                                                        wqdiasentresit = TRUNC(winidataultsit - wfimdataprisit) - 1;
                                                                END
                                                            END
                                                    END
                                            END
                                            -- Sol 18917 - Fim

                                            -- Sol 18917 - Marcelo B. M. - 28/08/2017
                                            IF (COALESCE(wcountsituacao,0) = 2) THEN
                                                BEGIN
                                                    wsql3 = 'select min(bddatainisit) from vrh_emp_tsitcol where bdcodemp = '||:bdcodemp||' and bdcodcol = '||:bdcodcol||';';

                                                    IF (wsql3 IS NOT NULL) THEN
                                                    BEGIN
                                                        FOR EXECUTE STATEMENT wsql3 INTO
                                                            :wdatainiprisit
                                                        DO
                                                            BEGIN
                                                                wcountqtddias = wcountqtddias + 1;
                                                                wqtddias = COALESCE(TRUNC(wdatainiprisit - wdatainicioprazo),0);

                                                                IF ((wcountqtddias > 1) OR (wqtddias < 0))  THEN
                                                                    wqtddias = 0;
                                                            END
                                                    END
                                                END
                                            -- Sol 18917 - Marcelo B. M. - 28/08/2017 - Fim

                                            wqdediasrestantes = wqdediasrestantes - TRUNC(wdatainisit - wdatainicioprazo) + COALESCE(wqdiasentresit,0) + COALESCE(wqtddias,0);
                                            wdataultimasaidaafastamento = wdatainisit + wqdediasafastado;
                        
                                            wqdiasentresit = 0;
                                            wqdediasafastado = 0;
                                        END
                                    END

                                   wdatainicioprazo = wdataultimasaidaafastamento;
                                   wdiasprazo2col = wqdediasrestantes;
                
                                END
        
                        END

                    SUSPEND;
                END
            ELSE
                SUSPEND;

        END

END
^

/* Alter (SP_REL_CONSULTA_CONFIGURAVEL2) */
ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL2 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDCODPLANO INTEGER,
BDCODQUADRO INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDLINHA INTEGER,
BDTITULOS VARCHAR(640))
 AS
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wcolunaatual INTEGER;
DECLARE VARIABLE wmes CHAR(2);
DECLARE VARIABLE wano CHAR(4);
DECLARE VARIABLE windice INTEGER;
DECLARE VARIABLE wnumcolunas INTEGER;
DECLARE VARIABLE wnumlinhas INTEGER;
DECLARE VARIABLE wlinhaatual INTEGER;
DECLARE VARIABLE wdescricao VARCHAR(80);
BEGIN
  /*
    #6566:
    modifica??o para aceitar mais de 8 colunas no relat?rio
  */
  bdcol01 = NULL;
  bdcol02 = NULL;
  bdcol03 = NULL;
  bdcol04 = NULL;
  bdcol05 = NULL;
  bdcol06 = NULL;
  bdcol07 = NULL;
  bdcol08 = NULL;
  bdtitulos = '';

  FOR SELECT c.bdcodmatriz,c.bdcodemp,c.bdcodplaconsconf,c.bdcodqplaconsconf,
             c.bdref,COUNT(c.bdordem) AS "BDNUMCOLUNAS"
      FROM vef_rel_cons_anual_conf c
      INNER JOIN tempresas e ON e.bdcodemp = c.bdcodemp
      GROUP BY bdcodmatriz, c.bdcodemp, c.bdcodplaconsconf, c.bdcodqplaconsconf, c.bdref
      ORDER BY bdcodmatriz, c.bdcodemp, c.bdcodplaconsconf, c.bdcodqplaconsconf, c.bdref
  INTO
    :bdcodmatriz,
    :bdcodemp,
    :bdcodplano,
    :bdcodquadro,
    :bdref, 
    :wnumcolunas
  DO
    BEGIN
      wano = SUBSTRING(:bdref FROM 1 FOR 4);
      wmes = SUBSTRING(:bdref FROM 5 FOR 2);
      SELECT FIRST 1 bdanomes FROM sp_retorna_mesano_extenso(:wmes, :wano,  '/') INTO :bdmesextenso;

      --N?mero de linhas para cada quadro (n?mero de formulas no quadro / 8) arredondado para cima
      wNumLinhas = CEIL((CAST(:wnumcolunas AS NUMERIC(15,2))/CAST(8 AS NUMERIC(15,2))));
      wColunaAtual = 1;
      wIndice = 0;
      wLinhaAtual = 0;

      WHILE (:wLinhaAtual < wNumLinhas) DO
        BEGIN                                                   --TCONFCONSFORM.BDDESCRICAO ? um varchar(80), garante que vai ter no m?ximo 80 caracteres a descri??o
          FOR SELECT FIRST 8 SKIP (:wLinhaAtual * 8) f.bdvalor, LEFT(f.bddescricao, 80) AS "BDDESCRICAO"
              FROM vef_rel_cons_anual_conf f
              WHERE f.bdcodmatriz       = :bdcodmatriz AND
                    f.bdcodemp          = :bdcodemp AND
                    f.bdcodplaconsconf  = :bdcodplano AND
                    f.bdcodqplaconsconf = :bdcodquadro AND
                    f.bdref             = :bdref
              ORDER BY f.bdordem
          INTO
            :wvalor,
            :wdescricao
          DO
            BEGIN
              wIndice = :wIndice + 1;
    
              IF (:wColunaAtual = 1) THEN
                bdcol01 = :wvalor;
              ELSE IF (:wColunaAtual = 2) THEN
                bdcol02 = :wvalor;
              ELSE IF (:wColunaAtual = 3) THEN
                bdcol03 = :wvalor;
              ELSE IF (:wColunaAtual = 4) THEN
                bdcol04 = :wvalor;
              ELSE IF (:wColunaAtual = 5) THEN
                bdcol05 = :wvalor;
              ELSE IF (:wColunaAtual = 6) THEN
                bdcol06 = :wvalor;
              ELSE IF (:wColunaAtual = 7) THEN
                bdcol07 = :wvalor;
              ELSE IF (:wColunaAtual = 8) THEN
                bdcol08 = :wvalor;

              bdtitulos = :bdtitulos || LPAD(:wdescricao, 80);

              IF ((MOD(:wColunaAtual, 8) = 0) OR (:wIndice = :wnumcolunas)) THEN
                BEGIN
                  bdlinha = :wlinhaatual;
                  bdtitulos = RPAD(:bdtitulos, 640);
                  SUSPEND;
    
                  wColunaAtual = 1;
                  bdcol01 = NULL;
                  bdcol02 = NULL;
                  bdcol03 = NULL;
                  bdcol04 = NULL;
                  bdcol05 = NULL;
                  bdcol06 = NULL;
                  bdcol07 = NULL;
                  bdcol08 = NULL;
                  bdtitulos = '';
                END
              ELSE
                wColunaAtual = :wColunaAtual + 1;
            END
          wLinhaAtual = :wLinhaAtual + 1;
        END
    END
END
^

/* Alter (SP_REL_RESUMO_IMPOSTOS) */
ALTER PROCEDURE SP_REL_RESUMO_IMPOSTOS(PRCODEMP VARCHAR(10000),
PRCODIMP VARCHAR(10000),
PRCODSIS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRDTVCTOINI DATE,
PRDTVCTOFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(200),
BDCODREC INTEGER,
BDCODSIS INTEGER,
BDCODPERIODO INTEGER,
BDDESCPERIODO VARCHAR(40),
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDMESEXTENSO VARCHAR(20),
BDQUOTA INTEGER,
BDCODCOL INTEGER,
BDCODEMPCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDPERIODO DATE,
BDNUMREFDOC VARCHAR(20),
BDDATAVCTO DATE,
BDVALOR NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDJUROS NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDOBS BLOB,
BDORDEMCOMPL INTEGER,
BDBASEIMP NUMERIC(15,6),
BDALIQIMP NUMERIC(15,6),
BDVLRIMPORIGINAL NUMERIC(15,6),
BDVLRACUMULO NUMERIC(15,6),
BDVLRMULTAJUROS NUMERIC(15,6),
BDVLROUTENTIDADE NUMERIC(15,6),
BDTIPOIMPOSTO INTEGER,
BDCOMPENSACAO NUMERIC(15,6),
BDVLRACUOUTENT NUMERIC(15,6),
BDREFPAG INTEGER,
BDDTPGTO DATE)
 AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WMES CHAR(10);
DECLARE VARIABLE WANO CHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wSql = 'select DARF.BDCODEMP, ';
  wSql = wSql || 'DARF.BDCODIMP, ';
  wSql = wSql || 'IMP.BDDESCIMP, ';
  wSql = wSql || 'IMP.BDCODREC, ';
  wSql = wSql || 'IMP.BDCODSIS, ';
  wSql = wSql || 'DARF.BDCODPERIODO, ';
  wSql = wSql || 'periodo.bddescricao, ';
  wSql = wSql || 'DARF.BDREFERENCIA, ';
  wSql = wSql || 'DARF.BDQUOTA, ';
  wSql = wSql || 'DARF.BDDATAVCTO , ';

  wSql = wSql || 'DARF.BDBASEIMP , ';
  wSql = wSql || 'DARF.BDALIQIMP , ';
  wSql = wSql || 'DARF.BDVLRIMPORIGINAL , ';
  wSql = wSql || 'DARF.BDVALOR , ';
  wSql = wSql || 'DARF.BDMULTA , ';
  wSql = wSql || 'DARF.BDJUROS , ';
  wSql = wSql || 'DARF.BDTOTAL , ';
  wSql = wSql || 'DARF.BDOBS , ';
  wSql = wSql || 'DARF.BDORDEMCOMPL , ';
  wSql = wSql || 'DARF.BDVLRMULTAJUROS , ';
  wSql = wSql || 'DARF.BDVLROUTENTIDADE, ';
  wSql = wSql || 'DARF.BDORDEM, ';
  wSql = wSql || 'DARF.BDCHAVEDARF ';

  wsql = wsql || 'from tdarfpadrao DARF , timposto IMP , ttiposperiodo periodo, VW_EMPRESAS_REF_ATUAL emp ';

  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wWhere||PRCODEMP||' ';

  IF ((prcodimp IS NOT NULL) OR (prcodimp > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||prcodimp||' ';
     END

  IF ((prcodsis IS NOT NULL) OR (prcodsis > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||prcodsis||' ';
     END

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.BDREFERENCIA >= '||prrefini||' ';
     END

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.BDREFERENCIA <= '||prreffin||' ';
     END

  IF (prdtvctoini IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.bddatavcto >= '||''''||prdtvctoini||'''';
     END

  IF (prdtvctofim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.bddatavcto <= '||''''||prdtvctofim||'''';
     END

  IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

  wwhere = wwhere||' and (imp.bdcodimp = darf.bdcodimp) and (emp.bdcodemp = darf.bdcodemp) and (darf.bdcodperiodo = periodo.bdcodperiodo)';

  wgroupby = '';
  worderby = 'order by DARF.BDCODIMP, DARF.BDORDEM, DARF.bdreferencia, DARF.BDCODPERIODO';

  wsql = wsql||wwhere||wgroupby||worderby;

  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodemp,
      :BDCODIMP,
      :BDDESCIMP,
      :bdcodrec,
      :bdcodsis,
      :BDCODPERIODO,
      :bddescperiodo,
      :BDREFERENCIA,
      :BDQUOTA,
      :BDDATAVCTO ,
      :BDBASEIMP ,
      :BDALIQIMP ,
      :BDVLRIMPORIGINAL ,
      :BDVALOR ,
      :BDMULTA ,
      :BDJUROS ,
      :BDTOTAL ,
      :BDOBS ,
      :BDORDEMCOMPL ,
      :BDVLRMULTAJUROS ,
      :BDVLROUTENTIDADE,
      :BDORDEM,
      :BDCHAVEDARF  DO
      BEGIN


    wano = SUBSTRING(bdreferencia FROM 1 FOR 4);
    wmes = SUBSTRING(bdreferencia FROM 5 FOR 2);

    IF (wmes = '01') THEN
       bdmesextenso =  'Janeiro / ' || wano;
    IF (wmes = '02') THEN
       bdmesextenso =  'Fevereiro / ' || wano;
    IF (wmes = '03') THEN
       bdmesextenso =  'Mar?o / ' || wano;
    IF (wmes = '04') THEN
       bdmesextenso =  'Abril / ' || wano;
    IF (wmes = '05') THEN
       bdmesextenso =  'Maio / ' || wano;
    IF (wmes = '06') THEN
       bdmesextenso =  'Junho / ' || wano;
    IF (wmes = '07') THEN
       bdmesextenso =  'Julho / ' || wano;
    IF (wmes = '08') THEN
       bdmesextenso =  'Agosto / ' || wano;
    IF (wmes = '09') THEN
       bdmesextenso =  'Setembro / ' || wano;
    IF (wmes = '10') THEN
       bdmesextenso =  'Outubro / ' || wano;
    IF (wmes = '11') THEN
       bdmesextenso =  'Novembro / ' || wano;
    IF (wmes = '12') THEN
       bdmesextenso =  'Dezembro / ' || wano;


        SELECT MAX(pgto.bddatapgto) FROM tdarfgerpgto pgto
               WHERE (PGTO.bdcodemp = :bdcodemp AND PGTO.BDCHAVEDARF = :BDCHAVEDARF) INTO :BDDTPGTO;

        SUSPEND;
      END
END
^

/* Alter (SP_RELDEMRECDESP) */
ALTER PROCEDURE SP_RELDEMRECDESP(PRCODESC VARCHAR(500),
PRTIPODEM INTEGER,
PRDATAINICIAL VARCHAR(10),
PRDATAFINAL VARCHAR(10),
PRCHAVECTABAN VARCHAR(500),
PRCODOBRSER VARCHAR(10240),
PRCODDESP VARCHAR(10240),
PRNIVEL INTEGER,
PRTIPORECDESP INTEGER,
PRDEMLANCREEMBOLSO DM_BOOLEAN)
 RETURNS(BDCODSERDESP INTEGER,
BDCLASSIFICACAO VARCHAR(60),
BDDESCRICAO VARCHAR(100),
BDTIPO INTEGER,
BDPERIODO01 VARCHAR(12),
BDVLRPERIODO01 NUMERIC(15,2),
BDPERIODO02 VARCHAR(12),
BDVLRPERIODO02 NUMERIC(15,2),
BDPERIODO03 VARCHAR(12),
BDVLRPERIODO03 NUMERIC(15,2),
BDPERIODO04 VARCHAR(12),
BDVLRPERIODO04 NUMERIC(15,2),
BDPERIODO05 VARCHAR(12),
BDVLRPERIODO05 NUMERIC(15,2),
BDPERIODO06 VARCHAR(12),
BDVLRPERIODO06 NUMERIC(15,2),
BDPERIODO07 VARCHAR(12),
BDVLRPERIODO07 NUMERIC(15,2),
BDPERIODO08 VARCHAR(12),
BDVLRPERIODO08 NUMERIC(15,2),
BDPERIODO09 VARCHAR(12),
BDVLRPERIODO09 NUMERIC(15,2),
BDPERIODO10 VARCHAR(12),
BDVLRPERIODO10 NUMERIC(15,2),
BDPERIODO11 VARCHAR(12),
BDVLRPERIODO11 NUMERIC(15,2),
BDPERIODO12 VARCHAR(12),
BDVLRPERIODO12 NUMERIC(15,2),
BDVLRTOTPERIODO NUMERIC(15,2))
 AS
declare variable VULTDIAMES integer;
declare variable VPERIODOFINAL varchar(10);
declare variable VPERIODOINICIAL varchar(10);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSERDESP varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODSERDESP integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
begin
  vguardaserdesp = '';
  vclassaux = '';
  vcodserdespaux = 0;
  vsql = '';
  vsqlserdesp = '';
  vultdiames = 0;
  vnumperiodo = 0;
  vperiodoinicial = '';
  vperiodofinal = '';

  vperiodo01 = '';
  vvlrperiodo01 = 0;
  vperiodo02 = '';
  vvlrperiodo02 = 0;
  vperiodo03 = '';
  vvlrperiodo03 = 0;
  vperiodo04 = '';
  vvlrperiodo04 = 0;
  vperiodo05 = '';
  vvlrperiodo05 = 0;
  vperiodo06 = '';
  vvlrperiodo06 = 0;
  vperiodo07 = '';
  vvlrperiodo07 = 0;
  vperiodo08 = '';
  vvlrperiodo08 = 0;
  vperiodo09 = '';
  vvlrperiodo09 = 0;
  vperiodo10 = '';
  vvlrperiodo10 = 0;
  vperiodo11 = '';
  vvlrperiodo11 = 0;
  vperiodo12 = '';
  vvlrperiodo12 = 0;
  DELETE FROM TMP_DEMRECDESP_ANALITICAS;

  IF (prtiporecdesp = 0) THEN -- Servi?os
     BEGIN
       /* Antes de tudo, obter os servi?os selecionados de acordo com as op??es "t?tulos" e "anal?ticas".
       prnivel = 0: apenas a op??o "t?tulos" est? checada.
       prnivel = 1: apenas a op??o "anal?ticas" est? checada.
       prnivel = 2: ambas op??es est?o checadas. */

       IF (prnivel = 0) THEN
          BEGIN
            vsqlserdesp = 'select s.bdcodobrser, s.bdclassificacao, s.bddescricao, s.bdtipo ';
            vsqlserdesp = vsqlserdesp || 'from (';
            vsqlserdesp = vsqlserdesp || '       select bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
            vsqlserdesp = vsqlserdesp || '       from vct_base_servico ';

            IF (:prcodobrser <> '') THEN
                vsqlserdesp = vsqlserdesp || 'where bdcodobrser in ('||:prcodobrser||') ';

            vsqlserdesp = vsqlserdesp || '      ) ser ';
            vsqlserdesp = vsqlserdesp || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'') ';

            /* Se prnivel = 0 ent?o apenas a op??o "t?tulo" est? selecionada. Neste caso
            iremos trazer tamb?m as anal?ticas para que seja feito o c?lculo dos per?odos.
            Posteriormente apenas exibimos as t?tulos no relat?rio. */

            vsqlserdesp = vsqlserdesp || 'group by bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
            vsqlserdesp = vsqlserdesp || 'order by bdclassificacao ';
          END
       ELSE
         IF (prnivel = 1) THEN
            BEGIN
              /* Se apenas a op??o "anal?ticas" est? selecionada, ent?o basta
              trazer as pr?prias anal?ticas selecionadas. */
              vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
              vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
              vsqlserdesp = vsqlserdesp || 'where ser.bdtipo = 1';
      
              IF (:prcodobrser <> '') THEN
                 vsqlserdesp = vsqlserdesp || 'and ser.bdcodobrser in ('||:prcodobrser||') ';

              vsqlserdesp = vsqlserdesp || 'order by bdclassificacao ';
            END
         ELSE -- Ent?o possui t?tulos e anal?ticas selecionadas
           IF (prnivel = 2) THEN
              BEGIN
                if (prcodobrser = '') then
                   begin
                     vguardaserdesp = '';
                     vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                     vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
                     vsqlserdesp = vsqlserdesp || 'order by bdclassificacao';
                   end
                else
                   begin
                    /* Se t?tulos e anal?ticas foram selecionadas, dever? trazer as anal?ticas das t?tulos
                    que est?o selecionadas e tamb?m dever? trazer as t?tulos das anal?ticas que foram selecionadas.*/
        
                    -- Primeiramente pegar as t?tulos que foram selecionadas
                    vsql = 'select list(ser.bdcodobrser) from vct_base_servico ser ';
                    vsql = vsql || 'where ser.bdtipo = 0 ';
    
                    IF (:prcodobrser <> '') THEN
                       vsql = vsql || 'and ser.bdcodobrser in ('||:prcodobrser||') ';
                    EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
        
                    IF (vguardaserdesp IS NOT NULL) THEN
                       BEGIN
                         -- Em seguida, obter as anal?ticas destas t?tulos e guardar em vguardaservicos.
                         vsql = 'select s.bdcodobrser, s.bdclassificacao ';
                         vsql = vsql || 'from (';
                         vsql = vsql || '       select bdcodobrser, bdclassificacao, bddescricao ';
                         vsql = vsql || '       from vct_base_servico ';
                         vsql = vsql || '       where bdcodobrser in('||:vguardaserdesp||') ';
                         vsql = vsql || '      ) ser ';
                         vsql = vsql || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'')';
                  
                         vguardaserdesp = '';
        
                         FOR
                         EXECUTE STATEMENT :vsql
                         INTO
                         :vcodserdesp,
                         :vclassserdesp
                         DO
                         BEGIN
                           vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                         END
                       END
                    ELSE
                      vguardaserdesp = '';
    
    
                    -- Obtendo somente as anal?ticas selecionadas
                    vsql = 'select ser.bdcodobrser, ser.bdclassificacao ';
                    vsql = vsql || 'from (';
                    vsql = vsql || 'select bdcodobrser, bdclassificacao ';
                    vsql = vsql || 'from vct_base_servico ';
                    vsql = vsql || 'where bdtipo = 1 ';
    
                    IF (:prcodobrser <> '') THEN
                    vsql = vsql || 'and bdcodobrser in ('||:prcodobrser||') ';
    
                    vsql = vsql || ') ser ';
              
                    FOR
                    EXECUTE STATEMENT :vsql
                    INTO
                    :vcodserdesp,
                    :vclassserdesp
                    DO
                    BEGIN
                      vstop = 'FALSE';
                      vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                      vclassaux = :vclassserdesp;
          
                      /* A implementa??o abaixo vai removendo sempre o ?ltimo n?vel da classifica??o
                      para obter todas as t?tulos que compoem a anal?tica, e vai guardando o c?digo
                      de cada t?tulo na vari?vel vguardaserdesp. */
                      WHILE (UPPER(:vstop) = 'FALSE') DO
                        BEGIN
                          SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
    
                          IF (vposicaoponto > 0) THEN
                             BEGIN
                               SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classifica??o
                               SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a invers?o seria o ?ltimo ponto)
                               SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                               SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente

                               SELECT COALESCE(bdcodobrser,0) FROM vct_base_servico WHERE bdclassificacao = :vclassaux INTO :vcodserdespaux;
    
                               IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                  vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                             END
                          ELSE
                            BEGIN
                              vstop = 'TRUE';
                            END
                        END
                    END
                    vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
        
                    -- Por fim, junta todos os servi?os relacionados em um sql.
                    vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                    vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
                    vsqlserdesp = vsqlserdesp || 'where ser.bdcodobrser in ('||:vguardaserdesp||') ';
                    vsqlserdesp = vsqlserdesp || 'order by bdclassificacao';
                 end
              END


       -- Depois de ter obtido todos os servi?os, trazer apenas os que possuem rela??o com os lan?amentos financeiros.

       if (:vguardaserdesp <> '') then
          begin
             vguardaserdesp = '';
             vsql = 'select list(ser.bdcodobrser) from ('||:vsqlserdesp||') ser where ser.bdtipo = 1';
             EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
          end

       vsql = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bddesconto ';
       vsql = vsql || 'from vct_base_servico ser ';
       vsql = vsql || 'where exists ';
       vsql = vsql || ' (';
       vsql = vsql || '    select bdcodobrser from vfin_esc_tlancbancario lan ';
       vsql = vsql || '    where (lan.bdcodobrser = ser.bdcodobrser) ';
       vsql = vsql || '    and lan.bdtiposervdesp = 0 ';
       vsql = vsql || '    and lan.bdvalorlanc > 0 ';

       IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';

       IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

       if (Upper(:prdemlancreembolso) = 'FALSE') then
          begin
            vsql = vsql || 'and not exists (';
            vsql = vsql || '   select rec.* from VFIN_ESC_TRECFATURASERVICO rec ';
            vsql = vsql || '   inner join VFIN_ESC_TORIGEMSERFAT orig on (orig.bdcodcli = rec.bdcodcli and orig.bdcodesc = rec.bdcodesc and orig.bdchavefatura = rec.bdchavefatura and orig.bdordemser = rec.bdordemser) ';
            vsql = vsql || '   inner join VFIN_ESC_TSERVICOFIXO serfix on (serfix.bdcodcli = orig.bdcodcli and serfix.bdcodesc = orig.bdcodesc and serfix.bdchaveserfix = orig.bdchaveserfix ';
            vsql = vsql || '   and serfix.bdordemserfix = orig.bdordemserfix) ';
            vsql = vsql || '   inner join VFIN_ESC_TVINC_PAG_SERVIC vinc on (vinc.bdcodcli = serfix.bdcodcli and vinc.bdcodesc = serfix.bdcodesc and vinc.bdchaveserfix = serfix.bdchaveserfix and ';
            vsql = vsql || '   vinc.bdordemserfix = serfix.bdordemserfix) ';
            vsql = vsql || '   where rec.bdcodesc = lan.bdcodesc and ';
            vsql = vsql || '   rec.bdcodcli = lan.bdcodcli and ';
            vsql = vsql || '   rec.bdchavefatura = lan.bdchavefatura and ';
            vsql = vsql || '   rec.bdordemser = lan.bdordemser and ';
            vsql = vsql || '   rec.bdordemrecser = lan.bdordemrecser ';
            vsql = vsql || ')';
          end

       vsql = vsql || ' )';

       IF (:vguardaserdesp <> '') THEN
          vsql = vsql || 'and ser.bdcodobrser in ('||:vguardaserdesp||') ';

     END
  ELSE
    BEGIN -- Despesas
      IF (prnivel = 0) THEN -- Ent?o s? possui t?tulos selecionadas
         BEGIN
           vsqlserdesp = 'select d.bdcoddesp, d.bdclassdesp, d.bddescdesp, d.bdtipodesp ';
           vsqlserdesp = vsqlserdesp || 'from (';
           vsqlserdesp = vsqlserdesp || '       select bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
           vsqlserdesp = vsqlserdesp || '       from vfin_base_tdespesa ';

           IF (:prcoddesp <> '') THEN
              vsqlserdesp = vsqlserdesp || 'where bdcoddesp in ('||:prcoddesp||') ';

           vsqlserdesp = vsqlserdesp || '      ) desp ';
           vsqlserdesp = vsqlserdesp || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';

           /* Se prnivel = 0 ent?o apenas a op??o "t?tulo" est? selecionada. Neste caso
           iremos trazer tamb?m as anal?ticas para que seja feito o c?lculo dos per?odos.
           Posteriormente apenas exibimos as t?tulos no relat?rio. */

           vsqlserdesp = vsqlserdesp || 'group by bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
           vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
         END
      ELSE
        IF (prnivel = 1) THEN -- Ent?o s? possui anal?ticas selecionadas
           BEGIN
             /* Se apenas a op??o "anal?ticas" est? selecionada, ent?o basta
             trazer as pr?prias anal?ticas selecionadas. */
             vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
             vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
             vsqlserdesp = vsqlserdesp || 'where desp.bdtipodesp = 1 ';

             IF (:prcoddesp <> '') THEN
                vsqlserdesp = vsqlserdesp || 'and desp.bdcoddesp in ('||:prcoddesp||') ';

             vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
           END
        ELSE -- Ent?o possui t?tulos e anal?ticas selecionadas, e obrigatoriamente as duas op??es "t?tulos" e "anal?ticas" est?o checadas.
          IF (prnivel = 2) THEN
             BEGIN

                if (prcoddesp = '') then
                   begin
                     vguardaserdesp = '';
                     vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                     vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                     vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
                   end
                else
                   begin
                       /* Se t?tulos e anal?ticas foram selecionadas, dever? trazer as anal?ticas das t?tulos
                       que est?o selecionadas e tamb?m dever? trazer as t?tulos das anal?ticas que foram selecionadas.*/
            
                       -- Primeiramente pegar as t?tulos que foram selecionadas
                       vsql = 'select list(desp.bdcoddesp) from vfin_base_tdespesa desp ';
                       vsql = vsql || 'where desp.bdtipodesp = 0 ';
        
                       IF (:prcoddesp <> '') THEN
                          vsql = vsql || 'and desp.bdcoddesp in ('||:prcoddesp||')';
        
                       EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
              
                       IF (vguardaserdesp IS NOT NULL) THEN
                          BEGIN
                            -- Em seguida, obter as anal?ticas destas t?tulos e guardar em vguardaservicos.
                            vsql = 'select d.bdcoddesp, d.bdclassdesp ';
                            vsql = vsql || 'from (';
                            vsql = vsql || '       select bdcoddesp, bdclassdesp, bddescdesp ';
                            vsql = vsql || '       from vfin_base_tdespesa ';
                            vsql = vsql || '       where bdcoddesp in('||:vguardaserdesp||') ';
                            vsql = vsql || '      ) desp ';
                            vsql = vsql || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';
                   
                            vguardaserdesp = '';
                         
                            FOR
                            EXECUTE STATEMENT :vsql
                            INTO
                            :vcodserdesp,
                            :vclassserdesp
                            DO
                            BEGIN
                              vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                            END
                          END
                       ELSE
                         vguardaserdesp = '';
        
                       -- Obtendo somente as anal?ticas selecionadas
                       vsql = 'select desp.bdcoddesp, desp.bdclassdesp ';
                       vsql = vsql || 'from (';
                       vsql = vsql || 'select bdcoddesp, bdclassdesp ';
                       vsql = vsql || 'from vfin_base_tdespesa ';
                       vsql = vsql || 'where bdtipodesp = 1';
        
                       IF (:prcoddesp <> '') THEN
                          vsql = vsql || 'and bdcoddesp in ('||:prcoddesp||') ';
        
                       vsql = vsql || ') desp ';
            
                       FOR
                       EXECUTE STATEMENT :vsql
                       INTO
                       :vcodserdesp,
                       :vclassserdesp
                       DO
                       BEGIN
                         vstop = 'FALSE';
                         vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                         vclassaux = :vclassserdesp;
                  
                         /* A implementa??o abaixo vai removendo sempre o ?ltimo n?vel da classifica??o
                         para obter todas as t?tulos que compoem a anal?tica, e vai guardando o c?digo
                         de cada t?tulo na vari?vel vguardaserdesp. */
                         WHILE (UPPER(:vstop) = 'FALSE') DO
                           BEGIN
                             SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
                  
                             IF (vposicaoponto > 0) THEN
                                BEGIN
                                  SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classifica??o
                                  SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a invers?o seria o ?ltimo ponto)
                                  SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                                  SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente
                                  SELECT COALESCE(bdcoddesp,0) FROM vfin_base_tdespesa WHERE bdclassdesp = :vclassaux INTO :vcodserdespaux;
            
                                  IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                     vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                                END
                             ELSE
                               BEGIN
                                 vstop = 'TRUE';
                               END
                           END
                       END
        
                       vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
                
                       -- Por fim, junta todos os servi?os relacionados em um sql.
                       vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                       vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                       vsqlserdesp = vsqlserdesp || 'where desp.bdcoddesp in ('||:vguardaserdesp||') ';
                       vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
                end
             END



      -- Depois de ter obtido todos os servi?os, trazer apenas os que possuem rela??o com os lan?amentos financeiros.
      if (vguardaserdesp <> '') then
         begin
            vguardaserdesp = '';
            vsql = 'select list(desp.bdcoddesp) from ('||:vsqlserdesp||') desp where desp.bdtipodesp = 1';
            EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
         end

      vsql = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, (null) bddesconto ';
      vsql = vsql || 'from vfin_base_tdespesa desp ';
      vsql = vsql || 'where exists ';
      vsql = vsql || ' (';

      if (Upper(:prdemlancreembolso) = 'FALSE') then
         begin
           vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lan ';
           vsql = vsql || 'left outer join vfin_esc_tvinc_pag_servic vinc on (vinc.bdcodesc = lan.bdcodesc and vinc.BDCHAVECTAPAG = lan.bdchavectapag ';
           vsql = vsql || 'and vinc.bdordemdesp = lan.bdordemdesp) ';
           vsql = vsql || 'where (lan.bdcoddesp = desp.bdcoddesp) ';
           vsql = vsql || 'and lan.bdtiposervdesp = 1 ';
           vsql = vsql || 'and lan.bdvalorlanc > 0 ';
           vsql = vsql || 'and vinc.bdcodesc is null  ';
         end
      else
        begin
          vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lan ';
          vsql = vsql || 'where (lan.bdcoddesp = desp.bdcoddesp) ';
          vsql = vsql || 'and lan.bdtiposervdesp = 1 ';
          vsql = vsql || 'and lan.bdvalorlanc > 0 ';
        end

      if ((:prcodesc <> '') and (:prcodesc is not null)) then
         vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';

      IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||')';


      vsql = vsql || ' )';

      IF (:vguardaserdesp <> '') THEN
         vsql = vsql || 'and desp.bdcoddesp in ('||:vguardaserdesp||') ';
    END

  /* Adicionar todas as anal?ticas em uma tabela tempor?ria com os valores de seus per?odos */
  FOR
  EXECUTE STATEMENT :vsql
  INTO
  :vcodserdesp,
  :vclassserdesp,
  :vdescserdesp,
  :vDesconto
  DO
  BEGIN
    vstop = 'FALSE';
    vperiodoinicial = '';
    vperiodofinal = '';
    vnumperiodo = 0;
  
    WHILE (UPPER(vstop) = 'FALSE') DO
      BEGIN
        vnumperiodo = :vnumperiodo +1;
  
        IF (:prtipodem = 0) THEN -- Demonstrativo total
           BEGIN
             vperiodoinicial = :prdatainicial;
             vperiodofinal = :prdatafinal;

             SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
           END
        ELSE
          IF (:prtipodem = 1) THEN -- Demonstrativo mensal
             BEGIN
               IF (:vperiodoinicial = '') THEN
                  BEGIN
                    vperiodoinicial = prdatainicial;
                  END
               ELSE
                 BEGIN
                   -- Acrescentando um m?s ? data
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 1) INTO :vperiodoinicial;
                   vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                 END

                 -- Obtendo o ?ltimo dia do m?s
                 SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodoinicial FROM 1 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodoinicial FROM 7 FOR 4) AS INTEGER)) INTO :vultdiames;
                 vperiodofinal = SUBSTRING(:vperiodoinicial FROM 1 FOR 3)||:vultdiames||SUBSTRING(:vperiodoinicial FROM 6 FOR 5);


                 -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                    END
                 ELSE
                 IF (:vnumperiodo = 7) THEN
                    BEGIN
                      vperiodo07 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo07;
                    END
                 ELSE
                 IF (:vnumperiodo = 8) THEN
                    BEGIN
                      vperiodo08 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo08;
                    END
                 ELSE
                 IF (:vnumperiodo = 9) THEN
                    BEGIN
                      vperiodo09 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo09;
                    END
                 ELSE
                 IF (:vnumperiodo = 10) THEN
                    BEGIN
                      vperiodo10 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo10;
                    END
                 ELSE
                 IF (:vnumperiodo = 11) THEN
                    BEGIN
                      vperiodo11 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo11;
                    END
                 ELSE
                 IF (:vnumperiodo = 12) THEN
                    BEGIN
                      vperiodo12 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo12;
                    END
             END
          ELSE
            IF (:prtipodem = 2) THEN -- Demonstrativo bimestral
               BEGIN
                 IF (:vperiodoinicial = '') THEN
                    BEGIN
                      vperiodoinicial = :prdatainicial;
                    END
                 ELSE
                   BEGIN
                     -- Por ser bimestral, dever? acrescentar dois meses ? data
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 2) INTO :vperiodoinicial;
                     vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                   END

                 /* Acrescentando um m?s ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                 Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 28/02/2017 */
                 SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 1) INTO :vperiodofinal;
                 SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                 vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
  
                 -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = '1? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = '2? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = '3? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = '4? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = '5? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = '6? bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                    END
               END
            ELSE
              IF (:prtipodem = 3) THEN -- Demonstrativo trimestral
                 BEGIN
                   IF (:vperiodoinicial = '') THEN
                       BEGIN
                         vperiodoinicial = :prdatainicial;
                       END
                   ELSE
                     BEGIN
                       -- Por ser trimestral, dever? acrescentar tr?s meses ? data
                       SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 3) INTO :vperiodoinicial;
                       vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                     END

                   /* Acrescentando tr?s meses ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                   Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 31/03/2017 */
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 2) INTO :vperiodofinal;
                   SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                   vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
                   -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                   IF (:vnumperiodo = 1) THEN
                      BEGIN
                        vperiodo01 = '1? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                      END
                   ELSE
                   IF (:vnumperiodo = 2) THEN
                      BEGIN
                        vperiodo02 = '2? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                      END
                   ELSE
                   IF (:vnumperiodo = 3) THEN
                      BEGIN
                        vperiodo03 = '3? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                      END
                   ELSE
                   IF (:vnumperiodo = 4) THEN
                      BEGIN
                        vperiodo04 = '4? trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                      END
                 END
              ELSE
                IF (:prtipodem = 4) THEN -- Demonstrativo semestral
                   BEGIN
                     IF (:vperiodoinicial = '') THEN
                       BEGIN
                         vperiodoinicial = :prdatainicial;
                       END
                     ELSE
                       BEGIN
                         -- Por ser semestral, dever? acrescentar seis meses ? data
                         SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 6) INTO :vperiodoinicial;
                         vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                       END

                     /* Acrescentando cinco meses ? refer?ncia final com base na refer?ncia inicial e obtendo o ?ltimo dia deste m?s.
                     Ex: Se o per?odo inicial for 01/01/2017, o per?odo final dever? ser 30/06/2017 */
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 5) INTO :vperiodofinal;
                     SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                     vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
  
                     -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                     IF (:vnumperiodo = 1) THEN
                        BEGIN
                          vperiodo01 = '1? semestre';
                          SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                        END
                     ELSE
                     IF (:vnumperiodo = 2) THEN
                        BEGIN
                          vperiodo02 = '2? semestre';
                          SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                        END
                   END
                ELSE
                  BEGIN
                    IF (:prtipodem = 5) THEN -- Desmonstrativo anual
                       BEGIN
                         IF (:vperiodoinicial = '') THEN
                             BEGIN
                               vperiodoinicial = :prdatainicial;
                             END
                         ELSE
                           BEGIN
                             -- Por ser anual, dever? acrescentar um ano ? data
                             SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 12) INTO :vperiodoinicial;
                             vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                           END
                         -- O ?ltimo dia do ano sempre ser? 31/12/ + o ano que foi incrementado no vperiodoinicial
                         vperiodofinal = '12/31/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
             
                         -- Guardando o per?odo e o valor do per?odo para posteriormente inserir um registro na tablela tempor?ria contendo estas informa??es.
                         IF (:vnumperiodo = 1) THEN
                            BEGIN
                              vperiodo01 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo01;
                            END
                         ELSE
                         IF (:vnumperiodo = 2) THEN
                            BEGIN
                              vperiodo02 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo02;
                            END
                         ELSE
                         IF (:vnumperiodo = 3) THEN
                            BEGIN
                              vperiodo03 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo03;
                            END
                         ELSE
                         IF (:vnumperiodo = 4) THEN
                            BEGIN
                              vperiodo04 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo04;
                            END
                         ELSE
                         IF (:vnumperiodo = 5) THEN
                            BEGIN
                              vperiodo05 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo05;
                            END
                         ELSE
                         IF (:vnumperiodo = 6) THEN
                            BEGIN
                              vperiodo06 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo06;
                            END
                         ELSE
                         IF (:vnumperiodo = 7) THEN
                            BEGIN
                              vperiodo07 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo07;
                            END
                         ELSE
                         IF (:vnumperiodo = 8) THEN
                            BEGIN
                              vperiodo08 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo08;
                            END
                         ELSE
                         IF (:vnumperiodo = 9) THEN
                            BEGIN
                              vperiodo09 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo09;
                            END
                         ELSE
                         IF (:vnumperiodo = 10) THEN
                            BEGIN
                              vperiodo10 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo10;
                            END
                         ELSE
                         IF (:vnumperiodo = 11) THEN
                            BEGIN
                              vperiodo11 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo11;
                            END
                         ELSE
                         IF (:vnumperiodo = 12) THEN
                            BEGIN
                              vperiodo12 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp) INTO :vvlrperiodo12;
                            END
                       END
                  END

        IF (:vperiodofinal = :prdatafinal) THEN
           vstop = 'TRUE';
      END

      vvlrtotperiodo = :vvlrperiodo01 + :vvlrperiodo02 + :vvlrperiodo03 + :vvlrperiodo04 + :vvlrperiodo05 + :vvlrperiodo06 + :vvlrperiodo07 +
                       :vvlrperiodo08 + :vvlrperiodo09 + :vvlrperiodo10 + :vvlrperiodo11 + :vvlrperiodo12;

      if (Upper(:vdesconto) = 'TRUE') then
         begin
           vvlrtotperiodo = - :vvlrtotperiodo;
           vvlrperiodo01 = - :vvlrperiodo01;
           vvlrperiodo02 = - :vvlrperiodo02;
           vvlrperiodo03 = - :vvlrperiodo03;
           vvlrperiodo04 = - :vvlrperiodo04;
           vvlrperiodo05 = - :vvlrperiodo05;
           vvlrperiodo06 = - :vvlrperiodo06;
           vvlrperiodo07 = - :vvlrperiodo07;
           vvlrperiodo08 = - :vvlrperiodo08;
           vvlrperiodo09 = - :vvlrperiodo09;
           vvlrperiodo10 = - :vvlrperiodo10;
           vvlrperiodo11 = - :vvlrperiodo11;
           vvlrperiodo12 = - :vvlrperiodo12;
         end

      INSERT INTO TMP_DEMRECDESP_ANALITICAS (BDCODOBRSER, BDCLASSIFICACAO, BDPERIODO01, BDVLRPERIODO01, BDPERIODO02, BDVLRPERIODO02, BDPERIODO03, BDVLRPERIODO03,
      BDPERIODO04, BDVLRPERIODO04, BDPERIODO05, BDVLRPERIODO05, BDPERIODO06, BDVLRPERIODO06, BDPERIODO07, BDVLRPERIODO07, BDPERIODO08, BDVLRPERIODO08,
      BDPERIODO09, BDVLRPERIODO09, BDPERIODO10, BDVLRPERIODO10, BDPERIODO11, BDVLRPERIODO11, BDPERIODO12, BDVLRPERIODO12, BDVLRTOTPERIODO)
      VALUES (:vcodserdesp, :vclassserdesp, :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
      :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08, :vperiodo09, :vvlrperiodo09,
      :vperiodo10, :vvlrperiodo10, :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12, :vvlrtotperiodo);

   END

   FOR
   EXECUTE STATEMENT :vsqlserdesp
   INTO
   :vcodserdesp,
   :vclassserdesp,
   :vdescserdesp,
   :vtiposerdesp
   DO
   BEGIN
     bdcodserdesp = :vcodserdesp;
     bdclassificacao = :vclassserdesp;
     bddescricao = :vdescserdesp;
     bdtipo = :vtiposerdesp;
     bdvlrtotperiodo = 0;

     SELECT bdperiodo01, SUM(bdvlrperiodo01) bdvlrperiodo01, bdperiodo02, SUM(bdvlrperiodo02) bdvlrperiodo02, bdperiodo03, SUM(bdvlrperiodo03) bdvlrperiodo03,
     bdperiodo04, SUM(bdvlrperiodo04) bdvlrperiodo04, bdperiodo05, SUM(bdvlrperiodo05) bdvlrperiodo05, bdperiodo06, SUM(bdvlrperiodo06) bdvlrperiodo06,
     bdperiodo07, SUM(bdvlrperiodo07) bdvlrperiodo07, bdperiodo08, SUM(bdvlrperiodo08) bdvlrperiodo08, bdperiodo09, SUM(bdvlrperiodo09) bdvlrperiodo09,
     bdperiodo10, SUM(bdvlrperiodo10) bdvlrperiodo10, bdperiodo11, SUM(bdvlrperiodo11) bdvlrperiodo11, bdperiodo12, SUM(bdvlrperiodo12) bdvlrperiodo12,
     SUM(bdvlrtotperiodo) bdvlrtotperiodo
     FROM TMP_DEMRECDESP_ANALITICAS
     WHERE bdclassificacao LIKE :vclassserdesp||'%'
     GROUP BY bdperiodo01, bdperiodo02, bdperiodo03, bdperiodo04, bdperiodo05, bdperiodo06, bdperiodo07,
     bdperiodo08, bdperiodo09, bdperiodo10, bdperiodo11, bdperiodo12
     INTO :bdperiodo01, :bdvlrperiodo01, :bdperiodo02, :bdvlrperiodo02, :bdperiodo03, :bdvlrperiodo03, :bdperiodo04, :bdvlrperiodo04,
     :bdperiodo05, :bdvlrperiodo05, :bdperiodo06, :bdvlrperiodo06, :bdperiodo07, :bdvlrperiodo07, :bdperiodo08, :bdvlrperiodo08,
     :bdperiodo09, :bdvlrperiodo09, :bdperiodo10, :bdvlrperiodo10, :bdperiodo11, :bdvlrperiodo11, :bdperiodo12, :bdvlrperiodo12,
     :bdvlrtotperiodo;

     -- Servi?os de desconto vem negativos
     IF (:bdvlrtotperiodo <> 0) THEN
        BEGIN
          SUSPEND;
        END
   END

   DELETE FROM TMP_DEMRECDESP_ANALITICAS;
END
^

/* Alter (SP_RETORNA_SALDO_EMP) */
ALTER PROCEDURE SP_RETORNA_SALDO_EMP(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(5000);
DECLARE VARIABLE wtemcc SMALLINT = 0;
DECLARE VARIABLE wtamanho INTEGER;
DECLARE VARIABLE wclassificacao VARCHAR(50);
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wdebito NUMERIC(15,2);
DECLARE VARIABLE wcredito NUMERIC(15,2);
DECLARE VARIABLE wlevel INTEGER;
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wvlr NUMERIC(15,2);
DECLARE VARIABLE wpermite INTEGER;
BEGIN
  codemp = prcodemp;
  SALDO_ANT_DEB = 0;
  SALDO_ANT_CRE = 0;
  saldo_anterior = 0;
  SALDO_DEB = 0;
  SALDO_CRE = 0;
  saldo_atual = 0;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and tpla.bdctalon like '''||wclassificacao||'%'' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROD = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_DEB do
     if (SALDO_DEB is null) then
        SALDO_DEB = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_DEB = SALDO_DEB + wvlr;
    END

--  exception ex_date;

  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROC = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_CRE do
     if (SALDO_CRE is null) then
        SALDO_CRE = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_CRE = SALDO_CRE + wvlr;
    END

  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';
/* #alt:6153 - gilberto - 09/08/2013 - retirado para sempre calcular zeramento no saldo anterior
  if (prignorazeramento = 1) then
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento
*/
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
     wsql = wsql||' and (TLAN.BDCODTERCEIROD = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_DEB do
     if (SALDO_ANT_DEB is null) then
        SALDO_ANT_DEB = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_ANT_DEB = SALDO_ANT_DEB + wvlr;
    END

  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';
/* #alt:6153 - gilberto - 09/08/2013 - retirado para sempre calcular zeramento no saldo anterior
  if (prignorazeramento = 1) then
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento
*/
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((BDCONCC is null) or (upper(bdconcc) = '|| '''FALSE'''||'))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em cosidera??o apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROC = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_CRE do
     if (SALDO_ANT_CRE is null) then
        SALDO_ANT_CRE = 0; */
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      IF (wpermite = 1) THEN
        SALDO_ANT_CRE = SALDO_ANT_CRE + wvlr;
    END

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;

  SUSPEND;
END
^

/* Alter (SP_RETORNA_SALDO_MATRIZFILIAL) */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WCODEMPEFILIAL INTEGER;
DECLARE VARIABLE WSALDODEB NUMERIC(15,2);
DECLARE VARIABLE WSALDOCRE NUMERIC(15,2);
DECLARE VARIABLE WSALANTDEB NUMERIC(15,2);
DECLARE VARIABLE WSALANTCRE NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
BEGIN
  codemp = prcodemp;

  IF (prmatrizfiliais IS NULL) THEN
     prmatrizfiliais = prcodemp;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and tpla.bdctalon like '''||wclassificacao||'%'' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);



  -- retorna as empresas selecionadas
  wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||PRMATRIZFILIAIS||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  wsaldodeb = 0;
  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  wsaldocre = 0;
  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  wsalantdeb = 0;
  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  wsalantcre = 0;

  movimento = 0;

  FOR EXECUTE STATEMENT wsqlemp
              INTO :wcodempefilial DO
  BEGIN


  -- SALDO A D?BITO ____________________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsaldodeb do
  if (wsaldodeb is null) then
     wsaldodeb=0;*/
  wsaldodeb = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsaldodeb = wsaldodeb + wvlr;
    END
  saldo_deb = saldo_deb + wsaldodeb;

--  exception ex_date;

  -- SALDO A CR?DITO ___________________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN '; */
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsaldocre do
  if (wsaldocre is null) then
     wsaldocre=0;*/
  wsaldocre = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsaldocre = wsaldocre + wvlr;
    END
  saldo_cre = saldo_cre + wsaldocre;

  -- SALDO ANTERIOR A D?BITO _________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsalantdeb do
  if (wsalantdeb is null) then
     wsalantdeb=0;*/
  wsalantdeb = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsalantdeb = wsalantdeb + wvlr;
    END
  saldo_ant_deb = saldo_ant_deb + wsalantdeb;

  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';  */
  wsql = 'Select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT ? FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT ? FEITO PARA QUANDO N?O TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lan?amento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial';
  --#alt:5837.
  /*for execute statement wSQL into :wsalantcre do
  if (wsalantcre is null) then
     wsalantcre=0;*/
  wsalantcre = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wfilial,:wtipolancfilial,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        wsalantcre = wsalantcre + wvlr;
    END

  saldo_ant_cre = saldo_ant_cre + wsalantcre;

END /* matriz e filiais */

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;
  ELSE
    BEGIN
      movimento = saldo_atual - saldo_anterior;
    END

  SUSPEND;
END
^

/* Alter (SP_RETORNA_SALDO_MATRIZFILIAL_X) */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL_X(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0,
PRCODTERCEIRO INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER,
CHAVELAN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WCODEMPEFILIAL INTEGER;
DECLARE VARIABLE WSALDODEB NUMERIC(15,2);
DECLARE VARIABLE WSALDOCRE NUMERIC(15,2);
DECLARE VARIABLE WSALANTDEB NUMERIC(15,2);
DECLARE VARIABLE WSALANTCRE NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WVLR_SALANT_DEB NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALATU_DEB NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALANT_CRE NUMERIC(15,2);
DECLARE VARIABLE WVLR_SALATU_CRE NUMERIC(15,2);
DECLARE VARIABLE WCHAVELAN INTEGER;
DECLARE VARIABLE WDEBCRE INTEGER;
BEGIN
  codemp = prcodemp;
  IF (prmatrizfiliais IS NULL) THEN
     prmatrizfiliais = prcodemp;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: N?o conciliados
  --   3: Pendentes
  --   4: Normal (todos, por?m sem mostrar a coluna no relat?rio)

  -- pega a classifica??o da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou n?o as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||' and tpla.bdctalon starts with '''||wclassificacao||''' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- retorna as empresas selecionadas
  wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  --wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) '; --alt:13181 - N?o usa para nada este join. Pedro
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||PRMATRIZFILIAIS||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  -- SALDO A D?BITO ____________________________________________________________
  SALDO_DEB = 0;
  wsaldodeb = 0;
  -- SALDO A CR?DITO ___________________________________________________________
  SALDO_CRE = 0;
  wsaldocre = 0;
  -- SALDO ANTERIOR A D?BITO _________________________________________________
  SALDO_ANT_DEB = 0;
  wsalantdeb = 0;
  -- SALDO ANTERIOR A CR?DITO __________________________________________________
  SALDO_ANT_CRE = 0;
  wsalantcre = 0;
  movimento = 0;

  FOR EXECUTE STATEMENT wsqlemp
              INTO :wcodempefilial DO
  BEGIN

    --alt:11995 - 12/08/2015 - Somente ir? agruprar tudo se n?o estiver fazendo isso na integra??o do Cont?bil pro Lalur (na parte de gravar as chaves dos lan?amentos integrados). Pedro
    wSQL = '';
    IF ((PRINTCONTABILLALUR IS NULL) OR (PRINTCONTABILLALUR = 0))  THEN
      BEGIN
        wsql =        'select bddebcre, bdcodemp, bdfilial, bdtipolancfilial, null as BDCHAVE,';
        wsql = wsql|| '       sum(bdsalant_deb) as bdsalant_deb, sum(bdsalatu_deb) as bdsalatu_deb, ';
        wsql = wsql|| '       sum(bdsalant_cre) as bdsalant_cre, sum(bdsalatu_cre) as bdsalatu_cre  ';
    
        wsql = wsql|| ' from (';
      END
    --alt:11995 - Fim

    /*****D?bito***************************************************************************************************************************************************************************/

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| 'Select 1 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, TLAN.BDCHAVE, ';
    ELSE
      wsql = wsql|| 'Select 1 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, ';
    --alt:13181 - Fim

    --if ((prcc <> 0) and (not (prcc is null))) then
    --   SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP))
    --else
      --coalesce(sum(tlan.bdvalor),0) AS SOMA
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata < '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalant_deb, ';
    
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata >= '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalatu_deb, ';
        wsql = wsql|| '0 as bdsalant_cre, 0 as bdsalatu_cre ';
    
        wsql = wsql|| ' FROM VSUC_EMPRESAS_TLAN TLAN ';
    
    IF (wlevel > 1) THEN
       BEGIN
         wsql = wsql|| ' inner join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null)) ';
         IF (prrelcta IS NOT NULL) THEN
            wsql = wsql|| ' and (tpla.bdrelcta = '||prrelcta||')) ';
         ELSE
            wsql = wsql|| ' ) ';
       END
  
    wsql = wsql|| ' where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';

    --alt:11995 - 30/07/2015 - Quando for o processo de integra??o do cont?bil para o lalur n?o deve somar os lan?amentos j? integrados manualmente. Pedro
    IF (PRINTCONTABILLALUR = 1) THEN
       wsql = wsql||' and (not exists (select BDCHAVE from VLAL_VINCULO_CONTABIL_LALUR where BDCODEMPFILIAL = tlan.BDCODEMP and BDCHAVE = tlan.BDCHAVE))';
  
    IF (prcontabilizacao <> 99) THEN
       wsql = wsql|| ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

    IF (wlevel = 1) THEN
       wsql = wsql|| ' and (tlan.bddebito = '||prconta||') ';
    ELSE
       wsql = wsql|| ' and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

    --#Alt:19568. Inclu?do o filtro do participante
    IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
       wsql = wsql|| ' and (tlan.bdcodterceirod = '||prcodterceiro||') ';
    
    --alt:7728 - Estava comentado o ignorar zeramento, habilitei novamente porque estava gerando uma diferen?a de saldos. Pedro
    IF (prignorazeramento = 1) THEN
       wsql = wsql|| ' AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
    --alt:7728 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
       --  AND (TLCC.bdcodtpcc = 'prcc')
    
    IF (bdconciliados = 1) THEN
       wsql = wsql|| ' and (Upper(BDCONCD) = '''||'TRUE'||''') ';
    ELSE
    IF (bdconciliados = 2) THEN
       wsql = wsql|| ' and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null)) ';
  
    wsql = wsql|| ' and (tlan.bddata <= '''||wdatfin||''') ';

    --alt:11995 - Se estiver carregando as chaves de lan?amentos para a integra??o do Lalur, n?o pode carregar chaves de per?odos anteriores. Pedro
    IF (PRINTCONTABILLALUR = 1)  THEN
      wsql = wsql|| ' and (tlan.bddata >= '''||wdatini||''') ';

    --alt:9604 - Alterada regra do c?digo da empresa e c?digo da filial, pois antes ele n?o verificava o TipoLancFilial
    --e pegava registros que estavam lan?ado na filial ou na matriz que n?o deveriam trazer aqui. Pedro
    --wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
    wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL <> 1) or (bdfilial = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL = 1)) ';
  
    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, TLAN.BDCHAVE ';
    ELSE
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial ';
    --alt:13181 - Fim
    

    /******Cr?dito**************************************************************************************************************************************************************/
    wsql = wsql|| ' union all ';

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' Select 2 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, TLAN.BDCHAVE, 0 as bdsalant_deb, 0 as bdsalatu_deb, ';
    ELSE
      wsql = wsql|| 'Select 2 as BDDEBCRE, tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial, 0 as bdsalant_deb, 0 as bdsalatu_deb, ';
    --alt:13181 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
      --   SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP))
      --else
        --coalesce(sum(tlan.bdvalor),0) AS SOMA
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata < '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalant_cre, ';
    
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata >= '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalatu_cre ';
    
        wsql = wsql|| ' FROM VSUC_EMPRESAS_TLAN TLAN ';
    
    IF (wlevel > 1) THEN
       BEGIN
         wsql = wsql|| ' inner join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null)) ';
         IF (prrelcta IS NOT NULL) THEN
            wsql = wsql|| ' and (tpla.bdrelcta = '||prrelcta||')) ';
         ELSE
            wsql = wsql|| ' ) ';
       END
    
    wsql = wsql|| ' where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
    
    --alt:11995 - 30/07/2015 - Quando for o processo de integra??o do cont?bil para o lalur n?o deve somar os lan?amentos j? integrados manualmente. Pedro
    IF (printcontabillalur = 1) THEN
       wsql = wsql||' and (not exists (select BDCHAVE from VLAL_VINCULO_CONTABIL_LALUR where BDCODEMPFILIAL = tlan.BDCODEMP and BDCHAVE = tlan.BDCHAVE))';

    IF (prcontabilizacao <> 99) THEN
       wsql = wsql|| ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

    IF (wlevel = 1) THEN
       wsql = wsql|| ' and (tlan.bdcredito = '||prconta||') ';
    ELSE
       wsql = wsql|| ' and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

    --#Alt:19568. Inclu?do o filtro do participante
    IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
       wsql = wsql|| ' and (tlan.bdcodterceiroc = '||prcodterceiro||') ';
    
    --alt:7728 - Estava comentado o ignorar zeramento, habilitei novamente porque estava gerando uma diferen?a de saldos. Pedro
    IF (prignorazeramento = 1) THEN
       wsql = wsql|| ' AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
    --alt:7728 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
       --  AND (TLCC.bdcodtpcc = 'prcc')
    
    IF (bdconciliados = 1) THEN
       wsql = wsql|| ' and (Upper(BDCONCD) = '''||'TRUE'||''') ';
    ELSE
    IF (bdconciliados = 2) THEN
       wsql = wsql|| ' and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null)) ';
  
    wsql = wsql|| ' and (tlan.bddata <= '''||wdatfin||''') ';

    --alt:11995 - Se estiver carregando as chaves de lan?amentos para a integra??o do Lalur, n?o pode carregar chaves de per?odos anteriores. Pedro
    IF (PRINTCONTABILLALUR = 1)  THEN
      wsql = wsql|| ' and (tlan.bddata >= '''||wdatini||''') ';

    --alt:9604 - Alterada regra do c?digo da empresa e c?digo da filial, pois antes ele n?o verificava o TipoLancFilial
    --e pegava registros que estavam lan?ado na filial ou na matriz que n?o deveriam trazer aqui. Pedro
    --wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
    wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL <> 2) or (bdfilial = '||wcodempefilial||' and TLAN.BDTIPOLANCFILIAL = 2)) ';
  

    --alt:13181 - 04/03/2016 - Se n?o estiver gravando a integra??o, n?o precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial, TLAN.BDCHAVE ';
    ELSE
       wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, tlan.bdfilial, tlan.bdtipolancfilial ';
    --alt:13181 - Fim

  --alt:11995 - 12/08/2015 - Somente ir? agruprar tudo se n?o estiver fazendo isso na integra??o do Cont?bil pro Lalur (na parte de gravar as chaves dos lan?amentos integrados). Pedro
  IF ((PRINTCONTABILLALUR IS NULL) OR (PRINTCONTABILLALUR = 0))  THEN
    wsql = wsql|| ' ) group by bddebcre, bdcodemp, bdfilial, bdtipolancfilial ';

  wvlr_salant_deb = 0;
  wvlr_salatu_deb = 0;
  wvlr_salant_cre = 0;
  wvlr_salatu_cre = 0;

  wsalantdeb = 0;
  wsaldodeb = 0;
  wsalantcre = 0;
  wsaldocre = 0;

  FOR EXECUTE STATEMENT wSQL INTO :wdebcre, :wcodemp,:wfilial,:wtipolancfilial, :CHAVELAN, :wvlr_salant_deb, :wvlr_salatu_deb, :wvlr_salant_cre, :wvlr_salatu_cre DO
    BEGIN
      IF (wvlr_salant_deb IS NULL) THEN
         wvlr_salant_deb = 0;

      IF (wvlr_salatu_deb IS NULL) THEN
         wvlr_salatu_deb = 0;

      IF (wvlr_salant_cre IS NULL) THEN
         wvlr_salant_cre = 0;

      IF (wvlr_salatu_cre IS NULL) THEN
         wvlr_salatu_cre = 0;

      --alt:13903 - 29/03/2016 - N?o estava verificando a regra do "lan?ar a" quando era no cr?dito, estava fixo o d?bito. Pedro
      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wdebcre,:wcodempefilial,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
      IF (wpermite = 1) THEN
        BEGIN
          wsalantdeb = wsalantdeb + wvlr_salant_deb;
          wsaldodeb = wsaldodeb + wvlr_salatu_deb;
          wsalantcre = wsalantcre + wvlr_salant_cre;
          wsaldocre = wsaldocre + wvlr_salatu_cre;

          --alt:11995 - 12/08/2015 - Se estiver fazendo o processo de gravar as chaves integradas do Cont?bil pro Lalur deve retornar um lan?amento para cada registro. Pedro
          IF ((CHAVELAN > 0) AND (printcontabillalur = 1)) THEN
            BEGIN
              CODEMP = :wcodempefilial;
              SUSPEND;
            END
        END
    END

    saldo_deb = saldo_deb + wsaldodeb;
    saldo_ant_deb = saldo_ant_deb + wsalantdeb;
    saldo_cre = saldo_cre + wsaldocre;
    saldo_ant_cre = saldo_ant_cre + wsalantcre;

  END /* matriz e filiais */

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB - SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE - SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;
  ELSE
    BEGIN
      movimento = saldo_atual - saldo_anterior;
    END

  --alt:11995 - 12/08/2015 - S? retorna aqui se n?o estiver fazendo o processo de integra??o, para n?o duplicar registros. Pedro
  IF ((printcontabillalur = 0) OR (printcontabillalur IS NULL))  THEN
    SUSPEND;
END
^

/* Alter (SP_VALIDA_EXPORTACAO_SPED) */
ALTER PROCEDURE SP_VALIDA_EXPORTACAO_SPED(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRBLOCO CHAR(4))
 AS
DECLARE VARIABLE WENTRADA INTEGER;
DECLARE VARIABLE WSAIDA INTEGER;
DECLARE VARIABLE WSQL VARCHAR(200);
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WQTDMAX INTEGER;
BEGIN
  wEntrada = 0;
  wSaida   = 1;
  PRBLOCO  = UPPER(:PRBLOCO);

  wSQL =          'SELECT COUNT(S.BDORDEMINCO) BDQTD ';
  wSQL = :wSQL || 'FROM TEXPORTACAO_SPED_INCO S ';
  wSQL = :wSQL || 'WHERE S.BDID = '''||:PRARQUIVO||''' ';
  wSQL = :wSQL || 'GROUP BY S.BDID';

  SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_LIM_INCO_EXPORTACAO') FROM RDB$DATABASE INTO :wQtdMax;
  SETORDEMSEQUENCIAL(0);  

  IF (:PRBLOCO = 'C100') THEN
    BEGIN
  /*****************************************************************************
   *                                   C113                                    *
   ****************************************************************************/
    
   IF (:PRDTINI > '12/31/2016') THEN
     BEGIN
       /*1 - Chave NFE inv?lida!*/
       INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
       SELECT :PRARQUIVO, C113.BDCHAVE, 1, :wEntrada, 'C113' /*Entrada*/
       FROM (
             SELECT MOVINF.BDCHAVE, MOVINF.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE(C113.BDCHAVENFE)) BDISVALID
             FROM (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                   FROM (
                         SELECT M.BDCODEMP, M.BDCHAVE
                         FROM VEF_EMP_TMOVENT M
                         WHERE M.BDCODEMP = :PRCODEMP
                         AND M.BDMODELO IN (1, 4, 55, 100)
                         AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                        ) MOV
                   JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  ) MOVINF                                                                                                                                            /*Modelos: 55, 57*/
             JOIN VEF_EMP_TMOVENTDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC AND C113.BDCODDOCFIS IN(30, 31))
            ) C113
       WHERE C113.BDISVALID = 'FALSE'
       UNION ALL
       SELECT :PRARQUIVO, C113.BDCHAVE, 1, :wSaida, 'C113' /*Sa?da*/
       FROM (
             SELECT MOVINF.BDCHAVE, MOVINF.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE(C113.BDCHAVENFE)) BDISVALID
             FROM (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                   FROM (
                         SELECT M.BDCODEMP, M.BDCHAVE
                         FROM VEF_EMP_TMOVSAI M
                         WHERE M.BDCODEMP = :PRCODEMP
                         AND M.BDMODELO IN (1, 4, 55, 100)
                         AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        ) MOV
                   JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  ) MOVINF                                                                                                                                            /*Modelos: 55, 57*/
             JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC AND C113.BDCODDOCFIS IN(30, 31))
            ) C113
       WHERE C113.BDISVALID = 'FALSE';
     END
      
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/
  /*2 - Produto sem vinculo com a empresa!*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODPROD, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, PRO.BDORDEMPRO, VINC.BDCODPROD, 2, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
       ) ENT
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')))
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, PRO.BDORDEMPRO, VINC.BDCODPROD, 2, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
       ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*3 - O valor total do desconto declarado no Registro C100 n?o confere com o somat?rio dos valores dos descontos declarados nos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, 3, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDORDEM
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) ENT
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
        GROUP BY ENT.BDCODEMP, ENT.BDCHAVE
       ) PRO
  JOIN VEF_EMP_TMOVENT LAN ON(LAN.BDCODEMP = PRO.BDCODEMP AND LAN.BDCHAVE = PRO.BDCHAVE)
  WHERE LAN.BDDESCONTONOTA <> PRO.BDVLRDESC
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, 3, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDORDEM
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) SAI
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
        GROUP BY SAI.BDCODEMP, SAI.BDCHAVE
       ) PRO
  JOIN VEF_EMP_TMOVSAI LAN ON(LAN.BDCODEMP = PRO.BDCODEMP AND LAN.BDCHAVE = PRO.BDCHAVE)
  WHERE LAN.BDDESCONTONOTA <> PRO.BDVLRDESC;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*4 - O valor declarado no campo Valor do PIS, no Registro C100, deve corresponder ? soma dos valores declarados no mesmo campo dos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 4, :wEntrada, 'C170' /*Entrada*/
  FROM (
        --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a vers?o com a altera??o abaixo corretamente.
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTPIS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPISPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTPIS <> PRO.BDVLRPISPROD
  UNION ALL
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 4, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTPIS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPISPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTPIS <> PRO.BDVLRPISPROD;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*5 - O valor declarado no campo Valor do Cofins, no Registro C100, deve corresponder ? soma dos valores declarados no mesmo campo dos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 5, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTCOFINS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINSPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTCOFINS <> PRO.BDVLRCOFINSPROD
  UNION ALL
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 5, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTCOFINS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINSPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTCOFINS <> PRO.BDVLRCOFINSPROD;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*6 - Quando o campo ALIQ_ICMS (Al?quota do ICMS) for preenchido com um valor maior que zero no Registro C170, os valores dos campos VL_BC_ICMS e VL_ICMS tamb?m devem ser maiores que zero.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 6, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 ((PRO.BDALIQICMS > 0) AND ((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) AND ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 6, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 ((PRO.BDALIQICMS > 0) AND ((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) AND ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*7 - O campo VL_BC_IPI (Valor da base de c?lculo do IPI) e/ou VL_IPI (Valor do IPI) est?(?o) inconsistente(s) no Registro C170. Observar: Os campos VL_BC_IPI e VL_IPI n?o devem ser maior que 0 (zero) quando a CST-IPI for diferente de: 00 e/ou 50.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 7, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI NOT IN(1, 8) AND ((PRO.BDBCIPI > 0) OR (PRO.BDVLRIPI > 0)))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 7, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI NOT IN(1, 8) AND ((PRO.BDBCIPI > 0) OR (PRO.BDVLRIPI > 0)));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*8 - Registro C170 se os dois ?ltimos d?gitos do C?digo da Situa??o Tribut?ria (CST_ICMS) forem diferentes de: 30, 40, 41,50 e/ou 60.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 8, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTICMS = 1 AND (((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) OR
                                                           ((PRO.BDALIQICMS IS NULL) OR (PRO.BDALIQICMS = 0)) OR
                                                           ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 8, :wSaida, 'C170' /*Sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTICMS = 1 AND (((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) OR
                                                           ((PRO.BDALIQICMS IS NULL) OR (PRO.BDALIQICMS = 0)) OR
                                                           ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*9 - O campo Base de IPI/aliquota/valor do IPI deve ser maior que 0 (zero) se o Campo CST_IPI estiver preenchido com CST?s representativos de receitas tributadas ou opera??es com direito a cr?dito: 00 (Entrada) e/ou 50 (Sa?das).*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 9, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI IN (1, 8) AND (((PRO.BDBCIPI IS NULL) OR (PRO.BDBCIPI = 0)) OR
                                                                ((PRO.BDALIQIPI IS NULL) OR (PRO.BDALIQIPI = 0)) OR
                                                                ((PRO.BDVLRIPI IS NULL) OR (PRO.BDVLRIPI = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 9, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI IN (1, 8) AND (((PRO.BDBCIPI IS NULL) OR (PRO.BDBCIPI = 0)) OR
                                                                ((PRO.BDALIQIPI IS NULL) OR (PRO.BDALIQIPI = 0)) OR
                                                                ((PRO.BDVLRIPI IS NULL) OR (PRO.BDVLRIPI = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*10 - Itens declarados com CFOP de ativo imobilizado devem ser declarados com o tipo do item igual a 08.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 10, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 9
  AND C170.BDCODNAT IN(1406, 1551, 2406, 2551)
  UNION ALL
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 10, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 9
  AND C170.BDCODNAT IN(1406, 1551, 2406, 2551);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*11 - Itens declarados com CFOP de uso e consumo devem ser declarados com o tipo do item igual a 07.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 11, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 8
  AND C170.BDCODNAT IN(1407, 1556, 2407, 2556, 1653, 2653)
  UNION ALL
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 11, :wSaida, 'C170' /*sa?da*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 8
  AND C170.BDCODNAT IN(1407, 1556, 2407, 2556, 1653, 2653);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*12 - Deve ser informado se o C?digo da Situa??o Tribut?ria referente ao IPI (CST_IPI) for igual a: 01,02,03,04,05
    13 - Deve ser informado se o C?digo da Situa??o Tribut?ria referente ao IPI (CST_IPI) for igual a: 51,52,53,54,55*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 12, :wEntrada, 'C110' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND PRO.BDCODCSTIPI IN(2, 3, 4, 5, 6))
  LEFT OUTER JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 13, :wSaida, 'C110' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND PRO.BDCODCSTIPI IN(9, 10, 11, 12, 13))
  LEFT OUTER JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  WHERE INF.BDCHAVE IS NULL; /*N?o existe informa??o complementar para este lan?amento*/
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*14 - Normalmente deve ser informado se os dois ?ltimos d?gitos do C?digo da Situa??o Tribut?ria referente ao ICMS (CST_ICMS) forem iguais a:
         20, 30, 40, 41, 50, 51 e/ou 70. Consulte a legisla??o do seu estado sobre a obrigatoriedade.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 14, :wEntrada, 'C110' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) IN (20, 30, 40, 41, 50, 51, 70)
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 14, :wSaida, 'C110' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE INF.BDCHAVE IS NULL /*N?o existe informa??o complementar para este lan?amento*/
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) IN (20, 30, 40, 41, 50, 51, 70);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*15 - Diverg?ncia entre CST e CFOP em opera??o sujeita ao regime de substitui??o tribut?ria no Registro C170. O CST deve possuir final 10,30,60 e 70 ou os c?digos 201,202,203 e 500.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 15, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDCODNAT
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE (((MOV.BDCODNAT >= 1401000) AND (MOV.BDCODNAT <= 1415000)) OR ((MOV.BDCODNAT >= 2401000) AND (MOV.BDCODNAT <= 2415000)))
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) NOT IN(10, 30, 60, 70)
  AND CST.BDCSTICMS NOT IN(201, 202, 203, 500);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
    
  /*16 - Diverg?ncia entre CST e CFOP em opera??o de compra de material para uso ou consumo. Para CFOP?s de compra de material para uso ou consumo (1.556 e 2.556), o CST deve ter os 2? e 3? d?gitos iguais a 90 ? outras.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 16, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE MOV.BDCODNAT IN(1556, 2556)
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) <> '90';
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*17 - Foram detectados CFOP(s) de energia el?trica, comunica??o/telecomunica??o e/ou transportes indevidamente declarado(s) no Registro C190.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 17, :wEntrada, 'C190' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO = 1
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND
                                       SUBSTRING(I.BDCODNAT FROM 1 FOR 4) IN(1207, 1153, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 2153, 2207, 2251, 2252, 2253, 2254, 2255, 2256, 2257,
                                                                             3207, 3251, 5153, 5207, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 6153, 6207, 6251, 6252, 6253, 6254,
                                                                             6255, 6256, 6257, 6258, 7207, 7251, 1205, 1301, 1302, 1303, 1304, 1305, 1306, 2205, 2301, 2302, 2303, 2304,
                                                                             2305, 2306, 3205, 3301, 5205, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 6205, 6301, 6302, 6303, 6304, 6305,
                                                                             6306, 6307, 7205, 7301, 1206, 1351, 1352, 1353, 1354, 1355, 1356, 1360, 1931, 1932, 2206, 2351, 2352, 2353,
                                                                             2354, 2355, 2356, 2931, 2932, 3206, 3351, 3352, 3353, 3354, 3355, 3356, 5206, 5351, 5352, 5353, 5354, 5355,
                                                                             5356, 5357, 5359, 5360, 5931, 5932, 6206, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6359, 6360, 7206, 7358))
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 17, :wSaida, 'C190' /*sa?da*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO = 1
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND
                                       SUBSTRING(I.BDCODNAT FROM 1 FOR 4) IN(1207, 1153, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 2153, 2207, 2251, 2252, 2253, 2254, 2255, 2256, 2257,
                                                                             3207, 3251, 5153, 5207, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 6153, 6207, 6251, 6252, 6253, 6254,
                                                                             6255, 6256, 6257, 6258, 7207, 7251, 1205, 1301, 1302, 1303, 1304, 1305, 1306, 2205, 2301, 2302, 2303, 2304,
                                                                             2305, 2306, 3205, 3301, 5205, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 6205, 6301, 6302, 6303, 6304, 6305,
                                                                             6306, 6307, 7205, 7301, 1206, 1351, 1352, 1353, 1354, 1355, 1356, 1360, 1931, 1932, 2206, 2351, 2352, 2353,
                                                                             2354, 2355, 2356, 2931, 2932, 3206, 3351, 3352, 3353, 3354, 3355, 3356, 5206, 5351, 5352, 5353, 5354, 5355,
                                                                             5356, 5357, 5359, 5360, 5931, 5932, 6206, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6359, 6360, 7206, 7358))
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM);
    
  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  /*18 - Sem produto.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, MOV.BDCHAVE, 18, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVENT M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  WHERE PRO.BDORDEMPRO IS NULL
  UNION ALL
  SELECT :PRARQUIVO, MOV.BDCHAVE, 18, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVSAI M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  WHERE PRO.BDORDEMPRO IS NULL;
    
  /*19 - Com indicador de pagamento a prazo sem informa??o de parcelas.*/
  /*A partir dos produtos*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, MOV.BDCHAVE, 19, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE
        FROM VEF_EMP_TMOVENT M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO = 1
        AND M.BDCONDPGTO = 1 /*Prazo*/
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVENTPAR PAR ON(PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
  WHERE PAR.BDORDEMPAR IS NULL
  UNION ALL
  SELECT :PRARQUIVO, MOV.BDCHAVE, 19, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVSAI M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND M.BDCONDPGTO = 1 /*Prazo*/        
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON(PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
  WHERE PAR.BDORDEMPAR IS NULL;
    
  /*20 - Existe diferen?a entre base/valor de ICMS da nota e a base/valor de ICMS dos produtos.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 20, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = ENT.BDORDEM)
  WHERE ENT.BDBCICMS <> I.BDBASEICMS
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 20, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
  WHERE SAI.BDBCICMS <> I.BDBASEICMS;
    
  /*21 - Existe diferen?a entre base/valor de IPI da nota e a base/valor de IPI dos produtos.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 21, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = ENT.BDORDEM)
  WHERE ENT.BDBCIPI <> I.BDBASEIPI
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 21, :wSaida, 'C100' /*Sa?da*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
  WHERE SAI.BDBCIPI <> I.BDBASEIPI;
    END
  ELSE
  IF (:PRBLOCO = 'D100') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
      SELECT :PRARQUIVO, MOV.BDCHAVE, 22, :wEntrada, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, COALESCE(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))), '') BDCHAVECTEREF
            FROM VEF_EMP_TMOVENT E
            JOIN VEF_EMP_TD100ENT D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE MOV.BDCHAVECTEREF <> ''
      UNION ALL
      SELECT :PRARQUIVO, MOV.BDCHAVE, 22, :wSaida, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, COALESCE(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))), '') BDCHAVECTEREF
            FROM VEF_EMP_TMOVSAI E
            JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE MOV.BDCHAVECTEREF <> '';
    END
END
^

/* Alter (SP_VRH_VAL_RAIS_FF_REF) */
ALTER PROCEDURE SP_VRH_VAL_RAIS_FF_REF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
DECLARE VARIABLE WANOINI INTEGER;
DECLARE VARIABLE WANOFIM INTEGER;
BEGIN
  /* Procedure Text */
  wAnoIni = CAST(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wAnoFim = CAST(SUBSTRING(CAST(prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  IF ((premp IS NOT NULL) AND (premp <> '')) THEN
     BEGIN
       premp = UPPER(premp);
       IF (POSITION('TAB.BDCODEMP',premp) > 0) THEN
          BEGIN
            SELECT bdresult FROM strtran(:premp,'TAB.BDCODEMP','COL.BDCODEMP') INTO premp;
          END
     END

  WHILE (wAnoIni <= wAnoFim) DO
    BEGIN
      FOR SELECT BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade FROM SP_VRH_VAL_RAIS_FF(:premp,:prcol,:wanoini)
          INTO BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade DO

          IF ((bdref >= prrefini) AND (bdref <= prreffim)) THEN
             SUSPEND;

      wAnoIni = wanoini+ 1;
    END

END
^

/* Alter (SP_VRHF_DECLARACAO_DOMESTICO) */
ALTER PROCEDURE SP_VRHF_DECLARACAO_DOMESTICO(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRANOBASE INTEGER,
PRTOMADOR INTEGER,
PRCODSIND INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRORDEM VARCHAR(50),
PRDATAEMISSAO VARCHAR(10),
PRSITUACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADM DATE,
BDDATARESCISAO DATE,
BDPIS VARCHAR(14),
BDCPF VARCHAR(14),
BDCOMPETENCIA INTEGER,
BDSALMIN NUMERIC(15,6),
BDBINSSN NUMERIC(15,6),
BDBINSSFE NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDREMUNERACAO NUMERIC(18,6),
BDINSSPATRONAL NUMERIC(15,6),
BDDIFERENCAINSS NUMERIC(15,6),
BDTOTALCONTRPATRONAL NUMERIC(15,6),
BDPARCELANAODEDUTIVEL NUMERIC(15,6),
BDINF VARCHAR(20),
BDORDEM VARCHAR(50),
BDDATAEMISSAO VARCHAR(10),
BDANOBASE INTEGER)
 AS
declare variable WULTDIA varchar(10);
declare variable WPRIDIA varchar(10);
declare variable WDIA varchar(10);
declare variable WMES varchar(10);
declare variable WORDEM varchar(50);
declare variable WPRIDIAEMISSAO varchar(10);
declare variable WULTDIAEMISSAO varchar(10);
declare variable WWHERE varchar(30000);
declare variable WSQLALIQ varchar(500);
declare variable WSQL varchar(30000);
declare variable WALIQINSS numeric(18,6);
declare variable WBASE numeric(18,6);
BEGIN
  wpridia = '01/01/'||pranobase;
  wultdia = '12/31/'||pranobase;

  wmes = SUBSTRING(:prdataemissao FROM 4 FOR 2);
  SELECT ultdia FROM ultimo_dia_mes(:wmes, :pranobase) INTO :wdia;
  wpridiaemissao = wmes||'/01/'||pranobase;
  wultdiaemissao = wmes||'/'||wdia||'/'||pranobase;

  wwhere = '';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       wwhere = ' where ' || prcodemp;

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wwhere = wwhere || ' and ' || prcodcol;
     END
  ELSE
     BEGIN
       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wwhere = ' where ' || prcodcol;
     END

  IF (prtomador > 0) THEN
     wordem = ', ORDEM ';
  ELSE
     wordem = ', null ';

  wsql = 'select distinct BDCODEMPRESA, BDCODCOLABORADOR, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOCREF.BDPISCOL, COL.BDCPFCOL, REF, ' ||
         'max(SALMIN.BDSALMIN) SALMIN, COALESCE(INSS, 0), COALESCE(INSSFE, 0), COALESCE(INSS13, 0), INF ' || wordem;

  IF (prtomador > 0) THEN
     wordem = ', NULL AS ORDEM ';
  ELSE
     wordem = '';

  wsql = wsql || 'from (select FN.BDCODEMP as BDCODEMPRESA, FN.BDCODCOL as BDCODCOLABORADOR, FN.BDREFFN as REF, ' ||
         'FN.BDBINSSFN as INSS, FN.BDBINSSFEFOLFN as INSSFE, FN.BDBINSS13FN as INSS13, '''' as INF ' || wordem || ' from VRHF_EMP_TFOLHANORMAL FN ' || wwhere;

  wsql = wsql || ' union all select FC.BDCODEMP as BDCODEMPRESA, FC.BDCODCOL as BDCODCOLABORADOR, FC.BDREFCOMP as REF, ' ||
            'FC.BDBINSSFC as INSS, FC.BDBINSSFEFOLFC as INSSFE, FC.BDBINSS13FC as INSS13, ''Fol. Compl.'' as INF' || wordem || ' from VRHF_EMP_TFOLHACOMP FC ' || wwhere;

  wsql = wsql || ' union all select F13SAL.BDCODEMP as BDCODEMPRESA, F13SAL.BDCODCOL as BDCODCOLABORADOR, F13SAL.BDREF13 as REF, ' ||
            'F13SAL.BDBASEINSS13 as INSS, 0 as INSSFE, 0 as INSS13, ''13? Sal.'' as INF' || wordem || ' from VRHF_EMP_T13SAL F13SAL ' || wwhere;

  IF (prtomador > 0) THEN
     wordem = ', FT.BDORDEM AS ORDEM ';

  wsql = wsql || ' union all select FT.BDCODEMP as BDCODEMPRESA, FT.BDCODCOL as BDCODCOLABORADOR, FT.BDREFTOMADOR as REF, ' ||
            'SUM(FT.BDBINSSFT) as INSS, SUM(FT.BDBINSSFEFOLFT) as INSSFE, SUM(FT.BDBINSS13FT) as INSS13, '''' as INF' || wordem || ' from VRHF_EMP_TFOLHATOMADOR FT ' || wwhere ||
            ' group by REF, BDCODEMPRESA, BDCODCOLABORADOR, INF';

  IF (prtomador > 0) THEN
     BEGIN
       wsql = wsql || ', FT.BDORDEM ';
       wordem = ', FTC.BDORDEM AS ORDEM ';
     END

  wsql = wsql || ' union all select FTC.BDCODEMP as BDCODEMPRESA, FTC.BDCODCOL as BDCODCOLABORADOR, FTC.bdreftomador as REF, ' ||
            'FTC.BDBINSSFC as INSS, FTC.BDBINSSFEFOLFC as INSSFE, FTC.BDBINSS13FC as INSS13, ''Fol. Compl'' as INF' || wordem || ' from VRHF_EMP_TFOLTOMCOMP FTC ' || wwhere;

  IF (prtomador > 0) THEN
     wordem = ', FER.BDORDEM AS ORDEM';

  wsql = wsql || ' union all select FER.BDCODEMP as BDCODEMPRESA, FER.BDCODCOL as BDCODCOLABORADOR, FER.BDREFINIFE as REF, ' ||
            'FER.BDBASEINSSFE as INSS, 0 as INSSFE, 0 as INSS13, ''F?rias'' as INF' || wordem || ' from VRH_EMP_TFERIAS FER ' || wwhere || ') ';

  wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = BDCODEMPRESA and COL.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRH_EMP_TCOLCON_DOC DOC on (DOC.BDCODEMP = COL.BDCODEMP and DOC.BDCODCOL = COL.BDCODCOL) ' ||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = BDCODEMPRESA and RESC.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRHF_TABELAS_TSALMIN SALMIN on (SALMIN.BDREFSM <= REF) ' ||
         'left outer join VRH_EMP_TCOLCON_VINC VINC on (VINC.BDCODEMP = BDCODEMPRESA and VINC.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRH_BASE_TCLASSE CLAS on (VINC.BDCODCLA = CLAS.BDCODCLA) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = BDCODEMPRESA and COLCAD.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = BDCODEMPRESA and DOCREF.BDCODCOL = BDCODCOLABORADOR) ';

  -- Filtros
  IF (prtomador > 0) THEN
     BEGIN
       wsql = wsql || 'left outer join VRHF_EMP_TPREPFN PREP on (prep.bdcodemp = bdcodempresa and prep.bdcodcol = bdcodcolaborador and prep.bdordem = ordem) ';
     END

  IF (prcodsind > 0) THEN
     wsql = wsql || 'left outer join VRH_EMP_TCOL_VINC VINC2 on (vinc2.bdcodemp = bdcodempresa and vinc2.bdcodcol = bdcodcolaborador) ';

  IF (prfuncao > 0) THEN
     wsql = wsql || 'left outer join VRH_EMP_TCOL_VINCDIA coldia on (coldia.bdcodemp = bdcodempresa and coldia.bdcodcol = bdcodcolaborador) ';

  IF (prsituacao = 0) THEN
     wSql = wSql || ' join SP_SOMENTE_ATIVOS(''' || wpridia || ''', ''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ';

  IF (prsituacao = 2) THEN
     wSql = wSql || ' join SP_SOMENTE_DEMITIDOS(''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 3) THEN
     wSql = wSql || ' join SP_SOMENTE_ADMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 4) THEN
     wSql = wSql || ' join SP_SOMENTE_DEMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 5) THEN
     wSql = wSql || ' join SP_ATIVOS_SEM_DEMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 6) THEN
     wSql = wSql || ' join SP_ATI_SEM_DEM_COM_TRANSF(''' || wpridia || ''',''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 7) THEN
     wSql = wSql || ' join SP_ATI_SEM_AFAST_MES_INT(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 8) THEN
     wSql = wSql || ' join SP_AFASTADOS_MES_INTEIRO(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  -- Where e filtros
  wwhere = ' where clas.bdgrupocla = 7 and SUBSTRING(CAST(REF AS VARCHAR(6)) FROM 1 FOR 4) = ' || pranobase;

  IF (prtomador > 0) THEN
     BEGIN
       wwhere = wwhere || ' and prep.bdcodtpcc = '||prtomador;
       wordem = ', ORDEM ';
     END
  ELSE
     wordem = '';

  IF (prcodsind > 0) THEN
     wwhere = wwhere||' and vinc2.bdcodsintrab = '||prcodsind;

  IF (prclasse > 0) THEN
     wwhere = wwhere||' and vinc.bdcodcla = '||prclasse;

  IF (prfuncao > 0) THEN
     wwhere = wwhere||' and coldia.bdcodtfuc = '||prfuncao;

  wsql = wsql || wwhere || ' group by BDCODEMPRESA, BDCODCOLABORADOR, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOCREF.BDPISCOL, COL.BDCPFCOL, REF, ' ||
         'INSS, INSSFE, INSS13, INF ' || wordem;

  IF (prordem IS NOT NULL AND prordem <> '') THEN
     BEGIN
       IF (PRORDEM = 'BDCODCOL') THEN
          wsql = wsql || 'ORDER BY BDCODEMPRESA, BDCODCOLABORADOR, REF, INF ';
       ELSE
          wsql = wsql || 'ORDER BY BDCODEMPRESA, COLCAD.BDNOMCOL, REF, INF ';
     END
  ELSE
     wsql = wsql || 'ORDER BY BDCODEMPRESA, REF, INF ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcodcol,
    :bdnomcol,
    :bddataadm,
    :bddatarescisao,
    :bdpis,
    :bdcpf,
    :bdcompetencia,
    :bdsalmin,
    :bdbinssn,
    :bdbinssfe,
    :bdbinss13,
    :bdinf,
    :bdordem
  DO
    BEGIN
      bdremuneracao = bdbinssn + bdbinssfe + bdbinss13;
      bddataemissao = prdataemissao;
      bdanobase = pranobase;
      bdtotalcontrpatronal  = bdremuneracao * 12 / 100;

      IF ((bdremuneracao - bdsalmin) > 0) THEN
         bdparcelanaodedutivel = (bdremuneracao - bdsalmin) * 12 / 100;
      ELSE
         bdparcelanaodedutivel = 0;

      wbase = 0;
      IF (bdbinssn IS NOT NULL AND bdbinssn > 0) THEN
         BEGIN
           wbase = bdbinssn;
           wsqlaliq = 'select fol.bdaliqinssfn from vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
                || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
         END
      ELSE
      IF (bdbinssfe IS NOT NULL AND bdbinssfe > 0) THEN
         BEGIN
           wbase = bdbinssfe;
           wsqlaliq = 'select fol.bdaliqinssfefolfn from vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
           || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
         END
      ELSE
      IF (bdbinss13 IS NOT NULL AND bdbinss13 > 0) THEN
        BEGIN
          wbase = bdbinss13;
          wsqlaliq = 'select fol.bdaliqinss13fn vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
          || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
        END
      ELSE
      -- N?o tem c?lculo nenhum
        wsqlaliq = '';

      IF (wsqlaliq IS NOT NULL AND wsqlaliq <> '') THEN
        BEGIN
          FOR EXECUTE STATEMENT wsqlaliq
          INTO
            :waliqinss
          DO
            BEGIN
              bdinsspatronal = wbase * waliqinss / 100;
            
              IF (bdremuneracao < bdsalmin) THEN
                 bddiferencainss = 0;
              ELSE
                 bddiferencainss = (bdremuneracao - bdsalmin) * waliqinss / 100;
            END
        END
      ELSE
        BEGIN
          bdinsspatronal = 0;
          bddiferencainss = 0;
        END

      SUSPEND;
    END
END
^

/* Alter (VRHF_SP_TTEMPOTRAB) */
ALTER PROCEDURE VRHF_SP_TTEMPOTRAB(PRCODEMP INTEGER,
PRCODFUN INTEGER,
PRDATAENT DATE,
PRHORAENT TIME,
PRDATASAI DATE,
PRHORASAI TIME)
 RETURNS(BDTEMPO INTEGER)
 AS
DECLARE VARIABLE wdataatu DATE;
DECLARE VARIABLE wdiasemana INTEGER;
DECLARE VARIABLE wsqlhorario VARCHAR(32700);
DECLARE VARIABLE whorario INTEGER;
DECLARE VARIABLE whoraent TIME;
DECLARE VARIABLE whorasai TIME;
BEGIN
  bdtempo = 0;
  /* Procedure Text */
    wdataatu = prdataent;
    WHILE (wdataatu <= prdatasai) DO
    BEGIN
      wdiasemana = EXTRACT(WEEKDAY FROM wdataatu);
    
        wsqlhorario = 'select first 1 qh.bdcodqh from VRH_EMP_TCOL_VINCDIA cd'||
                        ' left outer join vrh_base_tqh_dias qh on (cd.bdcodqh = qh.bdcodqh)'||
                        ' left outer join vrh_base_tqh_horario qhh on (qh.bdcodqh = qhh.bdcodqhh)'||
                        ' where cd.bdcodemp = '||:prcodemp||' and cd.bdcodcol = '||:prcodfun||' and'||
                        ' qh.bddiasemqh = '||wdiasemana||' and'||
                        ' cd.bddatacol = (select first 1 cd.bddatacol from VRH_EMP_TCOL_VINCDIA cd'||
                        '                    left outer join vrh_base_tqh_dias qh on (cd.bdcodqh = qh.bdcodqh)'||
                        '                    left outer join vrh_base_tqh_horario qhh on (qh.bdcodqh = qhh.bdcodqhh)'||
                        '                    where cd.bdcodemp = '||:prcodemp||' and cd.bdcodcol = '||:prcodfun||
                        '                    and cd.bddatacol <= cast('||''''||CAST(wdataatu AS VARCHAR(10))||''''||' as date)'||
                        '                    order by cd.bddatacol desc)'||
                        ' order by cd.bddatacol desc';

    
        FOR EXECUTE STATEMENT wsqlhorario INTO :WHORARIO DO
          BEGIN
              wsqlhorario = 'select tqh.bdqhhsent,tqh.bdqhhssai from vrh_base_tqh_horas tqh'||
                            ' where tqh.bdcodqhh = '||:whorario;
    
              FOR EXECUTE STATEMENT wsqlhorario INTO :whoraent,:whorasai DO
                BEGIN
                  IF ((wdataatu = prdatasai) AND (whoraent > prhorasai)) THEN
                     BREAK;
    
                  IF (wdataatu = prdataent) THEN
                     BEGIN
                       IF (whoraent < :prhoraent) THEN
                          BEGIN
                            whoraent = :prhoraent;
                          END
                     END
    
                  IF (wdataatu = prdatasai) THEN
                     BEGIN
                       IF (whorasai > prhorasai) THEN
                          BEGIN
                            whorasai = prhorasai;
                          END
                     END
    
                   IF ((whoraent > :prhoraent) OR ((whoraent < :prhoraent) AND (whorasai > :prhoraent)) OR
                      (((whoraent < :prhoraent) AND (whorasai < :prhoraent)) AND (whorasai < whoraent))) THEN
                      BEGIN
                        IF  (whorasai < whoraent) THEN
                           BEGIN
                              bdtempo = bdtempo + CAST((CAST('23:59' AS TIME) - whoraent)/60 AS INTEGER) + 1;
                              bdtempo = bdtempo + CAST(CAST(whorasai - CAST('00:00' AS TIME) AS INTEGER)/60 AS INTEGER);
                           END
                        ELSE
                           BEGIN
                              bdtempo = bdtempo + CAST((whorasai - whoraent)/60 AS INTEGER);
                           END
                      END
                END
          END
    
      IF (wdataatu = prdatasai) THEN
         BREAK;
    
      SELECT PRDIASEGUINTE FROM dia_seguinte(:wdataatu) INTO wdataatu;
    END
  SUSPEND;
END
^

/* Alter (VSUC_SP_BALANCETE_MENSAL) */
ALTER PROCEDURE VSUC_SP_BALANCETE_MENSAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDDATINI DATE,
BDDATFIN DATE,
BDAPECTA VARCHAR(20))
 AS
DECLARE VARIABLE WDATINI DATE;
DECLARE VARIABLE WDATFIN DATE;
BEGIN
  wdatini = prdatini;
  wdatfin = addmonth(wdatini, 1)-1;
  WHILE (wdatfin <= prdatfin) DO
    BEGIN
      bddatini = wdatini;
      bddatfin = wdatfin;
      FOR SELECT BDCODEMP, BDNOMEMP, BDCNPJEMP, BDCODMATRIZ, BDCODEMPFILIAL, BDCODPLAPADRAO,
                 BDCODCTA, BDCTALON, BDNOMCTA, BDTIPCTA, BDCODTPCC, BDNOMTPCC,
                 BDSALDO_ANTERIOR, BDSALDO_ANT_DEB, BDSALDO_ANT_CRE, BDSALDO_DEB,
                 BDSALDO_CRE, BDSALDO_ATUAL, BDGRPCTA, BDTPCCLON, BDMOVIMENTO,
                 BDFORMULA, BDRELCTA, BDCLANOM, BDAPECTA
          FROM vsuc_sp_retorna_balancete(:prcodemp, :wdatini, :wdatfin, :prindice, :prignora_zeramento, :prctaini, :prctafin, :prcodtpcc, :prrefemp, :prlansemcc, 0, :prnaomostracontacomp,
                                         :prconsolidada, :prdetalharctaparticipante, :PRAGRUPARPARTICIPANTEPORCNPJ, :prconcatenacodparticipante, :prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado, 0)
          INTO :BDCODEMP, :BDNOMEMP, :BDCNPJEMP, :BDCODMATRIZ, :BDCODEMPFILIAL, :BDCODPLAPADRAO,
               :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDCODTPCC, :BDNOMTPCC,
               :BDSALDO_ANTERIOR, :BDSALDO_ANT_DEB, :BDSALDO_ANT_CRE, :BDSALDO_DEB,
               :BDSALDO_CRE, :BDSALDO_ATUAL, :BDGRPCTA, :BDTPCCLON, :BDMOVIMENTO,
               :BDFORMULA, :BDRELCTA, :BDCLANOM, :BDAPECTA DO
          SUSPEND;

      wdatini = addmonth(wdatini, 1);
      wdatfin = addmonth(wdatini, 1)-1;
    END
END
^

/* Alter (VSUC_SP_BALANCO_PATRIMONIAL) */
ALTER PROCEDURE VSUC_SP_BALANCO_PATRIMONIAL(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSEMCC INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSAL_ANT_DEB NUMERIC(15,2),
BDSAL_ANT_CRE NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDCODEMPFILIAL INTEGER,
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20),
BDPERTENCECONTA INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(4096);
DECLARE VARIABLE WSQLTCC VARCHAR(1024);
DECLARE VARIABLE WSEQCTA VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WCTALONATIVO VARCHAR(40);
DECLARE VARIABLE WCTALONPATLIQ VARCHAR(40);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
DECLARE VARIABLE WCODEMPATUAL INTEGER;
DECLARE VARIABLE WRELCONTA INTEGER;
BEGIN
  -- sql referente as empresas selecionadas
  wsqlemp = 'select bdcodemp, bdcodmatriz, bdcodplapadrao,  bdcodcentros from vw_empresas_ref_atual where bdcodemp in ('||prcodemp||') order by bdcodmatriz,  bdcodemp';
  -- laco das empresas selecionadas
  wdatahora = CURRENT_TIMESTAMP;

  FOR EXECUTE STATEMENT wsqlemp
      INTO :wcodemp, :bdcodmatriz, :wcodplapadrao, :wcodcentros DO
      BEGIN
        -- retorna a primeira conta do ativo
        SELECT FIRST 1 planos_tpla.bdcodtpla, planos_tpla.bdctalon FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
        AND planos_tpla.bdctalon = :prctalonini
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini, :wctalonativo;

        -- retorna a primeira conta do passivo a descoberto
        SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
        AND planos_tpla.bdctalon = :prctalonpas
        ORDER BY planos_tpla.bdctalon ASC INTO :wctalonpatliq;

        -- retorna a ultima conta do resto do plano
        wsql = 'select first 1 planos_tpla.bdcodtpla from planos_tpla ';
        wsql = wsql||'where planos_tpla.bdcodplapadrao = '||wcodplapadrao;
        wsql = wsql||' and substring(planos_tpla.bdctalon from 1 for '||strlen(prctalonfin)||') = '''||prctalonfin||'''';
        wsql = wsql||'order by planos_tpla.bdctalon desc';
        EXECUTE STATEMENT wsql INTO :wcodctafin;

        -- sql responsavel pela limpeza da tabela cache de saldos
--        delete from VSUC_EMPRESAS_TBALANCETE;
        DELETE FROM VSUC_EMPRESAS_TBALANCETE_3 WHERE bdcodemp <> 0;
-- gilberto - 20/03/2015 - ALT:#9178 - alterado para calcular cc com rotina "VSUC_SP_RETORNA_SALDO_CONTAS_XZ"
        IF ((prlistacc IS NULL) OR (TRIM(prlistacc) = '')) THEN
           BEGIN
             FOR SELECT tsal.codemp, tsal.codplapadrao, tsal.conta, tsal.classificacao, tsal.nomeconta, tsal.tipconta,
                        tsal.saldo_anterior, tsal.saldo_ant_deb, tsal.saldo_ant_cre, tsal.saldo_atual, tsal.saldo_deb, tsal.saldo_cre,
                        tref.bdnomemp, temp.bdcnpjemp, tsal.formula, tsal.participante, tsal.GRUPOCONTA, tsal.apecta, tsal.pertenceconta, tsal.relconta
                 FROM VSUC_SP_RETORNA_SALDO_CONTAS_X(:wcodemp, :wcodctaini, :wcodctafin, :prdatini, :prdatfin, :prindice, :prignzer, :bdcodtpcc, :wcodplapadrao,0,
                                                     :prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                 LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.codemp)
                 LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                 WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                        WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                        AND tempresas_ref.bdrefemp <= :prrefemp
                                        ORDER BY tempresas_ref.bdrefemp DESC) --and
                       --((tsal.relconta = 0) or (tsal.relconta is null)) -- RelConta -> 0 - Balan?o Patrimonial | 1 - Demonstra??o de Resultado
                 INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                      :bdsalant, :bdsal_ant_deb, :bdsal_ant_cre, :bdsalatu, :bdsaldo_deb, :bdsaldo_cre,
                      :bdnomemp, :bdcnpjemp, :bdformula, :wparticipante, :bdgrpcta, :bdapecta, :BDPERTENCECONTA, :wrelconta DO
             BEGIN
               -- Sol. #3208 - Bruno Borges 08/05/2012

               --alt:11586 - Precisa retornar zero pra quando vai imprimir sem CC e as linhas de espa?o entre t?tulos. Como Null estava dando problema na ordena??o. Pedro
               bdcodtpcc = 0;

               bdcodempfilial = bdcodemp;

               SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
               IF (wpos <> 0) THEN
                  BEGIN
                    IF (bdcodmatriz IS NULL) THEN
                       bdcodmatriz = bdcodemp;

                    bdcodemp = bdcodmatriz;

                    --bdcodmatriz = bdcodemp;
                    --if (bdcodmatriz is null) then
                    --   bdcodmatriz = bdcodemp;

                    --bdcodemp = bdcodmatriz;
                  END
               -- Fim
               -- sql para verificar se a conta atual e uma titulo geral
               bdsalmov = bdsalatu - bdsalant;

               IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonativo)) = wctalonativo) THEN
                  bdseqcta = 'ATIVO';
               ELSE
                 IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonpatliq)) = wctalonpatliq) THEN
                   bdseqcta = 'PASSIVO A DESCOBERTO';
                 ELSE
                 --alt:7876 - Verifica o grupo da conta para saber se deve exibir ou excluir. (o que tem o "DEL" ? deletado pelo Delphi). Pedro
                 IF ((wrelconta = 0) OR (wrelconta IS NULL)) THEN
                    bdseqcta = 'X';
                 ELSE
                    bdseqcta = 'DEL';

               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                 BEGIN
                   --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                   FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                       --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta, -- alt:#6647 - gilberto - 12/09/2013
                       FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                            :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                       -- Fim
                       INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                       BEGIN
                         IF (prconcatenacodparticipante = 1) THEN
                           BEGIN
                             wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                        -- 100 -> m?ximo de caracteres para nome da conta
                                        -- 003 -> qtd de caracteres " - ";
                             wpos     = ((100 - wpos) - 3);
                             bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                           END

                         bdsalmov = bdsalatu - bdsalant;
                         SUSPEND;
                       END
                 END
               ELSE
                 BEGIN
                   -- gilberto
                   IF ((NOT prconsolidada IS NULL) AND (prconsolidada <> 0)) THEN
                     SUSPEND;
                   ELSE
                     BEGIN
                       SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                       IF ((wfind IS NULL) OR (wfind = 0)) THEN
                         SUSPEND;
                       ELSE
                         IF (bdtipcta = 2) THEN
                           SUSPEND;
                     END
                 END
             END
           END
        ELSE
           BEGIN
             FOR SELECT tsal.bdcodemp, tsal.bdcodplapadrao, tsal.bdconta, tsal.bdclassificacao, tsal.bdnomeconta, tsal.bdtipconta,
                        tsal.bdsaldo_anterior, tsal.bdsaldo_ant_deb, tsal.bdsaldo_ant_cre, tsal.bdsaldo_atual, tsal.bdsaldo_deb, tsal.bdsaldo_cre,
                        tref.bdnomemp, temp.bdcnpjemp, tsal.bdformula, tsal.bdparticipante, tsal.bdGRUPOCONTA, tsal.bdapecta, tsal.bdpertenceconta, tsal.bdrelconta,
                        COALESCE(tsal.bdcodtpcc, 0), tsal.bdnomtpcc, tref.bdcodcentros
                 FROM vsuc_sp_retorna_saldo_contas_xz(:wcodemp, :wcodctaini, :wcodctafin, :prdatini, :prdatfin, :prindice, :prignzer, :prlistacc, :wcodplapadrao,:prsemcc,
                                                      0, :prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                 LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.bdcodemp)
                 LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                 WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                        WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                        AND tempresas_ref.bdrefemp <= :prrefemp
                                        ORDER BY tempresas_ref.bdrefemp DESC) --and
                       --((tsal.relconta = 0) or (tsal.relconta is null)) -- RelConta -> 0 - Balan?o Patrimonial | 1 - Demonstra??o de Resultado
                 INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                      :bdsalant, :bdsal_ant_deb, :bdsal_ant_cre, :bdsalatu, :bdsaldo_deb, :bdsaldo_cre,
                      :bdnomemp, :bdcnpjemp, :bdformula, :wparticipante, :bdgrpcta, :bdapecta, :BDPERTENCECONTA, :wrelconta, :bdcodtpcc, :bdnomtpcc, :bdcodcentros DO
             BEGIN
               -- Sol. #3208 - Bruno Borges 08/05/2012

               bdcodempfilial = bdcodemp;

               SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
               IF (wpos <> 0) THEN
                  BEGIN
                    IF (bdcodmatriz IS NULL) THEN
                       bdcodmatriz = bdcodemp;

                    bdcodemp = bdcodmatriz;

                    --bdcodmatriz = bdcodemp;
                    --if (bdcodmatriz is null) then
                    --   bdcodmatriz = bdcodemp;

                    --bdcodemp = bdcodmatriz;
                  END
               -- Fim
               -- sql para verificar se a conta atual e uma titulo geral
               bdsalmov = bdsalatu - bdsalant;

               IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonativo)) = wctalonativo) THEN
                  bdseqcta = 'ATIVO';
               ELSE
                 IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonpatliq)) = wctalonpatliq) THEN
                   bdseqcta = 'PASSIVO A DESCOBERTO';
                 ELSE
                 --alt:7876 - Verifica o grupo da conta para saber se deve exibir ou excluir. (o que tem o "DEL" ? deletado pelo Delphi). Pedro
                 IF ((wrelconta = 0) OR (wrelconta IS NULL)) THEN
                    bdseqcta = 'X';
                 ELSE
                    bdseqcta = 'DEL';

               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                 BEGIN
                   --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                   FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                       --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta, -- alt:#6647 - gilberto - 12/09/2013
                       FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                            :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                       -- Fim
                       INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                       BEGIN
                         IF (prconcatenacodparticipante = 1) THEN
                           BEGIN
                             wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                        -- 100 -> m?ximo de caracteres para nome da conta
                                        -- 003 -> qtd de caracteres " - ";
                             wpos     = ((100 - wpos) - 3);
                             bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                           END

                         bdsalmov = bdsalatu - bdsalant;
                         SUSPEND;
                       END
                 END
               ELSE
                 BEGIN
                   -- gilberto
                   IF ((NOT prconsolidada IS NULL) AND (prconsolidada <> 0)) THEN
                     SUSPEND;
                   ELSE
                     BEGIN
                       SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                       IF ((wfind IS NULL) OR (wfind = 0)) THEN
                         SUSPEND;
                       ELSE
                         IF (bdtipcta = 2) THEN
                           SUSPEND;
                     END
                 END
             END
           END
      END
END
^

/* Alter (VSUC_SP_LISTA_CTA_RAZAO_VIDEO) */
ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO(PRCODEMP VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRDATINI DATE,
PRDATFIM DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRTIPORAZAO INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDNOMCTA VARCHAR(100),
BDCTALON VARCHAR(40),
BDCODPARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(3000);
DECLARE VARIABLE wsql2 VARCHAR(3000);
DECLARE VARIABLE wsqlemp VARCHAR(3000);
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wsaldo_deb NUMERIC(15,2);
DECLARE VARIABLE wsaldo_cre NUMERIC(15,2);
DECLARE VARIABLE wnomcta VARCHAR(100);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wsomavlr NUMERIC(15,2);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wparticipante INTEGER;
DECLARE VARIABLE wcodempaux INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wcodcta INTEGER;
DECLARE VARIABLE wtipocta INTEGER;
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wsomavlraux NUMERIC(15,2);
DECLARE VARIABLE wempprinc INTEGER;
BEGIN
  -- Foi aleterado a rotina para melhorar o desempenho
  /*wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao ';
  wsql = wsql||'from planos_tpla tpla ';
  wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao) ';
  wsql = wsql||'where ';
  wsql = wsql||'tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and ((tpla.bdcodtpla = tlan.bddebito) or (tpla.bdcodtpla = tlan.bdcredito)) ';
  wsql = wsql||'and (tlan.bddata between '''||prdatini||''' and '''||prdatfim||''') ';
  wsql = wsql||'and tpla.bdcodtpla in (select tcta.bdcodtpla from planos_tpla tcta ';
  wsql = wsql||'                       where (tcta.bdcodplapadrao = tlan.bdcodplapadrao) and ';
  wsql = wsql||'                       (tcta.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''') ';
  if (prTipoRazao = 1) then
    begin
      wsql = wsql||' and ((((bdconcd = ''TRUE'') and (not bddebito is null)) and (tpla.bdcodtpla = tlan.bddebito)) ';
      wsql = wsql||' or (((BDCONCC = ''TRUE'') and (not bdcredito is null))) and (tpla.bdcodtpla = tlan.bdcredito)) ';
    end
  else
    if (prTipoRazao = 2) then
      begin
        wsql = wsql||' and ((((bdconcd is null) and (not bddebito is null)) and (tpla.bdcodtpla = tlan.bddebito)) ';
        wsql = wsql||' or (((BDCONCC is null) and (not bdcredito is null))) and (tpla.bdcodtpla = tlan.bdcredito)) ';
      end
  wsql = wsql||'                       order by tcta.bdctalon)';*/
  wdatini = SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 1 FOR 4);

  IF (prctalonini = prctalonfim) THEN
    BEGIN
      wsql = '';
      wsql = 'select tpla.bdcodtpla, tpla.bdnomcta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao from planos_tpla tpla ';
      --#alt:5619 - gilberto - 13/08/2013 ______________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta > 0)) THEN
         wsql = wsql||' inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      ---------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||' where (tpla.bdcodplapadrao = '||prcodplapadrao||') and (tpla.bdctalon between '''||prctalonini||''' and  '''||prctalonfim||''' )';
      FOR EXECUTE STATEMENT wsql INTO :bdcodtpla,:bdnomcta,:bdctalon,:wparticipante,:wcodplapadrao DO
      BEGIN
        -- retorna as empresas selecionadas
        wsqlemp = 'select temp.bdcodemp from tempresas temp ';
        wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
        wsqlemp = wsqlemp||'order by temp.bdcodemp';
        -- executa o sql das empresas
        FOR EXECUTE STATEMENT wsqlemp INTO :wcodemp DO
        BEGIN
          wsomavlr = 0;
          wsql2    = '';
          --#alt:5837
          /*wsql2    = 'Select Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' (bdcodemp = '||wcodemp||') and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' ((bddebito = '||bdcodtpla||') or (bdcredito = '||bdcodtpla||'))';
          if (prTipoRazao = 1) then
            begin
              wsql2 = wsql2||' and ((((Upper(bdconcd) = ''TRUE'') and (not bddebito is null)) and (bddebito = '||bdcodtpla||')) ';
              wsql2 = wsql2||' or   (((Upper(bdconcc)  = ''TRUE'') and (not bdcredito is null)) and (bdcredito = '||bdcodtpla||'))) ';
            end
          else
            if (prTipoRazao = 2) then
              begin
                wsql2 = wsql2||' and (((((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) and (not bddebito is null)) and (bddebito = '||bdcodtpla||')) ';
                wsql2 = wsql2||' or   ((((Upper(bdconcc) = ''FALSE'') or (bdconcc is null)) and (not bdcredito is null)) and (bdcredito = '||bdcodtpla||'))) ';
              end */
          --D?bito
          wsql2    = 'Select bdcodemp,bdfilial,bdtipolancfilial,bddebito, 1 as bdtipcta, Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' ((bdcodemp = '||wcodemp||') or (bdfilial = '||wcodemp||')) and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' (bddebito = '||bdcodtpla||') ';
          --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
          IF (prcontabilizacao <> 99) THEN
            wsql2    = wsql2||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';
          IF (prTipoRazao = 1) THEN
            wsql2 = wsql2||' and (Upper(bdconcd) = ''TRUE'') ';
          ELSE
          IF (prTipoRazao = 2) THEN
            wsql2 = wsql2||' and ((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) ';
          wsql2 = wsql2||'Group By bdcodemp,bdfilial,bdtipolancfilial,bddebito ';

          wsql2 = wsql2||'union all ';
          --Cr?dito
          wsql2    = wsql2||'Select bdcodemp,bdfilial,bdtipolancfilial,bdcredito, 2 as bdtipcta, Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' ((bdcodemp = '||wcodemp||') or (bdfilial = '||wcodemp||')) and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' (bdcredito = '||bdcodtpla||') ';
          --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
          IF (prcontabilizacao <> 99) THEN
            wsql2    = wsql2||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';
          IF (prTipoRazao = 1) THEN
            wsql2 = wsql2||' and (Upper(bdconcc) = ''TRUE'') ';
          ELSE
          IF (prTipoRazao = 2) THEN
            wsql2 = wsql2||' and ((Upper(bdconcc) = ''FALSE'') or (bdconcd is null)) ';
          wsql2 = wsql2||'Group By bdcodemp,bdfilial,bdtipolancfilial,bdcredito ';
          --#alt:5837
          --execute statement wsql2 into :wsomavlr;
          FOR EXECUTE STATEMENT wsql2 INTO :wcodempaux,:wfilial,:wtipolancfilial,:wcodcta,:wtipocta,:wsomavlraux DO
            BEGIN
              SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipocta,:wcodemp,:wcodempaux,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
              IF (wpermite = 1) THEN
                wsomavlr = wsomavlr + wsomavlraux;
            END

          IF (wsomavlr > 0) THEN
            BEGIN
              -- Detalhado por participante
              IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN--#alt:6309
                BEGIN
                  FOR SELECT tctapar.bdnome, tctapar.bdclassificacao, tctapar.bdcodparticipante, tctapar.bdsaldo_deb, tctapar.bdsaldo_cre
                  --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,0,0,0, -- alt:#6647 - gilberto - 12/09/2013
                  FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,0,0,0,0,
                                                       :prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tctapar
                  INTO :wnomcta, :bdctalon, :bdcodparticipante,:wsaldo_deb,:wsaldo_cre  DO
                    BEGIN
                      IF ((wsaldo_deb <> 0) OR (wsaldo_cre <> 0))  THEN
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:bdcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 003 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              bdnomcta = bdcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                            END
                          SUSPEND;
                        END
                    END
                END
--              else
                SUSPEND;
            END
        END
      END
    END
  ELSE
    BEGIN
      wcodempaux = 0;
      wcodcta    = 0;

      wsql = '';
      --#alt:5837
      /*wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'(tlan.bdcodemp in ('||prcodemp||')) and ';
      wsql = wsql||'((tpla.bdcodtpla = tlan.bddebito) or (tpla.bdcodtpla = tlan.bdcredito)) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';*/
/*
      wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) and ';
      wsql = wsql||'(tpla.bdcodtpla = tlan.bddebito) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';
*/
      wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'       tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')) ';
      --#alt:5619 - gilberto - 13/08/2013 _____________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta <> 0)) THEN
         wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      --------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||'where ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';
      wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
         wsql = wsql||' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';
      wsql = wsql||' union all ';
/*
      wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 2 as bdtipolanc ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) and ';
      wsql = wsql||'(tpla.bdcodtpla = tlan.bdcredito) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';
*/
      wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'       tlan.bdcodemp, tlan.bdfilial,tlan.bdtipolancfilial, 1 as bdtipolanc ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')) ';
      --#alt:5619 - gilberto - 13/08/2013 _____________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta <> 0)) THEN
         wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      --------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||'where ((tlan.bdcodemp in ('||prcodemp||')) or (bdfilial in ('||prcodemp||'))) ';
      wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societ?rio | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql = wsql||' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';

      --Retorna a empresa principal
      SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
      IF (wpos = 0) THEN
        wempprinc = prcodemp;
      ELSE
        wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

      FOR EXECUTE STATEMENT wsql
      INTO :bdcodtpla,:bdnomcta,:bdctalon,:wparticipante,:wcodplapadrao,:wcodemp,:wfilial,:wtipolancfilial,:wtipocta DO
      BEGIN
        IF ((wcodemp <> wcodempaux) OR (bdcodtpla <> wcodcta)) THEN
          BEGIN
            -- Detalhado por participante
            IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN
              BEGIN
                FOR SELECT tctapar.bdnome, tctapar.bdclassificacao, tctapar.bdcodparticipante, tctapar.bdsaldo_deb, tctapar.bdsaldo_cre
                    --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla, -- alt:#6647 - gilberto - 12/09/2013
                    FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,
                                                         0,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tctapar
                INTO :wnomcta, :bdctalon, :bdcodparticipante,:wsaldo_deb,:wsaldo_cre  DO
                BEGIN
                  IF ((wsaldo_deb <> 0) OR (wsaldo_cre <> 0))  THEN
                    BEGIN
                      IF (prconcatenacodparticipante = 1) THEN
                        BEGIN
                          wpos     = CHARACTER_LENGTH(:bdcodparticipante);
                                     -- 100 -> m?ximo de caracteres para nome da conta
                                     -- 003 -> qtd de caracteres " - ";
                          wpos     = ((100 - wpos) - 3);
                          bdnomcta = bdcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                        END
                      SUSPEND;
                      wcodempaux = wcodemp;
                      wcodcta    = bdcodtpla;
                    END
                END
              END
            ELSE
              BEGIN
                SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipocta,:wempprinc,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                IF (wpermite = 1) THEN
                  SUSPEND;
                wcodempaux = wcodemp;
                wcodcta    = bdcodtpla;
              END
          END
      END
    END
END
^

/* Alter (VSUC_SP_MOVIMENTO_MENSAL) */
ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRCC VARCHAR(5000),
PRANOINICIAL INTEGER,
PRANOFINAL INTEGER,
PRREFEMP INTEGER,
PRPARTICIPANTE INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDDEB01 NUMERIC(15,2),
BDDEB02 NUMERIC(15,2),
BDDEB03 NUMERIC(15,2),
BDDEB04 NUMERIC(15,2),
BDDEB05 NUMERIC(15,2),
BDDEB06 NUMERIC(15,2),
BDDEB07 NUMERIC(15,2),
BDDEB08 NUMERIC(15,2),
BDDEB09 NUMERIC(15,2),
BDDEB10 NUMERIC(15,2),
BDDEB11 NUMERIC(15,2),
BDDEB12 NUMERIC(15,2),
BDCRE01 NUMERIC(15,2),
BDCRE02 NUMERIC(15,2),
BDCRE03 NUMERIC(15,2),
BDCRE04 NUMERIC(15,2),
BDCRE05 NUMERIC(15,2),
BDCRE06 NUMERIC(15,2),
BDCRE07 NUMERIC(15,2),
BDCRE08 NUMERIC(15,2),
BDCRE09 NUMERIC(15,2),
BDCRE10 NUMERIC(15,2),
BDCRE11 NUMERIC(15,2),
BDCRE12 NUMERIC(15,2),
BDMOV01 NUMERIC(15,2),
BDMOV02 NUMERIC(15,2),
BDMOV03 NUMERIC(15,2),
BDMOV04 NUMERIC(15,2),
BDMOV05 NUMERIC(15,2),
BDMOV06 NUMERIC(15,2),
BDMOV07 NUMERIC(15,2),
BDMOV08 NUMERIC(15,2),
BDMOV09 NUMERIC(15,2),
BDMOV10 NUMERIC(15,2),
BDMOV11 NUMERIC(15,2),
BDMOV12 NUMERIC(15,2),
BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2),
BDSALTOTDEB NUMERIC(15,2),
BDSALTOTCRE NUMERIC(15,2),
BDSALTOTMOV NUMERIC(15,2),
BDSALTOTATU NUMERIC(15,2),
BDANO INTEGER,
BDGRPCTA INTEGER,
BDDEBANT NUMERIC(15,2),
BDCREANT NUMERIC(15,2),
BDMOVANT NUMERIC(15,2),
BDSALANT NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WBDSALTOTDEB NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTCRE NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTMOV NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTATU NUMERIC(15,2);
DECLARE VARIABLE WBDDEBANT NUMERIC(15,2);
DECLARE VARIABLE WBDCREANT NUMERIC(15,2);
DECLARE VARIABLE WBDSALANT NUMERIC(15,2);
DECLARE VARIABLE WBDDEB01 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB02 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB03 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB04 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB05 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB06 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB07 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB08 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB09 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB10 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB11 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB12 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE01 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE02 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE03 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE04 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE05 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE06 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE07 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE08 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE09 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE10 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE11 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE12 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV01 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV02 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV03 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV04 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV05 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV06 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV07 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV08 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV09 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV10 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV11 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV12 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL01 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL02 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL03 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL04 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL05 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL06 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL07 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL08 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL09 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL10 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL11 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL12 NUMERIC(15,2);
BEGIN
  wcount = 0;
  WHILE (wcount <= pranofinal - pranoinicial) DO
    BEGIN
      BDANO = :pranoinicial + :wcount;
      --Precisa zerar o valores para n?o interferir nos valores dos pr?ximos anos
      bdsaltotdeb = 0;
      bdsaltotcre = 0;
      bdsaltotmov = 0;
      bdsaltotatu = 0;
      bddebant    = 0;
      bdcreant    = 0;
      bdmovant    = 0;
      bdsalant    = 0;

      bddeb01 = 0;
      bddeb02 = 0;
      bddeb03 = 0;
      bddeb04 = 0;
      bddeb05 = 0;
      bddeb06 = 0;
      bddeb07 = 0;
      bddeb08 = 0;
      bddeb09 = 0;
      bddeb10 = 0;
      bddeb11 = 0;
      bddeb12 = 0;

      bdcre01 = 0;
      bdcre02 = 0;
      bdcre03 = 0;
      bdcre04 = 0;
      bdcre05 = 0;
      bdcre06 = 0;
      bdcre07 = 0;
      bdcre08 = 0;
      bdcre09 = 0;
      bdcre10 = 0;
      bdcre11 = 0;
      bdcre12 = 0;

      --alt:9515 - Adicionado campo do movimento. Pedro
      bdmov01 = 0;
      bdmov02 = 0;
      bdmov03 = 0;
      bdmov04 = 0;
      bdmov05 = 0;
      bdmov06 = 0;
      bdmov07 = 0;
      bdmov08 = 0;
      bdmov09 = 0;
      bdmov10 = 0;
      bdmov11 = 0;
      bdmov12 = 0;

      bdsal01 = 0;
      bdsal02 = 0;
      bdsal03 = 0;
      bdsal04 = 0;
      bdsal05 = 0;
      bdsal06 = 0;
      bdsal07 = 0;
      bdsal08 = 0;
      bdsal09 = 0;
      bdsal10 = 0;
      bdsal11 = 0;
      bdsal12 = 0;

      wsql = 'select bdcodemp from tempresas where bdcodemp in ('||prcodemp||')';
      FOR EXECUTE STATEMENT wsql INTO :wcodemp DO
          BEGIN
            SELECT bdano, bdgrpcta, bdsaltotdeb, bdsaltotcre, bdsaltotmov, bdsaltotatu, bddebant, bdcreant, bdsalant,
                   bddeb01, bddeb02, bddeb03, bddeb04, bddeb05, bddeb06, bddeb07, bddeb08, bddeb09, bddeb10, bddeb11, bddeb12,
                   bdcre01, bdcre02, bdcre03, bdcre04, bdcre05, bdcre06, bdcre07, bdcre08, bdcre09, bdcre10, bdcre11, bdcre12,
                   bdmov01, bdmov02, bdmov03, bdmov04, bdmov05, bdmov06, bdmov07, bdmov08, bdmov09, bdmov10, bdmov11, bdmov12,
                   bdsal01, bdsal02, bdsal03, bdsal04, bdsal05, bdsal06, bdsal07, bdsal08, bdsal09, bdsal10, bdsal11, bdsal12
            FROM vsuc_sp_retorna_mov_mensal(:wcodemp, :prconta, :prcc, :bdano, :bdano, :prrefemp, :prparticipante, :prignorazeramento,:prcontabilizacao,:prmatrizfilialconsolidado)
            INTO :bdano, :bdgrpcta, :wbdsaltotdeb, :wbdsaltotcre, :wbdsaltotmov, :wbdsaltotatu, :wbddebant, :wbdcreant, :wbdsalant,
                 :wbddeb01, :wbddeb02, :wbddeb03, :wbddeb04, :wbddeb05, :wbddeb06, :wbddeb07, :wbddeb08, :wbddeb09, :wbddeb10, :wbddeb11, :wbddeb12,
                 :wbdcre01, :wbdcre02, :wbdcre03, :wbdcre04, :wbdcre05, :wbdcre06, :wbdcre07, :wbdcre08, :wbdcre09, :wbdcre10, :wbdcre11, :wbdcre12,
                 :wbdmov01, :wbdmov02, :wbdmov03, :wbdmov04, :wbdmov05, :wbdmov06, :wbdmov07, :wbdmov08, :wbdmov09, :wbdmov10, :wbdmov11, :wbdmov12,
                 :wbdsal01, :wbdsal02, :wbdsal03, :wbdsal04, :wbdsal05, :wbdsal06, :wbdsal07, :wbdsal08, :wbdsal09, :wbdsal10, :wbdsal11, :wbdsal12;

            bdsaltotdeb = COALESCE(bdsaltotdeb, 0) + COALESCE(wbdsaltotdeb, 0);
            bdsaltotcre = COALESCE(bdsaltotcre, 0) + COALESCE(wbdsaltotcre, 0);
            bdsaltotatu = COALESCE(bdsaltotatu, 0) + COALESCE(wbdsaltotatu, 0);
            bdsaltotmov = COALESCE(bdsaltotmov, 0) + COALESCE(wbdsaltotmov, 0);
            bddebant    = COALESCE(bddebant, 0) + COALESCE(wbddebant, 0);
            bdcreant    = COALESCE(bdcreant, 0) + COALESCE(wbdcreant, 0);
            bdsalant    = COALESCE(bdsalant, 0) + COALESCE(wbdsalant, 0);

            bddeb01 = COALESCE(bddeb01, 0) + COALESCE(wbddeb01, 0);
            bddeb02 = COALESCE(bddeb02, 0) + COALESCE(wbddeb02, 0);
            bddeb03 = COALESCE(bddeb03, 0) + COALESCE(wbddeb03, 0);
            bddeb04 = COALESCE(bddeb04, 0) + COALESCE(wbddeb04, 0);
            bddeb05 = COALESCE(bddeb05, 0) + COALESCE(wbddeb05, 0);
            bddeb06 = COALESCE(bddeb06, 0) + COALESCE(wbddeb06, 0);
            bddeb07 = COALESCE(bddeb07, 0) + COALESCE(wbddeb07, 0);
            bddeb08 = COALESCE(bddeb08, 0) + COALESCE(wbddeb08, 0);
            bddeb09 = COALESCE(bddeb09, 0) + COALESCE(wbddeb09, 0);
            bddeb10 = COALESCE(bddeb10, 0) + COALESCE(wbddeb10, 0);
            bddeb11 = COALESCE(bddeb11, 0) + COALESCE(wbddeb11, 0);
            bddeb12 = COALESCE(bddeb12, 0) + COALESCE(wbddeb12, 0);

            bdcre01 = COALESCE(bdcre01, 0) + COALESCE(wbdcre01, 0);
            bdcre02 = COALESCE(bdcre02, 0) + COALESCE(wbdcre02, 0);
            bdcre03 = COALESCE(bdcre03, 0) + COALESCE(wbdcre03, 0);
            bdcre04 = COALESCE(bdcre04, 0) + COALESCE(wbdcre04, 0);
            bdcre05 = COALESCE(bdcre05, 0) + COALESCE(wbdcre05, 0);
            bdcre06 = COALESCE(bdcre06, 0) + COALESCE(wbdcre06, 0);
            bdcre07 = COALESCE(bdcre07, 0) + COALESCE(wbdcre07, 0);
            bdcre08 = COALESCE(bdcre08, 0) + COALESCE(wbdcre08, 0);
            bdcre09 = COALESCE(bdcre09, 0) + COALESCE(wbdcre09, 0);
            bdcre10 = COALESCE(bdcre10, 0) + COALESCE(wbdcre10, 0);
            bdcre11 = COALESCE(bdcre11, 0) + COALESCE(wbdcre11, 0);
            bdcre12 = COALESCE(bdcre12, 0) + COALESCE(wbdcre12, 0);

            --alt:9515 - Adicionados campos do movimento. Pedro
            bdmov01 = COALESCE(bdmov01, 0) + COALESCE(wbdmov01, 0);
            bdmov02 = COALESCE(bdmov02, 0) + COALESCE(wbdmov02, 0);
            bdmov03 = COALESCE(bdmov03, 0) + COALESCE(wbdmov03, 0);
            bdmov04 = COALESCE(bdmov04, 0) + COALESCE(wbdmov04, 0);
            bdmov05 = COALESCE(bdmov05, 0) + COALESCE(wbdmov05, 0);
            bdmov06 = COALESCE(bdmov06, 0) + COALESCE(wbdmov06, 0);
            bdmov07 = COALESCE(bdmov07, 0) + COALESCE(wbdmov07, 0);
            bdmov08 = COALESCE(bdmov08, 0) + COALESCE(wbdmov08, 0);
            bdmov09 = COALESCE(bdmov09, 0) + COALESCE(wbdmov09, 0);
            bdmov10 = COALESCE(bdmov10, 0) + COALESCE(wbdmov10, 0);
            bdmov11 = COALESCE(bdmov11, 0) + COALESCE(wbdmov11, 0);
            bdmov12 = COALESCE(bdmov12, 0) + COALESCE(wbdmov12, 0);

            bdsal01 = COALESCE(bdsal01, 0) + COALESCE(wbdsal01, 0);
            bdsal02 = COALESCE(bdsal02, 0) + COALESCE(wbdsal02, 0);
            bdsal03 = COALESCE(bdsal03, 0) + COALESCE(wbdsal03, 0);
            bdsal04 = COALESCE(bdsal04, 0) + COALESCE(wbdsal04, 0);
            bdsal05 = COALESCE(bdsal05, 0) + COALESCE(wbdsal05, 0);
            bdsal06 = COALESCE(bdsal06, 0) + COALESCE(wbdsal06, 0);
            bdsal07 = COALESCE(bdsal07, 0) + COALESCE(wbdsal07, 0);
            bdsal08 = COALESCE(bdsal08, 0) + COALESCE(wbdsal08, 0);
            bdsal09 = COALESCE(bdsal09, 0) + COALESCE(wbdsal09, 0);
            bdsal10 = COALESCE(bdsal10, 0) + COALESCE(wbdsal10, 0);
            bdsal11 = COALESCE(bdsal11, 0) + COALESCE(wbdsal11, 0);
            bdsal12 = COALESCE(bdsal12, 0) + COALESCE(wbdsal12, 0);
          END

      wcount = wcount + 1;
      SUSPEND;
    END
END
^

/* Alter (VSUC_SP_RETORNA_BALANCETE) */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRORDEM INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDRE INTEGER = 0,
PRTODOPLANOCONTAS INTEGER = 0,
PRDETALHAREMPREENDIMENTO INTEGER = 0,
PRDETALHARUNIDIMOB INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDCODTER INTEGER,
BDAPECTA VARCHAR(20),
BDSALDO_ANTERIOR_DRE NUMERIC(15,2),
BDSALDO_ANT_DEB_DRE NUMERIC(15,2),
BDSALDO_ANT_CRE_DRE NUMERIC(15,2),
BDRAIZCNPJPARTICIPANTE VARCHAR(10),
BDRAIZCLASSIFICACAOCTA VARCHAR(40))
 AS
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WSALDO_ANT_DEB NUMERIC(15,2);
DECLARE VARIABLE WSALDO_DEB NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_CRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ATUAL NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCLANOM VARCHAR(140);
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WGRPCTA SMALLINT;
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
DECLARE VARIABLE WSALDO_ANTERIOR_DRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_DEB_DRE NUMERIC(15,2);
DECLARE VARIABLE WSALDO_ANT_CRE_DRE NUMERIC(15,2);
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCODTPCCANT INTEGER;
DECLARE VARIABLE WNOMTPCC VARCHAR(40);
DECLARE VARIABLE WTPCCLON VARCHAR(20);
declare variable WCODEMPREENDIMENTO integer;
declare variable WCODUNIDIMOB integer;
declare variable WDESCEMPREENDIMENTO varchar(500);
declare variable WDESCUNIDIMOB varchar(500);
declare variable WCADINCORP integer;
declare variable WRAIZCTASEMEMPREENDIMENTO varchar(40);
declare variable WRAIZCTASEMEMPREENDIMENTOANT varchar(40);
BEGIN
-- select * from VSUC_SP_RETORNA_BALANCETE('13,14', '01/01/2015', '12/31/2015', 0, 19, 35, '', 201204, 0, 0,1, 1, 0,'1,2,3,4') order by bdcodtpcc, bdctalon
  DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
  -- retorna as empresas selecionadas
  wsql = 'select case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  wpos = POSITION(',', :prcodemp);
  IF (wpos <> 0) THEN
     wsql = wsql||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsql = wsql||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsql = wsql||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsql = wsql||'       end bdcodemp, ';
  wsql = wsql||'       temp.bdcodemp bdcodempfilial, ';
  wsql = wsql||'       tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  wdatahora = CURRENT_TIMESTAMP;
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        bdcodter = 0;
        wcadincorp = 0;
        -- delete from vsuc_empresas_tbalancete where bdcodemp <> 0;
        -- verifica se existe centro de custo selecionado
        IF (prcodtpcc = '') THEN
           BEGIN
             bdcodtpcc = 0;
             bdnomtpcc = '';
             bdtpcclon = '';


             --#alt:11436 - Adiconado controle para o parametro de imprimir o plano de contas completo PRTODOPLANOCONTAS. Ana - 15/12/2016
             -- retorna todas as contas do plano de contas sem o centro de custo
             FOR SELECT tsalcta.conta, tsalcta.classificacao, tsalcta.nomeconta, tsalcta.tipconta, tsalcta.GRUPOCONTA,
                        tsalcta.saldo_ant_deb, tsalcta.saldo_ant_cre, tsalcta.saldo_deb,
                        tsalcta.saldo_cre, tsalcta.saldo_atual,
                        tsalcta.saldo_anterior, tsalcta.formula, tsalcta.relconta, tsalcta.clanom, tsalcta.participante, tsalcta.apecta,
                        tsalcta.saldo_ant_deb_dre, tsalcta.saldo_ant_cre_dre, tsalcta.saldo_anterior_dre
                 FROM vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prindice, :prignora_zeramento, 0, :bdcodplapadrao,:prlansemcc,
                                                     :prnaomostracontacomp,:prconsolidada,:prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,:prdre, :prtodoplanocontas) tsalcta
                 INTO :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta, :bdgrpcta,
                      :bdsaldo_ant_deb, :bdsaldo_ant_cre, :bdsaldo_deb, :bdsaldo_cre, :bdsaldo_atual,
                      :bdsaldo_anterior, :bdformula, :bdrelcta, :bdclanom, :wparticipante, :bdapecta,
                      :bdsaldo_ant_deb_dre, :bdsaldo_ant_cre_dre, :bdsaldo_anterior_dre DO
                 BEGIN
                   -- Detalhado por participante
                   IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                     BEGIN
--                       delete from vsuc_empresas_tbalancete_2 tbalan where tbalan.bdcodemp = :bdcodempfilial and tbalan.bddatahora = :wdatahora and tbalan.bdcodtpla = :bdcodcta;
                       --delete from vsuc_empresas_tbalancete_3 tbalan where tbalan.bdcodemp = :bdcodempfilial and tbalan.bdcodtpla = :bdcodcta;


                       FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_deb, tsalctapar.bdsaldo_ant_deb,
                                  tsalctapar.bdsaldo_cre, tsalctapar.bdsaldo_ant_cre, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdmovimento,
                                  tsalctapar.bdcodparticipante, tsalctapar.bdraizcnpjparticipante, tsalctapar.bdraizclassificacaocta
                           --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           --from vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           --                                     :prignora_zeramento,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado) tsalctapar
                           --alt:9167 - Adicionado par?metro para agrupar participantes por CNPJ. Pedro
                           FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                           INTO :bdnomcta, :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                :wcodparticipante, :bdraizcnpjparticipante, :bdraizclassificacaocta DO
                           BEGIN

                             bdcodter = :wcodparticipante;
                             bdclanom = SUBSTRING(bdctalon FROM 1 FOR strlen(bdctalon)-10)||' '||bdnomcta;
                             SUSPEND;
                           END

                     END
                   ELSE
                     BEGIN
                       --Detalhado por incorporadora
                       if ((prdetalharempreendimento = 1) or (prdetalharunidimob = 1)) then
                         BEGIN
                           wcadincorp = 0;
                           wnomcta = bdnomcta;
                           if (wctalonant is null) then
                             wctalonant = bdctalon;

                           FOR SELECT tsalctaincorp.bdclassificacao, tsalctaincorp.bdsaldo_deb, tsalctaincorp.bdsaldo_ant_deb, tsalctaincorp.bdsaldo_cre, tsalctaincorp.bdsaldo_ant_cre,
                                  tsalctaincorp.bdsaldo_atual, tsalctaincorp.bdsaldo_anterior, tsalctaincorp.bdmovimento, tsalctaincorp.bdcodempreendimento, tsalctaincorp.bdcodunidimob,
                                  tsalctaincorp.bddescempreendimento, tsalctaincorp.bddescunidimob, tsalctaincorp.bdraizclassificacaocta, tsalctaincorp.BDRAIZCTASEMEMPREENDIMENTO
                               FROM VSUC_SP_RETORNA_SALDOS_CTAINCOR(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                    0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :wctalonant, :bdtipcta, :wraizctasemempreendimentoant,
                                                                    :prdetalharempreendimento, :prdetalharunidimob) tsalctaincorp
                               INTO :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                    :wcodempreendimento, :wcodunidimob,:wdescempreendimento, :wdescunidimob, :bdraizclassificacaocta, :WRAIZCTASEMEMPREENDIMENTO DO
                               BEGIN
                                 if ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) then
                                   bdnomcta = bdnomcta||' ('||wdescempreendimento||')';

                                 if (wcodunidimob IS NOT NULL) then
                                   bdnomcta = bdnomcta||' ('||wdescunidimob||')';

                                 if (wraizctasemempreendimento IS NOT NULL) then
                                   wraizctasemempreendimentoant = wraizctasemempreendimento;

                             SUSPEND;

                                 wcadincorp = 1;
                                 bdnomcta = wnomcta;
                           END
                         END

                       bdcodter = 0;
                       bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                       --#Alt:19049
                       bdraizcnpjparticipante = '';
                       --#alt:20415. Ana - 22/09/2017
                       bdraizclassificacaocta = '';

                       --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
                       --#alt:11436 - Adicionada condi??o do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
                       --alt:7847 - Trocada a verifica??o, s? imprime se tiver movimento ou se estiver marcado para imprimir contas sem movimento. Pedro
                       --ALT:8067 - Adicionada exce??o para retornar contas t?tulo, mesmo zeradas, porque quando a anal?tica dela for uma f?rmula elas sempre retornar?o zeradas do banco. Pedro                       
                       IF ((wcadincorp = 0 ) and
                          ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                           (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                           (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                           (PRTODASASCONTAS = 1) OR (BDTIPCTA = 0) OR (bdformula <> '') OR (prtodoplanocontas = 1))) THEN
                           BEGIN
                             SUSPEND;
                           END

                     END

                     if (bdtipcta = 0) then
                       wctalonant = bdctalon;
                 END
           END
        ELSE
           BEGIN
             bdcodter = 0;
             -- retorna a conta longa da conta inicial
             SELECT tpla.bdctalon FROM planos_tpla tpla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :prctaini
             INTO :wctalonant;
             -- inicializa as variaveis
             bdsaldo_ant_cre = 0;
             bdsaldo_ant_deb = 0;
             bdsaldo_cre = 0;
             bdsaldo_deb = 0;
             bdsaldo_anterior = 0;
             bdsaldo_atual = 0;

             --#alt:17388 - Removi o campo bdformula do retorno, pois estava duplicado e atribuia direto pro return deixando o retorno com valor incorreto. Ana - 23/01/2018
             FOR SELECT bdconta, bdclassificacao, bdnomeconta, bdtipconta, BDGRUPOCONTA,
                        bdsaldo_ant_deb, bdsaldo_ant_cre, bdsaldo_deb,
                        bdsaldo_cre, bdsaldo_atual, bdsaldo_anterior,
                        bdformula, bdrelconta, bdclanom, /*bdformula,*/ bdapecta,
                        bdsaldo_ant_deb_dre, bdsaldo_ant_cre_dre, bdsaldo_anterior_dre,
                        bdcodtpcc, bdnomtpcc, bdtpcclon
                        FROM vsuc_sp_retorna_saldo_contas_xz(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prindice, :prignora_zeramento, :prcodtpcc,
                                                            :bdcodplapadrao, :prlansemcc, :prordem, :prnaomostracontacomp, :prconsolidada, :prniveisconta,
                                                            :prcontabilizacao, :prmatrizfilialconsolidado, :prdre) tsalcta
                        INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta,
                             :wsaldo_ant_deb, :wsaldo_ant_cre, :wsaldo_deb,
                             :wsaldo_cre, :wsaldo_atual, :wsaldo_anterior,
                             :wformula, :bdrelcta, :wclanom, /*:bdformula,*/ :bdapecta,
                             :wsaldo_ant_deb_dre, :wsaldo_ant_cre_dre, :wsaldo_anterior_dre,
                             :wcodtpcc, :wnomtpcc, :wtpcclon DO
                      BEGIN
                         --alt:9381 - Quando for nullo troca para zero, sen?o n?o consegue totalizar
                         --corretamente por centro de custo onde for sem centro de custos. Pedro
                         IF (wcodtpcc IS NULL) THEN
                           wcodtpcc = 0;

                         --#Alt:19049
                         bdraizcnpjparticipante = '';
                         --#alt:20416. Ana - 22/09/2017
                         bdraizclassificacaocta = '';

                         --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
                         --#alt:11436 - Adicionada condição do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
                         IF ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                             (BDTIPCTA = 0) OR (bdformula <> '') OR  (prtodoplanocontas = 1)) THEN
                             BEGIN
                               IF ((wctalonant <> wctalon) OR (COALESCE(wcodtpccant, 0) <> COALESCE(wcodtpcc, 0))) THEN
                                  SUSPEND;

                               bdcodcta  = wconta;
                               bdctalon  = wctalon;
                               bdnomcta  = wnomcta;
                               bdtipcta  = wtipcta;
                               bdclanom  = wclanom;
                               bdgrpcta  = wgrpcta;
                               bdformula = wformula;
                               bdcodtpcc = wcodtpcc;
                               bdnomtpcc = wnomtpcc;
                               bdtpcclon = wtpcclon;
 
                               bdsaldo_ant_cre = wsaldo_ant_cre;
                               bdsaldo_ant_deb = wsaldo_ant_deb;
                               bdsaldo_cre = wsaldo_cre;
                               bdsaldo_deb = wsaldo_deb;
                               bdsaldo_anterior = wsaldo_anterior;
                               bdsaldo_atual = wsaldo_atual;

                               --alt:9179 - N?o estava imprimindo o BDMOVIMENTO para os centros de custos. Pedro
                               bdmovimento = bdsaldo_atual - bdsaldo_anterior;
 
                               bdsaldo_ant_cre_dre = wsaldo_ant_cre_dre;
                               bdsaldo_ant_deb_dre = wsaldo_ant_deb_dre;
                               bdsaldo_anterior_dre = wsaldo_anterior_dre;
                             END
                         ELSE
                             BEGIN
                               bdcodcta  = wconta;
                               bdctalon  = wctalon;
                               bdnomcta  = wnomcta;
                               bdtipcta  = wtipcta;
                               bdclanom  = wclanom;
                               bdgrpcta  = wgrpcta;
                               bdformula = wformula;
                               bdcodtpcc = wcodtpcc;
                               bdnomtpcc = wnomtpcc;
                               bdtpcclon = wtpcclon;

                               bdsaldo_ant_cre = bdsaldo_ant_cre + wsaldo_ant_cre;
                               bdsaldo_ant_deb = bdsaldo_ant_deb + wsaldo_ant_deb;
                               bdsaldo_cre = bdsaldo_cre + wsaldo_cre;
                               bdsaldo_deb = bdsaldo_deb + wsaldo_deb;
                               bdsaldo_anterior = bdsaldo_anterior + wsaldo_anterior;
                               bdsaldo_atual = bdsaldo_atual + wsaldo_atual;

                               --alt:9179 - N?o estava imprimindo o BDMOVIMENTO para os centros de custos. Pedro
                               bdmovimento = bdsaldo_atual - bdsaldo_anterior;
 
                               bdsaldo_ant_cre_dre = bdsaldo_ant_cre_dre + wsaldo_ant_cre_dre;
                               bdsaldo_ant_deb_dre = bdsaldo_ant_deb_dre + wsaldo_ant_deb_dre;
                               bdsaldo_anterior_dre = bdsaldo_anterior_dre + wsaldo_anterior_dre;
                            END
                         wctalonant = wctalon;
                         wcodtpccant = wcodtpcc;
                      END

             --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
             --#alt:11436 - Adicionada condição do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
             --alt:9386 - Adicionado esse suspend porque se ele soma centros de custos iguais, o ?ltimo n?o ? impresso. Pedro
             IF ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                 (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                 (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR (BDTIPCTA = 0) OR (bdformula <> '') OR (prtodoplanocontas = 1)) THEN
                   SUSPEND;
             --alt:9386 - Fim

           END

--        delete from vsuc_empresas_tbalancete_2 where bdcodemp <> 0 and bddatahora = :wdatahora;
        DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;

      END
END
^

/* Alter (VSUC_SP_RETORNA_BALANCO_PATRIMO) */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRIMO(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(2048),
PRNAOMOSTRACONTACOMP INTEGER,
PRCTASEMMOV INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDANAVER NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20))
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(4096);
DECLARE VARIABLE WLENGTH INTEGER;
DECLARE VARIABLE WVALTIT NUMERIC(15,2);
DECLARE VARIABLE WSQLTCC VARCHAR(1024);
DECLARE VARIABLE WSEQCTA VARCHAR(100);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
BEGIN
  wsqlemp = 'select case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos <> 0) THEN
     wsqlemp = wsqlemp||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsqlemp = wsqlemp||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsqlemp = wsqlemp||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsqlemp = wsqlemp||'       end bdcodemp, ';
  wsqlemp = wsqlemp||'       temp.bdcodemp bdcodempfilial, ';
  wsqlemp = wsqlemp||'       tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';

  wdatahora = CURRENT_TIMESTAMP;

  FOR EXECUTE STATEMENT wsqlemp
--      into :wcodemp, :bdcodmatriz, :wcodplapadrao, :wcodcentros do
      INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        IF (bdcodmatriz IS NULL) THEN
           bdcodmatriz = 0;
        -- retorna a primeira conta referente a classificacao
        SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :bdcodplapadrao
        AND planos_tpla.bdctalon = :prctalonini
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini;
        -- retorna a ultima conta referente a classificacao
        SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :bdcodplapadrao
        AND planos_tpla.bdctalon = :prctalonfin
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctafin;
        -- sql responsavel pela limpeza da tabela cache de saldos
        --delete from VSUC_EMPRESAS_TBALANCETE_2; Fabiano: 23/05/2012 N?o pode apagar tudo porque tem outros usu?rios que est?o comitando dados. S? posso apagar o que ? meu.
--        delete from vsuc_empresas_tbalancete_2 where bdcodemp <> 0 and bddatahora = :wdatahora;
        DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
        -- verificacao dos centro de custos selecionados
        IF ((TRIM(prlistacc) <> '') AND (wcodcentros IS NOT NULL)) THEN
           BEGIN
             wsqltcc = 'select tpcc.bdcodtpcc, tpcc.bdnomcta from centros_tpcc tpcc ';
             wsqltcc = wsqltcc||'where tpcc.bdcodcentro = '||wcodcentros;
             wsqltcc = wsqltcc||' and tpcc.bdcodtpcc in ('||prlistacc||')';
           END
        ELSE
        -- o retorno desse sql deve ser 0 para que o laco passe pelo menos uma vez pelo calculo de saldos,
        -- isso deve acontecer quando nao ha centro de custo selecionado
           BEGIN
             wsqltcc = 'select case when (temp.bdcodemp <> 0) then 0 end, tref.bdnomemp ';
             wsqltcc = wsqltcc||'from tempresas temp ';
             wsqltcc = wsqltcc||'inner join tempresas_ref tref on (tref.bdcodemp = temp.bdcodemp) ';
             --Pegava sempre a mesma empresa
             --wsqltcc = wsqltcc||'where temp.bdcodemp = '||bdcodemp;
             wsqltcc = wsqltcc||'where temp.bdcodemp = '||bdcodempfilial;
             wsqltcc = wsqltcc||' and tref.bdrefemp = (select first 1 tempresas_ref.bdrefemp from tempresas_ref ';
             wsqltcc = wsqltcc||                      'where tempresas_ref.bdcodemp = temp.bdcodemp ';
             wsqltcc = wsqltcc||                      'and tempresas_ref.bdrefemp <= '||prrefemp;
             wsqltcc = wsqltcc||                      ' order by tempresas_ref.bdrefemp desc) ';
           END
        -- laco dos centro de custos
        IF (NOT ((bdcodplapadrao IS NULL) AND (wcodcentros IS NULL))) THEN
        FOR EXECUTE STATEMENT wsqltcc
            INTO :bdcodtpcc, :bdnomtpcc DO
            BEGIN
              -- caso nao ha centro de custo selecionado, o nome do mesmo deve ser em branco
              IF (bdcodtpcc = 0) THEN
                 BEGIN
                   bdnomtpcc = '';
                   bdcodcentros = 0;
                 END
              ELSE
                 bdcodcentros = wcodcentros;
              -- laco do calculo dos saldos do plano de contas
              FOR SELECT tsal.codemp, tsal.codplapadrao, tsal.conta, tsal.classificacao,
                         tsal.nomeconta, tsal.tipconta, tsal.saldo_anterior, tsal.saldo_atual,
                         tref.bdnomemp, temp.bdcnpjemp, tsal.formula, tsal.grupoconta, tsal.participante, tsal.apecta
                  FROM vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :wcodctaini, :wcodctafin, :prdatini, :prindice, :prdatfin, :prignzer, :bdcodtpcc, :bdcodplapadrao,
                                                      0,:prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                  LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.codemp)
                  LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                  WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                         WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                         AND tempresas_ref.bdrefemp <= :prrefemp
                                         ORDER BY tempresas_ref.bdrefemp DESC)
                  INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                       :bdsalant, :bdsalatu, :bdnomemp, :bdcnpjemp, :bdformula, :BDGRPCTA,  :wparticipante, :bdapecta DO
              BEGIN
                -- Detalhado por participante
                IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                  BEGIN
                    --#alt:17868. Adicionado par?metro para agrupar por CNPJ. Ana - 12/05/2017
                    FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                        --from vsuc_sp_retorna_saldos_cta_part(:bdcodemp,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,-- alt:#6647 - gilberto - 12/09/2013
                        FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodemp,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                             :prignzer,0,0,0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :pragruparparticipanteporcnpj) tsalctapar
                        INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 03 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                            END

                          -- se a conta for "patrimonio liquido"
                          IF (bdctalon = prctalonpas) THEN
                            BEGIN
                              wseqcta = bdnomcta;
                              IF (bdsalatu IS NULL) THEN
                                wvaltit = 0;
                              ELSE
                                wvaltit = bdsalatu;
                            END
                          bdsalmov = bdsalatu - bdsalant;
                          bdseqcta = wseqcta;
                          -- c?lculo do percentual da analise vertical
                          IF (wvaltit = 0) THEN
                            bdanaver = 0;
                          ELSE
                            bdanaver = (bdsalatu * 100) / wvaltit;

                          SUSPEND;
                        END
                  END
                ELSE
                  BEGIN
                    -- sql para verificar se a conta atual ? uma titulo geral
                    SELECT FIRST 1 tpos.pos FROM pos('.', :bdctalon) tpos INTO :wlength;
                    IF (wlength IS NULL) THEN
                      wlength = 0;
                    -- se a conta for uma "titulo geral" ou "patrimonio liquido"
                    IF ((wlength = 0) OR (bdctalon = prctalonpas)) THEN
                      BEGIN
                        wseqcta = bdnomcta;
                        IF (bdsalatu IS NULL) THEN
                          wvaltit = 0;
                        ELSE
                          wvaltit = bdsalatu;
                      END
                    bdsalmov = bdsalatu - bdsalant;
                    bdseqcta = wseqcta;
                    -- caculo do percentual da analise vertical
                    IF (wvaltit = 0) THEN
                      bdanaver = 0;
                    ELSE
                      bdanaver = (bdsalatu * 100) / wvaltit;

                --alt:7847 - Algu?m, talvez o Gilberto havia comentado esta parte que s? d? o suspend se a conta tiver movimento ou for para imprimir contas sem movimento.
                --Estou descomentando essa parte e comentando a que foi adicionada para imprimir sempre as contas consolidadas, pois pelo que vimos, atualmente n?o faz sentido. Pedro
                IF ((prctasemmov = 0) AND ((bdsalatu <> 0) OR (bdsalmov <> 0)) OR (prctasemmov = 1)) THEN
                   SUSPEND;
--                     gilberto
/*                    if ((not prconsolidada is null) and (prconsolidada <> 0)) then
                      suspend;
                    else
                      begin
                        select bdresult from vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) into :wfind;
                        if ((wfind is null) or (wfind = 0)) then
                          suspend;
                        else
                          if (bdtipcta = 2) then
                            suspend;
                      end*/
                  END
              END
            END
      END
END
^

/* Alter (VSUC_SP_RETORNA_COMPARATIVO) */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO(PREMPRESAS VARCHAR(1024),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRINDICE INTEGER,
PRTIPCOMP INTEGER,
PRCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDFORMULA VARCHAR(1024))
 AS
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WFIND INTEGER;
DECLARE VARIABLE WCLASSINI VARCHAR(50);
DECLARE VARIABLE WCLASSFIN VARCHAR(50);
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WSQLUPDATE VARCHAR(10240);
DECLARE VARIABLE WSQLTPCC VARCHAR(10240);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCTA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WNOMTPCC VARCHAR(40);
DECLARE VARIABLE WSALATU NUMERIC(15,2);
DECLARE VARIABLE WMOVIMENTO NUMERIC(15,2);
DECLARE VARIABLE WSALDORELATORIO NUMERIC(15,2);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WSQLCONTAS VARCHAR(10240);
DECLARE VARIABLE WSQLMESES VARCHAR(10240);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
BEGIN
  wdatahora = CURRENT_TIMESTAMP;
  --delete from vsuc_empresas_comparativo;

  wsql = 'select first 1 bdcodplapadrao from vw_empresas_ref_atual  ';
  wsql = wsql||'where bdcodemp in ('||prempresas||') ';
  EXECUTE STATEMENT wsql INTO :wcodplapadrao;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prctaini
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prctafin
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas anal?ticas
  SELECT BDRPOS FROM RPOS(',1,',','||:prniveisconta||',') INTO :wimpanalitica;

  wsql = 'select bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp, bdcodplapadrao ';
  wsql = wsql||'from vw_empresas_ref_atual ';
  wsql = wsql||'where bdcodemp in ('||prempresas||') ';

  wcount    = 0;
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao DO
      BEGIN
        -- giovanni... insere somente as contas com lancamentos

        wsqlcontas = '';
        wsqlcontas = wsqlcontas||' select distinct CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta, CONTAS.bdgrupocta, CONTAS.bdnomcta, CONTAS.bdformula, ';
        --alt:7211 - Alterado de wcodemp para prempresas para passar a empresa matriz e suas filiais, caso sejam informadas. Pedro
        --wsqlcontas = wsqlcontas||' CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS('||wcodemp||', '||wcodplapadrao||','''||prdatini||''','''||prdatfin||''','''||wclassini||''','''||wclassfin||''',0,0,0,3,0) CONTAS ';
        wsqlcontas = wsqlcontas||' CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS('''||prempresas||''', '||wcodplapadrao||','''||prdatini||''','''||prdatfin||''','''||wclassini||''','''||wclassfin||''',0,0,0,3,0) CONTAS ';
        wsqlcontas = wsqlcontas||' order by BDCTALON';


        FOR EXECUTE STATEMENT wsqlcontas
            INTO :wcodcta, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wformula, :wparticipante DO
          BEGIN
            -- Filtro pelo n?vel da conta
            SELECT contar_char FROM contar_char(:wctalon,'.') INTO :wnivelconta;
            wnivelconta = wnivelconta + 1;
            SELECT BDRPOS FROM RPOS(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',') INTO :windice;
            IF ((prniveisconta = '9999') OR           -- N?o tem filtro
                (wnivelconta = 1) OR                  -- O primeiro n?vel sempre imprime
                ((windice > 0) AND (:wtipcta = 0)) OR -- O n?vel da conta foi selecionado no filtro e ? t?tulo
                ((windice > 0) AND (wimpanalitica > 0) AND (:wtipcta = 1))) THEN -- ? do n?vel selecionado, anal?tica e foi selecionado para imprimir as contas anal?ticas
              BEGIN
                -- Tratamento para detalhar participante
                IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (wtipcta = 1)) THEN
                  BEGIN
                    FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdcodparticipante
                        --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfin,:wcodcta,:prignzer,0,1,0, -- alt:#6647 - gilberto - 12/09/2013
                        FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfin,:wcodcta,:prindice,:prignzer,0,1,0,
                                                             :prempresas,:prcontabilizacao,:prmatrizfilialconsolidado) tsalctapar
                        INTO :wnomcta, :wctalon, :wcodparticipante DO
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                         -- 100 -> m?ximo de caracteres para nome da conta
                                         -- 03 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              wnomcta = wcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                            END

                          INSERT INTO vsuc_empresas_comparativo (bddatahora, bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp, bdcodplapadrao, bdcodcta,
                                                                 bdctalon, bdtipcta, bdgrpcta, bdnomcta, bdformula)
                          VALUES(:wdatahora, :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao, :wcodcta, :wctalon, :wtipcta, :wgrpcta ,:wnomcta, :wformula);
                        END
                  END
                ELSE
                  BEGIN
                    INSERT INTO vsuc_empresas_comparativo (bddatahora, bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp,
                                                           bdcodplapadrao, bdcodcta, bdctalon, bdtipcta, bdgrpcta, bdnomcta, bdformula)
                    VALUES (:wdatahora, :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao, :wcodcta, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wformula);
                  END
              END
          END
      END

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdatini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatfin FROM 1 FOR 4)||SUBSTRING(prdatfin FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdatini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = CAST(SUBSTRING(prdatfin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdatini FROM 1 FOR 4) AS INTEGER);
       IF (wtotal = 0) THEN
          wtotal = 1;
       ELSE
          wTotal = wTotal +1;
     END

  wcount = 0;
  WHILE (wcount < wtotal) DO
    BEGIN
      -- mensal ________________________________________________________
      IF (prtipcomp = 0) THEN
         BEGIN
           wdata_inicial = addmonth(prdatini, wcount);
           wdata_final   = addmonth(prdatini, wcount+1)-1;
         END
      ELSE
      -- anual _________________________________________________________
         BEGIN
           wdata_inicial = addyear(prdatini, wcount);
           wdata_final   = addyear(prdatini, wcount+1)-1;
         END

      IF (wdata_final <= prdatfin) THEN
         BEGIN
           wsqlmeses = '';
           wsqlmeses = wsqlmeses|| ' select bdcodemp, bdnomemp, bdcnpjemp, bdcodmatriz, bdcodplapadrao, bdcodcta, bdctalon, bdnomcta, bdtipcta, bdgrpcta, bdcodtpcc, bdnomtpcc, ';
           wsqlmeses = wsqlmeses|| ' bdsaldo_atual, bdmovimento ';
           wsqlmeses = wsqlmeses|| ' from vsuc_sp_retorna_balancete(''' || :prempresas || ''', ''' || :wdata_inicial || ''', ''';
           wsqlmeses = wsqlmeses|| :wdata_final || ''', ' || :prignzer || ', ' || :prctaini || ', ' || :prctafin || ', '||:prindice||', ''' ||  :prcc || ''' , ' || :prrefemp || ', ';
           wsqlmeses = wsqlmeses|| :prlansemcc || ', 0, 0, 0,'|| :prdetalharctaparticipante || ',0, '''|| :prniveisconta ||''',0,'||:prcontabilizacao||','||:prmatrizfilialconsolidado||')';

/*
           if (prtiposaldo = 2) then
              wsqlmeses = wsqlmeses|| ' where bdsaldo_atual <> 0';
           else
              wsqlmeses = wsqlmeses|| ' where bdmovimento <> 0';*/
           ----
           FOR EXECUTE STATEMENT wsqlmeses
               INTO :wcodemp, :wnomemp, :wcnpjemp, :wcodmatriz, :wcodplapadrao,
                    :wcodcta, :wctalon, :wnomcta, :wtipcta, :wgrpcta, :wcodtpcc, :wnomtpcc,
                    :wsalatu, :wmovimento DO
           BEGIN
             --alt:7333 - Retirado o filtro, pois agora deve trazer tano o saldo quanto o movimento. Pedro
             /*if (prtiposaldo = 2) then
                wSaldoRelatorio = wsalatu;
             else
                wSaldoRelatorio = wmovimento;*/

             --alt:7333 - Adicionados campos do movimento. Pedro
             wsqlupdate = 'update vsuc_empresas_comparativo set ';
             IF (wcount = 0) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO01 = coalesce(BDSALDO01, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO01 = coalesce(BDMOVIMENTO01, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 1) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO02 = coalesce(BDSALDO02, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO02 = coalesce(BDMOVIMENTO02, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 2) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO03 = coalesce(BDSALDO03, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO03 = coalesce(BDMOVIMENTO03, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 3) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO04 = coalesce(BDSALDO04, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO04 = coalesce(BDMOVIMENTO04, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 4) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO05 = coalesce(BDSALDO05, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO05 = coalesce(BDMOVIMENTO05, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 5) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO06 = coalesce(BDSALDO06, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO06 = coalesce(BDMOVIMENTO06, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 6) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO07 = coalesce(BDSALDO07, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO07 = coalesce(BDMOVIMENTO07, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 7) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO08 = coalesce(BDSALDO08, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO08 = coalesce(BDMOVIMENTO08, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 8) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO09 = coalesce(BDSALDO09, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO09 = coalesce(BDMOVIMENTO09, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 9) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO10 = coalesce(BDSALDO10, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO10 = coalesce(BDMOVIMENTO10, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 10) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO11 = coalesce(BDSALDO11, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO11 = coalesce(BDMOVIMENTO11, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 11) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO12 = coalesce(BDSALDO12, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO12 = coalesce(BDMOVIMENTO12, 0) + '||COALESCE(wMovimento, 0);
                END
             wSqlUpdate = wSqlUpdate||' where bdcodemp = '||wcodemp;
             wSqlUpdate = wSqlUpdate||' and bddatahora = '''||wdatahora||'''';
             wSqlUpdate = wSqlUpdate||' and bdcodcta = '||wcodcta;
             wSqlUpdate = wSqlUpdate||' and bdctalon = '''||wctalon||'''';
             IF (TRIM(prcc) <> '') THEN
                wSqlUpdate = wSqlUpdate||' and bdcodtpcc = '||wcodtpcc;

             EXECUTE STATEMENT wSqlUpdate;
           END
         END
      wcount = wcount + 1;
    END

  -- implementado para que se possa agrupar todas as filiais somando os saldos
  IF (PRAGRUPAEMPRESAFILIAIS = 1) THEN
     BEGIN
       wsql = 'select first 1 bdcodemp, bdcodmatriz, bdcnpjemp, bdnomemp, bdcodplapadrao ';
       wsql = wsql||'from vw_empresas_ref_atual ';
       wsql = wsql||'where bdcodemp in ('||prempresas||') ';
       EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodmatriz, :bdcnpjemp, :bdnomemp, :bdcodplapadrao;

       --alt:7333 - Adicionados campos do movimento. Pedro
       FOR SELECT DISTINCT  tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA, tcomp.BDTIPCTA, tcomp.BDGRPCTA, COALESCE(tcomp.BDCODTPCC, 0), tcomp.BDNOMTPCC, tcomp.bdformula,
                  SUM(COALESCE(tcomp.BDSALDO01, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO01, 0)), SUM(COALESCE(tcomp.BDSALDO02, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO02, 0)),
                  SUM(COALESCE(tcomp.BDSALDO03, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO03, 0)), SUM(COALESCE(tcomp.BDSALDO04, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO04, 0)),
                  SUM(COALESCE(tcomp.BDSALDO05, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO05, 0)), SUM(COALESCE(tcomp.BDSALDO06, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO06, 0)),
                  SUM(COALESCE(tcomp.BDSALDO07, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO07, 0)), SUM(COALESCE(tcomp.BDSALDO08, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO08, 0)),
                  SUM(COALESCE(tcomp.BDSALDO09, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO09, 0)), SUM(COALESCE(tcomp.BDSALDO10, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO10, 0)),
                  SUM(COALESCE(tcomp.BDSALDO11, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO11, 0)), SUM(COALESCE(tcomp.BDSALDO12, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO12, 0))
           FROM vsuc_empresas_comparativo tcomp
           WHERE  (bddatahora = :wdatahora)
           GROUP BY tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA, tcomp.BDTIPCTA, tcomp.BDGRPCTA, tcomp.BDCODTPCC, tcomp.BDNOMTPCC, tcomp.bdformula
           ORDER BY tcomp.bdctalon, tcomp.bdcodtpcc
           --alt:7333 - Adicionados campos do movimento. Pedro
           INTO :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :bdformula,
                :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02,
                :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
                :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06,
                :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
                :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10,
                :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
           BEGIN
             BDQTDCOMP = wtotal;
             --alt:7333 - Adicionados campos do movimento. Pedro
             IF ((BDSALDO01 <> 0 OR BDSALDO02 <> 0 OR BDSALDO03 <> 0 OR BDSALDO04 <> 0 OR
                  BDSALDO05 <> 0 OR BDSALDO06 <> 0 OR BDSALDO07 <> 0 OR BDSALDO08 <> 0 OR
                  BDSALDO09 <> 0 OR BDSALDO10 <> 0 OR BDSALDO11 <> 0 OR BDSALDO12 <> 0) OR
                 (BDMOVIMENTO01 <> 0 OR BDMOVIMENTO02 <> 0 OR BDMOVIMENTO03 <> 0 OR BDMOVIMENTO04 <> 0 OR
                  BDMOVIMENTO05 <> 0 OR BDMOVIMENTO06 <> 0 OR BDMOVIMENTO07 <> 0 OR BDMOVIMENTO08 <> 0 OR
                  BDMOVIMENTO09 <> 0 OR BDMOVIMENTO10 <> 0 OR BDMOVIMENTO11 <> 0 OR BDMOVIMENTO12 <> 0) OR
                 (BDTIPCTA = 0) OR (BDFORMULA <> '')) THEN
                 SUSPEND;
           END
     END
  ELSE
  --alt:7333 - Adicionados campos do movimento. Pedro
  FOR SELECT tcomp.BDCODEMP, tcomp.BDCODMATRIZ, tcomp.BDNOMEMP, tcomp.BDCNPJEMP,
             tcomp.bdcodplapadrao, tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA,
             tcomp.BDTIPCTA, tcomp.BDGRPCTA, COALESCE(tcomp.BDCODTPCC, 0), tcomp.BDNOMTPCC,
             tcomp.BDSALDO01, tcomp.BDMOVIMENTO01, tcomp.BDSALDO02, tcomp.BDMOVIMENTO02,
             tcomp.BDSALDO03, tcomp.BDMOVIMENTO03, tcomp.BDSALDO04, tcomp.BDMOVIMENTO04,
             tcomp.BDSALDO05, tcomp.BDMOVIMENTO05, tcomp.BDSALDO06, tcomp.BDMOVIMENTO06,
             tcomp.BDSALDO07, tcomp.BDMOVIMENTO07, tcomp.BDSALDO08, tcomp.BDMOVIMENTO08,
             tcomp.BDSALDO09, tcomp.BDMOVIMENTO09, tcomp.BDSALDO10, tcomp.BDMOVIMENTO10,
             tcomp.BDSALDO11, tcomp.BDMOVIMENTO11, tcomp.BDSALDO12, tcomp.BDMOVIMENTO12, tcomp.bdformula
      FROM vsuc_empresas_comparativo tcomp
      WHERE  (bddatahora = :wdatahora)
      --alt:7333 - Adicionados campos do movimento. Pedro
      ORDER BY tcomp.bdcodemp, tcomp.bdcodmatriz, tcomp.bdctalon, tcomp.bdcodtpcc
      INTO :BDCODEMP, :bdcodmatriz, :BDNOMEMP, :BDCNPJEMP, :bdcodplapadrao,
           :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC,
           :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02,
           :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
           :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06,
           :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
           :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10,
           :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12, :bdformula DO
      BEGIN
        BDQTDCOMP = wtotal;
        SUSPEND;
      END

  --N?o utiliza mais o "vsuc_empresas_tbalancete", mas sim o "vsuc_empresas_tbalancete_2"
  --delete from vsuc_empresas_tbalancete;
  DELETE FROM vsuc_empresas_comparativo WHERE bdcodemp <> 0 AND bddatahora = :wdatahora;
END
^

/* Alter (VSUC_SP_RETORNA_COMPARATIVO_X) */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO_X(PRCODEMP VARCHAR(255),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATAINI DATE,
PRDATAFIN DATE,
PRINDICE INTEGER,
PRCTASEMMOV INTEGER,
PRIMPRIMIRCOLUNASEXTRAS INTEGER,
PRTIPCOMP INTEGER,
PRCODTPCC VARCHAR(1024),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRCTACONSOLIDADA INTEGER,
PRFORMACALC INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP VARCHAR(100),
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDFORMULA VARCHAR(1024),
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDMEDIASALDO NUMERIC(15,2),
BDTOTALSALDO NUMERIC(15,2),
BDMEDIAMOVIMENTO NUMERIC(15,2),
BDTOTALMOVIMENTO NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(24000);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  --#alt:20462. Criada nova SP para melhorar o desempenho. A antiga permanecer? para caso houver lentid?es ou erros futuros. Ana - 08/05/2018
  IF (PRFORMACALC = 1) THEN
   BEGIN
     FOR SELECT BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA, BDCODEMPFILIAL,
                BDSALDO01, BDMOVIMENTO01, BDSALDO02, BDMOVIMENTO02, BDSALDO03, BDMOVIMENTO03, BDSALDO04, BDMOVIMENTO04,
                BDSALDO05, BDMOVIMENTO05, BDSALDO06, BDMOVIMENTO06, BDSALDO07, BDMOVIMENTO07, BDSALDO08, BDMOVIMENTO08,
                BDSALDO09, BDMOVIMENTO09, BDSALDO10, BDMOVIMENTO10, BDSALDO11, BDMOVIMENTO11, BDSALDO12, BDMOVIMENTO12,
                BDQTDCOMP
         FROM VSUC_SP_RETORNA_COMPARATIVO_Y(:prcodemp, :prctaini, :prctafin, :prdataini, :prdatafin, :prindice, :prctasemmov, :prtipcomp, :prcodtpcc, :prtiposaldo, :prrefemp, :prignzer,
                                            :prlansemcc, :pragrupaempresafiliais, :prdetalharctaparticipante, :prniveisconta, :prcontabilizacao, :prmatrizfilialconsolidado,
                                            :prctaconsolidada)

      INTO
      :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
      :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
      :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
      :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12,
      :BDQTDCOMP DO
        SUSPEND;

   END
  ELSE
  BEGIN
      -- Caso seja para agrupar as empresas eu busco o c?digo, nome e CNPJ separadamente
      IF (pragrupaempresafiliais = 1) THEN
        BEGIN
          wpos = POSITION(',', :prcodemp);
          IF (wpos <> 0) THEN
            wcodemp = COALESCE(CAST(SUBSTRING(prcodemp FROM 1 FOR (wpos -1)) AS INTEGER),0);
          ELSE
            wcodemp = COALESCE(CAST(:prcodemp AS INTEGER),0);
    
          SELECT emp.bdcodemp,emp.bdcnpjemp,ref.bdnomemp  FROM tempresas emp
          INNER JOIN vw_empresas_ref_atual ref ON (ref.bdcodemp = emp.bdcodemp)
          WHERE (emp.bdcodemp = :wcodemp) INTO :wcodemp, :wcnpjemp, :wnomemp;
        END
    
      -- mensal ____________________________________________________________________
      IF (prtipcomp = 0) THEN
         BEGIN
           wtotal = 0;
           wdata_inicial = prdataini;
           WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafin FROM 1 FOR 4)||SUBSTRING(prdatafin FROM 6 FOR 2) AS INTEGER)) DO
             BEGIN
               wtotal = wtotal + 1;
               wdata_inicial = addmonth(prdataini, wtotal);
             END
         END
      ELSE
      -- anual _____________________________________________________________________
         BEGIN
           wtotal = CAST(SUBSTRING(prdatafin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER);
           IF (wtotal = 0) THEN
              wtotal = 1;
           ELSE
              wTotal = wTotal +1;
         END
    
      wcount = 0;
      WHILE (wcount < wtotal) DO
        BEGIN
          -- mensal ________________________________________________________
          IF (prtipcomp = 0) THEN
             BEGIN
               wdata_inicial = addmonth(prdataini, wcount);
               wdata_final   = addmonth(prdataini, wcount + 1) - 1;
             END
          ELSE
          -- anual _________________________________________________________
             BEGIN
               wdata_inicial = addyear(prdataini, wcount);
               wdata_final   = addyear(prdataini, wcount + 1) - 1;
             END
    
          IF (wsql IS NULL) THEN
             BEGIN
               IF (pragrupaempresafiliais = 1) THEN
                 wsql = 'Select null as BDCODEMP, BDCODPLAPADRAO, BDCODCTA, null as BDCODMATRIZ, null as BDNOMEMP, null as BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,null as BDCODEMPFILIAL,';
               ELSE
                 wsql = 'Select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
    
               wsql = wsql||' sum(coalesce(BDSALDO01, 0)) as BDSALDO01, sum(coalesce(BDMOVIMENTO01, 0)) as BDMOVIMENTO01, sum(coalesce(BDSALDO02, 0)) as BDSALDO02, sum(coalesce(BDMOVIMENTO02, 0)) as BDMOVIMENTO02,';
               wsql = wsql||' sum(coalesce(BDSALDO03, 0)) as BDSALDO03, sum(coalesce(BDMOVIMENTO03, 0)) as BDMOVIMENTO03, sum(coalesce(BDSALDO04, 0)) as BDSALDO04, sum(coalesce(BDMOVIMENTO04, 0)) as BDMOVIMENTO04,';
               wsql = wsql||' sum(coalesce(BDSALDO05, 0)) as BDSALDO05, sum(coalesce(BDMOVIMENTO05, 0)) as BDMOVIMENTO05, sum(coalesce(BDSALDO06, 0)) as BDSALDO06, sum(coalesce(BDMOVIMENTO06, 0)) as BDMOVIMENTO06,';
               wsql = wsql||' sum(coalesce(BDSALDO07, 0)) as BDSALDO07, sum(coalesce(BDMOVIMENTO07, 0)) as BDMOVIMENTO07, sum(coalesce(BDSALDO08, 0)) as BDSALDO08, sum(coalesce(BDMOVIMENTO08, 0)) as BDMOVIMENTO08,';
               wsql = wsql||' sum(coalesce(BDSALDO09, 0)) as BDSALDO09, sum(coalesce(BDMOVIMENTO09, 0)) as BDMOVIMENTO09, sum(coalesce(BDSALDO10, 0)) as BDSALDO10, sum(coalesce(BDMOVIMENTO10, 0)) as BDMOVIMENTO10,';
               wsql = wsql||' sum(coalesce(BDSALDO11, 0)) as BDSALDO11, sum(coalesce(BDMOVIMENTO11, 0)) as BDMOVIMENTO11, sum(coalesce(BDSALDO12, 0)) as BDSALDO12, sum(coalesce(BDMOVIMENTO12, 0)) as BDMOVIMENTO12';
               wsql = wsql||' from (';
             END
          ELSE
             wsql = wsql||' union all ';
    
          IF (wcount = 0) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' bdsaldo_atual as BDSALDO01, bdmovimento as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
          ELSE
          IF (wcount = 1) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, bdsaldo_atual as BDSALDO02, bdmovimento as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE  
           IF (wcount = 2) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' bdsaldo_atual as BDSALDO03, bdmovimento as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 3) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, bdsaldo_atual as BDSALDO04, bdmovimento as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 4) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' bdsaldo_atual as BDSALDO05, bdmovimento as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 5) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, bdsaldo_atual as BDSALDO06, bdmovimento as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 6) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' bdsaldo_atual as BDSALDO07, bdmovimento as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 7) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, bdsaldo_atual as BDSALDO08, bdmovimento as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 8) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' bdsaldo_atual as BDSALDO09, bdmovimento as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 9) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, bdsaldo_atual as BDSALDO10, bdmovimento as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 10) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' bdsaldo_atual as BDSALDO11, bdmovimento as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 11) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, bdsaldo_atual as BDSALDO12, bdmovimento as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||PRCTASEMMOV||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
    
          wcount = wcount + 1;
        END
    
      wsql = wsql||' ) group by BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDNOMEMP, BDCODMATRIZ, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA, BDCODEMPFILIAL';
    
      FOR EXECUTE STATEMENT wsql INTO
          :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
          :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
          :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
          :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
        BEGIN
          IF (pragrupaempresafiliais = 1) THEN
            BEGIN
              bdcodemp       = wcodemp;
              bdcnpjemp      = wcnpjemp;
              bdnomemp       = wnomemp;
              bdcodempfilial = bdcodemp;
            END
    
          BDQTDCOMP = wtotal;
    
          IF ((PRFORMACALC = 0) AND (PRIMPRIMIRCOLUNASEXTRAS = 1)) THEN
             BEGIN
               BDTOTALSALDO = (COALESCE(BDSALDO01, 0) + COALESCE(BDSALDO02, 0) + COALESCE(BDSALDO03, 0) + COALESCE(BDSALDO04, 0) + COALESCE(BDSALDO05, 0) + COALESCE(BDSALDO06, 0) +
                               COALESCE(BDSALDO07, 0) + COALESCE(BDSALDO08, 0) + COALESCE(BDSALDO09, 0) + COALESCE(BDSALDO10, 0) + COALESCE(BDSALDO11, 0) + COALESCE(BDSALDO12, 0));
               BDMEDIASALDO = BDTOTALSALDO / wtotal;
    
               BDTOTALMOVIMENTO = (COALESCE(BDMOVIMENTO01, 0) + COALESCE(BDMOVIMENTO02, 0) + COALESCE(BDMOVIMENTO03, 0) + COALESCE(BDMOVIMENTO04, 0) +
                                   COALESCE(BDMOVIMENTO05, 0) + COALESCE(BDMOVIMENTO06, 0) + COALESCE(BDMOVIMENTO07, 0) + COALESCE(BDMOVIMENTO08, 0) +
                                   COALESCE(BDMOVIMENTO09, 0) + COALESCE(BDMOVIMENTO10, 0) + COALESCE(BDMOVIMENTO11, 0) + COALESCE(BDMOVIMENTO12, 0));
               BDMEDIAMOVIMENTO = BDTOTALMOVIMENTO / wtotal;
             END
    
          SUSPEND;
        END
  END
END
^

/* Alter (VSUC_SP_RETORNA_REL_ORCA) */
ALTER PROCEDURE VSUC_SP_RETORNA_REL_ORCA(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNORA_ZERAMENTO INTEGER,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRINDICE INTEGER,
PRCODTPCC VARCHAR(2048),
PRREFEMP INTEGER,
PRLANSEMCC INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDOREALIZADO NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER)
 AS
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WSALDOREALIZADO NUMERIC(15,2);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WGRPCTA SMALLINT;
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
BEGIN
  wdatahora = CURRENT_TIMESTAMP;

  -- retorna as empresas selecionadas
  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        DELETE FROM VSUC_EMPRESAS_REL_TORCAMENTO WHERE bdcodemp <> 0 AND bddatahora = :wdatahora;
        -- verifica se existe centro de custo selecionado
        IF (prcodtpcc = '') THEN
           BEGIN
             bdcodtpcc = 0;
             bdnomtpcc = '';
             bdtpcclon = '';
             -- retorna todas as contas do plano de contas sem o centro de custo
             FOR SELECT tsalcta.conta, tsalcta.classificacao, tsalcta.nomeconta, tsalcta.tipconta, tsalcta.GRUPOCONTA,
                        tsalcta.bdrealizado,  tsalcta.formula, tsalcta.relconta
                 FROM vsuc_sp_retorna_saldo_orca(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prIndice, :prignora_zeramento, 0, :bdcodplapadrao,
                                                 :wdatahora,:prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsalcta
                 INTO :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta, :bdgrpcta,
                      :bdsaldorealizado,  :bdformula, :bdrelcta DO
                 BEGIN
                       BEGIN
                         --bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                         SUSPEND;
                       END
                 END
           END
        ELSE
           BEGIN
             -- retorna a conta londa da conta inicial
             SELECT tpla.bdctalon FROM planos_tpla tpla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :prctaini
             INTO :wctalonant;
             -- inicializa as variaveis
             bdsaldorealizado = 0;
             -- sql por centro de custo selecionado
             wsql = 'select tpcc.bdcodtpcc, tpcc.bdnomcta, tpcc.bdctalon from centros_tpcc tpcc ';
             wsql = wsql||'where tpcc.bdcodcentro = (select first 1 temp.bdcodcentros from tempresas_ref temp ';
             wsql = wsql||                          'where temp.bdcodemp in ('||bdcodemp||')';
             wsql = wsql||                         ' and temp.bdrefemp <= '||prrefemp;
             wsql = wsql||                         ' order by temp.bdrefemp desc) ';
             wsql = wsql||'and tpcc.bdcodtpcc in ('||prcodtpcc||')';
             -- execucao do sql por centro de custo para trazer os lancamnetos sem o centro de custo
             IF (prlansemcc = 1) THEN
                BEGIN
                  FOR EXECUTE STATEMENT wsql
                      INTO :bdcodtpcc, :bdnomtpcc, :bdtpcclon DO
                      BEGIN
                        -- laco que retorna as contas por centro de custo selecionado
                        FOR SELECT bdcodcta, bdctalon, bdnomcta, bdtipcta, bdgrpcta, bdsalantdeb, bdformula, bdrelcta, bdformula
                            FROM vsuc_sp_retorna_saldo_contas_cc(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prignora_zeramento, :bdcodtpcc,
                                                                 :bdcodplapadrao,0)
                            INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta, : wsaldorealizado, :wformula, :bdrelcta, :bdformula DO
                            BEGIN
                              IF (wctalonant <> wctalon) THEN
                                 BEGIN
                                       BEGIN
                                         bdcodtpcc = NULL;
                                         bdnomtpcc = 'Sem Centro de Custo';
                                         bdtpcclon = NULL;
                                         -- bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                                         SUSPEND;
                                       END
     
                                   bdcodcta = wconta;
                                   bdctalon = wctalon;
                                   bdnomcta = wnomcta;
                                   bdtipcta = wtipcta;
                                   bdgrpcta = wgrpcta;
                                   bdformula = wformula;
                                 END
                              ELSE
                                 BEGIN
                                   bdcodcta = wconta;
                                   bdctalon = wctalon;
                                   bdnomcta = wnomcta;
                                   bdtipcta = wtipcta;
                                   bdgrpcta = wgrpcta;
                                   bdformula = wformula;
                                 END
                              wctalonant = wctalon;
                            END
                      END
                END

             -- execucao do sql por centro de custo
             FOR EXECUTE STATEMENT wsql
                 INTO :bdcodtpcc, :bdnomtpcc, :bdtpcclon DO
                 BEGIN
                   -- laco que retorna as contas por centro de custo selecionado
                   FOR SELECT conta, classificacao, nomeconta, tipconta, GRUPOCONTA, bdrealizado,
                              formula, relconta
                       FROM vsuc_sp_retorna_saldo_orca(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prIndice, :prignora_zeramento, :bdcodtpcc,
                                                       :bdcodplapadrao,:wdatahora,:prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado)
                       INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta,
                            :wsaldorealizado, :wformula, :bdrelcta DO
                       BEGIN
                         IF (wctalonant <> wctalon) THEN
                            BEGIN
                              SUSPEND;
                              bdcodcta = wconta;
                              bdctalon = wctalon;
                              bdnomcta = wnomcta;
                              bdtipcta = wtipcta;
                              bdgrpcta = wgrpcta;
                              bdformula = wformula;
                              bdsaldorealizado = :wsaldorealizado;
                            END
                         ELSE
                            BEGIN
                              bdcodcta = wconta;
                              bdctalon = wctalon;
                              bdnomcta = wnomcta;
                              bdtipcta = wtipcta;
                              bdgrpcta = wgrpcta;
                              bdformula = wformula;
                              bdsaldorealizado = :wsaldorealizado;
                            END
                         wctalonant = wctalon;
                       END
                 END
           END
      END
END
^

/* Restore proc. body: SP_EXPORTA_BLOCOC_ENT */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_ENT(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
BEGIN
  --22326
  /*****************************************************************************
   *-------------------------------->>ENTRADA<<--------------------------------*
   ****************************************************************************/

   /*
     OBS: A Orderna??o dos registros ? feita pelo campo BDCHAVEREG que ? uma classifica??o.
          Classifica??o: Empresa.Chave.Reg.Chave.Reg....
          EX: C170: 000010.0000012587.C100.C170.000001
              C195: 000010.0000012587.C100.C195.000001
              C197: 000010.0000012587.C100.C195.000001.C197.000001
   */

  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
  SELECT  :PRARQUIVO BDID,
          LPAD(ENT.BDCODEMP, 6, '0')||'.0.'||LPAD(ENT.BDCHAVE, 10, '0')||'.C100',
          'C100' BDREG,
          ('|C100|0|'||M.BDEMITENTE||         --IND_EMIT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))))|| --COD_PART
           '|'||MOD.BDMODELOSTR||             --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
           '|'||M.BDSERIE||                   --SER
           '|'||M.BDNUMDOCINI||               --NUM_DOC
           '|'||COALESCE(IIF(M.BDMODELO IN (55, 65), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAENTRADAENT, 'DDMMYYYY')))|| --DT_E_S
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(ENT.BDVLRCONTAB, '.', ','))|| --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))||   --IND_PGTO
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_DESC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_ABAT_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ','))||    --VL_MERC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN M.BDMODELO = 65 THEN '9' WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRFRETE, 0.00), '.', ','))||  --VL_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRSEGURO, 0.00), '.', ','))|| --VL_SEG
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLROUTDESP, 0.00), '.', ','))||--VL_OUT_DA
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRICMS, 0.00), '.', ','))||    --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(IIF(ENT.BDVLRST > 0, COALESCE(ENT.BDBASEST, 0.00), 0.00), '.', ',')))|| --VL_BC_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(ENT.BDVLRST, 0.00), '.', ',')))||           --VL_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(ENT.BDVLRIPI, 0.00), '.', ',')))||          --VL_IPI
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPIS, 0.00), '.', ',')))||      --VL_PIS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINS, 0.00), '.', ',')))||   --VL_COFINS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPISST, 0.00), '.', ',')))||    --VL_PIS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINSST, 0.00), '.', ',')))|| --VL_COFINS_ST
           '|') BDLINHA, IIF(((M.BDMODELO = 65) OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) ENT
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = ENT.BDCODEMP AND M.BDCHAVE = ENT.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = ENT.BDCODEMP AND C100.BDCHAVE = ENT.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE)
  LEFT OUTER JOIN (
                   SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM
                   FROM VEF_EMP_TMOVPROENT P
                   WHERE P.BDCODEMP = :PRCODEMP
                   GROUP BY P.BDCODEMP, P.BDCHAVE
                  ) PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   C101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C101.0000000001',
             'C101' BDREG,
             '|C101|'||REPLACE(COALESCE(C.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVENT M
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDMODELO = 55
            AND M.BDVALORNOTA > 0
            AND M.BDCODSITNF NOT IN(1, 7)
            AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
           ) MOV
      JOIN VEF_EMP_TC100ENT C ON(C.BDCODEMP = MOV.BDCODEMP AND C.BDCHAVE = MOV.BDCHAVE AND
                                 (((C.BDVLR_FCP_UF_DEST IS NOT NULL) AND (C.BDVLR_FCP_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_DEST IS NOT NULL) AND (C.BDVLRICMS_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_REM IS NOT NULL) AND (C.BDVLRICMS_UF_REM > 0))));
    END

  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C110                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODINFCOM, BDORDEMINFCOM)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0'),
             'C110' BDREG,
             '|C110|'||COALESCE(CADINF.BDCODINFCOM, '')||
             '|'||COALESCE(TRIM(REPLACE(SUBSTRING(MOVINF.BDDESCCOMPIC FROM 1 FOR 255), '|', '')), '')||'|',
             CADINF.BDCODINFCOM, CADINF.BDORDEMINFCOM
      FROM (
            SELECT INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON(CADINF.BDORDEMINFCOM = MOVINF.BDORDEMINFCOM AND CADINF.BDCODEMP = MOVINF.BDCODEMP);

      /*****************************************************************************
       *                                   C111                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C111.'||LPAD(REF.BDORDEMPROREF, 6, '0'),
             'C111',
             '|C111|'||COALESCE(TRIM(REF.BDNUMPROC), '')||
             '|'||IIF(REF.BDINDPROCESSO = '4', '9', COALESCE(REF.BDINDPROCESSO, ''))||'|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTPROREF REF ON(REF.BDCODEMP = MOVINF.BDCODEMP AND REF.BDCHAVE = MOVINF.BDCHAVE AND REF.BDORDEMIC = MOVINF.BDORDEMIC);
    
      /*****************************************************************************
       *                                   C112                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C112.'||LPAD(C112.BDORDEMDOCAREF, 6, '0'),
             'C112',
             '|C112'||
             '|'||COALESCE(C112.BDMODCODDA, 0)|| --COD_DA
             '|'||COALESCE(UF.BDSIGLAUF, '')||   --UF
             '|'||COALESCE(C112.BDNUMDA, '')||   --NUM_DA
             '|'||COALESCE(C112.BDCODAUT, '')||  --COD_AUT
             '|'||REPLACE(CAST(COALESCE(C112.BDVLRDA, 0.00) AS NUMERIC(15, 2)), '.', ',')|| --VL_DA
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTVCTO, 'DDMMYYYY'))||        --DT_VCTO
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTPGTO, 'DDMMYYYY'))||        --DT_PGTO
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTDOCAREF C112 ON(C112.BDCODEMP = MOVINF.BDCODEMP AND C112.BDCHAVE = MOVINF.BDCHAVE AND C112.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C112.BDCODUF);
    
      /*****************************************************************************
       *                                   C113                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C113.'||LPAD(C113.BDORDEMDOCFREF, 6, '0'),
             'C113',
             '|C113'||
             '|'||IIF(C113.BDINDOPER IS NULL, 0, C113.BDINDOPER)|| --IND_OPER
             '|'||COALESCE(C113.BDINDEMIT, 0)||   --IND_EMIT
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C113.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')|| --COD_MOD
             '|'||COALESCE(C113.BDSERIE, '')||    --SER
             '|'||COALESCE(C113.BDSUBSERIE, '')|| --SUB
             '|'||COALESCE(C113.BDNUMDOC, '')||   --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C113.BDDTEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||COALESCE(IIF(((DOCFIS.BDDOCFIS IN(55, 57, 65)) AND (:PRDTINI > '12/31/2016')), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_DOCe
             '|', C113.BDCODTER
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C113.BDCODDOCFIS)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER= C113.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C113.bdcodter);
    
      /*****************************************************************************
       *                                   C114                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C114.'||LPAD(C114.BDORDEMCUPREF, 6, '0'),
             'C114',
             '|C114'||
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')||   --COD_MOD
             '|'||COALESCE(C114.BDNRSERCAIXA, '')|| --ECF_FAB
             '|'||COALESCE(C114.BDNUMCAIXA, '')||   --ECF_CX
             '|'||COALESCE(C114.BDNUMDOC, '')||     --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C114.BDDTDOC, 'DDMMYYYY')), '')||
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTCUPREF C114 ON(C114.BDCODEMP = MOVINF.BDCODEMP AND C114.BDCHAVE = MOVINF.BDCHAVE AND C114.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C114.BDCODDOCFIS);

      /*****************************************************************************
       *                                   C120                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C120.'||LPAD(C120.BDORDEMOPIMP, 6, '0'),
             'C120',
             '|C120'||
             '|'||COALESCE(C120.BDCODDOCIMP, '')|| --COD_DOC_IMP
             '|'||COALESCE(C120.BDNUMDOCIMP, '')|| --NUM_DOC__IMP
             '|'||REPLACE(CAST(COALESCE(C120.BDVLRPAGOPIS, 0.00) AS NUMERIC(15, 2)), '.', ',')||    --PIS_IMP
             '|'||REPLACE(CAST(COALESCE(C120.BDVLRPAGOCOFINS, 0.00) AS NUMERIC(15, 2)), '.', ',')|| --COFINS_IMP
             '|'||COALESCE(C120.BDNUMDRAW, '')|| --NUM_ACDRAW
             '|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVENT M
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDMODELO IN (1, 4, 55, 65, 100)
            AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND m.bdcodsitnf NOT IN (2,3,4,5)
           ) MOV
      JOIN VEF_EMP_TMOVENTOPIMP C120 ON(C120.BDCODEMP = MOV.BDCODEMP AND C120.BDCHAVE = MOV.BDCHAVE);

      /*****************************************************************************
       *                                   C140                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.0.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C140',
             '|C140'||
             '|'||COALESCE(MOV.BDEMITENTE, '')|| --IND_EMIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN '00'
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN '01'
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN '02'
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN '03'
                       ELSE '99'
                  END|| --IND_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN ''
                       ELSE COALESCE(PAR.BDOUTROSPAR, '')
                  END|| --DESC_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN PAR.BDDUPLICATAPAR
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN PAR.BDCHEQUEPAR
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN PAR.BDPROMISSPAR
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN PAR.BDOUTROSPAR
                       ELSE COALESCE(PAR.BDOUTROSPAR, MOV.BDNUMDOCINI)
                  END|| --NUM_TIT
             '|'||COALESCE(TOTPAR.BDQTDPAR, '')|| --QTD_PARC
             '|'||REPLACE(COALESCE(TOTPAR.BDVALORDUPLICATA, 0.00), '.', ',')|| --VL_TIT
             '|'
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDEMITENTE,
                   ENT.BDVALORNOTA, ENT.BDNUMDOCINI
            FROM VEF_EMP_TMOVENT ENT
            WHERE ENT.BDCODEMP = :PRCODEMP
            AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND ENT.BDMODELO = 1 --somente modelo 1
            AND ent.bdcodsitnf NOT IN (2,3,4,5)
           ) MOV
      JOIN VEF_EMP_TMOVENTPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE AND PAR.BDORDEMPAR = (SELECT MIN(P.BDORDEMPAR) FROM VEF_EMP_TMOVENTPAR P WHERE P.BDCODEMP = PAR.BDCODEMP AND P.BDCHAVE = PAR.BDCHAVE))
      LEFT OUTER JOIN (
                       SELECT P.BDCODEMP, P.BDCHAVE, COUNT(P.BDORDEMPAR) BDQTDPAR, SUM(COALESCE(P.BDVALORPAR, 0)) BDVALORDUPLICATA
                       FROM VEF_EMP_TMOVENTPAR P
                       GROUP BY P.BDCODEMP, P.BDCHAVE
                      ) TOTPAR ON(TOTPAR.BDCODEMP = PAR.BDCODEMP AND TOTPAR.BDCHAVE = PAR.BDCHAVE);

      /*****************************************************************************
       *                                   C141                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.0.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.C141.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C141',
             '|C141'||
             '|'||PAR.BDORDEMPAR|| --NUM_PARC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(PAR.BDDATAVENCTOPAR, 'DDMMYYYY')), '')|| --DT_VCTO
             '|'||REPLACE(COALESCE(PAR.BDVALORPAR, 0.00), '.', ',')|| --VL_PARC
             '|'
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDEMITENTE,
                   ENT.BDVALORNOTA, ENT.BDNUMDOCINI
            FROM VEF_EMP_TMOVENT ENT
            WHERE ENT.BDCODEMP = :PRCODEMP
            AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND ENT.BDMODELO = 1 --somente modelo 1
            AND ent.bdcodsitnf NOT IN (2,3,4,5)
           ) MOV
      JOIN VEF_EMP_TMOVENTPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
      ORDER BY PAR.BDORDEMPAR;
    END

  /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCODNAT)
  SELECT  :PRARQUIVO BDID,
         LPAD(ENT.BDCODEMP, 6, '0')||'.0.'||LPAD(ENT.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
          'C170' BDREG,
          '|C170'||
--          '|'||PRO.BDORDEMPRO|| --NUM_ITEM
          '|'||GETORDEMSEQUENCIAL(PRO.BDCHAVE)|| --NUM_ITEM
          --#Alt:21967. Quando a empresa n?o possu?a o respectivo produto vinculado o registro estava levando vazio. Quando isso acontecer foi
          --tratado para levar a informa??o do produto ?nico. Esse tratamento ? feito para o c?digo e a descri??o.
          --'|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), COALESCE(VINC.BDCODPROD,''), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          --'|'||TRIM(REPLACE(COALESCE(VINC.BDDESCPROD, ''), '|', ''))|| --DESCR_COMPL
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                   IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                   COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          '|'||TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                                COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                                COALESCE(VINC.BDDESCPROD,'')), '|', ''))|| --DESCR_COMPL
          '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 5)), '.', ',')|| --QTD
          '|'||COALESCE(IIF(((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')), UN_REF.BDAPEUNIMED, UN.BDAPEUNIMED), '')|| --UNID
          '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
          '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
          '|'||IIF((UPPER(PRO.BDMOVFISICO) = 'TRUE'), 0, 1)|| --IND_MOV
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(I.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||COALESCE(I.BDCODNAT, '')|| --COD_NAT
          '|'||REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(COALESCE(PRO.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
          '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, COALESCE(PRO.BDBCST, 0.00)), '.', ',')||   --VL_BC_ICMS_ST
          '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2)), '.', ',')|| --ALIQ_ST
          '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, COALESCE(PRO.BDVLRST, 0.00)), '.', ',')||  --VL_ICMS_ST
          '|'|| --IND_APUR
          '|'||IIF(IPI.BDCODCSTIPI IS NULL, '', LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, 0))|| --CST_IPI
          '|'|| --COD_ENQ
          '|'||REPLACE(COALESCE(PRO.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQIPI, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_IPI
          '|'||REPLACE(COALESCE(PRO.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
          '|'||COALESCE(PIS.BDCSTPIS, '')|| --CST_PIS
          '|'||REPLACE(COALESCE(PRO.BDBCPIS, 0.00), '.', ',')|| --VL_BC_PIS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_PIS
          '|'||'0,00'|| --QUANT_BC_PIS
          '|'||'0,00'|| --ALIQ_PIS(em reais)
          '|'||REPLACE(COALESCE(PRO.BDVLRPIS, 0.00), '.', ',')|| --VL_PIS
          '|'||COALESCE(COF.BDCSTCOF, '')|| --CST_COFINS
          '|'||REPLACE(COALESCE(PRO.BDBCCOFINS, 0.00), '.', ',')|| --VL_BC_COFINS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_COFINS
          '|'||'0,00'|| --QUANT_BC_COFINS
          '|'||'0,00'|| --ALIQ_COFINS(em reais)
          '|'||REPLACE(COALESCE(PRO.BDVLRCOFINS, 0.00), '.', ',')|| --VL_COFINS
          '|'||COALESCE(PRO.BDCODCTA, '')|| --COD_CTA
          '|', PRO.BDCODPROD, I.BDCODNAT
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, SUM(COALESCE(I.BDVLRST, 0)) BDVLRST
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
        GROUP BY ENT.BDCODEMP, ENT.BDCHAVE
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
  /*Produto*/
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)
  LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD) --#Alt:21967.
--  LEFT OUTER JOIN TCADPRO_REF REF ON(REF.BDCODEMP = PRO.BDCODEMP AND REF.BDCODPROD = PRO.BDCODPROD AND ((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')))
  /*Produto por refer?ncia*/
  LEFT OUTER JOIN TCADPRO_VINC VINC_REF ON(VINC_REF.BDCODEMP = PRO.BDCODEMP AND VINC_REF.BDCODPROD = PRO.BDCODPROD)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN_REF ON(UN_REF.BDCODUNIMED = VINC_REF.BDCODUNIMED)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
  LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = PRO.BDCODCSTCOF);

  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C171                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
               LPAD(PRO.BDCODEMP, 6, '0')||'.0.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C171.'||LPAD(C171.BDORDEMC171, 6, '0'),
                'C171' BDREG,
                '|C171'||
                '|'||COALESCE(C171.BDNUMTANQUE, '')|| --NUM_TANQUE
                '|'||COALESCE(REPLACE(C171.BDQTDEVOLUME, '.', ','), '')||--QTDE
                '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVENT M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) ENT
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                 ) ENT
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TC171ENT C171 ON(C171.BDCODEMP = PRO.BDCODEMP AND C171.BDCHAVE = PRO.BDCHAVE AND C171.BDORDEM = PRO.BDORDEM AND C171.BDORDEMPRO = PRO.BDORDEMPRO);      
    
      /*****************************************************************************
       *                                   C173                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
               LPAD(PRO.BDCODEMP, 6, '0')||'.0.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C173.'||LPAD(C173.BDORDEMOPMED, 6, '0'),
                'C173' BDREG,
                '|C173'||
                '|'||COALESCE(C173.BDNRLOTE, '')|| --LOTE_MED
                '|'||REPLACE(COALESCE(C173.BDQTDITEM, 0.00), '.', ',')|| --QTD_ITEM
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTFABMED, 'DDMMYYYY')), '')|| --DT_FAB
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTVALMED, 'DDMMYYYY')), '')|| --DT_VAL
                '|'||COALESCE(C173.BDINDTIPOMED, '')|| --IND_MED
                '|'||COALESCE(C173.BDTIPOMED, '')||    --TP_PROD
                '|'||REPLACE(COALESCE(CAST(C173.BDVLRMAXMED AS DM_NUMERIC_15_2), 0.00), '.', ',')||   --VL_TAB_MAX
                '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVENT M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) ENT
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                 ) ENT
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TOPMEDENT C173 ON(C173.BDCODEMP = PRO.BDCODEMP AND C173.BDCHAVE = PRO.BDCHAVE AND C173.BDORDEM = PRO.BDORDEM AND C173.BDORDEMPRO = PRO.BDORDEMPRO);
    END

  /*****************************************************************************
   *                                   C190                                    *
   ****************************************************************************/
  /*Monta o C190 a partir do movimento de produto*/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
        LPAD(C190.BDCODEMP, 6, '0')||'.0.'||LPAD(C190.BDCHAVE, 10, '0')||'.C100.C190.'||LPAD(GETORDEMSEQUENCIAL(C190.BDCHAVE), 10, '0'),
        'C190' BDREG,
        '|C190'||
        '|'||COALESCE(C190.BDCSTICMS, '')|| --CST_ICMS
        '|'||COALESCE(C190.BDCODNAT, '')|| --CFOP
        '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),
                                                      (IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0.00), '.', ',')|| --VL_OPR
        '|'||REPLACE(COALESCE(C190.BDBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
        '|'||REPLACE(COALESCE(C190.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, IIF(ITEM.BDVLRSTITEM = 0, NULL, C190.BDBCST)), 0.00), '.', ',')|| --VL_BC_ICMS_ST
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, IIF(ITEM.BDVLRSTITEM = 0, NULL, C190.BDVLRST)), 0.00), '.', ',')|| --VL_ICMS_ST
--        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((COALESCE(C190.BDVLRITEM, 0) + COALESCE(C190.BDVLRDESPACESSORIA, 0) + COALESCE(C190.BDVLRIPI, 0) + COALESCE(C190.BDVLRST, 0)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
        '|'|| --COD_OBS
        '|'
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, MOV.BDCODNAT, MOV.BDALIQICMS, ENT.BDMODELO, MOV.BDVLRITEM,
               MOV.BDVLRDESC, MOV.BDVLRFRETE, MOV.BDVLRDESPACESSORIA, MOV.BDVLRIPI, MOV.BDVLRST, MOV.BDBCICMS,
               MOV.BDVLRICMS, MOV.BDBCST, MOV.BDREDBCICMS, ENT.BDVALORNOTA,
               (COALESCE(MOV.BDVLRFRETE, 0) + COALESCE(MOV.BDVLRITEM, 0) +
                COALESCE(MOV.BDVLRDESPACESSORIA, 0) + COALESCE(MOV.BDVLRIPI, 0) +
                COALESCE(MOV.BDVLRST, 0) - COALESCE(MOV.BDVLRDESC, 0)) BDVLRTOT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                     COALESCE(PRO.BDCODCSTICMS, 0) BDCODCSTICMS,
                     COALESCE(MOV.BDCODNAT, 0) BDCODNAT,
                     CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS,
                     SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                     SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                     SUM(COALESCE(PRO.BDVLRFRETE, 0)) BDVLRFRETE,
                     SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) BDVLRDESPACESSORIA,
                     SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI,
                     SUM(COALESCE(PRO.BDVLRST, 0)) BDVLRST,
                     SUM(COALESCE(PRO.BDBCST, 0)) BDBCST,
                     SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS,
                     SUM(COALESCE(PRO.BDVLRICMS, 0)) BDVLRICMS,
                     SUM(COALESCE(PRO.BDREDBCICMS, 0)) BDREDBCICMS
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                    FROM VEF_EMP_TMOVENT M
                    JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                   ) MOV
              JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
              GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
             ) MOV
        JOIN VEF_EMP_TMOVENT ENT ON(ENT.BDCODEMP = MOV.BDCODEMP AND ENT.BDCHAVE = MOV.BDCHAVE)
        LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
       ) C190
  LEFT OUTER JOIN (
                   SELECT C190_TOT.BDCODEMP, C190_TOT.BDCHAVE, SUM(C190_TOT.BDVLRDIF) BDVLRDIF, COUNT(C190_TOT.BDCHAVE) BDORDEMMAX
                   FROM (
                         SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                                ((SUM(COALESCE(PRO.BDVLRITEM, 0)) +
                                  SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) +
                                  SUM(COALESCE(PRO.BDVLRIPI, 0)) +
                                  SUM(COALESCE(PRO.BDVLRST, 0)) +
                                  SUM(COALESCE(PRO.BDVLRFRETE, 0))) -
                                 SUM(COALESCE(PRO.BDVLRDESC, 0))
                                 ) BDVLRDIF
                         FROM (
                               SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                               FROM VEF_EMP_TMOVENT M
                               JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                               WHERE M.BDCODEMP = :PRCODEMP
                               AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                               AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                               AND M.BDMODELO IN (1, 4, 55, 65, 100)
                               AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                              ) MOV
                         JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
                        ) C190_TOT
                   GROUP BY C190_TOT.BDCODEMP, C190_TOT.BDCHAVE
                  ) TOT ON(TOT.BDCODEMP = C190.BDCODEMP AND TOT.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN (
                   SELECT M.BDCODEMP, M.BDCHAVE, SUM(COALESCE(I.BDVLRST, 0)) BDVLRSTITEM
                   FROM VEF_EMP_TMOVENT M
                   JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                   WHERE M.BDCODEMP = :PRCODEMP
                   AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                   AND M.BDMODELO IN (1, 4, 55, 65, 100)
                   AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                   GROUP BY M.BDCODEMP, M.BDCHAVE
                  ) ITEM ON(ITEM.BDCODEMP = C190.BDCODEMP AND ITEM.BDCHAVE = C190.BDCHAVE);

  /*Monta o C190 a partir da tabela do C190*/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C190.'||LPAD(GETORDEMSEQUENCIAL(MOV.BDCHAVE), 6, '0'),
          'C190' BDREG,
          '|C190'||
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLROPER, 0.00), '.', ',')|| --VL_OPR
          '|'||REPLACE(COALESCE(C190.BDVLRBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLRBCICMSST, 0.00), '.', ',')|| --VL_BC_ICMS_ST
          '|'||REPLACE(COALESCE(C190.BDVLRICMSST, 0.00), '.', ',')|| --VL_ICMS_ST
          '|'||REPLACE(IIF((SUBSTRING(COALESCE(ICMS.BDCSTICMS, 0) FROM CHAR_LENGTH(ICMS.BDCSTICMS)-1 FOR 2)) IN(20, 70), (COALESCE(C190.BDVLROPER, 0) - COALESCE(C190.BDVLRBCICMS, 0)), 0.00), '.', ',')|| --VL_RED_BC
          '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
          '|'|| --COD_OBS
          '|'
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM, ENT.BDCODSITNF, I.BDCODNAT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODSITNF
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODSITNF
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND ((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) OR (M.BDCODSITNF = 6) OR ((M.BDCODSITNF = 8) AND (M.BDMODELO = 1))) /*Sol. 20290 Gabriel Ariel (13/11/2017) - Agora exporta o C190 caso possua modelo 1 e siua??o 8*/
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
        WHERE ((NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (ENT.BDCODSITNF = 6))
       ) MOV
  JOIN VEF_EMP_TC190ENT C190 ON(C190.BDCODEMP = MOV.BDCODEMP AND C190.BDCHAVE = MOV.BDCHAVE AND C190.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = C190.BDCODCSTICMS);

  /*****************************************************************************
   *                                   C195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C195.'||LPAD(C195.BDORDEMOBS, 6, '0'),
         'C195' BDREG,
         '|C195'||
         '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
         '|'||TRIM(COALESCE(REPLACE(C195.BDDESCCOMPL, '|', ''), ''))|| --TXT_COMPL
         '|',
          C195.BDCODOBS
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE
        FROM VEF_EMP_TMOVENT ENT
        WHERE ENT.BDCODEMP = :PRCODEMP
        AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND ENT.BDCODSITNF NOT IN(2, 3, 4, 5)
       ) MOV
  JOIN VEF_EMP_TC195ENT C195 ON(C195.BDCODEMP = MOV.BDCODEMP AND C195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = C195.BDCODOBS);

  /*****************************************************************************
   *                                   C197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C195.'||LPAD(C197.BDORDEMOBS, 6, '0')||'.C197.'||LPAD(C197.BDORDEMOUTOBR, 6, '0'),
         'C197' BDREG,
         '|C197'||
         '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
         '|'||TRIM(COALESCE(REPLACE(C197.BDDESCCOMPL, '|', ''), ''))|| --DESCR_COMPL_AJ
         '|'||COALESCE(IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), VINC.BDCODPROD, VINC.BDCODSAIDA), '')|| --COD_ITEM
         '|'||REPLACE(COALESCE(C197.BDBICMS, 0.00), '.', ',')|| --VL_BC_ICMS
         '|'||REPLACE(CAST(COALESCE(C197.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
         '|'||REPLACE(COALESCE(C197.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
         '|'||REPLACE(COALESCE(C197.BDOUTVLR, 0.00), '.', ',')|| --VL_OUTROS
         '|', C197.BDCODPROD
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE
        FROM VEF_EMP_TMOVENT ENT
        WHERE ENT.BDCODEMP = :PRCODEMP
        AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND ENT.BDCODSITNF NOT IN(2, 3, 4, 5)
       ) MOV
  JOIN VEF_EMP_TC195ENT C195 ON(C195.BDCODEMP = MOV.BDCODEMP AND C195.BDCHAVE = MOV.BDCHAVE AND C195.BDCODOBS IS NOT NULL)
  JOIN VEF_EMP_TC197ENT C197 ON(C197.BDCODEMP = C195.BDCODEMP AND C197.BDCHAVE = C195.BDCHAVE AND C197.BDORDEMOBS = C195.BDORDEMOBS)
  LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = C197.BDCODAJU)
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = MOV.BDCODEMP AND VINC.BDCODPROD = C197.BDCODPROD);
END
^

/* Restore proc. body: SP_EXPORTA_BLOCOC_SAI */
ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
BEGIN
  --22326
  /*****************************************************************************
   *--------------------------------->>SA?DA<<---------------------------------*
   ****************************************************************************/

   /*
     OBS: A Orderna??o dos registros ? feita pelo campo BDCHAVEREG que ? uma classifica??o.
          Classifica??o: Empresa.Chave.Reg.Chave.Reg....
          EX: C170: 000010.0000012587.C100.C170.000001
              C195: 000010.0000012587.C100.C195.000001
              C197: 000010.0000012587.C100.C195.000001.C197.000001
   */

  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
  SELECT  :PRARQUIVO BDID,
          LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100',
          'C100' BDREG,
          ('|C100|1|'||M.BDEMITENTE||         --IND_EMIT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))))|| --COD_PART
           '|'||MOD.BDMODELOSTR||             --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
           '|'||M.BDSERIE||                   --SER
           '|'||M.BDNUMDOCINI||               --NUM_DOC
           '|'||COALESCE(IIF(M.BDMODELO IN (55, 65), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'DDMMYYYY')))|| --DT_E_S
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(SAI.BDVLRCONTAB, '.', ','))|| --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))|| --IND_PGTO
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))||   --VL_DESC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_ABAT_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ','))||    --VL_MERC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN M.BDMODELO = 65 THEN '9' WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRFRETE, 0.00), '.', ','))||  --VL_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRSEGURO, 0.00), '.', ','))|| --VL_SEG
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLROUTDESP, 0.00), '.', ','))||--VL_OUT_DA
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRICMS, 0.00), '.', ','))||    --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDBASEST, 0.00), '.', ',')))||          --VL_BC_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDVLRST, 0.00), '.', ',')))||           --VL_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDVLRIPI, 0.00), '.', ',')))||          --VL_IPI
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPIS, 0.00), '.', ',')))||      --VL_PIS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINS, 0.00), '.', ',')))||   --VL_COFINS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPISST, 0.00), '.', ',')))||    --VL_PIS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINSST, 0.00), '.', ',')))|| --VL_COFINS_ST
           '|') BDLINHA, IIF(((M.BDMODELO = 65) OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVsai M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) SAI
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = SAI.BDCODEMP AND C100.BDCHAVE = SAI.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE)
  LEFT OUTER JOIN (
                   SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM
                   FROM VEF_EMP_TMOVPROSAI P
                   WHERE P.BDCODEMP = :PRCODEMP
                   GROUP BY P.BDCODEMP, P.BDCHAVE
                  ) PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   C101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C101.0000000001',
             'C101' BDREG,
             '|C101|'||REPLACE(COALESCE(C.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVSAI M
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDMODELO = 55
            AND M.BDVALORNOTA > 0
            AND M.BDCODSITNF NOT IN(1, 7)
            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
           ) MOV
      JOIN VEF_EMP_TC100SAI C ON(C.BDCODEMP = MOV.BDCODEMP AND C.BDCHAVE = MOV.BDCHAVE AND
                                 (((C.BDVLR_FCP_UF_DEST IS NOT NULL) AND (C.BDVLR_FCP_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_DEST IS NOT NULL) AND (C.BDVLRICMS_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_REM IS NOT NULL) AND (C.BDVLRICMS_UF_REM > 0))));
    END

  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C110                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODINFCOM, BDORDEMINFCOM)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0'),
             'C110' BDREG,
             '|C110|'||COALESCE(CADINF.BDCODINFCOM, '')||
             '|'||COALESCE(TRIM(REPLACE(SUBSTRING(MOVINF.BDDESCCOMPIC FROM 1 FOR 255), '|', '')), '')||'|',
             CADINF.BDCODINFCOM, CADINF.BDORDEMINFCOM
      FROM (
            SELECT INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON(CADINF.BDORDEMINFCOM = MOVINF.BDORDEMINFCOM AND CADINF.BDCODEMP = MOVINF.BDCODEMP);
    
      /*****************************************************************************
       *                                   C111                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C111.'||LPAD(REF.BDORDEMPROREF, 6, '0'),
             'C111',
             '|C111|'||COALESCE(TRIM(REF.BDNUMPROC), '')||
             '|'||IIF(REF.BDINDPROCESSO = '4', '9', COALESCE(REF.BDINDPROCESSO, ''))||'|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIPROREF REF ON(REF.BDCODEMP = MOVINF.BDCODEMP AND REF.BDCHAVE = MOVINF.BDCHAVE AND REF.BDORDEMIC = MOVINF.BDORDEMIC);
    
      /*****************************************************************************
       *                                   C112                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C112.'||LPAD(C112.BDORDEMDOCAREF, 6, '0'),
             'C112',
             '|C112'||
             '|'||COALESCE(C112.BDMODCODDA, 0)|| --COD_DA
             '|'||COALESCE(UF.BDSIGLAUF, '')||   --UF
             '|'||COALESCE(C112.BDNUMDA, '')||   --NUM_DA
             '|'||COALESCE(C112.BDCODAUT, '')||  --COD_AUT
             '|'||REPLACE(CAST(COALESCE(C112.BDVLRDA, 0.00) AS NUMERIC(15, 2)), '.', ',')|| --VL_DA
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTVCTO, 'DDMMYYYY'))||        --DT_VCTO
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTPGTO, 'DDMMYYYY'))||        --DT_PGTO
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIDOCAREF C112 ON(C112.BDCODEMP = MOVINF.BDCODEMP AND C112.BDCHAVE = MOVINF.BDCHAVE AND C112.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C112.BDCODUF);
    
      /*****************************************************************************
       *                                   C113                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C113.'||LPAD(C113.BDORDEMDOCFREF, 6, '0'),
             'C113',
             '|C113'||
             '|'||IIF(C113.BDINDOPER IS NULL, 1, C113.BDINDOPER)|| --IND_OPER
             '|'||COALESCE(C113.BDINDEMIT, 0)||   --IND_EMIT
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C113.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')|| --COD_MOD
             '|'||COALESCE(C113.BDSERIE, '')||    --SER
             '|'||COALESCE(C113.BDSUBSERIE, '')|| --SUB
             '|'||COALESCE(C113.BDNUMDOC, '')||   --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C113.BDDTEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||COALESCE(IIF(((DOCFIS.BDDOCFIS IN(55, 57, 65)) AND (:PRDTINI > '12/31/2016')), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_DOCe
             '|', C113.BDCODTER
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C113.BDCODDOCFIS)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER= C113.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C113.bdcodter);
    
      /*****************************************************************************
       *                                   C114                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C114.'||LPAD(C114.BDORDEMCUPREF, 6, '0'),
             'C114',
             '|C114'||
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')||   --COD_MOD
             '|'||COALESCE(C114.BDNRSERCAIXA, '')|| --ECF_FAB
             '|'||COALESCE(C114.BDNUMCAIXA, '')||   --ECF_CX
             '|'||COALESCE(C114.BDNUMDOC, '')||     --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C114.BDDTDOC, 'DDMMYYYY')), '')||
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
    --              AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAICUPREF C114 ON(C114.BDCODEMP = MOVINF.BDCODEMP AND C114.BDCHAVE = MOVINF.BDCHAVE AND C114.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C114.BDCODDOCFIS);
    
      /*****************************************************************************
       *                                   C115                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(C115.BDCODEMP, 6, '0')||'.1.'||LPAD(C115.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(C115.BDORDEMIC, 6, '0')||'.C115.'||LPAD(C115.BDORDEMLOCCOL, 6, '0'),
             'C115',
             '|C115'||
             '|'||COALESCE(TIP.BDCODEXPTRAN, '')|| --IND_CARGA
             '|'||IIF(CHAR_LENGTH(COALESCE(TERCOL.BDCGCTER, '')) = 18, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna s? CNPJ*/, TERCOL.BDCODTER, TERCOL.BDCGCTER, '', '')), '')|| --CNPJ_COL
             '|'||COALESCE(REPLACE(REPLACE(UPPER((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERCOL.BDIETER))), 'ISENTO', ''), 'ISENTA', ''), '')|| --IE_COL
             '|'||IIF(CHAR_LENGTH(COALESCE(TERCOL.BDCGCTER, '')) = 18, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna s? CNPJ*/, TERCOL.BDCODTER, TERCOL.BDCGCTER, '', '')))|| --CPF_COL
             '|'||COALESCE(CIDCOL.BDCODIBGE, '')|| --COD_MUN_COL
             '|'||IIF(CHAR_LENGTH(COALESCE(TERENTG.BDCGCTER, '')) = 18, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna s? CNPJ*/, TERENTG.BDCODTER, TERENTG.BDCGCTER, '', '')), '')|| --CNPJ_ENTG
             '|'||COALESCE(REPLACE(REPLACE(UPPER((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERENTG.BDIETER))), 'ISENTO', ''), 'ISENTA', ''), '')|| --IE_ENTG
             '|'||IIF(CHAR_LENGTH(COALESCE(TERENTG.BDCGCTER, '')) = 18, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna s? CNPJ*/, TERENTG.BDCODTER, TERENTG.BDCGCTER, '', '')))|| --CPF_ENTG
             '|'||COALESCE(CIDENTG.BDCODIBGE, '')|| --COD_MUN_ENTG
             '|'
      FROM (
            SELECT C115.BDCODEMP, C115.BDCHAVE, C115.BDORDEMIC, C115.BDORDEMLOCCOL, C115.BDCODTRAN,
                   C115.BDCODTERCOLETA, C115.BDCODCIDCOLETA, C115.BDCODTERENTREGA, C115.BDCODCIDENTREGA
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE
                        FROM VEF_EMP_TMOVSAI M
                        WHERE M.BDCODEMP = :PRCODEMP
                        AND M.BDMODELO IN (1, 4, 55, 100)
                        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                       ) MOV
                  JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                 ) MOVINF
            JOIN VEF_EMP_TMOVSAILOCCOL C115 ON (C115.BDCODEMP = MOVINF.BDCODEMP AND C115.BDCHAVE = MOVINF.BDCHAVE AND C115.BDORDEMIC = MOVINF.BDORDEMIC)
           ) C115
      LEFT OUTER JOIN VEF_BASE_TTABTIPOTRAN TIP ON (TIP.BDCODTRAN = C115.BDCODTRAN)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERCOL ON (TERCOL.BDCODTER = C115.BDCODTERCOLETA)
      LEFT OUTER JOIN TCIDADE CIDCOL  ON (CIDCOL.BDCODCID  = C115.BDCODCIDCOLETA)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERENTG ON (TERENTG.BDCODTER = C115.BDCODTERENTREGA)
      LEFT OUTER JOIN TCIDADE CIDENTG ON (CIDENTG.BDCODCID = C115.BDCODCIDENTREGA);
    
      /*****************************************************************************
       *                                   C140                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.1.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C140',
             '|C140'||
             '|'||COALESCE(MOV.BDEMITENTE, '')|| --IND_EMIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN '00'
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN '01'
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN '02'
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN '03'
                       ELSE '99'
                  END|| --IND_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN ''
                       ELSE COALESCE(PAR.BDOUTROSPAR, '')
                  END|| --DESC_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN PAR.BDDUPLICATAPAR
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN PAR.BDCHEQUEPAR
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN PAR.BDPROMISSPAR
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN PAR.BDOUTROSPAR
                       ELSE COALESCE(PAR.BDOUTROSPAR, MOV.BDNUMDOCINI)
                  END|| --NUM_TIT
             '|'||COALESCE(TOTPAR.BDQTDPAR, '')|| --QTD_PARC
             '|'||REPLACE(COALESCE(TOTPAR.BDVALORDUPLICATA, 0.00), '.', ',')|| --VL_TIT
             '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDEMITENTE,
                   SAI.BDVALORNOTA, SAI.BDNUMDOCINI
            FROM VEF_EMP_TMOVSAI SAI
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO = 1 --somente modelo 1
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5)
           ) MOV
      JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE AND PAR.BDORDEMPAR = (SELECT MIN(P.BDORDEMPAR) FROM VEF_EMP_TMOVSAIPAR P WHERE P.BDCODEMP = PAR.BDCODEMP AND P.BDCHAVE = PAR.BDCHAVE))
      LEFT OUTER JOIN (
                       SELECT P.BDCODEMP, P.BDCHAVE, COUNT(P.BDORDEMPAR) BDQTDPAR, SUM(COALESCE(P.BDVALORPAR, 0)) BDVALORDUPLICATA
                       FROM VEF_EMP_TMOVSAIPAR P
                       GROUP BY P.BDCODEMP, P.BDCHAVE
                      ) TOTPAR ON(TOTPAR.BDCODEMP = PAR.BDCODEMP AND TOTPAR.BDCHAVE = PAR.BDCHAVE);
    
      /*****************************************************************************
       *                                   C141                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.1.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.C141.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C141',
             '|C141'||
             '|'||PAR.BDORDEMPAR|| --NUM_PARC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(PAR.BDDATAVENCTOPAR, 'DDMMYYYY')), '')|| --DT_VCTO
             '|'||REPLACE(COALESCE(PAR.BDVALORPAR, 0.00), '.', ',')|| --VL_PARC
             '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDEMITENTE,
                   SAI.BDVALORNOTA, SAI.BDNUMDOCINI
            FROM VEF_EMP_TMOVSAI SAI
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO = 1 --somente modelo 1
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5)
           ) MOV
      JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
      ORDER BY PAR.BDORDEMPAR;

      /*****************************************************************************
       *                                   C160                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(C160.BDCODEMP, 6, '0')||'.1.'||LPAD(C160.BDCHAVE, 10, '0')||'.C100.C160.0000000001',
             'C160',
             '|C160'||
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C160.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(REPLACE(C160.BDPLACAID, '-', ''), '')|| --VEIC_ID
             '|'||REPLACE(COALESCE(CAST(C160.BDQTDVOLTRAN AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --QTD_VOL
             '|'||REPLACE(COALESCE(CAST(C160.BDPESOBRUTO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_BRT
             '|'||REPLACE(COALESCE(CAST(C160.BDPESOLIQUIDO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_LIQ
             '|'||COALESCE(UF.BDSIGLAUF, '')|| --UD_ID
             '|', C160.BDCODTER
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE
            FROM VEF_EMP_TMOVSAI SAI
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO IN(1, 4)
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5)
           ) MOV
      JOIN VEF_EMP_TMOVSAIVLTRAN C160 ON(C160.BDCODEMP = MOV.BDCODEMP AND C160.BDCHAVE = MOV.BDCHAVE)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C160.BDCODUF)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = C160.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C160.BDCODTER);
    END

  /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCODNAT)
  SELECT  :PRARQUIVO BDID,
         LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
          'C170' BDREG,
          '|C170'||
          '|'||GETORDEMSEQUENCIAL(PRO.BDCHAVE)|| --NUM_ITEM
          --#Alt:21967. Quando a empresa n?o possu?a o respectivo produto vinculado o registro estava levando vazio. Quando isso acontecer foi
          --tratado para levar a informa??o do produto ?nico. Esse tratamento ? feito para o c?digo e a descri??o.
          --'|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), COALESCE(VINC.BDCODPROD,''), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          --'|'||TRIM(REPLACE(COALESCE(VINC.BDDESCPROD, ''), '|', ''))|| --DESCR_COMPL
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                   IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                   COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          '|'||TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                                COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                                COALESCE(VINC.BDDESCPROD, '')), '|', ''))|| --DESCR_COMPL
          '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 5)), '.', ',')|| --QTD
          '|'||COALESCE(IIF(((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')), UN_REF.BDAPEUNIMED, UN.BDAPEUNIMED), '')|| --UNID
          '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
          '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
          '|'||IIF((UPPER(PRO.BDMOVFISICO) = 'TRUE'), 0, 1)|| --IND_MOV
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(SAI.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||COALESCE(SAI.BDCODNAT, '')|| --COD_NAT
          '|'||REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(COALESCE(PRO.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
          '|'||REPLACE(COALESCE(PRO.BDBCST, 0.00), '.', ',')||   --VL_BC_ICMS_ST
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ST
          '|'||REPLACE(COALESCE(PRO.BDVLRST, 0.00), '.', ',')||  --VL_ICMS_ST
          '|'|| --IND_APUR
          '|'||IIF(IPI.BDCODCSTIPI IS NULL, '', LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, 0))|| --CST_IPI
          '|'|| --COD_ENQ
          '|'||REPLACE(COALESCE(PRO.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQIPI, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_IPI
          '|'||REPLACE(COALESCE(PRO.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
          '|'||COALESCE(PIS.BDCSTPIS, '')|| --CST_PIS
          '|'||REPLACE(COALESCE(PRO.BDBCPIS, 0.00), '.', ',')|| --VL_BC_PIS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_PIS
          '|'||'0,00'|| --QUANT_BC_PIS
          '|'||'0,00'|| --ALIQ_PIS(em reais)
          '|'||REPLACE(COALESCE(PRO.BDVLRPIS, 0.00), '.', ',')|| --VL_PIS
          '|'||COALESCE(COF.BDCSTCOF, '')|| --CST_COFINS
          '|'||REPLACE(COALESCE(PRO.BDBCCOFINS, 0.00), '.', ',')|| --VL_BC_COFINS
          '|'||REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_COFINS
          '|'||'0,00'|| --QUANT_BC_COFINS
          '|'||'0,00'|| --ALIQ_COFINS(em reais)
          '|'||REPLACE(COALESCE(PRO.BDVLRCOFINS, 0.00), '.', ',')|| --VL_COFINS
          '|'||COALESCE(PRO.BDCODCTA, '')|| --COD_CTA
          '|', PRO.BDCODPROD, SAI.BDCODNAT
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
       ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
  /*Produto*/
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)
  LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD) --#Alt:21967.
--  LEFT OUTER JOIN TCADPRO_REF REF ON(REF.BDCODEMP = PRO.BDCODEMP AND REF.BDCODPROD = PRO.BDCODPROD AND ((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')))
  /*Produto por refer?ncia*/
  LEFT OUTER JOIN TCADPRO_VINC VINC_REF ON(VINC_REF.BDCODEMP = PRO.BDCODEMP AND VINC_REF.BDCODPROD = PRO.BDCODPROD)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN_REF ON(UN_REF.BDCODUNIMED = VINC_REF.BDCODUNIMED)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
  LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = PRO.BDCODCSTCOF);

  IF (:PRPERFIL NOT IN (2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C172                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT  :PRARQUIVO BDID,
             LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C172.0000000001',
              'C172' BDREG,
              '|C172'||
              '|'||REPLACE(COALESCE(PRO.BDBCISSQN, 0.00), '.', ',')|| --VL_BC_ISSQN
              '|'||REPLACE(COALESCE(CAST(PRO.BDALIQISSQN AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --ALIQ_ISSQN
              '|'||REPLACE(COALESCE(PRO.BDVLRISSQN, 0.00), '.', ',')|| --VL_ISSQN
              '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE
                        FROM VEF_EMP_TMOVSAI M
                        WHERE M.BDCODEMP = :PRCODEMP
                        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        AND M.BDMODELO = 1
                        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                        AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                       ) MOV
                 ) SAI
            JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
           ) SAI
      JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM AND COALESCE(PRO.BDVLRISSQN, 0) > 0);
    
      /*****************************************************************************
       *                                   C173                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
               LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C173.'||LPAD(C173.BDORDEMOPMED, 6, '0'),
                'C173' BDREG,
                '|C173'||
                '|'||COALESCE(C173.BDNRLOTE, '')|| --LOTE_MED
                '|'||REPLACE(COALESCE(C173.BDQTDITEM, 0.00), '.', ',')|| --QTD_ITEM
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTFABMED, 'DDMMYYYY')), '')|| --DT_FAB
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTVALMED, 'DDMMYYYY')), '')|| --DT_VAL
                '|'||COALESCE(C173.BDINDTIPOMED, '')|| --IND_MED
                '|'||COALESCE(C173.BDTIPOMED, '')||    --TP_PROD
                '|'||REPLACE(COALESCE(CAST(C173.BDVLRMAXMED AS DM_NUMERIC_15_2), 0.00), '.', ',')||   --VL_TAB_MAX
                '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                              AND ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1))
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TOPMEDSAI C173 ON(C173.BDCODEMP = PRO.BDCODEMP AND C173.BDCHAVE = PRO.BDCHAVE AND C173.BDORDEM = PRO.BDORDEM AND C173.BDORDEMPRO = PRO.BDORDEMPRO);
    END

  /*****************************************************************************
   *                                   C176                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODTERAUX)
  SELECT  :PRARQUIVO BDID,
         LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C176.'||LPAD(C176.BDORDEMC176, 6, '0'),
          'C176' BDREG,
          '|C176'||
          '|'||COALESCE(L.BDMODELOSTR, '')|| --COD_MOD_ULT_E
          '|'||COALESCE(C176.BDNUM_DOC_ULT_E, '')|| --NUM_DOC_ULT_E
          '|'||COALESCE(C176.BDSER_ULT_E, '')|| --SER_ULT_E
          '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C176.BDDT_ULT_E, 'DDMMYYYY')), '')|| --DT_ULT_E
          '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C176.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART_ULT_E
          '|'||REPLACE(COALESCE(C176.BDQUANT_ULT_E, 0.000), '.', ',')|| --QUANT_ULT_E
          '|'||REPLACE(COALESCE(C176.BDVL_UNIT_ULT_E, 0.000), '.', ',')|| --VL_UNIT_ULT_E
          '|'||REPLACE(COALESCE(C176.BDVL_UNIT_BC_ST, 0.000), '.', ',')|| --VL_UNIT_BC_ST
          '|'||COALESCE(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_ULT_E)), 44, ' '), '')|| --CHAVE_NFE_ULT_E
          '|'||COALESCE(C176.BDNUM_ITEM_ULT_E, '')|| --VL_UNIT_BC_ST
          '|'||IIF(COALESCE(C176.BDVL_UNIT_BC_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_BC_ICMS_ULT_E, 0.00), '.', ','), '')|| --VL_UNIT_BC_ICMS_ULT_E
          '|'||IIF(COALESCE(C176.BDALIQ_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDALIQ_ICMS_ULT_E, 0.00), '.', ','), '')|| --ALIQ_ICMS_ULT_E
          '|'||IIF(COALESCE(C176.BDVL_UNIT_LIM_BC_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_LIM_BC_ICMS_ULT_E, 0.00), '.', ','), '')|| --VL_UNIT_LIMITE_BC_ICMS_ULT_E
          '|'||IIF(COALESCE(C176.BDVL_UNIT_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_ICMS_ULT_E, 0.000), '.', ','), '')|| --VL_UNIT_ICMS_ULT_E
          '|'||IIF(COALESCE(C176.BDALIQ_ST_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDALIQ_ST_ULT_E, 0.00), '.', ','), '')|| --ALIQ_ST_ULT_E
          '|'||IIF(COALESCE(C176.BDVL_UNIT_RES, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_RES, 0.000), '.', ','), '')|| --VL_UNIT_RES 
          '|'||COALESCE(IIF(C176.BDCOD_RESP_RET = -1, '', C176.BDCOD_RESP_RET + 1), '')|| --COD_RESP_RET
          '|'||COALESCE(M.BDCODEXPMOT, '')|| --COD_MOT_RES
          '|'||COALESCE(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_RET)), 44, ' '), '')|| --CHAVE_NFE_RET
          '|'||IIF(COALESCE(C176.BDCODTER_NFE, 0) > 0, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C176.BDCODTER_NFE, TER_NFE.BDCGCTER, TER_NFE.BDIETER, TerEmp_NFE.BDCODIGOARQUIVO)), '')|| --COD_PART_NFE_RET
          '|'||COALESCE(C176.BDSER_NFE_RET, '')||  --SER_NFE_RET
          '|'||COALESCE(C176.BDNUM_NFE_RET, '')||  --NUM_NFE_RET
          '|'||COALESCE(C176.BDITEM_NFE_RET, '')|| --ITEM_NFE_RET
          '|'||COALESCE(IIF(C176.BDCOD_DA = -1, '', C176.BDCOD_DA), '')|| --COD_DA
          '|'||COALESCE(C176.BDNUM_DA, '')|| --NUM_DA
          '|', C176.BDCODTER, C176.BDCODTER_NFE
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN(1, 55)
                    AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
       ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
  JOIN VEF_EMP_TMOVSTC176 C176 ON(C176.BDCODEMP = PRO.BDCODEMP AND C176.BDCHAVE = PRO.BDCHAVE AND C176.BDORDEM = PRO.BDORDEM AND C176.BDORDEMPRO = PRO.BDORDEMPRO)
  LEFT OUTER JOIN VEF_BASE_TTABMOTRES M ON (M.BDORDEMMOTRES = C176.BDORDEMMOTRES)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN L ON (L.BDMODELO = C176.BDMODELO)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = C176.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = C176.bdcodter)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER_NFE ON(TER_NFE.BDCODTER = C176.BDCODTER_NFE)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp_NFE ON (TerEmp_NFE.bdcodter = C176.BDCODTER_NFE);

  IF (:PRPERFIL NOT IN (2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C177                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C177.0000000001',
             'C177' BDREG,
             '|C177'||
             '|'||COALESCE(C177.BDCODSELOIPI, '')|| --COD_SELO_IPI
             '|'||COALESCE(C177.BDQTDSELOIPI, '')|| --QT_SELO_IPI
             '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                              AND ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1))
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TMOVPROSAIC177 C177 ON(C177.BDCODEMP = PRO.BDCODEMP AND C177.BDCHAVE = PRO.BDCHAVE AND C177.BDORDEM = PRO.BDORDEM AND C177.BDORDEMPRO = PRO.BDORDEMPRO AND C177.BDCODSELOIPI > 0);
    
      /*****************************************************************************
       *                                   C178                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C178.0000000001',
             'C178' BDREG,
             '|C178'||
             '|'||COALESCE(CLIPI.BDCODCLASSEIPI, '')|| --CL_ENQ
             '|'||REPLACE(COALESCE(C178.BDVLRUNIDADE, 0.00), '.', ',')||  --VL_UNID
             '|'||REPLACE(COALESCE(CAST(C178.BDQTDUNIDADE AS DM_NUMERIC_18_3), 0.000), '.', ',')|| --QUANT_PAD
             '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Pr?prio
                              AND ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1))
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5)
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TMOVPROSAIC178 C178 ON(C178.BDCODEMP = PRO.BDCODEMP AND C178.BDCHAVE = PRO.BDCHAVE AND C178.BDORDEM = PRO.BDORDEM AND C178.BDORDEMPRO = PRO.BDORDEMPRO)
      LEFT OUTER JOIN VEF_BASE_TTABCLASSEIPI CLIPI ON (CLIPI.BDORDEMCLAIPI = C178.BDORDEMCLAIPI)
      WHERE ((CLIPI.BDCODCLASSEIPI IS NOT NULL) AND (CLIPI.BDCODCLASSEIPI <> ''));
    END

  /*****************************************************************************
   *                                   C190                                    *
   ****************************************************************************/
   /*PARA FAZER O SELECT, NO LUGAR DO GETORDEM(0) COLOCAR (GETORDEM(0)+1), CASO FOR FAZER INSERT SELECT N?O COLOCAR O +1*/
  SETORDEMSEQUENCIAL(0);
  /*Monta o C190 a partir do movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
        LPAD(C190.BDCODEMP, 6, '0')||'.1.'||LPAD(C190.BDCHAVE, 10, '0')||'.C100.C190.'||LPAD(GETORDEMSEQUENCIAL(C190.BDCHAVE), 10, '0'),
        'C190' BDREG,
        '|C190'||
        '|'||COALESCE(C190.BDCSTICMS, '')|| --CST_ICMS
        '|'||COALESCE(C190.BDCODNAT, '')|| --CFOP
        '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),
                                                      (IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0.00), '.', ',')|| --VL_OPR
        '|'||REPLACE(COALESCE(C190.BDBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
        '|'||REPLACE(COALESCE(C190.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, C190.BDBCST), 0.00), '.', ',')|| --VL_BC_ICMS_ST
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, C190.BDVLRST), 0.00), '.', ',')|| --VL_ICMS_ST
--        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((COALESCE(C190.BDVLRITEM, 0) + COALESCE(C190.BDVLRDESPACESSORIA, 0) + COALESCE(C190.BDVLRIPI, 0) + COALESCE(C190.BDVLRST, 0)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
        '|'|| --COD_OBS
        '|'
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, MOV.BDCODNAT, MOV.BDALIQICMS, SAI.BDMODELO, MOV.BDVLRITEM,
               MOV.BDVLRDESC, MOV.BDVLRFRETE, MOV.BDVLRDESPACESSORIA, MOV.BDVLRIPI, MOV.BDVLRST, MOV.BDBCICMS,
               MOV.BDVLRICMS, MOV.BDBCST, MOV.BDREDBCICMS, SAI.BDVALORNOTA,
               (COALESCE(MOV.BDVLRFRETE, 0) + COALESCE(MOV.BDVLRITEM, 0) +
                COALESCE(MOV.BDVLRDESPACESSORIA, 0) + COALESCE(MOV.BDVLRIPI, 0) +
                COALESCE(MOV.BDVLRST, 0) - COALESCE(MOV.BDVLRDESC, 0)) BDVLRTOT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                     COALESCE(PRO.BDCODCSTICMS, 0) BDCODCSTICMS,
                     COALESCE(MOV.BDCODNAT, 0) BDCODNAT,
                     CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS,
                     SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                     SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                     SUM(COALESCE(PRO.BDVLRFRETE, 0)) BDVLRFRETE,
                     SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) BDVLRDESPACESSORIA,
                     SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI,
                     SUM(COALESCE(PRO.BDVLRST, 0)) BDVLRST,
                     SUM(COALESCE(PRO.BDBCST, 0)) BDBCST,
                     SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS,
                     SUM(COALESCE(PRO.BDVLRICMS, 0)) BDVLRICMS,
                     SUM(COALESCE(PRO.BDREDBCICMS, 0)) BDREDBCICMS
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                    FROM VEF_EMP_TMOVSAI M
                    JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                   ) MOV
              JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
              GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
             ) MOV
        JOIN VEF_EMP_TMOVSAI SAI ON(SAI.BDCODEMP = MOV.BDCODEMP AND SAI.BDCHAVE = MOV.BDCHAVE)
        LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
       ) C190
  LEFT OUTER JOIN (
                   SELECT C190_TOT.BDCODEMP, C190_TOT.BDCHAVE, SUM(C190_TOT.BDVLRDIF) BDVLRDIF, COUNT(C190_TOT.BDCHAVE) BDORDEMMAX
                   FROM (
                         SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                                ((SUM(COALESCE(PRO.BDVLRITEM, 0)) +
                                  SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) +
                                  SUM(COALESCE(PRO.BDVLRIPI, 0)) +
                                  SUM(COALESCE(PRO.BDVLRST, 0)) +
                                  SUM(COALESCE(PRO.BDVLRFRETE, 0))) -
                                 SUM(COALESCE(PRO.BDVLRDESC, 0))
                                 ) BDVLRDIF     
                         FROM (
                               SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                               FROM VEF_EMP_TMOVSAI M
                               JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                               WHERE M.BDCODEMP = :PRCODEMP
                               AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                               AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                               AND M.BDMODELO IN (1, 4, 55, 65, 100)
                               AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                              ) MOV
                         JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
                        ) C190_TOT
                   GROUP BY C190_TOT.BDCODEMP, C190_TOT.BDCHAVE
                  ) TOT ON(TOT.BDCODEMP = C190.BDCODEMP AND TOT.BDCHAVE = C190.BDCHAVE);

  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  /*Monta o C190 a partir da tabela do C190*/
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C190.'||LPAD(GETORDEMSEQUENCIAL(MOV.BDCHAVE), 6, '0'),
          'C190' BDREG,
          '|C190'||
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLROPER, 0.00), '.', ',')|| --VL_OPR
          '|'||REPLACE(COALESCE(C190.BDVLRBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
          '|'||REPLACE(COALESCE(C190.BDVLRBCICMSST, 0.00), '.', ',')|| --VL_BC_ICMS_ST
          '|'||REPLACE(COALESCE(C190.BDVLRICMSST, 0.00), '.', ',')|| --VL_ICMS_ST
          '|'||REPLACE(IIF((SUBSTRING(COALESCE(ICMS.BDCSTICMS, 0) FROM CHAR_LENGTH(ICMS.BDCSTICMS)-1 FOR 2)) IN(20, 70), (COALESCE(C190.BDVLROPER, 0) - COALESCE(C190.BDVLRBCICMS, 0)), 0.00), '.', ',')|| --VL_RED_BC
          '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
          '|'|| --COD_OBS
          '|'
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODSITNF, I.BDCODNAT
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODSITNF
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODSITNF
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND ((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) OR (M.BDCODSITNF = 6) OR ((M.BDCODSITNF = 8) AND (M.BDMODELO = 1))) /*Sol. 20290 Gabriel Ariel (13/11/2017) - Agora exporta o C190 caso possua modelo 1 e siua??o 8*/
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
        WHERE ((NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (SAI.BDCODSITNF = 6))
       ) MOV
  JOIN VEF_EMP_TC190SAI C190 ON(C190.BDCODEMP = MOV.BDCODEMP AND C190.BDCHAVE = MOV.BDCHAVE AND C190.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = C190.BDCODCSTICMS);

  /*Estourou o tamanho m?ximo da sp, ent?o a exporta??o dos registros C195 e 197 est?o na SP abaixo.
    Exporta??o de novos registros devem ser feitos na nova SP_EXPORTA_BLOCOC_SAI_AUX*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_AUX(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :PRTIPOEXPCODPART, :PRPERFIL);
END
^

/* Restore proc. body: SP_EXPORTA_BLOCOD_ENT */
ALTER PROCEDURE SP_EXPORTA_BLOCOD_ENT(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER)
 AS
BEGIN

  /*****************************************************************************
   *-------------------------------->>ENTRADA<<--------------------------------*
   ****************************************************************************/

  /*****************************************************************************
   *                                   D100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODINFCOM, BDORDEMINFCOM)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.0.'||LPAD(M.BDCHAVE, 10, '0')||'.D100',
          'D100' BDREG,
          ('|D100|0'||
           '|'||M.BDEMITENTE||
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)))|| --COD_PART
           '|'||MOD.BDMODELOSTR||            --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')|| --COD_SIT
           '|'||COALESCE(M.BDSERIE, '')||    --SER
           '|'||COALESCE(M.BDSUBSERIE, '')|| --SUB
           '|'||M.BDNUMDOCINI||              --NUM_DOC
           '|'||COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), '')||       --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAENTRADAENT, 'DDMMYYYY')))|| --DT_A_P
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(IIF(M.BDMODELO IN(57, 67), D100.BDTIPOCTE, ''), ''))|| --TP_CT-e
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF)), ''))|| --CHV_CTE_REF
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(MOV.BDVLRCONTAB, '.', ','), ''))||                --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(M.BDDESCONTONOTA, '.', ','), ''))||              --VL_DESC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((IIF(((INDFRETED100.BDCODEXPFRETE = '') OR (INDFRETED100.BDCODEXPFRETE IS NULL)), '0', INDFRETED100.BDCODEXPFRETE)), ''))|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(MOV.BDVLRCONTAB, '.', ','), ''))||                --VL_SERV
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDBASEICMS, 0.00), '.', ','), ''))|| --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDVLRICMS, 0.00), '.', ','), ''))||  --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDISENTASICMS + MOV.BDOUTRASICMS, 0.00), '.', ','), ''))|| --VL_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(INFCOMD100.BDCODINFCOM, ''))|| --COD_INF
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(D100.BDCODCTA, ''))||          --COD_CTA
           --Campos exportados apartir de 01/01/2018
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'||COALESCE(CIDORIGD100.BDCODIBGE, '')))|| --COD_MUN_ORIG
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'||COALESCE(CIDDESTD100.BDCODIBGE, '')))|| --COD_MUN_DEST
           '|'
           ), M.BDCODTER, INFCOMD100.BDCODINFCOM, INFCOMD100.BDORDEMINFCOM
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI,
               SUM(COALESCE(I.BDISENTASICMS, 0.00)) BDISENTASICMS,
               SUM(COALESCE(I.BDOUTRASICMS, 0.00)) BDOUTRASICMS
        FROM (
              SELECT E.BDCODEMP, E.BDCHAVE
              FROM VEF_EMP_TMOVENT E
              WHERE E.BDCODEMP = :PRCODEMP
              AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) MOV
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TD100ENT D100 ON (D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETED100 ON (D100.BDINDFRETE = INDFRETED100.BDORDEMFRETE)
  LEFT OUTER JOIN VEF_BASE_TCADINFCOM INFCOMD100 ON (D100.BDORDEMINFCOM = INFCOMD100.BDORDEMINFCOM)
  LEFT OUTER JOIN TCIDADE CIDORIGD100 ON (D100.BDCIDORIGEM = CIDORIGD100.BDCODCID)
  LEFT OUTER JOIN TCIDADE CIDDESTD100 ON (D100.BDCIDDEST = CIDDESTD100.BDCODCID)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   D101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.0.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D101',
             'D101' BDREG,
             ('|D101'||
              '|'||REPLACE(COALESCE(D100.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
             )
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                   SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB
            FROM (
                  SELECT E.BDCODEMP, E.BDCHAVE
                  FROM VEF_EMP_TMOVENT E
                  WHERE E.BDCODEMP = :PRCODEMP
                  AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND E.BDMODELO IN(57, 67)
                  AND E.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
                 ) MOV
            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
            GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
           ) M
      JOIN VEF_EMP_TD100ENT D100 ON(D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE AND ((D100.BDVLR_FCP_UF_DEST > 0) OR (D100.BDVLRICMS_UF_DEST > 0) OR (D100.BDVLRICMS_UF_REM > 0)))
      WHERE M.BDVLRCONTAB > 0;
    END

  /*****************************************************************************
   *                                   D190                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.0.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D190.'||LPAD(GETORDEMSEQUENCIAL(M.BDCHAVE), 10, '0'),
          'D190' BDREG,
          ('|D190'||
           '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
           '|'||COALESCE(SUBSTRING(I.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
           '|'||COALESCE(REPLACE(CAST(I.BDALIQICMS AS NUMERIC(6, 2)), '.', ','), '')||  --ALIQ_ICMS
           '|'||COALESCE(REPLACE(I.BDVLRCONTAB, '.', ','), '')|| --VL_OPR
           '|'||COALESCE(REPLACE(I.BDBASEICMS, '.', ','), '')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(I.BDVLRICMS, '.', ','), '')|| --VL_ICMS
           '|'||REPLACE(IIF((SUBSTRING(ICMS.BDCSTICMS FROM 1 FOR 2) IN (20, 70)), (COALESCE(I.BDISENTASICMS, 0) + COALESCE(I.BDOUTRASICMS , 0)), '0,00'), '.', ',')|| --VL_RED_BC
           '|'||COALESCE(I.BDCODOBS, '')|| --COD_OBS
           '|'  
           )
  FROM (
        SELECT E.BDCODEMP, E.BDCHAVE
        FROM VEF_EMP_TMOVENT E
        WHERE E.BDCODEMP = :PRCODEMP
        AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND E.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = I.BDCODCSTICMS);

  /*****************************************************************************
   *                                   D195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(D195.BDCODEMP, 6, '0')||'.0.'||LPAD(D195.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D195.BDORDEMOBS, 10, '0'),
         'D195' BDREG,
         ('|D195'||
          '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
          '|'||COALESCE(REPLACE(D195.BDDESCCOMPL, '|', ''), '')|| --TXT_COMPL
          '|'
         ), D195.BDCODOBS
  FROM (
        SELECT E.BDCODEMP, E.BDCHAVE
        FROM VEF_EMP_TMOVENT E
        WHERE E.BDCODEMP = :PRCODEMP
        AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND E.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195ENT D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = D195.BDCODOBS);

  /*****************************************************************************
   *                                   D197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT  :PRARQUIVO BDID,
          LPAD(D197.BDCODEMP, 6, '0')||'.0.'||LPAD(D197.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D197.BDORDEMOBS, 10, '0')||'.D197.'||LPAD(D197.BDORDEMOUTOBR, 10, '0'),
          'D197' BDREG,
          ('|D197'||
           '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
           '|'||COALESCE(REPLACE(D197.BDDESCCOMPL, '|', ''), '')|| --DESCR_COMPL_AJ
           '|'||COALESCE(IIF(PRO.BDCODSAIDA <> '', PRO.BDCODSAIDA, PRO.BDCODPROD), '')|| --COD_ITEM
           '|'||COALESCE(REPLACE(D197.BDBICMS, '.', ','), '')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(CAST(D197.BDALIQICMS AS DM_NUMERIC_15_2), '.', ','), '')|| --ALIQ_ICMS
           '|'||COALESCE(REPLACE(D197.BDVLRICMS, '.', ','), '')|| --VL_ICMS
           '|'||COALESCE(REPLACE(D197.BDOUTVLR, '.', ','), '')|| --VL_OUTROS
           '|'
           ), D197.BDCODPROD
  FROM (
        SELECT E.BDCODEMP, E.BDCHAVE
        FROM VEF_EMP_TMOVENT E
        WHERE E.BDCODEMP = :PRCODEMP
        AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND E.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195ENT D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD197ENT D197 ON(D197.BDCODEMP = D195.BDCODEMP AND D197.BDCHAVE = D195.BDCHAVE AND D197.BDORDEMOBS = D195.BDORDEMOBS)
  LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = D197.BDCODAJU)
  LEFT OUTER JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = D197.BDCODEMP AND PRO.BDCODPROD = D197.BDCODPROD);

END
^

/* Restore proc. body: SP_EXPORTA_BLOCOD_SAI */
ALTER PROCEDURE SP_EXPORTA_BLOCOD_SAI(PRCODEMP INTEGER,
PRDTINI DATE,
PRDTFIM DATE,
PRARQUIVO VARCHAR(100),
PRTIPOEXPCODPART INTEGER,
PRPERFIL INTEGER)
 AS
BEGIN

  /*****************************************************************************
   *--------------------------------->>SA?DA<<---------------------------------*
   ****************************************************************************/

  /*****************************************************************************
   *                                   D100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODINFCOM, BDORDEMINFCOM)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100',
          'D100' BDREG,
          ('|D100|1'||
           '|'||M.BDEMITENTE||
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)))|| --COD_PART
           '|'||MOD.BDMODELOSTR||            --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')|| --COD_SIT
           '|'||COALESCE(M.BDSERIE, '')||    --SER
           '|'||COALESCE(M.BDSUBSERIE, '')|| --SUB
           '|'||M.BDNUMDOCINI||              --NUM_DOC
           '|'||COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), '')||       --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_A_P
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(IIF(M.BDMODELO IN(57, 67), D100.BDTIPOCTE, ''), ''))|| --TP_CT-e
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF)), ''))|| --CHV_CTE_REF
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(MOV.BDVLRCONTAB, '.', ','), ''))||                --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(M.BDDESCONTONOTA, '.', ','), ''))||              --VL_DESC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((IIF(((INDFRETED100.BDCODEXPFRETE = '') OR (INDFRETED100.BDCODEXPFRETE IS NULL)), '0', INDFRETED100.BDCODEXPFRETE)), ''))|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(MOV.BDVLRCONTAB, '.', ','), ''))||                --VL_SERV
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDBASEICMS, 0.00), '.', ','), ''))|| --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDVLRICMS, 0.00), '.', ','), ''))||  --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(MOV.BDISENTASICMS + MOV.BDOUTRASICMS, 0.00), '.', ','), ''))|| --VL_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(INFCOMD100.BDCODINFCOM, ''))|| --COD_INF
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(D100.BDCODCTA, ''))||          --COD_CTA
           --Campos exportados apartir de 01/01/2018
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'||COALESCE(COALESCE(CIDORIGD100.BDCODIBGE, ORIG.BDCODIBGE), '')))|| --COD_MUN_ORIG
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'||COALESCE(COALESCE(CIDDESTD100.BDCODIBGE, DEST.BDCODIBGE), '')))|| --COD_MUN_DEST
           '|'
           ), M.BDCODTER, INFCOMD100.BDCODINFCOM, INFCOMD100.BDORDEMINFCOM
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI,
               SUM(COALESCE(I.BDISENTASICMS, 0.00)) BDISENTASICMS,
               SUM(COALESCE(I.BDOUTRASICMS, 0.00)) BDOUTRASICMS
        FROM (
              SELECT S.BDCODEMP, S.BDCHAVE
              FROM VEF_EMP_TMOVSAI S
              WHERE S.BDCODEMP = :PRCODEMP
              AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TD100SAI D100 ON (D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETED100 ON (D100.BDINDFRETE = INDFRETED100.BDORDEMFRETE)
  LEFT OUTER JOIN VEF_BASE_TCADINFCOM INFCOMD100 ON (D100.BDORDEMINFCOM = INFCOMD100.BDORDEMINFCOM)
  LEFT OUTER JOIN TCIDADE CIDORIGD100 ON (CIDORIGD100.BDCODCID = D100.BDCIDORIGEM)
  LEFT OUTER JOIN TCIDADE CIDDESTD100 ON (CIDDESTD100.BDCODCID = D100.BDCIDDEST)

  LEFT OUTER JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = MOV.BDCODEMP AND D160.BDCHAVE = MOV.BDCHAVE AND ((D160.BDCODCIDREMETENTE IS NOT NULL) OR (D160.BDCODCIDDESTINATARIO IS NOT NULL)))
  LEFT OUTER JOIN TCIDADE ORIG ON (ORIG.BDCODCID = D160.BDCODCIDREMETENTE)
  LEFT OUTER JOIN TCIDADE DEST ON (DEST.BDCODCID = D160.BDCODCIDDESTINATARIO)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   D101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D101',
             'D101' BDREG,
             ('|D101'||
              '|'||REPLACE(COALESCE(D100.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
             )
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                   SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB
            FROM (
                  SELECT S.BDCODEMP, S.BDCHAVE
                  FROM VEF_EMP_TMOVSAI S
                  WHERE S.BDCODEMP = :PRCODEMP
                  AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND S.BDMODELO IN(57, 67)
                  AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
                 ) MOV
            LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
            GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
           ) M
      JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE AND ((D100.BDVLR_FCP_UF_DEST > 0) OR (D100.BDVLRICMS_UF_DEST > 0) OR (D100.BDVLRICMS_UF_REM > 0)))
      WHERE M.BDVLRCONTAB > 0;
    END

  /*****************************************************************************
   *                                   D110                                    *
   ****************************************************************************/
  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      SETORDEMSEQUENCIAL(0);
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D110.'||LPAD(D110.BDORDEMST, 6, '0'),
             'D110' BDREG,
             ('|D110'||
              '|'||GETORDEMSEQUENCIAL(0)||--NUM_ITEM
              '|'||IIF(((PRO_VINC.BDCODSAIDA IS NULL) OR (PRO_VINC.BDCODSAIDA = '')), PRO_VINC.BDCODPROD, PRO_VINC.BDCODSAIDA)|| --COD_ITEM
              '|'||REPLACE(COALESCE(D110.BDVLRSER, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D110.BDOUTVAL, 0.00), '.', ',')||
              '|'
             ), PRO_VINC.BDCODPROD
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(7)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD110SAI D110 ON(D110.BDCODEMP = M.BDCODEMP AND D110.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCADPRO_VINC PRO_VINC ON(PRO_VINC.BDCODEMP = D110.BDCODEMP AND PRO_VINC.BDCODPROD = D110.BDCODPROD);

      /*****************************************************************************
       *                                   D120                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D110.'||LPAD(D120.BDORDEMST, 6, '0')||'.D120.'||LPAD(D120.BDORDEMD120, 6, '0'),
             'D120' BDREG,
             ('|D120'||
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')||
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')||
              '|'||COALESCE(REPLACE(D120.BDPLACAVEICULO, '-', ''), '')||
              '|'||COALESCE(UF.BDSIGLAUF, '')||
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(7)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD120COMPCON D120 ON(D120.BDCODEMP = M.BDCODEMP AND D120.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D120.BDCODCIDORIG)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D120.BDCODCIDDEST)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF)
      LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = D120.BDCODUF);

      /*****************************************************************************
       *                                   D130                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODTERAUX)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D130',
             'D130' BDREG,
             ('|D130'||
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, D130.BDCODTERCONSIGNATARIO, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)), '')|| --COD_PART_CONSG
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, D130.BDCODTERREDESPACHANTE, TER_DES.BDCGCTER, TER_DES.BDIETER, TerEmp_DES.BDCODIGOARQUIVO)), '')|| --COD_PART_RED
              '|'||COALESCE(D130.BDINDFRETERED, '')|| --IND_FRT_RED
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')|| --COD_MUN_ORIG
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')|| --COD_MUN_DEST
              '|'||COALESCE(TRIM(REPLACE(D130.BDPLACAID, '-', '')), '')||          --VEIC_ID
              '|'||REPLACE(COALESCE(D130.BDVLRLIQFRETE, 0.00), '.', ',')||   --VL_LIQ_FRT
              '|'||REPLACE(COALESCE(D130.BDVLRSECCAT, 0.00), '.', ',')||     --VL_SEC_CAT
              '|'||REPLACE(COALESCE(D130.BDVLRDESPACHO, 0.00), '.', ',')||   --VL_DESP
              '|'||REPLACE(COALESCE(D130.BDVLRPEDAGIO, 0.00), '.', ',')||    --VL_PEDG
              '|'||REPLACE(COALESCE(D130.BDVLROUTVAL, 0.00), '.', ',')||     --VL_OUT
              '|'||REPLACE(COALESCE(D130.BDVLRTOTALFRETE, 0.00), '.', ',')|| --VL_FRT
              '|'||COALESCE(UF.BDSIGLAUF, '')||                              --UF_ID
              '|'
             ), D130.BDCODTERCONSIGNATARIO, D130.BDCODTERREDESPACHANTE
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(8, 800)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD130COMPCON D130 ON(D130.BDCODEMP = M.BDCODEMP AND D130.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D130.BDCODCIDORIGEM)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D130.BDCODCIDDESTINO)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF)
      LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = D130.BDCODUF)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = D130.BDCODTERCONSIGNATARIO)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                             ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = D130.BDCODTERCONSIGNATARIO)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER_DES ON(TER_DES.BDCODTER = D130.BDCODTERREDESPACHANTE)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp_DES ON (TerEmp_DES.bdcodter = D130.BDCODTERREDESPACHANTE);

      /*****************************************************************************
       *                                   D160                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D160.BDORDEMCARTRANS, 6, '0'),
             'D160' BDREG,
             ('|D160'||
              '|'||COALESCE(REPLACE(D160.BDNRDESPACHO, '|', ''), '')|| --DESPACHO
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos n?meros forem iguais retorna em branco*/, 0, TERREM.BDCGCTER, '', '')), '')|| --CNPJ_CPF_REM
              '|'||COALESCE(IIF(((POSITION(UPPER(TERREM.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERREM.BDIETER), 'ISENTA') > 0)), '', (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERREM.BDIETER))), '')|| --IE_REM
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')|| --COD_MUN_ORI
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos n?meros forem iguais retorna em branco*/, 0, TERDES.BDCGCTER, '', '')), '')|| --CNPJ_CPF_DEST
              '|'||COALESCE(IIF(((POSITION(UPPER(TERDES.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERDES.BDIETER), 'ISENTA') > 0)), '', (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERDES.BDIETER))), '')|| --IE_DEST
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')|| --COD_MUN_DEST
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERREM ON (TERREM.BDCODTER = D160.BDCODTERREMETENTE)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERDES ON (TERDES.BDCODTER = D160.BDCODTERDESTINATARIO)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D160.BDCODCIDREMETENTE)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D160.BDCODCIDDESTINATARIO)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF);

      /*****************************************************************************
       *                                   D161                                    *
       ****************************************************************************/
      IF (:PRPERFIL = 0) THEN /*Perfil A*/
        BEGIN
          INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
          SELECT :PRARQUIVO BDID,
                 LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D160.BDORDEMCARTRANS, 6, '0')||'.D161',
                 'D161' BDREG,
                 ('|D161'||
                  '|'||COALESCE(TRAN.BDCODEXPTRAN, '')||
                  '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos n?meros forem iguais retorna em branco*/, 0, TERCOL.BDCGCTER, '', '')), '')|| --CNPJ_CPF_COL
                  '|'||COALESCE(IIF(((POSITION(UPPER(TERCOL.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERCOL.BDIETER), 'ISENTA') > 0)), '', TERCOL.BDIETER), '')||       --IE_REM
                  '|'||COALESCE(IIF(UFCOL.BDSIGLAUF = 'EX', '9999999', CIDCOL.BDCODIBGE), '')|| --COD_MUN_COL
                  '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos n?meros forem iguais retorna em branco*/, 0, TERENT.BDCGCTER, '', '')), '')|| --CNPJ_CPF_ENT
                  '|'||COALESCE(IIF(((POSITION(UPPER(TERENT.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERENT.BDIETER), 'ISENTA') > 0)), '', TERENT.BDIETER), '')||       --IE_ENTG
                  '|'||COALESCE(IIF(UFENT.BDSIGLAUF = 'EX', '9999999', CIDENT.BDCODIBGE), '')|| --COD_MUN_ENTG
                  '|'
                 )
          FROM (
                SELECT S.BDCODEMP, S.BDCHAVE
                FROM VEF_EMP_TMOVSAI S
                WHERE S.BDCODEMP = :PRCODEMP
                AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
                AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
               ) M
          JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE AND D160.BDCODCIDCOLETA > 0)
          JOIN VEF_BASE_TTABTIPOTRAN TRAN ON(TRAN.BDCODTRAN = D160.BDCODTRAN AND TRAN.BDCODEXPTRAN IS NOT NULL)
          LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERCOL ON (TERCOL.BDCODTER = D160.BDCODTERCOLETA)
          LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERENT ON (TERENT.BDCODTER = D160.BDCODTERENTREGA)
          LEFT OUTER JOIN TCIDADE CIDCOL ON (CIDCOL.BDCODCID = D160.BDCODCIDCOLETA)
          LEFT OUTER JOIN TUF UFCOL ON (UFCOL.BDCODUF = CIDCOL.BDCODUF)
          LEFT OUTER JOIN TCIDADE CIDENT ON (CIDENT.BDCODCID = D160.BDCODCIDENTREGA)
          LEFT OUTER JOIN TUF UFENT ON (UFENT.BDCODUF = CIDENT.BDCODUF);
        END

      /*****************************************************************************
       *                                   D162                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(D162.BDCODEMP, 6, '0')||'.1.'||LPAD(D162.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D162.BDORDEMCARTRANS, 6, '0')||'.D162.'||LPAD(D162.BDORDEMDOCFIS, 6, '0'),
             'D162' BDREG,
             ('|D162'||
              '|'||COALESCE(DOC.BDDOCFIS, '')|| --COD_MOD
              '|'||COALESCE(D162.BDSERIE, '')|| --SER
              '|'||COALESCE(D162.BDNRDOC, '')|| --NUM_DOC
              '|'||(SELECT BDDATA FROM SP_PARSE_DATE(D162.BDDTDOC, 'DDMMYYYY'))|| --DT_DOC
              '|'||REPLACE(COALESCE(CAST(D162.BDVLRDOC AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --VL_DOC
              '|'||REPLACE(COALESCE(CAST(D162.BDVLRMER AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --VL_MER
              '|'||COALESCE(SUBSTRING(ROUND(D162.BDQTDVOL) FROM 1 FOR POSITION('.', D162.BDQTDVOL)), 0.00)|| --QTD_VOL
              '|'||REPLACE(COALESCE(CAST(D162.BDPESOBRUTO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_BRT
              '|'||REPLACE(COALESCE(CAST(D162.BDPESOLIQ AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_LIQ
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
           ) M
      JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE/* AND D160.BDCODCIDCOLETA > 0*/)
      JOIN VEF_EMP_TD162DOCFIS D162 ON(D162.BDCODEMP = D160.BDCODEMP AND D162.BDCHAVE = D160.BDCHAVE AND D162.BDORDEMCARTRANS = D160.BDORDEMCARTRANS)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON(DOC.BDCODDOCFIS = D162.BDCODDOCFIS);
   END

  /*****************************************************************************
   *                                   D190                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D190.'||LPAD(GETORDEMSEQUENCIAL(M.BDCHAVE), 10, '0'),
          'D190' BDREG,
          ('|D190'||
           '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
           '|'||COALESCE(SUBSTRING(I.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
           '|'||COALESCE(REPLACE(CAST(I.BDALIQICMS AS NUMERIC(6, 2)), '.', ','), '')||  --ALIQ_ICMS
           '|'||COALESCE(REPLACE(I.BDVLRCONTAB, '.', ','), '')|| --VL_OPR
           '|'||COALESCE(REPLACE(I.BDBASEICMS, '.', ','), '')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(I.BDVLRICMS, '.', ','), '')|| --VL_ICMS
           '|'||REPLACE(IIF((SUBSTRING(ICMS.BDCSTICMS FROM 1 FOR 2) IN (20, 70)), (COALESCE(I.BDISENTASICMS, 0) + COALESCE(I.BDOUTRASICMS , 0)), '0,00'), '.', ',')|| --VL_RED_BC
           '|'||COALESCE(I.BDCODOBS, '')|| --COD_OBS
           '|'  
           )
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = I.BDCODCSTICMS);

  /*****************************************************************************
   *                                   D195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(D195.BDCODEMP, 6, '0')||'.1.'||LPAD(D195.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D195.BDORDEMOBS, 10, '0'),
         'D195' BDREG,
         ('|D195'||
          '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
          '|'||COALESCE(REPLACE(D195.BDDESCCOMPL, '|', ''), '')|| --TXT_COMPL
          '|'
         ), D195.BDCODOBS
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195SAI D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = D195.BDCODOBS);

  /*****************************************************************************
   *                                   D197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT  :PRARQUIVO BDID,
          LPAD(D197.BDCODEMP, 6, '0')||'.1.'||LPAD(D197.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D197.BDORDEMOBS, 10, '0')||'.D197.'||LPAD(D197.BDORDEMOUTOBR, 10, '0'),
          'D197' BDREG,
          ('|D197'||
           '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
           '|'||COALESCE(REPLACE(D197.BDDESCCOMPL, '|', ''), '')|| --DESCR_COMPL_AJ
           '|'||COALESCE(IIF(PRO.BDCODSAIDA <> '', PRO.BDCODSAIDA, PRO.BDCODPROD), '')|| --COD_ITEM
           '|'||COALESCE(REPLACE(D197.BDBICMS, '.', ','), '')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(CAST(D197.BDALIQICMS AS DM_NUMERIC_15_2), '.', ','), '')|| --ALIQ_ICMS
           '|'||COALESCE(REPLACE(D197.BDVLRICMS, '.', ','), '')|| --VL_ICMS
           '|'||COALESCE(REPLACE(D197.BDOUTVLR, '.', ','), '')|| --VL_OUTROS
           '|'
           ), D197.BDCODPROD
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195SAI D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD197SAI D197 ON(D197.BDCODEMP = D195.BDCODEMP AND D197.BDCHAVE = D195.BDCHAVE AND D197.BDORDEMOBS = D195.BDORDEMOBS)
  LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = D197.BDCODAJU)
  LEFT OUTER JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = D197.BDCODEMP AND PRO.BDCODPROD = D197.BDCODPROD);
END
^

SET TERM ; ^

